-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Expand file tree
/
Copy pathBunObject.zig
More file actions
2106 lines (1778 loc) · 84 KB
/
BunObject.zig
File metadata and controls
2106 lines (1778 loc) · 84 KB
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 Bun = @This();
/// How to add a new function or property to the Bun global
///
/// - Add a callback or property to the below struct
/// - @export it in the appropriate place
/// - Update "@begin bunObjectTable" in BunObject.cpp
/// - Getters use a generated wrapper function `BunObject_getter_wrap_<name>`
/// - Update "BunObject+exports.h"
/// - Run `bun run build`
pub const BunObject = struct {
// --- Callbacks ---
pub const allocUnsafe = toJSCallback(Bun.allocUnsafe);
pub const build = toJSCallback(Bun.JSBundler.buildFn);
pub const color = toJSCallback(bun.css.CssColor.jsFunctionColor);
pub const connect = toJSCallback(host_fn.wrapStaticMethod(api.Listener, "connect", false));
pub const createParsedShellScript = toJSCallback(bun.shell.ParsedShellScript.createParsedShellScript);
pub const createShellInterpreter = toJSCallback(bun.shell.Interpreter.createShellInterpreter);
pub const deflateSync = toJSCallback(JSZlib.deflateSync);
pub const file = toJSCallback(WebCore.Blob.constructBunFile);
pub const gunzipSync = toJSCallback(JSZlib.gunzipSync);
pub const gzipSync = toJSCallback(JSZlib.gzipSync);
pub const indexOfLine = toJSCallback(Bun.indexOfLine);
pub const inflateSync = toJSCallback(JSZlib.inflateSync);
pub const jest = toJSCallback(@import("../test/jest.zig").Jest.call);
pub const listen = toJSCallback(host_fn.wrapStaticMethod(api.Listener, "listen", false));
pub const mmap = toJSCallback(Bun.mmapFile);
pub const nanoseconds = toJSCallback(Bun.nanoseconds);
pub const openInEditor = toJSCallback(Bun.openInEditor);
pub const registerMacro = toJSCallback(Bun.registerMacro);
pub const resolve = toJSCallback(Bun.resolve);
pub const resolveSync = toJSCallback(Bun.resolveSync);
pub const serve = toJSCallback(Bun.serve);
pub const sha = toJSCallback(host_fn.wrapStaticMethod(Crypto.SHA512_256, "hash_", true));
pub const shellEscape = toJSCallback(Bun.shellEscape);
pub const shrink = toJSCallback(Bun.shrink);
pub const sleepSync = toJSCallback(Bun.sleepSync);
pub const spawn = toJSCallback(host_fn.wrapStaticMethod(api.Subprocess, "spawn", false));
pub const spawnSync = toJSCallback(host_fn.wrapStaticMethod(api.Subprocess, "spawnSync", false));
pub const udpSocket = toJSCallback(host_fn.wrapStaticMethod(api.UDPSocket, "udpSocket", false));
pub const which = toJSCallback(Bun.which);
pub const write = toJSCallback(jsc.WebCore.Blob.writeFile);
pub const zstdCompressSync = toJSCallback(JSZstd.compressSync);
pub const zstdDecompressSync = toJSCallback(JSZstd.decompressSync);
pub const zstdCompress = toJSCallback(JSZstd.compress);
pub const zstdDecompress = toJSCallback(JSZstd.decompress);
// --- Callbacks ---
// --- Lazy property callbacks ---
pub const Archive = toJSLazyPropertyCallback(Bun.getArchiveConstructor);
pub const CryptoHasher = toJSLazyPropertyCallback(Crypto.CryptoHasher.getter);
pub const CSRF = toJSLazyPropertyCallback(Bun.getCSRFObject);
pub const FFI = toJSLazyPropertyCallback(Bun.FFIObject.getter);
pub const FileSystemRouter = toJSLazyPropertyCallback(Bun.getFileSystemRouter);
pub const Glob = toJSLazyPropertyCallback(Bun.getGlobConstructor);
pub const MD4 = toJSLazyPropertyCallback(Crypto.MD4.getter);
pub const MD5 = toJSLazyPropertyCallback(Crypto.MD5.getter);
pub const SHA1 = toJSLazyPropertyCallback(Crypto.SHA1.getter);
pub const SHA224 = toJSLazyPropertyCallback(Crypto.SHA224.getter);
pub const SHA256 = toJSLazyPropertyCallback(Crypto.SHA256.getter);
pub const SHA384 = toJSLazyPropertyCallback(Crypto.SHA384.getter);
pub const SHA512 = toJSLazyPropertyCallback(Crypto.SHA512.getter);
pub const SHA512_256 = toJSLazyPropertyCallback(Crypto.SHA512_256.getter);
pub const JSONC = toJSLazyPropertyCallback(Bun.getJSONCObject);
pub const markdown = toJSLazyPropertyCallback(Bun.getMarkdownObject);
pub const mdx = toJSLazyPropertyCallback(Bun.getMdxObject);
pub const TOML = toJSLazyPropertyCallback(Bun.getTOMLObject);
pub const JSON5 = toJSLazyPropertyCallback(Bun.getJSON5Object);
pub const YAML = toJSLazyPropertyCallback(Bun.getYAMLObject);
pub const Transpiler = toJSLazyPropertyCallback(Bun.getTranspilerConstructor);
pub const argv = toJSLazyPropertyCallback(Bun.getArgv);
pub const cwd = toJSLazyPropertyCallback(Bun.getCWD);
pub const embeddedFiles = toJSLazyPropertyCallback(Bun.getEmbeddedFiles);
pub const enableANSIColors = toJSLazyPropertyCallback(Bun.enableANSIColors);
pub const hash = toJSLazyPropertyCallback(Bun.getHashObject);
pub const inspect = toJSLazyPropertyCallback(Bun.getInspect);
pub const origin = toJSLazyPropertyCallback(Bun.getOrigin);
pub const semver = toJSLazyPropertyCallback(Bun.getSemver);
pub const unsafe = toJSLazyPropertyCallback(Bun.getUnsafe);
pub const S3Client = toJSLazyPropertyCallback(Bun.getS3ClientConstructor);
pub const s3 = toJSLazyPropertyCallback(Bun.getS3DefaultClient);
pub const ValkeyClient = toJSLazyPropertyCallback(Bun.getValkeyClientConstructor);
pub const valkey = toJSLazyPropertyCallback(Bun.getValkeyDefaultClient);
pub const Terminal = toJSLazyPropertyCallback(Bun.getTerminalConstructor);
// --- Lazy property callbacks ---
// --- Getters ---
pub const main = Bun.getMain;
// --- Getters ---
// --- Setters ---
pub const setMain = Bun.setMain;
// --- Setters ---
fn lazyPropertyCallbackName(comptime baseName: anytype) [:0]const u8 {
return "BunObject_lazyPropCb_" ++ baseName;
}
fn callbackName(comptime baseName: anytype) [:0]const u8 {
return "BunObject_callback_" ++ baseName;
}
const toJSCallback = jsc.toJSHostFn;
const LazyPropertyCallback = fn (*jsc.JSGlobalObject, *jsc.JSObject) callconv(jsc.conv) JSValue;
fn toJSLazyPropertyCallback(comptime wrapped: anytype) LazyPropertyCallback {
return struct {
pub fn callback(this: *jsc.JSGlobalObject, object: *jsc.JSObject) callconv(jsc.conv) JSValue {
return bun.jsc.toJSHostCall(this, @src(), wrapped, .{ this, object });
}
}.callback;
}
pub fn exportAll() void {
if (!@inComptime()) {
@compileError("Must be comptime");
}
// --- Lazy property callbacks ---
@export(&BunObject.Archive, .{ .name = lazyPropertyCallbackName("Archive") });
@export(&BunObject.CryptoHasher, .{ .name = lazyPropertyCallbackName("CryptoHasher") });
@export(&BunObject.CSRF, .{ .name = lazyPropertyCallbackName("CSRF") });
@export(&BunObject.FFI, .{ .name = lazyPropertyCallbackName("FFI") });
@export(&BunObject.FileSystemRouter, .{ .name = lazyPropertyCallbackName("FileSystemRouter") });
@export(&BunObject.MD4, .{ .name = lazyPropertyCallbackName("MD4") });
@export(&BunObject.MD5, .{ .name = lazyPropertyCallbackName("MD5") });
@export(&BunObject.SHA1, .{ .name = lazyPropertyCallbackName("SHA1") });
@export(&BunObject.SHA224, .{ .name = lazyPropertyCallbackName("SHA224") });
@export(&BunObject.SHA256, .{ .name = lazyPropertyCallbackName("SHA256") });
@export(&BunObject.SHA384, .{ .name = lazyPropertyCallbackName("SHA384") });
@export(&BunObject.SHA512, .{ .name = lazyPropertyCallbackName("SHA512") });
@export(&BunObject.SHA512_256, .{ .name = lazyPropertyCallbackName("SHA512_256") });
@export(&BunObject.JSONC, .{ .name = lazyPropertyCallbackName("JSONC") });
@export(&BunObject.markdown, .{ .name = lazyPropertyCallbackName("markdown") });
@export(&BunObject.mdx, .{ .name = lazyPropertyCallbackName("mdx") });
@export(&BunObject.TOML, .{ .name = lazyPropertyCallbackName("TOML") });
@export(&BunObject.JSON5, .{ .name = lazyPropertyCallbackName("JSON5") });
@export(&BunObject.YAML, .{ .name = lazyPropertyCallbackName("YAML") });
@export(&BunObject.Glob, .{ .name = lazyPropertyCallbackName("Glob") });
@export(&BunObject.Transpiler, .{ .name = lazyPropertyCallbackName("Transpiler") });
@export(&BunObject.argv, .{ .name = lazyPropertyCallbackName("argv") });
@export(&BunObject.cwd, .{ .name = lazyPropertyCallbackName("cwd") });
@export(&BunObject.enableANSIColors, .{ .name = lazyPropertyCallbackName("enableANSIColors") });
@export(&BunObject.hash, .{ .name = lazyPropertyCallbackName("hash") });
@export(&BunObject.inspect, .{ .name = lazyPropertyCallbackName("inspect") });
@export(&BunObject.origin, .{ .name = lazyPropertyCallbackName("origin") });
@export(&BunObject.unsafe, .{ .name = lazyPropertyCallbackName("unsafe") });
@export(&BunObject.semver, .{ .name = lazyPropertyCallbackName("semver") });
@export(&BunObject.embeddedFiles, .{ .name = lazyPropertyCallbackName("embeddedFiles") });
@export(&BunObject.S3Client, .{ .name = lazyPropertyCallbackName("S3Client") });
@export(&BunObject.s3, .{ .name = lazyPropertyCallbackName("s3") });
@export(&BunObject.ValkeyClient, .{ .name = lazyPropertyCallbackName("ValkeyClient") });
@export(&BunObject.valkey, .{ .name = lazyPropertyCallbackName("valkey") });
@export(&BunObject.Terminal, .{ .name = lazyPropertyCallbackName("Terminal") });
// --- Lazy property callbacks ---
// --- Callbacks ---
@export(&BunObject.allocUnsafe, .{ .name = callbackName("allocUnsafe") });
@export(&BunObject.build, .{ .name = callbackName("build") });
@export(&BunObject.color, .{ .name = callbackName("color") });
@export(&BunObject.connect, .{ .name = callbackName("connect") });
@export(&BunObject.createParsedShellScript, .{ .name = callbackName("createParsedShellScript") });
@export(&BunObject.createShellInterpreter, .{ .name = callbackName("createShellInterpreter") });
@export(&BunObject.deflateSync, .{ .name = callbackName("deflateSync") });
@export(&BunObject.file, .{ .name = callbackName("file") });
@export(&BunObject.gunzipSync, .{ .name = callbackName("gunzipSync") });
@export(&BunObject.gzipSync, .{ .name = callbackName("gzipSync") });
@export(&BunObject.indexOfLine, .{ .name = callbackName("indexOfLine") });
@export(&BunObject.inflateSync, .{ .name = callbackName("inflateSync") });
@export(&BunObject.jest, .{ .name = callbackName("jest") });
@export(&BunObject.listen, .{ .name = callbackName("listen") });
@export(&BunObject.mmap, .{ .name = callbackName("mmap") });
@export(&BunObject.nanoseconds, .{ .name = callbackName("nanoseconds") });
@export(&BunObject.openInEditor, .{ .name = callbackName("openInEditor") });
@export(&BunObject.registerMacro, .{ .name = callbackName("registerMacro") });
@export(&BunObject.resolve, .{ .name = callbackName("resolve") });
@export(&BunObject.resolveSync, .{ .name = callbackName("resolveSync") });
@export(&BunObject.serve, .{ .name = callbackName("serve") });
@export(&BunObject.sha, .{ .name = callbackName("sha") });
@export(&BunObject.shellEscape, .{ .name = callbackName("shellEscape") });
@export(&BunObject.shrink, .{ .name = callbackName("shrink") });
@export(&BunObject.sleepSync, .{ .name = callbackName("sleepSync") });
@export(&BunObject.spawn, .{ .name = callbackName("spawn") });
@export(&BunObject.spawnSync, .{ .name = callbackName("spawnSync") });
@export(&BunObject.udpSocket, .{ .name = callbackName("udpSocket") });
@export(&BunObject.which, .{ .name = callbackName("which") });
@export(&BunObject.write, .{ .name = callbackName("write") });
@export(&BunObject.zstdCompressSync, .{ .name = callbackName("zstdCompressSync") });
@export(&BunObject.zstdDecompressSync, .{ .name = callbackName("zstdDecompressSync") });
@export(&BunObject.zstdCompress, .{ .name = callbackName("zstdCompress") });
@export(&BunObject.zstdDecompress, .{ .name = callbackName("zstdDecompress") });
// --- Callbacks ---
// --- LazyProperty initializers ---
@export(&createBunStdin, .{ .name = "BunObject__createBunStdin" });
@export(&createBunStderr, .{ .name = "BunObject__createBunStderr" });
@export(&createBunStdout, .{ .name = "BunObject__createBunStdout" });
// --- LazyProperty initializers ---
// --- Getters ---
@export(&BunObject.main, .{ .name = "BunObject_getter_main" });
// --- Getters ---
// --- Setters ---
@export(&BunObject.setMain, .{ .name = "BunObject_setter_main" });
// --- Setters ---
}
};
pub fn shellEscape(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue {
const arguments = callframe.arguments_old(1);
if (arguments.len < 1) {
return globalThis.throw("shell escape expected at least 1 argument", .{});
}
const jsval = arguments.ptr[0];
const bunstr = try jsval.toBunString(globalThis);
if (globalThis.hasException()) return .zero;
defer bunstr.deref();
var outbuf = std.array_list.Managed(u8).init(bun.default_allocator);
defer outbuf.deinit();
if (bun.shell.needsEscapeBunstr(bunstr)) {
const result = try bun.shell.escapeBunStr(bunstr, &outbuf, true);
if (!result) {
return globalThis.throw("String has invalid utf-16: {s}", .{bunstr.byteSlice()});
}
var str = bun.String.cloneUTF8(outbuf.items[0..]);
return str.transferToJS(globalThis);
}
return jsval;
}
pub fn braces(global: *jsc.JSGlobalObject, brace_str: bun.String, opts: gen.BracesOptions) bun.JSError!jsc.JSValue {
const brace_slice = brace_str.toUTF8(bun.default_allocator);
defer brace_slice.deinit();
var arena = std.heap.ArenaAllocator.init(bun.default_allocator);
defer arena.deinit();
var lexer_output = lexer_output: {
if (bun.strings.isAllASCII(brace_slice.slice())) {
break :lexer_output Braces.Lexer.tokenize(arena.allocator(), brace_slice.slice()) catch |err| {
return global.throwError(err, "failed to tokenize braces");
};
}
break :lexer_output Braces.NewLexer(.wtf8).tokenize(arena.allocator(), brace_slice.slice()) catch |err| {
return global.throwError(err, "failed to tokenize braces");
};
};
const expansion_count = Braces.calculateExpandedAmount(lexer_output.tokens.items[0..]);
if (opts.tokenize) {
const str = bun.handleOom(std.fmt.allocPrint(global.bunVM().allocator, "{f}", .{std.json.fmt(lexer_output.tokens.items[0..], .{})}));
defer global.bunVM().allocator.free(str);
var bun_str = bun.String.fromBytes(str);
return bun_str.toJS(global);
}
if (opts.parse) {
var parser = Braces.Parser.init(lexer_output.tokens.items[0..], arena.allocator());
const ast_node = parser.parse() catch |err| {
return global.throwError(err, "failed to parse braces");
};
const str = bun.handleOom(std.fmt.allocPrint(global.bunVM().allocator, "{f}", .{std.json.fmt(ast_node, .{})}));
defer global.bunVM().allocator.free(str);
var bun_str = bun.String.fromBytes(str);
return bun_str.toJS(global);
}
if (expansion_count == 0) {
return bun.String.toJSArray(global, &.{brace_str});
}
var expanded_strings = try arena.allocator().alloc(std.array_list.Managed(u8), expansion_count);
for (0..expansion_count) |i| {
expanded_strings[i] = std.array_list.Managed(u8).init(arena.allocator());
}
Braces.expand(
arena.allocator(),
lexer_output.tokens.items[0..],
expanded_strings,
lexer_output.contains_nested,
) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
error.UnexpectedToken => return global.throwPretty("Unexpected token while expanding braces", .{}),
};
var out_strings = try arena.allocator().alloc(bun.String, expansion_count);
for (0..expansion_count) |i| {
out_strings[i] = bun.String.fromBytes(expanded_strings[i].items[0..]);
}
return bun.String.toJSArray(global, out_strings[0..]);
}
pub fn which(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue {
const arguments_ = callframe.arguments_old(2);
const path_buf = bun.path_buffer_pool.get();
defer bun.path_buffer_pool.put(path_buf);
var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice());
defer arguments.deinit();
const path_arg = arguments.nextEat() orelse {
return globalThis.throw("which: expected 1 argument, got 0", .{});
};
var path_str: ZigString.Slice = ZigString.Slice.empty;
var bin_str: ZigString.Slice = ZigString.Slice.empty;
var cwd_str: ZigString.Slice = ZigString.Slice.empty;
defer {
path_str.deinit();
bin_str.deinit();
cwd_str.deinit();
}
if (path_arg.isEmptyOrUndefinedOrNull()) {
return jsc.JSValue.jsNull();
}
bin_str = try path_arg.toSlice(globalThis, globalThis.bunVM().allocator);
if (globalThis.hasException()) {
return .zero;
}
if (bin_str.len >= bun.MAX_PATH_BYTES) {
return globalThis.throw("bin path is too long", .{});
}
if (bin_str.len == 0) {
return jsc.JSValue.jsNull();
}
path_str = ZigString.Slice.fromUTF8NeverFree(
globalThis.bunVM().transpiler.env.get("PATH") orelse "",
);
cwd_str = ZigString.Slice.fromUTF8NeverFree(
globalThis.bunVM().transpiler.fs.top_level_dir,
);
if (arguments.nextEat()) |arg| {
if (!arg.isEmptyOrUndefinedOrNull() and arg.isObject()) {
if (try arg.get(globalThis, "PATH")) |str_| {
path_str = try str_.toSlice(globalThis, globalThis.bunVM().allocator);
}
if (try arg.get(globalThis, "cwd")) |str_| {
cwd_str = try str_.toSlice(globalThis, globalThis.bunVM().allocator);
}
}
}
if (Which.which(
path_buf,
path_str.slice(),
cwd_str.slice(),
bin_str.slice(),
)) |bin_path| {
return ZigString.init(bin_path).withEncoding().toJS(globalThis);
}
return jsc.JSValue.jsNull();
}
pub fn inspectTable(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue {
var args_buf = callframe.argumentsUndef(5);
var all_arguments = args_buf.mut();
if (all_arguments[0].isUndefinedOrNull() or !all_arguments[0].isObject())
return bun.String.empty.toJS(globalThis);
for (all_arguments) |arg| {
arg.protect();
}
defer {
for (all_arguments) |arg| {
arg.unprotect();
}
}
var arguments = all_arguments[0..];
const value = arguments[0];
if (!arguments[1].isArray()) {
arguments[2] = arguments[1];
arguments[1] = .js_undefined;
}
var formatOptions = ConsoleObject.FormatOptions{
.enable_colors = false,
.add_newline = false,
.flush = false,
.max_depth = 5,
.quote_strings = true,
.ordered_properties = false,
.single_line = true,
};
if (arguments[2].isObject()) {
try formatOptions.fromJS(globalThis, arguments[2..]);
}
// very stable memory address
var array = std.Io.Writer.Allocating.init(bun.default_allocator);
defer array.deinit();
const writer = &array.writer;
const Writer = @TypeOf(writer);
const properties: JSValue = if (arguments[1].jsType().isArray()) arguments[1] else .js_undefined;
var table_printer = try ConsoleObject.TablePrinter.init(
globalThis,
.Log,
value,
properties,
);
table_printer.value_formatter.depth = formatOptions.max_depth;
table_printer.value_formatter.ordered_properties = formatOptions.ordered_properties;
table_printer.value_formatter.single_line = formatOptions.single_line;
switch (formatOptions.enable_colors) {
inline else => |colors| table_printer.printTable(Writer, writer, colors) catch {
if (!globalThis.hasException())
return globalThis.throwOutOfMemory();
return .zero;
},
}
writer.flush() catch |e| switch (e) {
error.WriteFailed => return error.OutOfMemory,
};
return bun.String.createUTF8ForJS(globalThis, array.written());
}
pub fn inspect(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue {
const arguments = callframe.arguments_old(4).slice();
if (arguments.len == 0)
return bun.String.empty.toJS(globalThis);
for (arguments) |arg| {
arg.protect();
}
defer {
for (arguments) |arg| {
arg.unprotect();
}
}
var formatOptions = ConsoleObject.FormatOptions{
.enable_colors = false,
.add_newline = false,
.flush = false,
.max_depth = 8,
.quote_strings = true,
.ordered_properties = false,
};
if (arguments.len > 1) {
try formatOptions.fromJS(globalThis, arguments[1..]);
}
// very stable memory address
var array = std.Io.Writer.Allocating.init(bun.default_allocator);
defer array.deinit();
const writer = &array.writer;
// we buffer this because it'll almost always be < 4096
// when it's under 4096, we want to avoid the dynamic allocation
try ConsoleObject.format2(
.Debug,
globalThis,
arguments.ptr,
1,
writer,
formatOptions,
);
if (globalThis.hasException()) return error.JSError;
writer.flush() catch return globalThis.throwOutOfMemory();
// we are going to always clone to keep things simple for now
// the common case here will be stack-allocated, so it should be fine
var out = ZigString.init(array.written()).withEncoding();
const ret = out.toJS(globalThis);
return ret;
}
export fn Bun__inspect(globalThis: *JSGlobalObject, value: JSValue) bun.String {
// very stable memory address
var array = std.Io.Writer.Allocating.init(bun.default_allocator);
defer array.deinit();
const writer = &array.writer;
var formatter = ConsoleObject.Formatter{ .globalThis = globalThis };
defer formatter.deinit();
writer.print("{f}", .{value.toFmt(&formatter)}) catch return .empty;
writer.flush() catch return .empty;
return bun.String.cloneUTF8(array.written());
}
export fn Bun__inspect_singleline(globalThis: *JSGlobalObject, value: JSValue) bun.String {
var array = std.Io.Writer.Allocating.init(bun.default_allocator);
defer array.deinit();
const writer = &array.writer;
ConsoleObject.format2(.Debug, globalThis, (&value)[0..1].ptr, 1, writer, .{
.enable_colors = false,
.add_newline = false,
.flush = false,
.max_depth = std.math.maxInt(u16),
.quote_strings = true,
.ordered_properties = false,
.single_line = true,
}) catch return .empty;
if (globalThis.hasException()) return .empty;
writer.flush() catch return .empty;
return bun.String.cloneUTF8(array.written());
}
pub fn getInspect(globalObject: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue {
const fun = jsc.JSFunction.create(globalObject, "inspect", inspect, 2, .{});
var str = ZigString.init("nodejs.util.inspect.custom");
fun.put(globalObject, ZigString.static("custom"), jsc.JSValue.symbolFor(globalObject, &str));
fun.put(globalObject, ZigString.static("table"), jsc.JSFunction.create(globalObject, "table", inspectTable, 3, .{}));
return fun;
}
pub fn registerMacro(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue {
const arguments_ = callframe.arguments_old(2);
const arguments = arguments_.slice();
if (arguments.len != 2 or !arguments[0].isNumber()) {
return globalObject.throwInvalidArguments("Internal error registering macros: invalid args", .{});
}
const id = arguments[0].toInt32();
if (id == -1 or id == 0) {
return globalObject.throwInvalidArguments("Internal error registering macros: invalid id", .{});
}
if (!arguments[1].isCell() or !arguments[1].isCallable()) {
// TODO: add "toTypeOf" helper
return globalObject.throw("Macro must be a function", .{});
}
const get_or_put_result = VirtualMachine.get().macros.getOrPut(id) catch unreachable;
if (get_or_put_result.found_existing) {
get_or_put_result.value_ptr.*.?.value().unprotect();
}
arguments[1].protect();
get_or_put_result.value_ptr.* = arguments[1].asObjectRef();
return .js_undefined;
}
pub fn getCWD(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue {
return ZigString.init(VirtualMachine.get().transpiler.fs.top_level_dir).toJS(globalThis);
}
pub fn getOrigin(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue {
return ZigString.init(VirtualMachine.get().origin.origin).toJS(globalThis);
}
pub fn enableANSIColors(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue {
_ = globalThis;
return JSValue.jsBoolean(Output.enable_ansi_colors_stdout or Output.enable_ansi_colors_stderr);
}
fn getMain(globalThis: *jsc.JSGlobalObject) callconv(jsc.conv) jsc.JSValue {
const vm = globalThis.bunVM();
// If JS has set it to a custom value, use that one
if (vm.overridden_main.get()) |overridden_main| return overridden_main;
// Attempt to use the resolved filesystem path
// This makes `eval('require.main === module')` work when the main module is a symlink.
// This behavior differs slightly from Node. Node sets the `id` to `.` when the main module is a symlink.
use_resolved_path: {
if (vm.main_resolved_path.isEmpty()) {
// If it's from eval, don't try to resolve it.
if (strings.hasSuffixComptime(vm.main, "[eval]")) {
break :use_resolved_path;
}
if (strings.hasSuffixComptime(vm.main, "[stdin]")) {
break :use_resolved_path;
}
const fd = bun.sys.openatA(
if (comptime Environment.isWindows) bun.invalid_fd else bun.FD.cwd(),
vm.main,
// Open with the minimum permissions necessary for resolving the file path.
if (comptime Environment.isLinux) bun.O.PATH else bun.O.RDONLY,
0,
).unwrap() catch break :use_resolved_path;
defer fd.close();
if (comptime Environment.isWindows) {
var wpath: bun.WPathBuffer = undefined;
const fdpath = bun.getFdPathW(fd, &wpath) catch break :use_resolved_path;
vm.main_resolved_path = bun.String.cloneUTF16(fdpath);
} else {
var path: bun.PathBuffer = undefined;
const fdpath = bun.getFdPath(fd, &path) catch break :use_resolved_path;
// Bun.main === otherId will be compared many times, so let's try to create an atom string if we can.
if (bun.String.tryCreateAtom(fdpath)) |atom| {
vm.main_resolved_path = atom;
} else {
vm.main_resolved_path = bun.String.cloneUTF8(fdpath);
}
}
}
return vm.main_resolved_path.toJS(globalThis) catch .zero;
}
return ZigString.init(vm.main).toJS(globalThis);
}
fn setMain(global_this: *jsc.JSGlobalObject, new_value: JSValue) callconv(jsc.conv) bool {
global_this.bunVM().overridden_main.set(global_this, new_value);
return true;
}
pub fn getArgv(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue {
return node.process.getArgv(globalThis);
}
pub fn openInEditor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue {
var edit = &VirtualMachine.get().rareData().editor_context;
const args = callframe.arguments_old(4);
var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), args.slice());
defer arguments.deinit();
var path: string = "";
var editor_choice: ?Editor = null;
var line: ?string = null;
var column: ?string = null;
if (arguments.nextEat()) |file_path_| {
path = (try file_path_.toSlice(globalThis, arguments.arena.allocator())).slice();
}
if (arguments.nextEat()) |opts| {
if (!opts.isUndefinedOrNull()) {
if (try opts.getTruthy(globalThis, "editor")) |editor_val| {
var sliced = try editor_val.toSlice(globalThis, arguments.arena.allocator());
const prev_name = edit.name;
if (!strings.eqlLong(prev_name, sliced.slice(), true)) {
const prev = edit.*;
edit.name = sliced.slice();
edit.detectEditor(VirtualMachine.get().transpiler.env);
editor_choice = edit.editor;
if (editor_choice == null) {
edit.* = prev;
return globalThis.throw("Could not find editor \"{s}\"", .{sliced.slice()});
} else if (edit.name.ptr == edit.path.ptr) {
edit.name = arguments.arena.allocator().dupe(u8, edit.path) catch unreachable;
edit.path = edit.path;
}
}
}
if (try opts.getTruthy(globalThis, "line")) |line_| {
line = (try line_.toSlice(globalThis, arguments.arena.allocator())).slice();
}
if (try opts.getTruthy(globalThis, "column")) |column_| {
column = (try column_.toSlice(globalThis, arguments.arena.allocator())).slice();
}
}
}
const editor = editor_choice orelse edit.editor orelse brk: {
edit.autoDetectEditor(VirtualMachine.get().transpiler.env);
if (edit.editor == null) {
return globalThis.throw("Failed to auto-detect editor", .{});
}
break :brk edit.editor.?;
};
if (path.len == 0) {
return globalThis.throw("No file path specified", .{});
}
editor.open(edit.path, path, line, column, arguments.arena.allocator()) catch |err| {
return globalThis.throw("Opening editor failed {s}", .{@errorName(err)});
};
return .js_undefined;
}
pub fn getPublicPath(to: string, origin: URL, comptime Writer: type, writer: Writer) void {
return getPublicPathWithAssetPrefix(
to,
VirtualMachine.get().transpiler.fs.top_level_dir,
origin,
"",
comptime Writer,
writer,
.loose,
);
}
pub fn getPublicPathWithAssetPrefix(
to: string,
dir: string,
origin: URL,
asset_prefix: string,
comptime Writer: type,
writer: Writer,
comptime platform: bun.path.Platform,
) void {
const relative_path = if (strings.hasPrefix(to, dir))
strings.withoutTrailingSlash(to[dir.len..])
else
VirtualMachine.get().transpiler.fs.relativePlatform(dir, to, platform);
if (origin.isAbsolute()) {
if (strings.hasPrefix(relative_path, "..") or strings.hasPrefix(relative_path, "./")) {
writer.writeAll(origin.origin) catch return;
writer.writeAll("/abs:") catch return;
if (std.fs.path.isAbsolute(to)) {
writer.writeAll(to) catch return;
} else {
writer.writeAll(VirtualMachine.get().transpiler.fs.abs(&[_]string{to})) catch return;
}
} else {
origin.joinWrite(
Writer,
writer,
asset_prefix,
"",
relative_path,
"",
) catch return;
}
} else {
writer.writeAll(std.mem.trimLeft(u8, relative_path, "/")) catch unreachable;
}
}
pub fn sleepSync(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue {
const arguments = callframe.arguments_old(1);
// Expect at least one argument. We allow more than one but ignore them; this
// is useful for supporting things like `[1, 2].map(sleepSync)`
if (arguments.len < 1) {
return globalObject.throwNotEnoughArguments("sleepSync", 1, 0);
}
const arg = arguments.slice()[0];
// The argument must be a number
if (!arg.isNumber()) {
return globalObject.throwInvalidArgumentType("sleepSync", "milliseconds", "number");
}
//NOTE: if argument is > max(i32) then it will be truncated
const milliseconds = try arg.coerce(i32, globalObject);
if (milliseconds < 0) {
return globalObject.throwInvalidArguments("argument to sleepSync must not be negative, got {d}", .{milliseconds});
}
std.Thread.sleep(@as(u64, @intCast(milliseconds)) * std.time.ns_per_ms);
return .js_undefined;
}
pub const gc = Bun__gc;
export fn Bun__gc(vm: *jsc.VirtualMachine, sync: bool) callconv(.c) usize {
return vm.garbageCollect(sync);
}
pub fn shrink(globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue {
globalObject.vm().shrinkFootprint();
return .js_undefined;
}
fn doResolve(globalThis: *jsc.JSGlobalObject, arguments: []const JSValue) bun.JSError!jsc.JSValue {
var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments);
defer args.deinit();
const specifier = args.protectEatNext() orelse {
return globalThis.throwInvalidArguments("Expected a specifier and a from path", .{});
};
if (specifier.isUndefinedOrNull()) {
return globalThis.throwInvalidArguments("specifier must be a string", .{});
}
const from = args.protectEatNext() orelse {
return globalThis.throwInvalidArguments("Expected a from path", .{});
};
if (from.isUndefinedOrNull()) {
return globalThis.throwInvalidArguments("from must be a string", .{});
}
var is_esm = true;
if (args.nextEat()) |next| {
if (next.isBoolean()) {
is_esm = next.toBoolean();
} else {
return globalThis.throwInvalidArguments("esm must be a boolean", .{});
}
}
const specifier_str = try specifier.toBunString(globalThis);
defer specifier_str.deref();
const from_str = try from.toBunString(globalThis);
defer from_str.deref();
return doResolveWithArgs(
globalThis,
specifier_str,
from_str,
is_esm,
false,
false,
);
}
fn doResolveWithArgs(ctx: *jsc.JSGlobalObject, specifier: bun.String, from: bun.String, is_esm: bool, comptime is_file_path: bool, is_user_require_resolve: bool) bun.JSError!jsc.JSValue {
var errorable: ErrorableString = undefined;
var query_string = ZigString.Empty;
const specifier_decoded = if (specifier.hasPrefixComptime("file://"))
bun.jsc.URL.pathFromFileURL(specifier)
else
specifier.dupeRef();
defer specifier_decoded.deref();
try VirtualMachine.resolveMaybeNeedsTrailingSlash(
&errorable,
ctx,
specifier_decoded,
from,
&query_string,
is_esm,
is_file_path,
is_user_require_resolve,
);
if (!errorable.success) {
return ctx.throwValue(errorable.result.err.value);
}
if (query_string.len > 0) {
var stack = std.heap.stackFallback(1024, ctx.allocator());
const allocator = stack.get();
var arraylist = std.array_list.Managed(u8).initCapacity(allocator, 1024) catch unreachable;
defer arraylist.deinit();
try arraylist.writer().print("{f}{f}", .{
errorable.result.value,
query_string,
});
return ZigString.initUTF8(arraylist.items).toJS(ctx);
}
return errorable.result.value.toJS(ctx);
}
pub fn resolveSync(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue {
return try doResolve(globalObject, callframe.arguments());
}
pub fn resolve(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue {
const arguments = callframe.arguments_old(3);
const value = doResolve(globalObject, arguments.slice()) catch |e| {
const err = globalObject.takeError(e);
return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalObject, err);
};
return jsc.JSPromise.resolvedPromiseValue(globalObject, value);
}
export fn Bun__resolve(global: *JSGlobalObject, specifier: JSValue, source: JSValue, is_esm: bool) jsc.JSValue {
const specifier_str = specifier.toBunString(global) catch return .zero;
defer specifier_str.deref();
const source_str = source.toBunString(global) catch return .zero;
defer source_str.deref();
const value = doResolveWithArgs(global, specifier_str, source_str, is_esm, true, false) catch {
const err = global.tryTakeException().?;
return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(global, err);
};
return jsc.JSPromise.resolvedPromiseValue(global, value);
}
export fn Bun__resolveSync(global: *JSGlobalObject, specifier: JSValue, source: JSValue, is_esm: bool, is_user_require_resolve: bool) jsc.JSValue {
const specifier_str = specifier.toBunString(global) catch return .zero;
defer specifier_str.deref();
if (specifier_str.length() == 0) {
return global.ERR(.INVALID_ARG_VALUE, "The argument 'id' must be a non-empty string. Received ''", .{}).throw() catch .zero;
}
const source_str = source.toBunString(global) catch return .zero;
defer source_str.deref();
return jsc.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier_str, source_str, is_esm, true, is_user_require_resolve });
}
export fn Bun__resolveSyncWithPaths(
global: *JSGlobalObject,
specifier: JSValue,
source: JSValue,
is_esm: bool,
is_user_require_resolve: bool,
paths_ptr: ?[*]const bun.String,
paths_len: usize,
) jsc.JSValue {
const paths: []const bun.String = if (paths_len == 0) &.{} else paths_ptr.?[0..paths_len];
const specifier_str = specifier.toBunString(global) catch return .zero;
defer specifier_str.deref();
if (specifier_str.length() == 0) {
return global.ERR(.INVALID_ARG_VALUE, "The argument 'id' must be a non-empty string. Received ''", .{}).throw() catch .zero;
}
const source_str = source.toBunString(global) catch return .zero;
defer source_str.deref();
const bun_vm = global.bunVM();
bun.assert(bun_vm.transpiler.resolver.custom_dir_paths == null);
bun_vm.transpiler.resolver.custom_dir_paths = paths;
defer bun_vm.transpiler.resolver.custom_dir_paths = null;
return jsc.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier_str, source_str, is_esm, true, is_user_require_resolve });
}
export fn Bun__resolveSyncWithStrings(global: *JSGlobalObject, specifier: *bun.String, source: *bun.String, is_esm: bool) jsc.JSValue {
Output.scoped(.importMetaResolve, .visible)("source: {f}, specifier: {f}", .{ source.*, specifier.* });
return jsc.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier.*, source.*, is_esm, true, false });
}
export fn Bun__resolveSyncWithSource(global: *JSGlobalObject, specifier: JSValue, source: *bun.String, is_esm: bool, is_user_require_resolve: bool) jsc.JSValue {
const specifier_str = specifier.toBunString(global) catch return .zero;
defer specifier_str.deref();
if (specifier_str.length() == 0) {
return global.ERR(.INVALID_ARG_VALUE, "The argument 'id' must be a non-empty string. Received ''", .{}).throw() catch .zero;
}
return jsc.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier_str, source.*, is_esm, true, is_user_require_resolve });
}
pub fn indexOfLine(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue {
const arguments_ = callframe.arguments_old(2);
const arguments = arguments_.slice();
if (arguments.len == 0) {
return jsc.JSValue.jsNumberFromInt32(-1);
}
var buffer = arguments[0].asArrayBuffer(globalThis) orelse {
return jsc.JSValue.jsNumberFromInt32(-1);
};
var offset: usize = 0;
if (arguments.len > 1) {
const offset_value = try arguments[1].coerce(i64, globalThis);
offset = @intCast(@max(offset_value, 0));
}
const bytes = buffer.byteSlice();
var current_offset = offset;
const end = @as(u32, @truncate(bytes.len));
while (current_offset < end) {
if (strings.indexOfNewlineOrNonASCII(bytes, @as(u32, @truncate(current_offset)))) |i| {
const byte = bytes[i];
if (byte > 0x7F) {
current_offset += @max(strings.wtf8ByteSequenceLength(byte), 1);
continue;
}
if (byte == '\n') {
return jsc.JSValue.jsNumber(i);
}
current_offset = i + 1;
} else {
break;
}
}
return jsc.JSValue.jsNumberFromInt32(-1);
}
pub const Crypto = @import("./crypto.zig");
pub fn nanoseconds(globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue {
const ns = globalThis.bunVM().origin_timer.read();
return jsc.JSValue.jsNumberFromUint64(ns);
}
pub fn serve(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue {
const arguments = callframe.arguments_old(2).slice();
var config: jsc.API.ServerConfig = brk: {
var args = jsc.CallFrame.ArgumentsSlice.init(globalObject.bunVM(), arguments);
var config: jsc.API.ServerConfig = .{};