-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
ConsoleObject.zig
3397 lines (3042 loc) · 136 KB
/
ConsoleObject.zig
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
const std = @import("std");
const bun = @import("root").bun;
const JSC = bun.JSC;
const Output = bun.Output;
const ConsoleObject = @This();
const Shimmer = @import("./bindings/shimmer.zig").Shimmer;
const String = bun.String;
const JSGlobalObject = JSC.JSGlobalObject;
const JSValue = JSC.JSValue;
const strings = bun.strings;
const is_bindgen = JSC.is_bindgen;
const ZigException = JSC.ZigException;
const ZigString = JSC.ZigString;
const VirtualMachine = JSC.VirtualMachine;
const string = bun.string;
const JSLexer = bun.js_lexer;
const ScriptArguments = opaque {};
const JSPrinter = bun.js_printer;
const Environment = bun.Environment;
const default_allocator = bun.default_allocator;
const JestPrettyFormat = @import("./test/pretty_format.zig").JestPrettyFormat;
const JSPromise = JSC.JSPromise;
const EventType = JSC.EventType;
pub const shim = Shimmer("Bun", "ConsoleObject", @This());
pub const Type = *anyopaque;
pub const name = "Bun::ConsoleObject";
pub const include = "\"ConsoleObject.h\"";
pub const namespace = shim.namespace;
const Counter = std.AutoHashMapUnmanaged(u64, u32);
const BufferedWriter = std.io.BufferedWriter(4096, Output.WriterType);
error_writer: BufferedWriter,
writer: BufferedWriter,
counts: Counter = .{},
pub fn format(_: @This(), comptime _: []const u8, _: anytype, _: anytype) !void {}
pub fn init(error_writer: Output.WriterType, writer: Output.WriterType) ConsoleObject {
return ConsoleObject{
.error_writer = BufferedWriter{ .unbuffered_writer = error_writer },
.writer = BufferedWriter{ .unbuffered_writer = writer },
};
}
pub const MessageLevel = enum(u32) {
Log = 0,
Warning = 1,
Error = 2,
Debug = 3,
Info = 4,
_,
};
pub const MessageType = enum(u32) {
Log = 0,
Dir = 1,
DirXML = 2,
Table = 3,
Trace = 4,
StartGroup = 5,
StartGroupCollapsed = 6,
EndGroup = 7,
Clear = 8,
Assert = 9,
Timing = 10,
Profile = 11,
ProfileEnd = 12,
Image = 13,
_,
};
var stderr_mutex: bun.Lock = bun.Lock.init();
var stdout_mutex: bun.Lock = bun.Lock.init();
threadlocal var stderr_lock_count: u16 = 0;
threadlocal var stdout_lock_count: u16 = 0;
/// https://console.spec.whatwg.org/#formatter
pub fn messageWithTypeAndLevel(
//console_: ConsoleObject.Type,
_: ConsoleObject.Type,
message_type: MessageType,
//message_level: u32,
level: MessageLevel,
global: *JSGlobalObject,
vals: [*]const JSValue,
len: usize,
) callconv(.C) void {
if (comptime is_bindgen) {
return;
}
var console = global.bunVM().console;
// Lock/unlock a mutex incase two JS threads are console.log'ing at the same time
// We do this the slightly annoying way to avoid assigning a pointer
if (level == .Warning or level == .Error or message_type == .Assert) {
if (stderr_lock_count == 0) {
stderr_mutex.lock();
}
stderr_lock_count += 1;
} else {
if (stdout_lock_count == 0) {
stdout_mutex.lock();
}
stdout_lock_count += 1;
}
defer {
if (level == .Warning or level == .Error or message_type == .Assert) {
stderr_lock_count -= 1;
if (stderr_lock_count == 0) {
stderr_mutex.unlock();
}
} else {
stdout_lock_count -= 1;
if (stdout_lock_count == 0) {
stdout_mutex.unlock();
}
}
}
if (message_type == .Clear) {
Output.resetTerminal();
return;
}
if (message_type == .Assert and len == 0) {
const text = if (Output.enable_ansi_colors_stderr)
Output.prettyFmt("<r><red>Assertion failed<r>\n", true)
else
"Assertion failed\n";
console.error_writer.unbuffered_writer.writeAll(text) catch {};
return;
}
const enable_colors = if (level == .Warning or level == .Error)
Output.enable_ansi_colors_stderr
else
Output.enable_ansi_colors_stdout;
var buffered_writer = if (level == .Warning or level == .Error)
&console.error_writer
else
&console.writer;
var writer = buffered_writer.writer();
const Writer = @TypeOf(writer);
var print_length = len;
var print_options: FormatOptions = .{
.enable_colors = enable_colors,
.add_newline = true,
.flush = true,
};
if (message_type == .Table and len >= 1) {
// if value is not an object/array/iterable, don't print a table and just print it
var tabular_data = vals[0];
if (tabular_data.isObject()) {
const properties = if (len >= 2 and vals[1].jsType().isArray()) vals[1] else JSValue.undefined;
var table_printer = TablePrinter.init(
global,
level,
tabular_data,
properties,
);
switch (enable_colors) {
inline else => |colors| table_printer.printTable(Writer, writer, colors) catch return,
}
buffered_writer.flush() catch {};
return;
}
}
if (message_type == .Dir and len >= 2) {
print_length = 1;
var opts = vals[1];
if (opts.isObject()) {
if (opts.get(global, "depth")) |depth_prop| {
if (depth_prop.isInt32() or depth_prop.isNumber() or depth_prop.isBigInt())
print_options.max_depth = depth_prop.toU16()
else if (depth_prop.isNull())
print_options.max_depth = std.math.maxInt(u16);
}
if (opts.get(global, "colors")) |colors_prop| {
if (colors_prop.isBoolean())
print_options.enable_colors = colors_prop.toBoolean();
}
}
}
if (print_length > 0)
format2(
level,
global,
vals,
print_length,
@TypeOf(buffered_writer.unbuffered_writer.context),
Writer,
writer,
print_options,
)
else if (message_type == .Log) {
_ = console.writer.write("\n") catch 0;
console.writer.flush() catch {};
} else if (message_type != .Trace)
writer.writeAll("undefined\n") catch {};
if (message_type == .Trace) {
writeTrace(Writer, writer, global);
buffered_writer.flush() catch {};
}
}
const TablePrinter = struct {
const Column = struct {
name: String,
width: u32 = 1,
};
const RowKey = union(@This().Type) {
str: String,
num: u32,
const Type = enum { str, num };
};
const PADDING = 1;
globalObject: *JSGlobalObject,
level: MessageLevel,
value_formatter: ConsoleObject.Formatter,
tabular_data: JSValue,
properties: JSValue,
is_iterable: bool,
jstype: JSValue.JSType,
/// width of the "Values" column.
/// This column is not appended to "columns" from the start, because it needs to be the last column.
values_col_width: ?u32 = null,
values_col_idx: usize = std.math.maxInt(usize),
pub fn init(
globalObject: *JSGlobalObject,
level: MessageLevel,
tabular_data: JSValue,
properties: JSValue,
) TablePrinter {
return TablePrinter{
.level = level,
.globalObject = globalObject,
.tabular_data = tabular_data,
.properties = properties,
.is_iterable = tabular_data.isIterable(globalObject),
.jstype = tabular_data.jsType(),
.value_formatter = ConsoleObject.Formatter{
.remaining_values = &[_]JSValue{},
.globalThis = globalObject,
.ordered_properties = false,
.quote_strings = false,
.single_line = true,
.max_depth = 5,
},
};
}
const VisibleCharacterCounter = struct {
width: *usize = undefined,
pub const WriteError = error{};
pub const Writer = std.io.Writer(
VisibleCharacterCounter,
VisibleCharacterCounter.WriteError,
VisibleCharacterCounter.write,
);
pub fn write(this: VisibleCharacterCounter, bytes: []const u8) WriteError!usize {
this.width.* += strings.visible.width.exclude_ansi_colors.utf8(bytes);
return bytes.len;
}
pub fn writeAll(this: VisibleCharacterCounter, bytes: []const u8) WriteError!void {
this.width.* += strings.width.exclude_ansi_colors.utf8(bytes);
}
};
/// Compute how much horizontal space will take a JSValue when printed
fn getWidthForValue(this: *TablePrinter, value: JSValue) u32 {
var width: usize = 0;
var value_formatter = this.value_formatter;
const tag = ConsoleObject.Formatter.Tag.get(value, this.globalObject);
value_formatter.quote_strings = !(tag.tag == .String or tag.tag == .StringPossiblyFormatted);
value_formatter.format(
tag,
VisibleCharacterCounter.Writer,
VisibleCharacterCounter.Writer{
.context = .{
.width = &width,
},
},
value,
this.globalObject,
false,
);
return @truncate(width);
}
/// Update the sizes of the columns for the values of a given row, and create any additional columns as needed
fn updateColumnsForRow(this: *TablePrinter, columns: *std.ArrayList(Column), row_key: RowKey, row_value: JSValue) !void {
// update size of "(index)" column
const row_key_len: u32 = switch (row_key) {
.str => |value| @intCast(value.visibleWidthExcludeANSIColors(false)),
.num => |value| @truncate(bun.fmt.fastDigitCount(value)),
};
columns.items[0].width = @max(columns.items[0].width, row_key_len);
// special handling for Map: column with idx=1 is "Keys"
if (this.jstype.isMap()) {
const entry_key = row_value.getIndex(this.globalObject, 0);
const entry_value = row_value.getIndex(this.globalObject, 1);
columns.items[1].width = @max(columns.items[1].width, this.getWidthForValue(entry_key));
this.values_col_width = @max(this.values_col_width orelse 0, this.getWidthForValue(entry_value));
return;
}
if (row_value.isObject()) {
// object ->
// - if "properties" arg was provided: iterate the already-created columns (except for the 0-th which is the index)
// - otherwise: iterate the object properties, and create the columns on-demand
if (!this.properties.isUndefined()) {
for (columns.items[1..]) |*column| {
if (row_value.getWithString(this.globalObject, column.name)) |value| {
column.width = @max(column.width, this.getWidthForValue(value));
}
}
} else {
var cols_iter = JSC.JSPropertyIterator(.{
.skip_empty_name = false,
.include_value = true,
}).init(this.globalObject, row_value);
defer cols_iter.deinit();
while (cols_iter.next()) |col_key| {
const value = cols_iter.value;
// find or create the column for the property
const column: *Column = brk: {
const col_str = String.init(col_key);
for (columns.items[1..]) |*col| {
if (col.name.eql(col_str)) {
break :brk col;
}
}
// Need to ref this string because JSPropertyIterator
// uses `toString` instead of `toStringRef` for property names
col_str.ref();
try columns.append(.{ .name = col_str });
break :brk &columns.items[columns.items.len - 1];
};
column.width = @max(column.width, this.getWidthForValue(value));
}
}
} else if (this.properties.isUndefined()) {
// not object -> the value will go to the special "Values" column
this.values_col_width = @max(this.values_col_width orelse 1, this.getWidthForValue(row_value));
}
}
fn writeStringNTimes(comptime Writer: type, writer: Writer, comptime str: []const u8, n: usize) !void {
if (comptime str.len == 1) {
try writer.writeByteNTimes(str[0], n);
return;
}
for (0..n) |_| {
try writer.writeAll(str);
}
}
fn printRow(
this: *TablePrinter,
comptime Writer: type,
writer: Writer,
comptime enable_ansi_colors: bool,
columns: *std.ArrayList(Column),
row_key: RowKey,
row_value: JSValue,
) !void {
try writer.writeAll("│");
{
const len: u32 = switch (row_key) {
.str => |value| @truncate(value.visibleWidthExcludeANSIColors(false)),
.num => |value| @truncate(bun.fmt.fastDigitCount(value)),
};
const needed = columns.items[0].width -| len;
// Right-align the number column
try writer.writeByteNTimes(' ', needed + PADDING);
switch (row_key) {
.str => |value| try writer.print("{}", .{value}),
.num => |value| try writer.print("{d}", .{value}),
}
try writer.writeByteNTimes(' ', PADDING);
}
for (1..columns.items.len) |col_idx| {
const col = columns.items[col_idx];
try writer.writeAll("│");
var value = JSValue.zero;
if (col_idx == 1 and this.jstype.isMap()) { // is the "Keys" column, when iterating a Map?
value = row_value.getIndex(this.globalObject, 0);
} else if (col_idx == this.values_col_idx) { // is the "Values" column?
if (this.jstype.isMap()) {
value = row_value.getIndex(this.globalObject, 1);
} else if (!row_value.isObject()) {
value = row_value;
}
} else if (row_value.isObject()) {
value = row_value.getWithString(this.globalObject, col.name) orelse JSValue.zero;
}
if (value.isEmpty()) {
try writer.writeByteNTimes(' ', col.width + (PADDING * 2));
} else {
const len: u32 = this.getWidthForValue(value);
const needed = col.width -| len;
try writer.writeByteNTimes(' ', PADDING);
const tag = ConsoleObject.Formatter.Tag.get(value, this.globalObject);
var value_formatter = this.value_formatter;
value_formatter.quote_strings = !(tag.tag == .String or tag.tag == .StringPossiblyFormatted);
defer {
if (value_formatter.map_node) |node| {
node.data = value_formatter.map;
node.data.clearRetainingCapacity();
node.release();
}
}
value_formatter.format(
tag,
Writer,
writer,
value,
this.globalObject,
enable_ansi_colors,
);
try writer.writeByteNTimes(' ', needed + PADDING);
}
}
try writer.writeAll("│\n");
}
pub fn printTable(
this: *TablePrinter,
comptime Writer: type,
writer: Writer,
comptime enable_ansi_colors: bool,
) !void {
const globalObject = this.globalObject;
var stack_fallback = std.heap.stackFallback(@sizeOf(Column) * 16, this.globalObject.allocator());
var columns = try std.ArrayList(Column).initCapacity(stack_fallback.get(), 16);
defer {
for (columns.items) |*col| {
col.name.deref();
}
columns.deinit();
}
// create the first column " " which is always present
columns.appendAssumeCapacity(.{
.name = String.static(" "),
.width = 1,
});
// special case for Map: create the special "Key" column at index 1
if (this.jstype.isMap()) {
columns.appendAssumeCapacity(.{
.name = String.static("Key"),
});
}
// if the "properties" arg was provided, pre-populate the columns
if (!this.properties.isUndefined()) {
var properties_iter = JSC.JSArrayIterator.init(this.properties, globalObject);
while (properties_iter.next()) |value| {
try columns.append(.{
.name = value.toBunString(globalObject),
});
}
}
// rows first pass - calculate the column widths
{
if (this.is_iterable) {
var ctx_: struct { this: *TablePrinter, columns: *@TypeOf(columns), idx: u32 = 0, err: bool = false } = .{ .this = this, .columns = &columns };
this.tabular_data.forEachWithContext(globalObject, &ctx_, struct {
fn callback(_: *JSC.VM, _: *JSGlobalObject, ctx: *@TypeOf(ctx_), value: JSValue) callconv(.C) void {
updateColumnsForRow(ctx.this, ctx.columns, .{ .num = ctx.idx }, value) catch {
ctx.err = true;
};
ctx.idx += 1;
}
}.callback);
if (ctx_.err) return error.JSError;
} else {
var rows_iter = JSC.JSPropertyIterator(.{
.skip_empty_name = false,
.include_value = true,
}).init(globalObject, this.tabular_data);
defer rows_iter.deinit();
while (rows_iter.next()) |row_key| {
try this.updateColumnsForRow(&columns, .{ .str = String.init(row_key) }, rows_iter.value);
}
}
}
// append the special "Values" column as the last one, if it is present
if (this.values_col_width) |width| {
this.values_col_idx = columns.items.len;
try columns.append(.{
.name = String.static("Values"),
.width = width,
});
}
// print the table header (border line + column names line + border line)
{
for (columns.items) |*col| {
// also update the col width with the length of the column name itself
col.width = @max(col.width, @as(u32, @intCast(col.name.visibleWidthExcludeANSIColors(false))));
}
try writer.writeAll("┌");
for (columns.items, 0..) |*col, i| {
if (i > 0) try writer.writeAll("┬");
try writeStringNTimes(Writer, writer, "─", col.width + (PADDING * 2));
}
try writer.writeAll("┐\n│");
for (columns.items, 0..) |col, i| {
if (i > 0) try writer.writeAll("│");
const len = col.name.visibleWidthExcludeANSIColors(false);
const needed = col.width -| len;
try writer.writeByteNTimes(' ', 1);
if (comptime enable_ansi_colors) {
try writer.writeAll(Output.prettyFmt("<r><b>", true));
}
try writer.print("{}", .{col.name});
if (comptime enable_ansi_colors) {
try writer.writeAll(Output.prettyFmt("<r>", true));
}
try writer.writeByteNTimes(' ', needed + PADDING);
}
try writer.writeAll("│\n├");
for (columns.items, 0..) |col, i| {
if (i > 0) try writer.writeAll("┼");
try writeStringNTimes(Writer, writer, "─", col.width + (PADDING * 2));
}
try writer.writeAll("┤\n");
}
// rows second pass - print the actual table rows
{
if (this.is_iterable) {
var ctx_: struct { this: *TablePrinter, columns: *@TypeOf(columns), writer: Writer, idx: u32 = 0, err: bool = false } = .{ .this = this, .columns = &columns, .writer = writer };
this.tabular_data.forEachWithContext(globalObject, &ctx_, struct {
fn callback(_: *JSC.VM, _: *JSGlobalObject, ctx: *@TypeOf(ctx_), value: JSValue) callconv(.C) void {
printRow(ctx.this, Writer, ctx.writer, enable_ansi_colors, ctx.columns, .{ .num = ctx.idx }, value) catch {
ctx.err = true;
};
ctx.idx += 1;
}
}.callback);
if (ctx_.err) return error.JSError;
} else {
var rows_iter = JSC.JSPropertyIterator(.{
.skip_empty_name = false,
.include_value = true,
}).init(globalObject, this.tabular_data);
defer rows_iter.deinit();
while (rows_iter.next()) |row_key| {
try this.printRow(Writer, writer, enable_ansi_colors, &columns, .{ .str = String.init(row_key) }, rows_iter.value);
}
}
}
// print the table bottom border
{
try writer.writeAll("└");
try writeStringNTimes(Writer, writer, "─", columns.items[0].width + (PADDING * 2));
for (columns.items[1..]) |*column| {
try writer.writeAll("┴");
try writeStringNTimes(Writer, writer, "─", column.width + (PADDING * 2));
}
try writer.writeAll("┘\n");
}
}
};
pub fn writeTrace(comptime Writer: type, writer: Writer, global: *JSGlobalObject) void {
var holder = ZigException.Holder.init();
var vm = VirtualMachine.get();
defer holder.deinit(vm);
const exception = holder.zigException();
var err = ZigString.init("trace output").toErrorInstance(global);
err.toZigException(global, exception);
vm.remapZigException(exception, err, null, &holder.need_to_clear_parser_arena_on_deinit);
if (Output.enable_ansi_colors_stderr)
VirtualMachine.printStackTrace(
Writer,
writer,
exception.stack,
true,
) catch {}
else
VirtualMachine.printStackTrace(
Writer,
writer,
exception.stack,
false,
) catch {};
}
pub const FormatOptions = struct {
enable_colors: bool,
add_newline: bool,
flush: bool,
ordered_properties: bool = false,
quote_strings: bool = false,
max_depth: u16 = 2,
};
pub fn format2(
level: MessageLevel,
global: *JSGlobalObject,
vals: [*]const JSValue,
len: usize,
comptime RawWriter: type,
comptime Writer: type,
writer: Writer,
options: FormatOptions,
) void {
var fmt: ConsoleObject.Formatter = undefined;
defer {
if (fmt.map_node) |node| {
node.data = fmt.map;
node.data.clearRetainingCapacity();
node.release();
}
}
if (len == 1) {
fmt = ConsoleObject.Formatter{
.remaining_values = &[_]JSValue{},
.globalThis = global,
.ordered_properties = options.ordered_properties,
.quote_strings = options.quote_strings,
.max_depth = options.max_depth,
};
const tag = ConsoleObject.Formatter.Tag.get(vals[0], global);
var unbuffered_writer = if (comptime Writer != RawWriter)
if (@hasDecl(@TypeOf(writer.context.unbuffered_writer.context), "quietWriter"))
writer.context.unbuffered_writer.context.quietWriter()
else
writer.context.unbuffered_writer.context.writer()
else
writer;
if (tag.tag == .String) {
if (options.enable_colors) {
if (level == .Error) {
unbuffered_writer.writeAll(comptime Output.prettyFmt("<r><red>", true)) catch {};
}
fmt.format(
tag,
@TypeOf(unbuffered_writer),
unbuffered_writer,
vals[0],
global,
true,
);
if (level == .Error) {
unbuffered_writer.writeAll(comptime Output.prettyFmt("<r>", true)) catch {};
}
} else {
fmt.format(
tag,
@TypeOf(unbuffered_writer),
unbuffered_writer,
vals[0],
global,
false,
);
}
if (options.add_newline) _ = unbuffered_writer.write("\n") catch 0;
} else {
defer {
if (comptime Writer != RawWriter) {
if (options.flush) writer.context.flush() catch {};
}
}
if (options.enable_colors) {
fmt.format(
tag,
Writer,
writer,
vals[0],
global,
true,
);
} else {
fmt.format(
tag,
Writer,
writer,
vals[0],
global,
false,
);
}
if (options.add_newline) _ = writer.write("\n") catch 0;
}
return;
}
defer {
if (comptime Writer != RawWriter) {
if (options.flush) writer.context.flush() catch {};
}
}
var this_value: JSValue = vals[0];
fmt = ConsoleObject.Formatter{
.remaining_values = vals[0..len][1..],
.globalThis = global,
.ordered_properties = options.ordered_properties,
.quote_strings = options.quote_strings,
};
var tag: ConsoleObject.Formatter.Tag.Result = undefined;
var any = false;
if (options.enable_colors) {
if (level == .Error) {
writer.writeAll(comptime Output.prettyFmt("<r><red>", true)) catch {};
}
while (true) {
if (any) {
_ = writer.write(" ") catch 0;
}
any = true;
tag = ConsoleObject.Formatter.Tag.get(this_value, global);
if (tag.tag == .String and fmt.remaining_values.len > 0) {
tag.tag = .{ .StringPossiblyFormatted = {} };
}
fmt.format(tag, Writer, writer, this_value, global, true);
if (fmt.remaining_values.len == 0) {
break;
}
this_value = fmt.remaining_values[0];
fmt.remaining_values = fmt.remaining_values[1..];
}
if (level == .Error) {
writer.writeAll(comptime Output.prettyFmt("<r>", true)) catch {};
}
} else {
while (true) {
if (any) {
_ = writer.write(" ") catch 0;
}
any = true;
tag = ConsoleObject.Formatter.Tag.get(this_value, global);
if (tag.tag == .String and fmt.remaining_values.len > 0) {
tag.tag = .{ .StringPossiblyFormatted = {} };
}
fmt.format(tag, Writer, writer, this_value, global, false);
if (fmt.remaining_values.len == 0)
break;
this_value = fmt.remaining_values[0];
fmt.remaining_values = fmt.remaining_values[1..];
}
}
if (options.add_newline) _ = writer.write("\n") catch 0;
}
const CustomFormattedObject = struct {
function: JSValue = .zero,
this: JSValue = .zero,
};
pub const Formatter = struct {
remaining_values: []const JSValue = &[_]JSValue{},
map: Visited.Map = undefined,
map_node: ?*Visited.Pool.Node = null,
hide_native: bool = false,
globalThis: *JSGlobalObject,
indent: u32 = 0,
depth: u16 = 0,
max_depth: u16 = 8,
quote_strings: bool = false,
quote_keys: bool = false,
failed: bool = false,
estimated_line_length: usize = 0,
always_newline_scope: bool = false,
single_line: bool = false,
ordered_properties: bool = false,
custom_formatted_object: CustomFormattedObject = .{},
pub fn goodTimeForANewLine(this: *@This()) bool {
if (this.estimated_line_length > 80) {
this.resetLine();
return true;
}
return false;
}
pub fn resetLine(this: *@This()) void {
this.estimated_line_length = this.indent * 2;
}
pub fn addForNewLine(this: *@This(), len: usize) void {
this.estimated_line_length +|= len;
}
pub const ZigFormatter = struct {
formatter: *ConsoleObject.Formatter,
global: *JSGlobalObject,
value: JSValue,
pub const WriteError = error{UhOh};
pub fn format(self: ZigFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
self.formatter.remaining_values = &[_]JSValue{self.value};
defer {
self.formatter.remaining_values = &[_]JSValue{};
}
self.formatter.globalThis = self.global;
self.formatter.format(
Tag.get(self.value, self.global),
@TypeOf(writer),
writer,
self.value,
self.formatter.globalThis,
false,
);
}
};
// For detecting circular references
pub const Visited = struct {
const ObjectPool = @import("../pool.zig").ObjectPool;
pub const Map = std.AutoHashMap(JSValue.Type, void);
pub const Pool = ObjectPool(
Map,
struct {
pub fn init(allocator: std.mem.Allocator) anyerror!Map {
return Map.init(allocator);
}
}.init,
true,
16,
);
};
pub const Tag = enum {
StringPossiblyFormatted,
String,
Undefined,
Double,
Integer,
Null,
Boolean,
Array,
Object,
Function,
Class,
Error,
TypedArray,
Map,
MapIterator,
SetIterator,
Set,
BigInt,
Symbol,
CustomFormattedObject,
GlobalObject,
Private,
Promise,
JSON,
toJSON,
NativeCode,
JSX,
Event,
GetterSetter,
CustomGetterSetter,
Proxy,
RevokedProxy,
pub fn isPrimitive(this: Tag) bool {
return switch (this) {
.String,
.StringPossiblyFormatted,
.Undefined,
.Double,
.Integer,
.Null,
.Boolean,
.Symbol,
.BigInt,
=> true,
else => false,
};
}
pub inline fn canHaveCircularReferences(tag: Tag) bool {
return tag == .Array or tag == .Object or tag == .Map or tag == .Set;
}
const Result = struct {
tag: union(Tag) {
StringPossiblyFormatted: void,
String: void,
Undefined: void,
Double: void,
Integer: void,
Null: void,
Boolean: void,
Array: void,
Object: void,
Function: void,
Class: void,
Error: void,
TypedArray: void,
Map: void,
MapIterator: void,
SetIterator: void,
Set: void,
BigInt: void,
Symbol: void,
CustomFormattedObject: CustomFormattedObject,
GlobalObject: void,
Private: void,
Promise: void,
JSON: void,
toJSON: void,
NativeCode: void,
JSX: void,
Event: void,
GetterSetter: void,
CustomGetterSetter: void,
Proxy: void,
RevokedProxy: void,
pub fn isPrimitive(this: @This()) bool {
return @as(Tag, this).isPrimitive();
}
pub fn tag(this: @This()) Tag {
return @as(Tag, this);