-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy path01_console.js
3558 lines (3324 loc) · 103 KB
/
01_console.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
// Copyright 2018-2025 the Deno authors. MIT license.
/// <reference path="../../core/internal.d.ts" />
import { core, internals, primordials } from "ext:core/mod.js";
const {
isAnyArrayBuffer,
isArgumentsObject,
isArrayBuffer,
isAsyncFunction,
isBigIntObject,
isBooleanObject,
isBoxedPrimitive,
isDataView,
isDate,
isGeneratorFunction,
isMap,
isMapIterator,
isModuleNamespaceObject,
isNativeError,
isNumberObject,
isPromise,
isRegExp,
isSet,
isSetIterator,
isStringObject,
isTypedArray,
isWeakMap,
isWeakSet,
} = core;
import {
op_get_constructor_name,
op_get_non_index_property_names,
op_preview_entries,
} from "ext:core/ops";
import * as ops from "ext:core/ops";
const {
Array,
ArrayBufferPrototypeGetByteLength,
ArrayIsArray,
ArrayPrototypeFill,
ArrayPrototypeFilter,
ArrayPrototypeFind,
ArrayPrototypeForEach,
ArrayPrototypeIncludes,
ArrayPrototypeJoin,
ArrayPrototypeMap,
ArrayPrototypePop,
ArrayPrototypePush,
ArrayPrototypePushApply,
ArrayPrototypeReduce,
ArrayPrototypeShift,
ArrayPrototypeSlice,
ArrayPrototypeSort,
ArrayPrototypeSplice,
ArrayPrototypeUnshift,
BigIntPrototypeValueOf,
Boolean,
BooleanPrototypeValueOf,
DateNow,
DatePrototypeGetTime,
DatePrototypeToISOString,
Error,
ErrorCaptureStackTrace,
ErrorPrototype,
ErrorPrototypeToString,
FunctionPrototypeBind,
FunctionPrototypeCall,
FunctionPrototypeToString,
MapPrototypeDelete,
MapPrototypeEntries,
MapPrototypeForEach,
MapPrototypeGet,
MapPrototypeGetSize,
MapPrototypeHas,
MapPrototypeSet,
MathAbs,
MathFloor,
MathMax,
MathMin,
MathRound,
MathSqrt,
Number,
NumberIsInteger,
NumberIsNaN,
NumberParseInt,
NumberParseFloat,
NumberPrototypeToFixed,
NumberPrototypeToString,
NumberPrototypeValueOf,
ObjectAssign,
ObjectCreate,
ObjectDefineProperty,
ObjectFreeze,
ObjectFromEntries,
ObjectGetOwnPropertyDescriptor,
ObjectGetOwnPropertyNames,
ObjectGetOwnPropertySymbols,
ObjectGetPrototypeOf,
ObjectHasOwn,
ObjectIs,
ObjectKeys,
ObjectPrototype,
ObjectPrototypeIsPrototypeOf,
ObjectPrototypePropertyIsEnumerable,
ObjectSetPrototypeOf,
ObjectValues,
Proxy,
ReflectGet,
ReflectGetOwnPropertyDescriptor,
ReflectGetPrototypeOf,
ReflectHas,
ReflectOwnKeys,
RegExpPrototypeExec,
RegExpPrototypeSymbolReplace,
RegExpPrototypeTest,
RegExpPrototypeToString,
SafeArrayIterator,
SafeMap,
SafeMapIterator,
SafeRegExp,
SafeSet,
SafeSetIterator,
SafeStringIterator,
SetPrototypeAdd,
SetPrototypeGetSize,
SetPrototypeHas,
SetPrototypeValues,
String,
StringPrototypeCharCodeAt,
StringPrototypeCodePointAt,
StringPrototypeEndsWith,
StringPrototypeIncludes,
StringPrototypeIndexOf,
StringPrototypeLastIndexOf,
StringPrototypeMatch,
StringPrototypeNormalize,
StringPrototypePadEnd,
StringPrototypePadStart,
StringPrototypeRepeat,
StringPrototypeReplace,
StringPrototypeReplaceAll,
StringPrototypeSlice,
StringPrototypeSplit,
StringPrototypeStartsWith,
StringPrototypeToLowerCase,
StringPrototypeTrim,
StringPrototypeValueOf,
Symbol,
SymbolFor,
SymbolHasInstance,
SymbolIterator,
SymbolPrototypeGetDescription,
SymbolPrototypeToString,
SymbolPrototypeValueOf,
SymbolToStringTag,
TypedArrayPrototypeGetBuffer,
TypedArrayPrototypeGetByteLength,
TypedArrayPrototypeGetLength,
Uint8Array,
Uint32Array,
} = primordials;
let currentTime = DateNow;
if (ops.op_now) {
const hrU8 = new Uint8Array(8);
const hr = new Uint32Array(TypedArrayPrototypeGetBuffer(hrU8));
currentTime = function opNow() {
ops.op_now(hrU8);
return (hr[0] * 1000 + hr[1] / 1e6);
};
}
let noColorStdout = () => false;
let noColorStderr = () => false;
function setNoColorFns(stdoutFn, stderrFn) {
noColorStdout = stdoutFn;
noColorStderr = stderrFn;
}
function getStdoutNoColor() {
return noColorStdout();
}
function getStderrNoColor() {
return noColorStderr();
}
class AssertionError extends Error {
name = "AssertionError";
constructor(message) {
super(message);
}
}
function assert(cond, msg = "Assertion failed") {
if (!cond) {
throw new AssertionError(msg);
}
}
// Don't use 'blue' not visible on cmd.exe
const styles = {
special: "cyan",
number: "yellow",
bigint: "yellow",
boolean: "yellow",
undefined: "grey",
null: "bold",
string: "green",
symbol: "green",
date: "magenta",
// "name": intentionally not styling
// TODO(BridgeAR): Highlight regular expressions properly.
regexp: "red",
module: "underline",
internalError: "red",
temporal: "cyan",
};
const defaultFG = 39;
const defaultBG = 49;
// Set Graphics Rendition https://en.wikipedia.org/wiki/ANSI_escape_code#graphics
// Each color consists of an array with the color code as first entry and the
// reset code as second entry.
const colors = {
reset: [0, 0],
bold: [1, 22],
dim: [2, 22], // Alias: faint
italic: [3, 23],
underline: [4, 24],
blink: [5, 25],
// Swap foreground and background colors
inverse: [7, 27], // Alias: swapcolors, swapColors
hidden: [8, 28], // Alias: conceal
strikethrough: [9, 29], // Alias: strikeThrough, crossedout, crossedOut
doubleunderline: [21, 24], // Alias: doubleUnderline
black: [30, defaultFG],
red: [31, defaultFG],
green: [32, defaultFG],
yellow: [33, defaultFG],
blue: [34, defaultFG],
magenta: [35, defaultFG],
cyan: [36, defaultFG],
white: [37, defaultFG],
bgBlack: [40, defaultBG],
bgRed: [41, defaultBG],
bgGreen: [42, defaultBG],
bgYellow: [43, defaultBG],
bgBlue: [44, defaultBG],
bgMagenta: [45, defaultBG],
bgCyan: [46, defaultBG],
bgWhite: [47, defaultBG],
framed: [51, 54],
overlined: [53, 55],
gray: [90, defaultFG], // Alias: grey, blackBright
redBright: [91, defaultFG],
greenBright: [92, defaultFG],
yellowBright: [93, defaultFG],
blueBright: [94, defaultFG],
magentaBright: [95, defaultFG],
cyanBright: [96, defaultFG],
whiteBright: [97, defaultFG],
bgGray: [100, defaultBG], // Alias: bgGrey, bgBlackBright
bgRedBright: [101, defaultBG],
bgGreenBright: [102, defaultBG],
bgYellowBright: [103, defaultBG],
bgBlueBright: [104, defaultBG],
bgMagentaBright: [105, defaultBG],
bgCyanBright: [106, defaultBG],
bgWhiteBright: [107, defaultBG],
};
function defineColorAlias(target, alias) {
ObjectDefineProperty(colors, alias, {
__proto__: null,
get() {
return this[target];
},
set(value) {
this[target] = value;
},
configurable: true,
enumerable: false,
});
}
defineColorAlias("gray", "grey");
defineColorAlias("gray", "blackBright");
defineColorAlias("bgGray", "bgGrey");
defineColorAlias("bgGray", "bgBlackBright");
defineColorAlias("dim", "faint");
defineColorAlias("strikethrough", "crossedout");
defineColorAlias("strikethrough", "strikeThrough");
defineColorAlias("strikethrough", "crossedOut");
defineColorAlias("hidden", "conceal");
defineColorAlias("inverse", "swapColors");
defineColorAlias("inverse", "swapcolors");
defineColorAlias("doubleunderline", "doubleUnderline");
// https://tc39.es/ecma262/#sec-get-sharedarraybuffer.prototype.bytelength
let _getSharedArrayBufferByteLength;
function getSharedArrayBufferByteLength(value) {
// TODO(kt3k): add SharedArrayBuffer to primordials
_getSharedArrayBufferByteLength ??= ObjectGetOwnPropertyDescriptor(
// deno-lint-ignore prefer-primordials
SharedArrayBuffer.prototype,
"byteLength",
).get;
return FunctionPrototypeCall(_getSharedArrayBufferByteLength, value);
}
// The name property is used to allow cross realms to make a determination
// This is the same as WHATWG's structuredClone algorithm
// https://github.com/whatwg/html/pull/5150
function isAggregateError(value) {
return (
isNativeError(value) &&
value.name === "AggregateError" &&
ArrayIsArray(value.errors)
);
}
const kObjectType = 0;
const kArrayType = 1;
const kArrayExtrasType = 2;
const kMinLineLength = 16;
// Constants to map the iterator state.
const kWeak = 0;
const kIterator = 1;
const kMapEntries = 2;
// Escaped control characters (plus the single quote and the backslash). Use
// empty strings to fill up unused entries.
// deno-fmt-ignore
const meta = [
'\\x00', '\\x01', '\\x02', '\\x03', '\\x04', '\\x05', '\\x06', '\\x07', // x07
'\\b', '\\t', '\\n', '\\x0B', '\\f', '\\r', '\\x0E', '\\x0F', // x0F
'\\x10', '\\x11', '\\x12', '\\x13', '\\x14', '\\x15', '\\x16', '\\x17', // x17
'\\x18', '\\x19', '\\x1A', '\\x1B', '\\x1C', '\\x1D', '\\x1E', '\\x1F', // x1F
'', '', '', '', '', '', '', "\\'", '', '', '', '', '', '', '', '', // x2F
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', // x3F
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', // x4F
'', '', '', '', '', '', '', '', '', '', '', '', '\\\\', '', '', '', // x5F
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', // x6F
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\\x7F', // x7F
'\\x80', '\\x81', '\\x82', '\\x83', '\\x84', '\\x85', '\\x86', '\\x87', // x87
'\\x88', '\\x89', '\\x8A', '\\x8B', '\\x8C', '\\x8D', '\\x8E', '\\x8F', // x8F
'\\x90', '\\x91', '\\x92', '\\x93', '\\x94', '\\x95', '\\x96', '\\x97', // x97
'\\x98', '\\x99', '\\x9A', '\\x9B', '\\x9C', '\\x9D', '\\x9E', '\\x9F', // x9F
];
// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
const isUndetectableObject = (v) => typeof v === "undefined" && v !== undefined;
const strEscapeSequencesReplacer = new SafeRegExp(
"[\x00-\x1f\x27\x5c\x7f-\x9f]",
"g",
);
const keyStrRegExp = new SafeRegExp("^[a-zA-Z_][a-zA-Z_0-9]*$");
const numberRegExp = new SafeRegExp("^(0|[1-9][0-9]*)$");
// TODO(wafuwafu13): Figure out
const escapeFn = (str) => meta[StringPrototypeCharCodeAt(str, 0)];
function stylizeNoColor(str) {
return str;
}
// node custom inspect symbol
const nodeCustomInspectSymbol = SymbolFor("nodejs.util.inspect.custom");
// This non-unique symbol is used to support op_crates, ie.
// in extensions/web we don't want to depend on public
// Symbol.for("Deno.customInspect") symbol defined in the public API.
// Internal only, shouldn't be used by users.
const privateCustomInspect = SymbolFor("Deno.privateCustomInspect");
function getUserOptions(ctx, isCrossContext) {
const ret = {
stylize: ctx.stylize,
showHidden: ctx.showHidden,
depth: ctx.depth,
colors: ctx.colors,
customInspect: ctx.customInspect,
showProxy: ctx.showProxy,
maxArrayLength: ctx.maxArrayLength,
maxStringLength: ctx.maxStringLength,
breakLength: ctx.breakLength,
compact: ctx.compact,
sorted: ctx.sorted,
getters: ctx.getters,
numericSeparator: ctx.numericSeparator,
...ctx.userOptions,
};
// Typically, the target value will be an instance of `Object`. If that is
// *not* the case, the object may come from another vm.Context, and we want
// to avoid passing it objects from this Context in that case, so we remove
// the prototype from the returned object itself + the `stylize()` function,
// and remove all other non-primitives, including non-primitive user options.
if (isCrossContext) {
ObjectSetPrototypeOf(ret, null);
for (const key of new SafeArrayIterator(ObjectKeys(ret))) {
if (
(typeof ret[key] === "object" || typeof ret[key] === "function") &&
ret[key] !== null
) {
delete ret[key];
}
}
ret.stylize = ObjectSetPrototypeOf((value, flavour) => {
let stylized;
try {
stylized = `${ctx.stylize(value, flavour)}`;
} catch {
// Continue regardless of error.
}
if (typeof stylized !== "string") return value;
// `stylized` is a string as it should be, which is safe to pass along.
return stylized;
}, null);
}
return ret;
}
// Note: using `formatValue` directly requires the indentation level to be
// corrected by setting `ctx.indentationLvL += diff` and then to decrease the
// value afterwards again.
function formatValue(
ctx,
value,
recurseTimes,
typedArray,
) {
// Primitive types cannot have properties.
if (
typeof value !== "object" &&
typeof value !== "function" &&
!isUndetectableObject(value)
) {
return formatPrimitive(ctx.stylize, value, ctx);
}
if (value === null) {
return ctx.stylize("null", "null");
}
// Memorize the context for custom inspection on proxies.
const context = value;
// Always check for proxies to prevent side effects and to prevent triggering
// any proxy handlers.
// TODO(wafuwafu13): Set Proxy
const proxyDetails = core.getProxyDetails(value);
// const proxy = getProxyDetails(value, !!ctx.showProxy);
// if (proxy !== undefined) {
// if (ctx.showProxy) {
// return formatProxy(ctx, proxy, recurseTimes);
// }
// value = proxy;
// }
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it.
if (ctx.customInspect) {
if (
ReflectHas(value, customInspect) &&
typeof value[customInspect] === "function"
) {
return String(value[customInspect](inspect, ctx));
} else if (
ReflectHas(value, privateCustomInspect) &&
typeof value[privateCustomInspect] === "function"
) {
// TODO(nayeemrmn): `inspect` is passed as an argument because custom
// inspect implementations in `extensions` need it, but may not have access
// to the `Deno` namespace in web workers. Remove when the `Deno`
// namespace is always enabled.
return String(value[privateCustomInspect](inspect, ctx));
} else if (ReflectHas(value, nodeCustomInspectSymbol)) {
const maybeCustom = value[nodeCustomInspectSymbol];
if (
typeof maybeCustom === "function" &&
// Filter out the util module, its inspect function is special.
maybeCustom !== ctx.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)
) {
// This makes sure the recurseTimes are reported as before while using
// a counter internally.
const depth = ctx.depth === null ? null : ctx.depth - recurseTimes;
// TODO(@crowlKats): proxy handling
const isCrossContext = !ObjectPrototypeIsPrototypeOf(
ObjectPrototype,
context,
);
const ret = FunctionPrototypeCall(
maybeCustom,
context,
depth,
getUserOptions(ctx, isCrossContext),
ctx.inspect,
);
// If the custom inspection method returned `this`, don't go into
// infinite recursion.
if (ret !== context) {
if (typeof ret !== "string") {
return formatValue(ctx, ret, recurseTimes);
}
return StringPrototypeReplaceAll(
ret,
"\n",
`\n${StringPrototypeRepeat(" ", ctx.indentationLvl)}`,
);
}
}
}
}
// Using an array here is actually better for the average case than using
// a Set. `seen` will only check for the depth and will never grow too large.
if (ArrayPrototypeIncludes(ctx.seen, value)) {
let index = 1;
if (ctx.circular === undefined) {
ctx.circular = new SafeMap();
MapPrototypeSet(ctx.circular, value, index);
} else {
index = ctx.circular.get(value);
if (index === undefined) {
index = ctx.circular.size + 1;
MapPrototypeSet(ctx.circular, value, index);
}
}
return ctx.stylize(`[Circular *${index}]`, "special");
}
return formatRaw(ctx, value, recurseTimes, typedArray, proxyDetails);
}
function getClassBase(value, constructor, tag) {
const hasName = ObjectHasOwn(value, "name");
const name = (hasName && value.name) || "(anonymous)";
let base = `class ${name}`;
if (constructor !== "Function" && constructor !== null) {
base += ` [${constructor}]`;
}
if (tag !== "" && constructor !== tag) {
base += ` [${tag}]`;
}
if (constructor !== null) {
const superName = ObjectGetPrototypeOf(value).name;
if (superName) {
base += ` extends ${superName}`;
}
} else {
base += " extends [null prototype]";
}
return `[${base}]`;
}
const stripCommentsRegExp = new SafeRegExp(
"(\\/\\/.*?\\n)|(\\/\\*(.|\\n)*?\\*\\/)",
"g",
);
const classRegExp = new SafeRegExp("^(\\s+[^(]*?)\\s*{");
function getFunctionBase(value, constructor, tag) {
const stringified = FunctionPrototypeToString(value);
if (
StringPrototypeStartsWith(stringified, "class") &&
StringPrototypeEndsWith(stringified, "}")
) {
const slice = StringPrototypeSlice(stringified, 5, -1);
const bracketIndex = StringPrototypeIndexOf(slice, "{");
if (
bracketIndex !== -1 &&
(!StringPrototypeIncludes(
StringPrototypeSlice(slice, 0, bracketIndex),
"(",
) ||
// Slow path to guarantee that it's indeed a class.
RegExpPrototypeExec(
classRegExp,
RegExpPrototypeSymbolReplace(stripCommentsRegExp, slice),
) !== null)
) {
return getClassBase(value, constructor, tag);
}
}
let type = "Function";
if (isGeneratorFunction(value)) {
type = `Generator${type}`;
}
if (isAsyncFunction(value)) {
type = `Async${type}`;
}
let base = `[${type}`;
if (constructor === null) {
base += " (null prototype)";
}
if (value.name === "") {
base += " (anonymous)";
} else {
base += `: ${value.name}`;
}
base += "]";
if (constructor !== type && constructor !== null) {
base += ` ${constructor}`;
}
if (tag !== "" && constructor !== tag) {
base += ` [${tag}]`;
}
return base;
}
function formatRaw(ctx, value, recurseTimes, typedArray, proxyDetails) {
let keys;
let protoProps;
if (ctx.showHidden && (recurseTimes <= ctx.depth || ctx.depth === null)) {
protoProps = [];
}
const constructor = getConstructorName(value, ctx, recurseTimes, protoProps);
// Reset the variable to check for this later on.
if (protoProps !== undefined && protoProps.length === 0) {
protoProps = undefined;
}
let tag = value[SymbolToStringTag];
// Only list the tag in case it's non-enumerable / not an own property.
// Otherwise we'd print this twice.
if (
typeof tag !== "string"
// TODO(wafuwafu13): Implement
// (tag !== "" &&
// (ctx.showHidden
// ? Object.prototype.hasOwnProperty
// : Object.prototype.propertyIsEnumerable)(
// value,
// Symbol.toStringTag,
// ))
) {
tag = "";
}
let base = "";
let formatter = () => [];
let braces;
let noIterator = true;
let i = 0;
const filter = ctx.showHidden ? 0 : 2;
let extrasType = kObjectType;
if (proxyDetails !== null && ctx.showProxy) {
return `Proxy ` + formatValue(ctx, proxyDetails, recurseTimes);
} else {
// Iterators and the rest are split to reduce checks.
// We have to check all values in case the constructor is set to null.
// Otherwise it would not possible to identify all types properly.
if (ReflectHas(value, SymbolIterator) || constructor === null) {
noIterator = false;
if (ArrayIsArray(value)) {
// Only set the constructor for non ordinary ("Array [...]") arrays.
const prefix = (constructor !== "Array" || tag !== "")
? getPrefix(constructor, tag, "Array", `(${value.length})`)
: "";
keys = op_get_non_index_property_names(value, filter);
braces = [`${prefix}[`, "]"];
if (
value.length === 0 && keys.length === 0 && protoProps === undefined
) {
return `${braces[0]}]`;
}
extrasType = kArrayExtrasType;
formatter = formatArray;
} else if (
(proxyDetails === null && isSet(value)) ||
(proxyDetails !== null && isSet(proxyDetails[0]))
) {
const set = proxyDetails?.[0] ?? value;
const size = SetPrototypeGetSize(set);
const prefix = getPrefix(constructor, tag, "Set", `(${size})`);
keys = getKeys(set, ctx.showHidden);
formatter = constructor !== null
? FunctionPrototypeBind(formatSet, null, set)
: FunctionPrototypeBind(formatSet, null, SetPrototypeValues(set));
if (size === 0 && keys.length === 0 && protoProps === undefined) {
return `${prefix}{}`;
}
braces = [`${prefix}{`, "}"];
} else if (
(proxyDetails === null && isMap(value)) ||
(proxyDetails !== null && isMap(proxyDetails[0]))
) {
const map = proxyDetails?.[0] ?? value;
const size = MapPrototypeGetSize(map);
const prefix = getPrefix(constructor, tag, "Map", `(${size})`);
keys = getKeys(map, ctx.showHidden);
formatter = constructor !== null
? FunctionPrototypeBind(formatMap, null, map)
: FunctionPrototypeBind(formatMap, null, MapPrototypeEntries(map));
if (size === 0 && keys.length === 0 && protoProps === undefined) {
return `${prefix}{}`;
}
braces = [`${prefix}{`, "}"];
} else if (
(proxyDetails === null && isTypedArray(value)) ||
(proxyDetails !== null && isTypedArray(proxyDetails[0]))
) {
const typedArray = proxyDetails?.[0] ?? value;
keys = op_get_non_index_property_names(typedArray, filter);
const bound = typedArray;
const fallback = "";
if (constructor === null) {
// TODO(wafuwafu13): Implement
// fallback = TypedArrayPrototypeGetSymbolToStringTag(value);
// // Reconstruct the array information.
// bound = new primordials[fallback](value);
}
const size = TypedArrayPrototypeGetLength(typedArray);
const prefix = getPrefix(constructor, tag, fallback, `(${size})`);
braces = [`${prefix}[`, "]"];
if (typedArray.length === 0 && keys.length === 0 && !ctx.showHidden) {
return `${braces[0]}]`;
}
// Special handle the value. The original value is required below. The
// bound function is required to reconstruct missing information.
formatter = FunctionPrototypeBind(formatTypedArray, null, bound, size);
extrasType = kArrayExtrasType;
} else if (
(proxyDetails === null && isMapIterator(value)) ||
(proxyDetails !== null && isMapIterator(proxyDetails[0]))
) {
const mapIterator = proxyDetails?.[0] ?? value;
keys = getKeys(mapIterator, ctx.showHidden);
braces = getIteratorBraces("Map", tag);
// Add braces to the formatter parameters.
formatter = FunctionPrototypeBind(formatIterator, null, braces);
} else if (
(proxyDetails === null && isSetIterator(value)) ||
(proxyDetails !== null && isSetIterator(proxyDetails[0]))
) {
const setIterator = proxyDetails?.[0] ?? value;
keys = getKeys(setIterator, ctx.showHidden);
braces = getIteratorBraces("Set", tag);
// Add braces to the formatter parameters.
formatter = FunctionPrototypeBind(formatIterator, null, braces);
} else {
noIterator = true;
}
}
if (noIterator) {
keys = getKeys(value, ctx.showHidden);
braces = ["{", "}"];
if (constructor === "Object") {
if (isArgumentsObject(value)) {
braces[0] = "[Arguments] {";
} else if (tag !== "") {
braces[0] = `${getPrefix(constructor, tag, "Object")}{`;
}
if (keys.length === 0 && protoProps === undefined) {
return `${braces[0]}}`;
}
} else if (typeof value === "function") {
base = getFunctionBase(value, constructor, tag);
if (keys.length === 0 && protoProps === undefined) {
return ctx.stylize(base, "special");
}
} else if (
(proxyDetails === null && isRegExp(value)) ||
(proxyDetails !== null && isRegExp(proxyDetails[0]))
) {
const regExp = proxyDetails?.[0] ?? value;
// Make RegExps say that they are RegExps
base = RegExpPrototypeToString(
constructor !== null ? regExp : new SafeRegExp(regExp),
);
const prefix = getPrefix(constructor, tag, "RegExp");
if (prefix !== "RegExp ") {
base = `${prefix}${base}`;
}
if (
(keys.length === 0 && protoProps === undefined) ||
(recurseTimes > ctx.depth && ctx.depth !== null)
) {
return ctx.stylize(base, "regexp");
}
} else if (
(proxyDetails === null && isDate(value)) ||
(proxyDetails !== null && isDate(proxyDetails[0]))
) {
const date = proxyDetails?.[0] ?? value;
if (NumberIsNaN(DatePrototypeGetTime(date))) {
return ctx.stylize("Invalid Date", "date");
} else {
base = DatePrototypeToISOString(date);
if (keys.length === 0 && protoProps === undefined) {
return ctx.stylize(base, "date");
}
}
} else if (
proxyDetails === null &&
ObjectPrototypeIsPrototypeOf(globalThis.Intl.Locale.prototype, value)
) {
braces[0] = `${getPrefix(constructor, tag, "Intl.Locale")}{`;
ArrayPrototypeUnshift(
keys,
"baseName",
"calendar",
"caseFirst",
"collation",
"hourCycle",
"language",
"numberingSystem",
"numeric",
"region",
"script",
);
} else if (
proxyDetails === null &&
typeof globalThis.Temporal !== "undefined" &&
(
ObjectPrototypeIsPrototypeOf(
globalThis.Temporal.Instant.prototype,
value,
) ||
ObjectPrototypeIsPrototypeOf(
globalThis.Temporal.ZonedDateTime.prototype,
value,
) ||
ObjectPrototypeIsPrototypeOf(
globalThis.Temporal.PlainDate.prototype,
value,
) ||
ObjectPrototypeIsPrototypeOf(
globalThis.Temporal.PlainTime.prototype,
value,
) ||
ObjectPrototypeIsPrototypeOf(
globalThis.Temporal.PlainDateTime.prototype,
value,
) ||
ObjectPrototypeIsPrototypeOf(
globalThis.Temporal.PlainYearMonth.prototype,
value,
) ||
ObjectPrototypeIsPrototypeOf(
globalThis.Temporal.PlainMonthDay.prototype,
value,
) ||
ObjectPrototypeIsPrototypeOf(
globalThis.Temporal.Duration.prototype,
value,
)
)
) {
// Temporal is not available in primordials yet
// deno-lint-ignore prefer-primordials
return ctx.stylize(value.toString(), "temporal");
} else if (
(proxyDetails === null &&
(isNativeError(value) ||
ObjectPrototypeIsPrototypeOf(ErrorPrototype, value))) ||
(proxyDetails !== null &&
(isNativeError(proxyDetails[0]) ||
ObjectPrototypeIsPrototypeOf(ErrorPrototype, proxyDetails[0])))
) {
const error = proxyDetails?.[0] ?? value;
base = inspectError(error, ctx);
if (keys.length === 0 && protoProps === undefined) {
return base;
}
} else if (isAnyArrayBuffer(value)) {
// Fast path for ArrayBuffer and SharedArrayBuffer.
// Can't do the same for DataView because it has a non-primitive
// .buffer property that we need to recurse for.
const arrayType = isArrayBuffer(value)
? "ArrayBuffer"
: "SharedArrayBuffer";
const prefix = getPrefix(constructor, tag, arrayType);
if (typedArray === undefined) {
formatter = formatArrayBuffer;
} else if (keys.length === 0 && protoProps === undefined) {
return prefix +
`{ byteLength: ${
formatNumber(ctx.stylize, TypedArrayPrototypeGetByteLength(value))
} }`;
}
braces[0] = `${prefix}{`;
ArrayPrototypeUnshift(keys, "byteLength");
} else if (isDataView(value)) {
braces[0] = `${getPrefix(constructor, tag, "DataView")}{`;
// .buffer goes last, it's not a primitive like the others.
ArrayPrototypeUnshift(keys, "byteLength", "byteOffset", "buffer");
} else if (isPromise(value)) {
braces[0] = `${getPrefix(constructor, tag, "Promise")}{`;
formatter = formatPromise;
} else if (isWeakSet(value)) {
braces[0] = `${getPrefix(constructor, tag, "WeakSet")}{`;
formatter = ctx.showHidden ? formatWeakSet : formatWeakCollection;
} else if (isWeakMap(value)) {
braces[0] = `${getPrefix(constructor, tag, "WeakMap")}{`;
formatter = ctx.showHidden ? formatWeakMap : formatWeakCollection;
} else if (isModuleNamespaceObject(value)) {
braces[0] = `${getPrefix(constructor, tag, "Module")}{`;
// Special handle keys for namespace objects.
formatter = FunctionPrototypeBind(formatNamespaceObject, null, keys);
} else if (isBoxedPrimitive(value)) {
base = getBoxedBase(value, ctx, keys, constructor, tag);
if (keys.length === 0 && protoProps === undefined) {
return base;
}
} else {
if (keys.length === 0 && protoProps === undefined) {
// TODO(wafuwafu13): Implement
// if (isExternal(value)) {
// const address = getExternalValue(value).toString(16);
// return ctx.stylize(`[External: ${address}]`, 'special');
// }
return `${getCtxStyle(value, constructor, tag)}{}`;
}
braces[0] = `${getCtxStyle(value, constructor, tag)}{`;
}
}
}
if (recurseTimes > ctx.depth && ctx.depth !== null) {
let constructorName = StringPrototypeSlice(
getCtxStyle(value, constructor, tag),
0,
-1,
);
if (constructor !== null) {
constructorName = `[${constructorName}]`;
}
return ctx.stylize(constructorName, "special");
}
recurseTimes += 1;
ArrayPrototypePush(ctx.seen, value);
ctx.currentDepth = recurseTimes;
let output;
try {
output = formatter(ctx, value, recurseTimes);
for (i = 0; i < keys.length; i++) {
ArrayPrototypePush(
output,
formatProperty(ctx, value, recurseTimes, keys[i], extrasType),
);
}
if (protoProps !== undefined) {
ArrayPrototypePushApply(output, protoProps);
}
} catch (error) {
// TODO(wafuwafu13): Implement stack overflow check
return ctx.stylize(
`[Internal Formatting Error] ${error.stack}`,
"internalError",
);
}
if (ctx.circular !== undefined) {
const index = ctx.circular.get(value);
if (index !== undefined) {
const reference = ctx.stylize(`<ref *${index}>`, "special");
// Add reference always to the very beginning of the output.
if (ctx.compact !== true) {
base = base === "" ? reference : `${reference} ${base}`;
} else {
braces[0] = `${reference} ${braces[0]}`;
}
}
}
ArrayPrototypePop(ctx.seen);
if (ctx.sorted) {
const comparator = ctx.sorted === true ? undefined : ctx.sorted;
if (extrasType === kObjectType) {
output = ArrayPrototypeSort(output, comparator);
} else if (keys.length > 1) {
const sorted = ArrayPrototypeSort(
ArrayPrototypeSlice(output, output.length - keys.length),
comparator,
);
ArrayPrototypeSplice(
output,
output.length - keys.length,
keys.length,
...new SafeArrayIterator(sorted),
);
}