forked from Alhadis/Print
-
Notifications
You must be signed in to change notification settings - Fork 0
/
print.js
725 lines (676 loc) · 17.7 KB
/
print.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
/** @typedef {String|Symbol} Key */
/**
* Generate a human-readable representation of a value.
*
* @param {*} value - Value to inspect
* @param {Key} [key] - The value's corresponding member name
* @param {Object} [opts] - Additional settings for refining output
* @param {Boolean} [opts.all] - Display non-enumerable properties
* @param {Boolean} [opts.followGetters] - Invoke getter functions
* @param {Boolean} [opts.indexes] - Display the indexes of iterable entries
* @param {Number} [opts.maxDepth] - Hide object details after 𝑁 recursions
* @param {Boolean} [opts.noAmp] - Don't identify well-known symbols as `@@…`
* @param {Boolean} [opts.noHex] - Don't format byte-arrays as hexadecimal
* @param {Boolean} [opts.noSource] - Don't display function source code
* @param {Boolean} [opts.proto] - Show `__proto__` properties if possible
* @param {Boolean} [opts.sort] - Sort properties alphabetically
* @param {*} [opts.colours] - Options for printing in color
* @param {String} [opts.indent] - Prefix string to use for indentation. Defaults to '\t'.
* @param {WeakMap} [refs=new WeakMap()] - Tracked object references (internal-use only)
* @param {String} [path=""] - Accessor string used to identify a reference
* @param {Number} [depth=0] - Current recursion level
* @param {Number} [flags=0] - Bitmask of flags used internally
* @return {String}
*/
function print(value, ...args) {
// Resolve arguments
if (args.length === 1 && args[0] && typeof args[0] === "object") {
args.unshift(null);
}
let [key, opts = {}, refs = new WeakMap(), path = "", depth = 0, flags = 0] =
args;
let type = typeof value;
++depth;
let indent = typeof opts.indent === "string" ? opts.indent : "\t";
// Resolve decorator characters
let {
arrowFat = "=>",
arrowThin = "->",
braceLeft = "[",
braceRight = "]",
border = "│",
ellipsis = "…",
quote = '"',
quoteLeft = quote,
quoteRight = quote,
times = "×",
} = opts.chars || {};
// Resolve colour table
let { colours } = opts,
colourMode = 1;
switch (colours) {
case true:
case 256:
colourMode = 2;
// Fall-through
case 8:
colours = {};
break;
default:
colourMode = colours && typeof colours === "object" ? 2 : 0;
}
colours = { __proto__: null, ...colours };
for (const key in colours) {
if (typeof colours[key] === "number") {
colours[key] = "\x1B[38;5;" + colours[key] + "m";
}
}
const {
off = ["", "\x1B[0m", "\x1B[0m"][colourMode],
red = ["", "\x1B[31m", "\x1B[38;5;9m"][colourMode],
grey = ["", "\x1B[37m", "\x1B[38;5;8m"][colourMode],
green = ["", "\x1B[32m", "\x1B[38;5;10m"][colourMode],
darkGreen = ["", green, "\x1B[38;5;22m"][colourMode],
punct = ["", grey, "\x1B[38;5;237m"][colourMode],
keys = ["", "\x1B[39m", "\x1B[39m"][colourMode],
keyEscape = ["", red, "\x1B[38;5;124m"][colourMode],
typeColour = ["", "\x1B[1m", "\x1B[1m"][colourMode],
primitive = ["", "\x1B[35m", "\x1B[35m"][colourMode],
escape = ["", "\x1B[32m", "\x1B[38;5;28m"][colourMode],
date = ["", "\x1B[33m", "\x1B[38;5;130m"][colourMode],
hexBorder = ["", red, "\x1B[38;5;88m"][colourMode],
hexValue = red,
hexOffset = red,
reference = red,
srcBorder = darkGreen,
srcRowNum = green,
srcRowText = darkGreen,
nul = grey,
nulProt = grey,
undef = grey,
noExts = grey,
frozen = noExts,
sealed = noExts,
regex = green,
string = green,
symbol = green,
symbolFade = darkGreen,
braces = punct,
quotes = darkGreen,
empty = grey + "empty " + times + " ",
dot = punct + ".",
} = colours;
braceLeft = braces + braceLeft + off;
braceRight = braces + braceRight + off;
quoteLeft = quotes + quoteLeft + string;
quoteRight = quotes + quoteRight + off;
ellipsis = punct + ellipsis + off;
arrowFat = punct + arrowFat + off + " ";
arrowThin = reference + arrowThin + off + " ";
// Format symbols and property names
function formatKey(input) {
if (typeof input === "symbol") {
// Identify well-known symbols using ECMA-262's @@ notation
if (!opts.noAmp) {
const name = String(input).slice(14, -1);
if (input === Symbol[name]) {
return symbolFade + "@@" + symbol + esc(name, symbol) + off;
}
}
input = esc(input, symbol);
input =
input.startsWith("Symbol(") && input.endsWith(")")
? input.slice(7, -1)
: input;
return `${symbol}Symbol${symbolFade}(${
symbol + input + symbolFade
})${off}`;
}
return keys + esc(input, keys, keyEscape) + off;
}
// Resolve identifiers
key = key != null ? (flags & 1 ? key : formatKey(key)) : "";
path = path ? (key ? path + dot + keys + key : path) : key || "{root}";
key += key ? punct + ":" + off + " " : "";
// Escape control characters in string output
function esc(input, prevColour = off, escColour = escape) {
input = [...String(input)];
let result = "";
const { length } = input;
for (let ord, chr, i = 0; i < length; ++i) {
switch ((chr = input[i])) {
case "\0":
result += escColour + "\\0" + prevColour;
break;
case "\b":
result += escColour + "\\b" + prevColour;
break;
case "\t":
result += escColour + "\\t" + prevColour;
break;
case "\n":
result += escColour + "\\n" + prevColour;
break;
case "\f":
result += escColour + "\\f" + prevColour;
break;
case "\r":
result += escColour + "\\r" + prevColour;
break;
case "\v":
result += escColour + "\\v" + prevColour;
break;
case "\\":
result += escColour + "\\\\" + prevColour;
break;
case "\x07":
result += escColour + "\\a" + prevColour;
break;
case "\x1B":
result += escColour + "\\e" + prevColour;
break;
default:
result +=
(ord = chr.charCodeAt(0)) < 256 && !(96 & ord)
? escColour +
"\\x" +
ord.toString(16).padStart(2, "0").toUpperCase() +
prevColour
: chr;
}
}
return result;
}
// Special primitives that need no introduction
switch (value) {
case true:
case false:
case Infinity:
case -Infinity:
return key + primitive + value + off;
case null:
return key + nul + value + off;
case undefined:
return key + undef + value + off;
}
// Primitive values
switch (type) {
// Handled outside of this switch
case "object":
case "function":
break;
case "bigint":
case "number":
// Identify special numbers and mathematical constants by name
for (const global of [Math, Number]) {
const [name, skip] =
global === Math ? ["Math", flags & 4] : ["Number", flags & 2];
if (skip) {
continue;
}
for (const numKey of Object.getOwnPropertyNames(global)) {
if (numKey !== numKey.toUpperCase()) {
continue;
}
if (type === typeof global[numKey] && value === global[numKey]) {
return key + primitive + name + "." + primitive + numKey + off;
}
}
}
value = Object.is(value, -0) ? "-0" : String(value);
if (type === "bigint" && !value.endsWith("n")) {
value += "n";
}
return key + primitive + value + off;
case "string":
return key + quoteLeft + esc(value, string) + quoteRight;
default:
return key + formatKey(value);
}
// Handle circular references
if (refs.has(value)) {
return key + refs.get(value);
}
refs.set(value, arrowThin + keys + path);
const linesBefore = [];
const linesAfter = [];
const propLines = [];
const tooDeep = depth > opts.maxDepth && isFinite(opts.maxDepth);
const isArrayBuffer =
value instanceof ArrayBuffer ||
(typeof SharedArrayBuffer === "function" &&
value instanceof SharedArrayBuffer);
let isArrayLike = false;
let props = tooDeep ? null : Object.getOwnPropertyNames(value);
try {
isArrayLike = Symbol.iterator in value && Number(value.length) >= 0;
} catch (e) {
// Ignore gripes from `TypedArray.prototype.length`
}
// Handle null-prototypes
type = Object.getPrototypeOf(value);
if (type === null) {
tooDeep || linesBefore.push(nulProt + "Null prototype" + off);
}
// Resolve type annotation
else {
switch (type.constructor) {
case Object:
// Identify argument lists
if (
isArrayLike &&
!value[Symbol.toStringTag] &&
{}.toString.call(value) === "[object Arguments]"
) {
type = "Arguments";
break;
}
// Fall-through
case null:
case undefined:
case Array:
type = "";
break;
default:
type = esc(type.constructor.name);
}
}
if (type === "" && typeof value[Symbol.toStringTag] === "string") {
type = value[Symbol.toStringTag];
}
let typeSuffix = "";
if (!tooDeep) {
if (Object.isFrozen(value)) {
linesBefore.push(frozen + "Frozen" + off);
} else if (Object.isSealed(value)) {
linesBefore.push(sealed + "Sealed" + off);
} else if (!Object.isExtensible(value)) {
linesBefore.push(noExts + "Non-extensible" + off);
}
}
// Dates
if (value instanceof Date) {
const str = Date.prototype.toString.call(value);
linesBefore.push(
date +
(str === "Invalid Date"
? str
: Date.prototype.toISOString.call(value)) +
off
);
}
// Error objects
else if (
typeof value === "object" &&
value != null &&
typeof value.name === "string" &&
typeof value.message === "string" &&
typeof value.constructor === "function" &&
typeof value.constructor.name === "string" &&
value.constructor.name.endsWith("Error")
) {
const stackHeader = `${value.name}: ${value.message}\n`;
let stack = value.stack || "";
if (stack.startsWith(stackHeader)) {
stack = stack.slice(stackHeader.length);
}
linesBefore.push(
stackHeader +
stack
.split("\n")
.map((stackLine) => stackLine.replace(/^\s+/, indent))
.join("\n")
);
}
// Regular expressions
else if (value instanceof RegExp) {
linesBefore.push(regex + RegExp.prototype.toString.call(value) + off);
}
// Something without a single-line representation that's beyond our recursion limit
else if (tooDeep) {
linesBefore.push(ellipsis);
}
// Maps
else if (value instanceof Map) {
let index = 0,
p;
try {
for (let [k, v] of value) {
p = path + braceLeft + keys + index + dot + keys;
k = print(k, null, opts, refs, p + "key" + braceRight, depth);
v = print(v, null, opts, refs, p + "value" + braceRight, depth);
k =
keys +
index +
dot +
keys +
"key " +
(k.startsWith(arrowThin) ? "" : arrowFat) +
k;
v =
keys +
index +
dot +
keys +
"value " +
(v.startsWith(arrowThin) ? "" : arrowFat) +
v;
linesBefore.push(k, v, "");
++index;
}
// Remove trailing blank line
linesBefore.pop();
} catch (e) {
linesBefore.push(print(e, null, opts, refs, path, depth));
}
}
// Sets
else if (value instanceof Set) {
let index = 0;
try {
for (let v of value) {
v = print(
v,
null,
opts,
refs,
path + braceLeft + keys + index + braceRight,
depth
);
linesBefore.push(
index++ + " " + (v.startsWith(arrowThin) ? "" : arrowFat) + v
);
}
} catch (e) {
linesBefore.push(print(e, null, opts, refs, path, depth));
}
}
// Boxed primitives
else if (value instanceof Boolean) {
linesBefore.push(
print(true.valueOf.call(value), null, opts, refs, path, depth)
);
} else if (value instanceof Number) {
linesBefore.push(
print((1).valueOf.call(value), null, opts, refs, path, depth)
);
} else if (value instanceof String) {
linesBefore.push(
print("".valueOf.call(value), null, opts, refs, path, depth)
);
isArrayLike = false;
}
// Something that quacks like an array
else if (isArrayLike || isArrayBuffer) {
const entries = isArrayBuffer ? new Uint8Array(value) : value;
const { length } = entries;
// Filter out indexed properties, provided they're genuine
if (!isArrayBuffer && Array.isArray(props)) {
props = props.filter((x) => +x !== ~~x || +x < 0 || x > length - 1);
}
// Byte-arrays: format entries in hexadecimal, and arrange in od(1)-like columns
if (!opts.noHex && entries instanceof Uint8Array) {
for (let i = 0; i < length; i += 16) {
const offset =
hexBorder +
border +
hexOffset +
"0x" +
i.toString(16).padStart(8, "0").toUpperCase() +
hexBorder +
border +
off;
const row = [...entries.subarray(i, i + 16)]
.map((x) => x.toString(16).padStart(2, "0").toUpperCase())
.join(" ");
linesBefore.push(offset + hexValue + " " + row);
}
}
// Otherwise, list contents vertically
else {
let lastIndex = -1;
[].forEach.call(entries, (x, i) => {
if (lastIndex < i - 1) {
linesBefore.push(empty + `${i - lastIndex - 1}` + off);
}
linesBefore.push(
print(
x,
opts.indexes && !isArrayBuffer ? i : null,
opts,
refs,
path + braceLeft + keys + i + braceRight + off,
depth
)
);
lastIndex = i;
});
if (lastIndex < length - 1) {
linesBefore.push(empty + `${length - lastIndex - 1}`);
}
}
}
// Display function names
if (
typeof value === "function" &&
typeof value.name === "string" &&
value.name != ""
) {
const printedName = print(
value.name,
null,
opts,
refs,
path + dot + keys + "name",
depth
);
typeSuffix += " " + printedName;
}
// Display the source code of function objects
if (typeof value === "function" && !opts.noSource && !tooDeep) {
const source = [...Function.prototype.toString.call(value)];
const lines = [];
const { length } = source;
for (let i = 0, chr, str = ""; i < length; ) {
switch ((chr = source[i])) {
default:
str += chr;
break;
case "\r":
source[i + 1] === "\n" && ++i; // Fall-through
case "\n":
case "\u2028":
case "\u2029":
lines.push(str);
str = "";
}
++i >= length && str && lines.push(str);
}
const pad = lines.length.toString().length;
linesAfter.push(
...lines.map(
(line, index) =>
srcBorder +
border +
srcRowNum +
(index + 1).toString().padStart(pad, " ") +
srcBorder +
border +
srcRowText +
" " +
line +
off
)
);
}
// Property printing
if (!tooDeep) {
// Handle property sorting
props.push(...Object.getOwnPropertySymbols(value));
if (opts.sort) {
props.sort((a, b) =>
String(a).toLowerCase().localeCompare(String(b).toLowerCase())
);
}
// Identify Number/Math globals so we know when not to identify “magic” numbers
flags = ((Math === value) << 2) | ((Number === value) << 1);
// Show the `__proto__` object if possible (and requested)
if (opts.proto) {
let proto;
try {
proto = value.__proto__;
} catch (e) {
proto = e;
opts = { ...opts, proto: false };
}
propLines.push(print(proto, "__proto__", opts, refs, path, depth, flags));
}
// Inspect each property we're interested in displaying
for (let prop of props) {
const desc = Object.getOwnPropertyDescriptor(value, prop);
// Skip non-enumerable properties by default
if (!desc.enumerable && !opts.all) {
continue;
}
// Getter and/or setter
if (desc.get || desc.set) {
if (desc.get && opts.followGetters) {
let result;
try {
result = value[prop];
} catch (e) {
result = e;
}
propLines.push(print(result, prop, opts, refs, path, depth, flags));
} else {
prop = formatKey(prop);
if (desc.get) {
propLines.push(
print(desc.get, `get ${prop}`, opts, refs, path, depth, flags | 1)
);
}
if (desc.set) {
propLines.push(
print(desc.set, `set ${prop}`, opts, refs, path, depth, flags | 1)
);
}
}
} else {
propLines.push(print(desc.value, prop, opts, refs, path, depth, flags));
}
}
}
// If there's nothing of interest in a RegExp or Date object, use a 1-line form
let oneLine =
!propLines.length &&
(type === "RegExp" || type === "Date") &&
linesBefore.length === 1;
// Pick an appropriate pair of brackets
const brackets = isArrayLike ? ["[", "]"] : ["{", "}"];
const inputs = {
key,
type,
brackets,
oneLine,
linesBefore,
linesAfter,
propLines,
get tooDeep() {
return tooDeep;
},
indent,
typeSuffix,
opts,
colours: {
off,
red,
grey,
green,
darkGreen,
punct,
keys,
keyEscape,
typeColour,
primitive,
escape,
date,
hexBorder,
hexValue,
hexOffset,
reference,
srcBorder,
srcRowNum,
srcRowText,
nul,
nulProt,
undef,
noExts,
frozen,
sealed,
regex,
string,
symbol,
symbolFade,
braces,
quotes,
empty,
dot,
},
};
if (typeof value[print.custom] === "function") {
// custom function can mutate inputs object to change output
value[print.custom](inputs);
}
return printFormattedParts(inputs);
}
function printFormattedParts({
key,
type,
oneLine,
linesBefore,
linesAfter,
propLines,
tooDeep,
indent,
typeSuffix,
colours: { punct, off, typeColour },
brackets,
}) {
let valueParts = [punct + brackets[0] + off, "\n", punct + brackets[1] + off];
const numProps = propLines.length;
if (oneLine) {
valueParts = linesBefore;
type = "";
}
// Keep truncated objects on one line
else if (tooDeep) {
valueParts.splice(1, 1, linesBefore[0]);
}
// Otherwise, tally our lists and inject padding where it's needed
else {
if (linesBefore.length) {
numProps && linesBefore.push("");
propLines.unshift(...linesBefore);
}
if (linesAfter.length) {
numProps && linesAfter.unshift("");
propLines.push(...linesAfter);
}
if (propLines.length) {
for (const prop of propLines) {
for (const line of prop.split("\n")) {
valueParts[1] += `${indent}${line}\n`;
}
}
} else {
valueParts[1] = "";
}
}
return (
key +
(type ? typeColour + type + off + typeSuffix + " " : "") +
valueParts.join("")
);
}
print.custom = Symbol("print.custom");
module.exports = print;