-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1674 lines (1437 loc) · 41.1 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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// set encoding to utf8
process.stdout.setEncoding('utf8')
const async = require('async')
const colors = require('chalk')
const pkg = require('./package')
class Log {
/**
* Log boxes
*
* @param {*} parent - a parent box or a line
* @param opt
* @constructor
*/
constructor(parent, opt){
// generate id (time+rand)
this.id = (new Date().getTime()).toString(36)+((Math.random().toString(36).substr(2, 5)))
this.lines = []
this.parent = null
this.level = 0
this.printedLines = 0
// this.colors = colors
// make utils accessible
this.col = Log.col
this.strip = Log.strip
this.pad = Log.pad
// set color to colorText by default
if(typeof opt === 'object' && opt.color && !opt.colorText)
opt.colorText = opt.color
// default options
this.opt = Object.assign({
console: null, // object to receive the output of console2
border: typeof opt === 'number' ? opt : 1, // vertical border width (1 or 2)
color: typeof opt === 'string' ? opt : 'grey', // border color
colorText: typeof opt === 'string' ? opt : 'grey', // text color
isWorker: false, // run as a worker
map: [['...','…']], // auto replace
enableAutoOut: false, // enable auto out calls (used when in node console)
disableWelcome: false, // disable our kind welcome line
override: false, // override nodes console
animate: false, // animate idle status
over: false // box status
}, opt||{})
// is direct log
if(this._instanceof(parent)){
this.parent = parent
this.level = parent && parent.level ? parent.level+1 : 1
// inherit console object when not given
if(!this.opt.console)
this.opt.console = this.parent.opt.console
}
// use default
if(!this.opt.console)
this.opt.console = Log.console
this.timer = {
_: new Date().getTime(),
_calls: {}
}
if(this.level === 0){
// animate
if(this.opt.animate){
process.on('SIGINT', () => {
Log.clearLine()
process.stdout.write(Log.col('┘', this.opt.color)+"\n")
process.exit()
})
// passive set interval
setInterval(this._animate.bind(this), 500).unref()
}
}
}
//─── Static methods ──────────────────────────────────────────────────
/**
* Color[color] shortcut
*
* @param {String} str - the text
* @param {...String} cmd - the color or action (red, bold...)
* @returns {*}
*/
static col(str, cmd){
const cmds = Array.prototype.slice.call(arguments, 1)
// convert 2 str
if(typeof str != 'string')
str += ''
let res = str
switch(cmd){
// rainbow
// using the first 5 colors of Log.chalkColors
case 'rainbow':
const cols = Log.chalkColors.slice(0, 5)
return str.split('').map(function(char, i){
return colors[cols[i % cols.length]](char)
}).join('')
// zebra
// using white, then bgWhite & black
case 'zebra':
return str.split('').map(function(char, i){
return i % 2 ? colors.white(char) : colors.bgWhite.black.dim(char)
}).join('')
case 'code':
return colors.bgBlue.white(str.split('').map(function(char){
if('.,:;=()[]{}+-*|"/\''.indexOf(char) > -1)
return colors.grey(char)
return char
}).join(''))
}
// add attributes
cmds.forEach(function(cmd){
res = colors[cmd](res)
})
return res
}
/**
* Clear terminal line + set cursor to 0
*/
static clearLine(){
process.stdout.clearLine()
process.stdout.cursorTo(0)
return process.stdout
}
/**
* Truncate string
*
* @param {String} str
* @param {Number} length
* @param {String} [postfix]
* @returns {String}
*/
static truncate(str, length, postfix){
// convert 2 string
str = str+''
const plain = Log.strip(str)
// no action required
if(plain.length <= length)
return str
// default postfix
if(!postfix) postfix = '…'
// subtract postfix from length
length -= postfix.length
// return empty
if(length < 0)
return ''
return str.substring(str, length) + postfix
}
/**
* Uppercase first character
* @param {String} str
* @returns {String}
*/
static capitalize(str){
return str.substr(0,1).toUpperCase()+str.substr(1)
}
/**
* Pad a str
*
* Use in three ways:
* .pad('-', 5) = '-----'
* .pad('.', 7, 'Hello') = 'Hello..'
* .pad(' ', 7, 'Hello', true) = ' Hello'
*
* @param {String} padSymbol
* @param {Number} length
* @param {String} [str]
* @param {Boolean} [useLeftSide]
* @returns {String}
*/
static pad(padSymbol, length, str, useLeftSide){
let out = ''
if(str){
while(str.length < length){
if(useLeftSide)
str = padSymbol + str
else
str += padSymbol
}
return str
}
for(let i = 0; i < length; i += padSymbol.length){
if(useLeftSide)
out = padSymbol + out
else
out += padSymbol
}
return out
}
/**
* Format str in printf style as console does
* Slightly edited version of the original node utils.format
*
* @param f
* @returns {*}
*/
static format(f) {
const args = Array.prototype.slice.call(arguments)
if(args.length === 1) return args
let i = 1
const len = args.length
const str = String(f).replace(/%[sdj%]/g, function(x){
if(x === '%%') return '%'
if(i >= len) return x
switch (x) {
case '%s': return String(args[i++])
case '%d': return Number(args[i++])
case '%j':
try {
return JSON.stringify(args[i++])
} catch (_) {
return '[Circular]'
}
// falls through
default:
return x
}
})
// formatting happened
if(str !== args[0]){
// use result
args[0] = str
// remove formatting argument
args.splice(1, 1)
}
return args
}
/**
* Check if script is run from terminal
*
* @returns {boolean}
*/
static isTerminalConsole(){
return module && module.parent && (module.parent.id+'') === 'repl'
}
/**
* Parse keywords / add colors
*
* @param word
* @returns {String}
* @private
*/
static parseWord(word){
// basic types
if(word === null)
word = colors.grey.italic('null')
else if(word === undefined)
word = colors.red('undefined')
else if(word === true)
word = colors.green.bold('true')
else if(word === false)
word = colors.bold.red('false')
else if(word === pkg.name){
word = Log.col(word, 'rainbow')
}
else if(typeof word == 'number')
word = colors.cyan(word+'')
else {
let s = word.toString()
switch(s){
default: s = null
}
if(s)
word = s
}
return word
}
/**
* Wrap text
*
* @param {String} str
* @param {Number} length
* @returns {*}
*/
static wrap(str, length){
const lineWrap = require('linewrap')
return lineWrap(length, {
skipScheme:'ansi-color',
respectLineBreaks: 'multi',
tabWidth: 3
})(str)
}
/**
* Get stdout columns
*
* @returns {number}
* @private
*/
static getTerminalWidth(){
return process.stdout.columns-1 || 100
}
/**
* Pluralize a string, poor mans function
*
* @param nr
* @param str
* @returns {string}
*/
static plural(nr, str){
const i = parseFloat(nr)
nr = typeof nr == 'number' ? nr.toFixed(0) : nr
return str.replace('%s', Log.col(nr, 'cyan')) + (i !== 1 ? 's' : '')
}
// clone console
static console = Object.assign({}, console)
// color names
static chalkColors = ['cyan','green','yellow','red','magenta','blue','white','grey','black']
static chalkCommands = ['reset','bold','dim','italic','underline','inverse','hidden','strikethrough']
// shortcuts
static strip = colors.stripColor
//─── Dynamic methods ──────────────────────────────────────────────────
/**
* Override the console with this
*
* @returns {Log}
*/
overrideConsole(){
// im a dirty little whore
if(console instanceof Log)
return this.warn('Console already overwritten')
if(Log.isTerminalConsole()){
// disable 'undefined' console messages
process.stdin.emit('data', 'module.exports.repl.ignoreUndefined = true;\n')
}
// copy original console
this.opt.console = Log.console
// override console
console = Object.assign(console, this)
// finish
return this
}
/**
* Set options
*
* @param {String|Number|Object} opt
* @returns {Log}
*/
options(opt){
if(opt === undefined)
return this
// handle options('string') - color and 'ready'
if(typeof opt == 'string'){
opt = {color:opt}
}
// handle options(2) - border width
else if(opt === 1 || opt === 2){
opt = {border:opt}
}
// use color as colorText when colorText not given
if(opt.color && !opt.colorText)
opt.colorText = opt.color
// set options
this.opt = Object.assign(this.opt, opt)
return this
}
/**
* Create a new box
*
* @param [line]
* @param [opt]
* @returns {Log}
*/
box(line, opt){
if(arguments.length === 1){
// line could be either an option or a line
if(typeof line === 'string'){
// check if line is color
if(Log.chalkColors.indexOf(line) > -1 || Log.chalkCommands.indexOf(line) > -1){
opt = {color:line}
}
}
// line is no string and therefore an option
else {
opt = line
line = null
}
}
// create box
const box = new Log(this, opt||{})
// auto add 1st line when given
if(line){
box.line(line)
}
// add box to myself
this.line(box)
return box
}
/**
* Display help
*/
help(){
require('./help')
}
/**
* Save a line to buffer
*
* @param {String|Object} line
* @param {...String|Object} [option]
* @returns {Log}
*/
line(line, option){
let args = Array.prototype.slice.call(arguments)
const obj = {
prefix: ' ',
color: this.opt.color,
colorText: this.opt.colorText
}
// handle .line()
if(line === undefined){
args[0] = undefined
}
// try to find an option
option = (args[args.length-1]+'')
// prefix
if(option.substr(0,4) === 'pre:'){
args.pop()
obj.prefix = option.substr(4)
}
// color
else if(Log.chalkColors.indexOf(option) > -1 || Log.chalkCommands.indexOf(option) > -1){
args.pop()
obj.color = option
obj.colorText = option
}
// use format (sprintf) like console does
args = Log.format.apply(this, args)
// handle section
const processStash = () => {
// empty line (undefined,'')
if(!stash.length && line === undefined){
this.lines.push(obj)
}
// join word string
else if(stash.length){
obj.line = stash.join(' ')
// replace map (... > …)
if(Array.isArray(this.opt.map)){
this.opt.map.forEach(function(arr){
obj.line = obj.line.replace(arr[0],arr[1])
})
}
this.lines.push(obj)
}
// log
else if(this._instanceof(line)){
this.lines.push(line)
}
// empty stash
stash = []
}
// iterate args
let stash = []
args.forEach(function(word){
// types to strings
word = Log.parseWord(word)
// is str
if(typeof word == 'string'){
stash.push(word)
}
// object
else {
// skip sub boxes
if(this._instanceof(word))
return
// add to this.lines
processStash()
// log obj
this._try(this._object, word)
}
}.bind(this))
// add
processStash()
return this
}
/**
* Alias for this.line
*
* @returns {Log}
*/
_(...args){
return this.line.apply(this, args)
}
/**
* Alias for this.line
*
* @returns {Log}
*/
log(...args){
this.line.apply(this, args)
return this.out()
}
/**
* info - Alias for this.log in "green"
*
* @returns {Log}
*/
info(...args){
args.push('green')
this.line.apply(this, args)
this.out('info')
return this
}
/**
* ok - Shortcut to indicate sth went alright
*
* @returns {Log}
*/
ok(){
this.time('_').out()
return this
}
/**
* Alias for this.log
*
* @returns {Log}
*/
dir(...arg){
return this.log(...arg)
}
/**
* Alias for this.line in "red"
*
* @returns {Log}
*/
error(...args){
// add red
args.push('red')
// log
if(this.line){
this.line.apply(this, args)
this.out('error')
}
return this
}
/**
* Alias for this.line in "yellow"
*
* @returns {Log}
*/
warn(...args){
// add yellow
args.push('yellow')
// log
this.line.apply(this, args)
this.out('warn')
return this
}
/**
* Output time
*
* Use as:
* .time() - Prints time since box was initialized
* .time('TimerName') (1st call) - starts a timer for tony, outputs 'TimerName: start'
* .time('TimerName', true) (1st call) - same as above, no output
* .time('TimerName') (2nd call) - outputs 'TimerName: Xms'
* .time('TimerName', true) (2nd call) - outputs 'TimerName: Xms - reset', resets the timer
*
* @param {String} [label]
* @param {Boolean} [reset]
* @returns {Log}
*/
time(label, reset){
const now = new Date().getTime()
// initialize timer
if(label && !this.timer[label]){
this.timer[label] = now
// finish quietly
if(reset)
return this._autoOut()
// indicate event
this.line(Log.col(label, 'green')+': start')
return this._autoOut()
}
// calc
let passed = (now - (this.timer[label || '_']))
let lastExec = this.timer._calls[label || '_']
// build line
let line = Log.col(label === '_'?'OK':label || 'Time',passed<=10?'green':(passed<=100?'yellow':'red'))+Log.col(': ', 'grey')
+ Log.col(passed.toFixed(0)+'ms', label === '_' ? 'grey' : 'white')
+ (reset ? Log.col(' - ', 'grey') + Log.col('reset', 'yellow'):'')
// add "+Xms"
if(lastExec){
lastExec = (now - lastExec)
let str = lastExec.toFixed(0)
str = ' '+Log.col(Log.pad('─', (Log.getTerminalWidth()-(this.level+2)-Log.strip(line).length-str.length) - 7), 'grey')
+ ' +'+lastExec.toFixed(0)+'ms'
if(lastExec <= 10)
str = Log.col(str, 'green')
if(lastExec <= 100)
str = Log.col(str, 'yellow')
if(lastExec > 100)
str = Log.col(str, 'red')
line += str
}
// reset timer
if(label && this.timer[label] && reset){
this.timer[label] = now
}
// output time passed
this.line(line)
// save call time
this.timer._calls[label||'_'] = now
if(passed > 10000){
const res = []
const struc = {
year: 31536000,
month: 2592000,
day: 86400,
hour: 3600,
minute: 60,
second: 1
}
let delta = passed / 1000
// calc time
Object.keys(struc).forEach(function(key){
const r = Math.floor(delta / struc[key])
struc[key+'s'] = r
delta -= r * struc[key]
if(r > 0 || res.length > 0)
res.push(Log.plural(r, '%s '+key))
})
this.box(Log.col(res.join(' + '), 'grey')).over()
}
// output?
return this._autoOut()
}
/**
* Alias for this.time
*
* @returns {Log}
*/
timeEnd(...args){
return this.time(...args)
}
/**
* trace - beautified
*
* @param {String} [message]
*/
trace(message){
const obj = {}
Error.captureStackTrace(obj, this)
const lines = []
obj.stack.split("\n").forEach(function(line, indexLine){
// remove surrounding whitespaces
line = line.trim()
const words = []
// 1st line
if(indexLine === 0){
return lines.push(colors.yellow(message||'Trace')+colors.grey(': ')+colors.cyan(line))
}
// skip trace to this place
else if(indexLine === 1){
}
// show rest of stack
else {
// split to words
line.split(' ').forEach(function(word, indexWord){
switch(indexWord){
case 0:
//words.push(colors.grey(word))
break
case 1:
words.push(colors.white(word))
break
case 2:
words.push(colors.grey(word))
break
}
})
lines.push(words.join(' '))
}
})
let box
lines.forEach(function(line, i){
if(i === 0)
return box = this.line(line)
box = box.box(line).over()
}.bind(this))
if(box)
box._autoOut()
return this
}
/**
* Display text inside a box
*
* @param line
* @returns {Log}
*/
title(line){
const args = Array.prototype.slice.call(arguments)
const maxWidth = Log.getTerminalWidth()
// top border
this.line(Log.col(Log.pad('─', maxWidth - this.level - 2)+'┐', this.opt.color, 'dim'), 'pre:')
// build line
this.line.apply(this, args)
// get inserted line
const newLine = this.lines[this.lines.length-1]
// add right border
newLine.line += Log.pad(' ', maxWidth - this.level - Log.strip(newLine.line).length - 3)
+ Log.col('│', this.opt.color, 'dim')
// save to this.lines
this.lines[this.lines.length-1] = newLine
// bottom border
this.line(Log.col((Log.pad('─', maxWidth - this.level - 2)+'┘'), this.opt.color, 'dim'), 'pre:')
// use out?
return this
}
/**
* End the current line and insert an empty line (uses this.out!)
*/
spacer(){
// end line
this.out()
// empty line
this.opt.console.log(Log.col('┘', this.opt.col||'grey'))
this.printedLines = 0
return this
}
/**
* beep sound
*
* @returns {*}
*/
beep(label){
process.stdout.write('\x07')
return this.line(Log.col('BEEP'+(typeof label == 'string'?': '+label:''), 'red'))//.out()
}
/**
* Build output string
*
* @param {Function} callback
* @param {Boolean} [preserveLines=false]
* @returns {string}
*/
_buildString(callback, preserveLines){
const lines = []
const maxWidth = Log.getTerminalWidth()
let body = ''
let allNr = 0
let mapBase = this
// gather lines
const walk = (log, callbackWalk) => {
let boxNr = 0
// iterate lines
async.each(log.lines, function(line, callbackLines){
// sub box
if(this._instanceof(line)){
return line.opt.over ? walk(line, callbackLines) : callbackLines()
}
// format
lines.push({
id: log.id,
level: log.level,
boxNr: boxNr,
allNr: allNr,
prefix: line.prefix,
color: line.color,
colorText: line.colorText,
line: line.line,
log: log
})
// remove printed lines from stack
if(!preserveLines){
// Log.console.log('REMOVE', log.lines)
log.lines = log.lines.filter(function(l){
if(log._instanceof(l)) return l.id !== log.id
return l !== line
})
// this.lines = this.lines.filter(function(l){
// if(this._instanceof(l)) return l.id != log.id
// return l.line == line.line// || l.id == log.id
// }.bind(this))
}
// count
boxNr++
allNr++
// end
callbackLines()
}.bind(this), () => callbackWalk())
}
// prepare
walk(this, () => {
// iterate
async.each(lines, (obj, callbackLine) => {
const i = lines.indexOf(obj)
// count total output
this.printedLines++
// structure
const pre = {
str: '',
plain: ''
}
// shortcuts
obj.levelPrev = lines[i-1] ? lines[i-1].level : null
obj.levelNext = lines[i+1] ? lines[i+1].level : null
obj.hasPrev = lines[i-1] || false
obj.hasNext = lines[i+1] || false
obj.hasBoxPrev = obj.hasPrev && obj.hasPrev.id === obj.id
obj.hasBoxNext = obj.hasNext && obj.hasNext.id === obj.id
// iterate level times (|)
for(let posLeft = 0; posLeft <= obj.level; posLeft++){
let s
// set base obj
mapBase = obj.log.getParent(obj.level-posLeft)
// 1st from right
if(posLeft === obj.level){
if(this.printedLines === 1 && obj.level === 0)
s = '┌'
else if(obj.hasNext && obj.level === 0){
if(Log.strip(obj.line) === 'undefined')
s = '│'
else
s = '├'//┌
}
else if(obj.boxNr === 0){
if(obj.hasBoxNext || obj.levelNext > obj.level)
s = '┬'//┬
else if(obj.hasBoxPrev)
s = '└'//└
else if(obj.level === 0){
if(obj.line.substr(0,2) === ' ')
s = '│'
else
s = '├'
}
else
s = '─'//─
}
else if(obj.hasNext && obj.levelNext >= obj.level && Log.strip(obj.line) === 'undefined')
s = '│'
else if(
obj.hasNext
&& (
obj.hasNext.log.id === obj.log.id
|| (
obj.hasNext.log
&& obj.hasNext.log.parent
&& obj.hasNext.log.parent.id === obj.log.id
)
)
)
s = '├'
else if(['═','╛'].indexOf(obj.prefix.substr(0,1)) > -1)
s = '╘'
else if(obj.level === 0)
s = '├'
else
s = '└'
}
// 2nd from right when first of box
else if(obj.boxNr === 0 && posLeft === obj.level-1){
if(!obj.hasPrev)
s = '┬'//┌├
else if(!obj.hasNext || obj.hasNext && obj.hasNext.log.level < obj.level-1)
s = '┴'