forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.zig
2486 lines (2168 loc) · 93.3 KB
/
base.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
pub const js = @import("root").bun.JSC.C;
const std = @import("std");
const bun = @import("root").bun;
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
const Environment = bun.Environment;
const strings = bun.strings;
const MutableString = bun.MutableString;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
const JavaScript = @import("./javascript.zig");
const JSC = @import("root").bun.JSC;
const WebCore = @import("./webcore.zig");
const Test = @import("./test/jest.zig");
const Fetch = WebCore.Fetch;
const Response = WebCore.Response;
const Request = WebCore.Request;
const Router = @import("./api/filesystem_router.zig");
const IdentityContext = @import("../identity_context.zig").IdentityContext;
const uws = @import("root").bun.uws;
const Body = WebCore.Body;
const TaggedPointerTypes = @import("../tagged_pointer.zig");
const TaggedPointerUnion = TaggedPointerTypes.TaggedPointerUnion;
pub const ExceptionValueRef = [*c]js.JSValueRef;
pub const JSValueRef = js.JSValueRef;
fn ObjectPtrType(comptime Type: type) type {
if (Type == void) return Type;
return *Type;
}
const Internal = struct {
pub fn toJSWithType(globalThis: *JSC.JSGlobalObject, comptime Type: type, value: Type, exception: JSC.C.ExceptionRef) JSValue {
// TODO: refactor withType to use this instead of the other way around
return JSC.JSValue.c(To.JS.withType(Type, value, globalThis, exception));
}
pub fn toJS(globalThis: *JSC.JSGlobalObject, value: anytype, exception: JSC.C.ExceptionRef) JSValue {
return toJSWithType(globalThis, @TypeOf(value), value, exception);
}
};
pub usingnamespace Internal;
pub const To = struct {
pub const Cpp = struct {
pub fn PropertyGetter(
comptime Type: type,
) type {
return comptime fn (
this: ObjectPtrType(Type),
globalThis: *JSC.JSGlobalObject,
) callconv(.C) JSC.JSValue;
}
const toJS = Internal.toJSWithType;
pub fn GetterFn(comptime Type: type, comptime decl: std.meta.DeclEnum(Type)) PropertyGetter(Type) {
return struct {
pub fn getter(
this: ObjectPtrType(Type),
globalThis: *JSC.JSGlobalObject,
) callconv(.C) JSC.JSValue {
var exception_ref = [_]JSC.C.JSValueRef{null};
var exception: JSC.C.ExceptionRef = &exception_ref;
const result = toJS(globalThis, @call(.auto, @field(Type, @tagName(decl)), .{this}), exception);
if (exception.* != null) {
globalThis.throwValue(JSC.JSValue.c(exception.*));
return .zero;
}
return result;
}
}.getter;
}
};
pub const JS = struct {
pub fn withType(comptime Type: type, value: Type, context: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef {
return withTypeClone(Type, value, context, exception, false);
}
pub fn withTypeClone(comptime Type: type, value: Type, context: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef, clone: bool) JSC.C.JSValueRef {
if (comptime std.meta.trait.isNumber(Type)) {
return JSC.JSValue.jsNumberWithType(Type, value).asRef();
}
var zig_str: JSC.ZigString = undefined;
return switch (comptime Type) {
void => JSC.C.JSValueMakeUndefined(context),
bool => JSC.C.JSValueMakeBoolean(context, value),
[]const u8, [:0]const u8, [*:0]const u8, []u8, [:0]u8, [*:0]u8 => brk: {
zig_str = ZigString.init(value);
const val = zig_str.toValueAuto(context.ptr());
break :brk val.asObjectRef();
},
[]const JSC.ZigString => {
var array = JSC.JSValue.createStringArray(context.ptr(), value.ptr, value.len, clone).asObjectRef();
const values: []const JSC.ZigString = value;
defer bun.default_allocator.free(values);
if (clone) {
for (values) |out| {
if (out.isGloballyAllocated()) {
out.deinitGlobal();
}
}
}
return array;
},
[]const bun.String => {
defer {
for (value) |out| {
out.deref();
}
bun.default_allocator.free(value);
}
return bun.String.toJSArray(context, value).asObjectRef();
},
[]const PathString, []const []const u8, []const []u8, [][]const u8, [][:0]const u8, [][:0]u8 => {
if (value.len == 0)
return JSC.C.JSObjectMakeArray(context, 0, null, exception);
var stack_fallback = std.heap.stackFallback(512, bun.default_allocator);
var allocator = stack_fallback.get();
var zig_strings = allocator.alloc(ZigString, value.len) catch unreachable;
defer if (stack_fallback.fixed_buffer_allocator.end_index >= 511) allocator.free(zig_strings);
for (value, 0..) |path_string, i| {
if (comptime Type == []const PathString) {
zig_strings[i] = ZigString.init(path_string.slice());
} else {
zig_strings[i] = ZigString.init(path_string);
}
}
// there is a possible C ABI bug or something here when the ptr is null
// it should not be segfaulting but it is
// that's why we check at the top of this function
var array = JSC.JSValue.createStringArray(context.ptr(), zig_strings.ptr, zig_strings.len, clone).asObjectRef();
if (clone and value.len > 0) {
for (value) |path_string| {
if (comptime Type == []const PathString) {
bun.default_allocator.free(path_string.slice());
} else {
bun.default_allocator.free(path_string);
}
}
bun.default_allocator.free(value);
}
return array;
},
JSC.C.JSValueRef => value,
else => {
const Info: std.builtin.Type = comptime @typeInfo(Type);
if (comptime Info == .Enum) {
const Enum: std.builtin.Type.Enum = Info.Enum;
if (comptime !std.meta.trait.isNumber(Enum.tag_type)) {
zig_str = JSC.ZigString.init(@tagName(value));
return zig_str.toValue(context.ptr()).asObjectRef();
}
}
// Recursion can stack overflow here
if (comptime std.meta.trait.isSlice(Type)) {
const Child = comptime std.meta.Child(Type);
var array = JSC.JSValue.createEmptyArray(context, value.len);
for (value, 0..) |item, i| {
array.putIndex(
context,
@truncate(i),
JSC.JSValue.c(To.JS.withType(Child, item, context, exception)),
);
if (exception.* != null) {
return null;
}
}
return array.asObjectRef();
}
if (comptime std.meta.trait.isZigString(Type)) {
zig_str = JSC.ZigString.init(value);
return zig_str.toValue(context.ptr()).asObjectRef();
}
if (comptime Info == .Pointer) {
const Child = comptime std.meta.Child(Type);
if (comptime std.meta.trait.isContainer(Child) and @hasDecl(Child, "Class") and @hasDecl(Child.Class, "isJavaScriptCoreClass")) {
return Child.Class.make(context, value);
}
}
if (comptime Info == .Struct) {
if (comptime @hasDecl(Type, "Class") and @hasDecl(Type.Class, "isJavaScriptCoreClass")) {
if (comptime !@hasDecl(Type, "finalize")) {
@compileError(std.fmt.comptimePrint("JSC class {s} must implement finalize to prevent memory leaks", .{Type.Class.name}));
}
if (comptime !@hasDecl(Type, "toJS")) {
var val = bun.default_allocator.create(Type) catch unreachable;
val.* = value;
return Type.Class.make(context, val);
}
}
}
if (comptime @hasDecl(Type, "toJS") and @typeInfo(@TypeOf(@field(Type, "toJS"))).Fn.params.len == 2) {
var val = bun.default_allocator.create(Type) catch unreachable;
val.* = value;
return val.toJS(context).asObjectRef();
}
const res = value.toJS(context, exception);
if (@TypeOf(res) == JSC.C.JSValueRef) {
return res;
} else if (@TypeOf(res) == JSC.JSValue) {
return res.asObjectRef();
}
},
};
}
};
};
pub const Properties = struct {
pub const UTF8 = struct {
pub var filepath: string = "filepath";
pub const module: string = "module";
pub const globalThis: string = "globalThis";
pub const exports: string = "exports";
pub const log: string = "log";
pub const debug: string = "debug";
pub const name: string = "name";
pub const info: string = "info";
pub const error_: string = "error";
pub const warn: string = "warn";
pub const console: string = "console";
pub const require: string = "require";
pub const description: string = "description";
pub const initialize_bundled_module: string = "$$m";
pub const load_module_function: string = "$lOaDuRcOdE$";
pub const window: string = "window";
pub const default: string = "default";
pub const include: string = "include";
pub const env: string = "env";
pub const GET = "GET";
pub const PUT = "PUT";
pub const POST = "POST";
pub const PATCH = "PATCH";
pub const HEAD = "HEAD";
pub const OPTIONS = "OPTIONS";
pub const navigate = "navigate";
pub const follow = "follow";
};
pub const Refs = struct {
pub var empty_string_ptr = [_]u8{0};
pub var empty_string: js.JSStringRef = undefined;
};
pub fn init() void {
Refs.empty_string = js.JSStringCreateWithUTF8CString(&Refs.empty_string_ptr);
}
};
const JSValue = JSC.JSValue;
const ZigString = JSC.ZigString;
pub const PathString = bun.PathString;
pub fn JSError(
_: std.mem.Allocator,
comptime fmt: string,
args: anytype,
ctx: js.JSContextRef,
exception: ExceptionValueRef,
) void {
@setCold(true);
exception.* = createError(ctx, fmt, args).asObjectRef();
}
pub fn createError(
globalThis: *JSC.JSGlobalObject,
comptime fmt: string,
args: anytype,
) JSC.JSValue {
if (comptime std.meta.fields(@TypeOf(args)).len == 0) {
var zig_str = JSC.ZigString.init(fmt);
if (comptime !strings.isAllASCIISimple(fmt)) {
zig_str.markUTF16();
}
return zig_str.toErrorInstance(globalThis);
} else {
var fallback = std.heap.stackFallback(256, default_allocator);
var allocator = fallback.get();
var buf = std.fmt.allocPrint(allocator, fmt, args) catch unreachable;
var zig_str = JSC.ZigString.init(buf);
zig_str.detectEncoding();
// it alwayas clones
const res = zig_str.toErrorInstance(globalThis);
allocator.free(buf);
return res;
}
}
pub fn throwTypeError(
code: JSC.Node.ErrorCode,
comptime fmt: string,
args: anytype,
ctx: js.JSContextRef,
exception: ExceptionValueRef,
) void {
exception.* = toTypeError(code, fmt, args, ctx).asObjectRef();
}
pub fn toTypeErrorWithCode(
code: []const u8,
comptime fmt: string,
args: anytype,
ctx: js.JSContextRef,
) JSC.JSValue {
@setCold(true);
var zig_str: JSC.ZigString = undefined;
if (comptime std.meta.fields(@TypeOf(args)).len == 0) {
zig_str = JSC.ZigString.init(fmt);
zig_str.detectEncoding();
} else {
var buf = std.fmt.allocPrint(default_allocator, fmt, args) catch unreachable;
zig_str = JSC.ZigString.init(buf);
zig_str.detectEncoding();
zig_str.mark();
}
const code_str = ZigString.init(code);
return JSC.JSValue.createTypeError(&zig_str, &code_str, ctx.ptr());
}
pub fn toTypeError(
code: JSC.Node.ErrorCode,
comptime fmt: string,
args: anytype,
ctx: js.JSContextRef,
) JSC.JSValue {
return toTypeErrorWithCode(@tagName(code), fmt, args, ctx);
}
pub fn throwInvalidArguments(
comptime fmt: string,
args: anytype,
ctx: js.JSContextRef,
exception: ExceptionValueRef,
) void {
@setCold(true);
return throwTypeError(JSC.Node.ErrorCode.ERR_INVALID_ARG_TYPE, fmt, args, ctx, exception);
}
pub fn toInvalidArguments(
comptime fmt: string,
args: anytype,
ctx: js.JSContextRef,
) JSC.JSValue {
@setCold(true);
return toTypeError(JSC.Node.ErrorCode.ERR_INVALID_ARG_TYPE, fmt, args, ctx);
}
pub fn getAllocator(_: js.JSContextRef) std.mem.Allocator {
return default_allocator;
}
/// Print a JSValue to stdout; this is only meant for debugging purposes
pub fn dump(value: JSValue, globalObject: *JSC.JSGlobalObject) !void {
var formatter = JSC.ZigConsoleClient.Formatter{ .globalThis = globalObject };
try Output.errorWriter().print("{}\n", .{value.toFmt(globalObject, &formatter)});
Output.flush();
}
pub const JSStringList = std.ArrayList(js.JSStringRef);
pub const ArrayBuffer = extern struct {
ptr: [*]u8 = undefined,
offset: u32 = 0,
len: u32 = 0,
byte_len: u32 = 0,
typed_array_type: JSC.JSValue.JSType = .Cell,
value: JSC.JSValue = JSC.JSValue.zero,
shared: bool = false,
pub const Strong = struct {
array_buffer: ArrayBuffer,
held: JSC.Strong = .{},
pub fn clear(this: *ArrayBuffer.Strong) void {
var ref: *JSC.napi.Ref = this.ref orelse return;
ref.set(JSC.JSValue.zero);
}
pub fn slice(this: *const ArrayBuffer.Strong) []u8 {
return this.array_buffer.slice();
}
pub fn deinit(this: *ArrayBuffer.Strong) void {
this.held.deinit();
}
};
pub const empty = ArrayBuffer{ .offset = 0, .len = 0, .byte_len = 0, .typed_array_type = .Uint8Array, .ptr = undefined };
pub const name = "Bun__ArrayBuffer";
pub const Stream = std.io.FixedBufferStream([]u8);
pub inline fn stream(this: ArrayBuffer) Stream {
return Stream{ .pos = 0, .buf = this.slice() };
}
pub fn create(globalThis: *JSC.JSGlobalObject, bytes: []const u8, comptime kind: BinaryType) JSValue {
JSC.markBinding(@src());
return switch (comptime kind) {
.Uint8Array => Bun__createUint8ArrayForCopy(globalThis, bytes.ptr, bytes.len, false),
.Buffer => Bun__createUint8ArrayForCopy(globalThis, bytes.ptr, bytes.len, true),
.ArrayBuffer => Bun__createArrayBufferForCopy(globalThis, bytes.ptr, bytes.len),
else => @compileError("Not implemented yet"),
};
}
pub fn createEmpty(globalThis: *JSC.JSGlobalObject, comptime kind: JSC.JSValue.JSType) JSValue {
JSC.markBinding(@src());
return switch (comptime kind) {
.Uint8Array => Bun__createUint8ArrayForCopy(globalThis, null, 0, false),
.ArrayBuffer => Bun__createArrayBufferForCopy(globalThis, null, 0),
else => @compileError("Not implemented yet"),
};
}
pub fn createBuffer(globalThis: *JSC.JSGlobalObject, bytes: []const u8) JSValue {
JSC.markBinding(@src());
return Bun__createUint8ArrayForCopy(globalThis, bytes.ptr, bytes.len, true);
}
extern "C" fn Bun__createUint8ArrayForCopy(*JSC.JSGlobalObject, ptr: ?*const anyopaque, len: usize, buffer: bool) JSValue;
extern "C" fn Bun__createArrayBufferForCopy(*JSC.JSGlobalObject, ptr: ?*const anyopaque, len: usize) JSValue;
pub fn fromTypedArray(ctx: JSC.C.JSContextRef, value: JSC.JSValue) ArrayBuffer {
var out = std.mem.zeroes(ArrayBuffer);
std.debug.assert(value.asArrayBuffer_(ctx.ptr(), &out));
out.value = value;
return out;
}
pub fn fromBytes(bytes: []u8, typed_array_type: JSC.JSValue.JSType) ArrayBuffer {
return ArrayBuffer{ .offset = 0, .len = @as(u32, @intCast(bytes.len)), .byte_len = @as(u32, @intCast(bytes.len)), .typed_array_type = typed_array_type, .ptr = bytes.ptr };
}
pub fn toJSUnchecked(this: ArrayBuffer, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.JSValue {
// The reason for this is
// JSC C API returns a detached arraybuffer
// if you pass it a zero-length TypedArray
// we don't ever want to send the user a detached arraybuffer
// that's just silly.
if (this.byte_len == 0) {
if (this.typed_array_type == .ArrayBuffer) {
return create(ctx, "", .ArrayBuffer);
}
if (this.typed_array_type == .Uint8Array) {
return create(ctx, "", .Uint8Array);
}
// TODO: others
}
if (this.typed_array_type == .ArrayBuffer) {
return JSC.JSValue.fromRef(JSC.C.JSObjectMakeArrayBufferWithBytesNoCopy(
ctx,
this.ptr,
this.byte_len,
MarkedArrayBuffer_deallocator,
@as(*anyopaque, @ptrFromInt(@intFromPtr(&bun.default_allocator))),
exception,
));
}
return JSC.JSValue.fromRef(JSC.C.JSObjectMakeTypedArrayWithBytesNoCopy(
ctx,
this.typed_array_type.toC(),
this.ptr,
this.byte_len,
MarkedArrayBuffer_deallocator,
@as(*anyopaque, @ptrFromInt(@intFromPtr(&bun.default_allocator))),
exception,
));
}
const log = Output.scoped(.ArrayBuffer, false);
pub fn toJS(this: ArrayBuffer, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.JSValue {
if (!this.value.isEmpty()) {
return this.value;
}
// If it's not a mimalloc heap buffer, we're not going to call a deallocator
if (this.len > 0 and !bun.Mimalloc.mi_is_in_heap_region(this.ptr)) {
log("toJS but will never free: {d} bytes", .{this.len});
if (this.typed_array_type == .ArrayBuffer) {
return JSC.JSValue.fromRef(JSC.C.JSObjectMakeArrayBufferWithBytesNoCopy(
ctx,
this.ptr,
this.byte_len,
null,
null,
exception,
));
}
return JSC.JSValue.fromRef(JSC.C.JSObjectMakeTypedArrayWithBytesNoCopy(
ctx,
this.typed_array_type.toC(),
this.ptr,
this.byte_len,
null,
null,
exception,
));
}
return this.toJSUnchecked(ctx, exception);
}
pub fn toJSWithContext(
this: ArrayBuffer,
ctx: JSC.C.JSContextRef,
deallocator: ?*anyopaque,
callback: JSC.C.JSTypedArrayBytesDeallocator,
exception: JSC.C.ExceptionRef,
) JSC.JSValue {
if (!this.value.isEmpty()) {
return this.value;
}
if (this.typed_array_type == .ArrayBuffer) {
return JSC.JSValue.fromRef(JSC.C.JSObjectMakeArrayBufferWithBytesNoCopy(
ctx,
this.ptr,
this.byte_len,
callback,
deallocator,
exception,
));
}
return JSC.JSValue.fromRef(JSC.C.JSObjectMakeTypedArrayWithBytesNoCopy(
ctx,
this.typed_array_type.toC(),
this.ptr,
this.byte_len,
callback,
deallocator,
exception,
));
}
pub const fromArrayBuffer = fromTypedArray;
/// The equivalent of
///
/// ```js
/// new ArrayBuffer(view.buffer, view.byteOffset, view.byteLength)
/// ```
pub inline fn byteSlice(this: *const @This()) []u8 {
return this.ptr[this.offset .. this.offset + this.byte_len];
}
/// The equivalent of
///
/// ```js
/// new ArrayBuffer(view.buffer, view.byteOffset, view.byteLength)
/// ```
pub const slice = byteSlice;
pub inline fn asU16(this: *const @This()) []u16 {
return std.mem.bytesAsSlice(u16, @as([*]u16, @alignCast(this.ptr))[this.offset..this.byte_len]);
}
pub inline fn asU16Unaligned(this: *const @This()) []align(1) u16 {
return std.mem.bytesAsSlice(u16, @as([*]align(1) u16, @alignCast(this.ptr))[this.offset..this.byte_len]);
}
pub inline fn asU32(this: *const @This()) []u32 {
return std.mem.bytesAsSlice(u32, @as([*]u32, @alignCast(this.ptr))[this.offset..this.byte_len]);
}
};
pub const MarkedArrayBuffer = struct {
buffer: ArrayBuffer,
allocator: ?std.mem.Allocator = null,
pub const Stream = ArrayBuffer.Stream;
pub inline fn stream(this: *MarkedArrayBuffer) Stream {
return this.buffer.stream();
}
pub fn fromTypedArray(ctx: JSC.C.JSContextRef, value: JSC.JSValue) MarkedArrayBuffer {
return MarkedArrayBuffer{
.allocator = null,
.buffer = ArrayBuffer.fromTypedArray(ctx, value),
};
}
pub fn fromArrayBuffer(ctx: JSC.C.JSContextRef, value: JSC.JSValue) MarkedArrayBuffer {
return MarkedArrayBuffer{
.allocator = null,
.buffer = ArrayBuffer.fromArrayBuffer(ctx, value),
};
}
pub fn fromString(str: []const u8, allocator: std.mem.Allocator) !MarkedArrayBuffer {
var buf = try allocator.dupe(u8, str);
return MarkedArrayBuffer.fromBytes(buf, allocator, JSC.JSValue.JSType.Uint8Array);
}
pub fn fromJS(global: *JSC.JSGlobalObject, value: JSC.JSValue, _: JSC.C.ExceptionRef) ?MarkedArrayBuffer {
const array_buffer = value.asArrayBuffer(global) orelse return null;
return MarkedArrayBuffer{ .buffer = array_buffer, .allocator = null };
}
pub fn fromBytes(bytes: []u8, allocator: std.mem.Allocator, typed_array_type: JSC.JSValue.JSType) MarkedArrayBuffer {
return MarkedArrayBuffer{
.buffer = ArrayBuffer.fromBytes(bytes, typed_array_type),
.allocator = allocator,
};
}
pub const empty = MarkedArrayBuffer{
.allocator = null,
.buffer = ArrayBuffer.empty,
};
pub inline fn slice(this: *const @This()) []u8 {
return this.buffer.byteSlice();
}
pub fn destroy(this: *MarkedArrayBuffer) void {
const content = this.*;
if (this.allocator) |allocator| {
this.allocator = null;
allocator.free(content.buffer.slice());
allocator.destroy(this);
}
}
pub fn init(allocator: std.mem.Allocator, size: u32, typed_array_type: js.JSTypedArrayType) !*MarkedArrayBuffer {
const bytes = try allocator.alloc(u8, size);
var container = try allocator.create(MarkedArrayBuffer);
container.* = MarkedArrayBuffer.fromBytes(bytes, allocator, typed_array_type);
return container;
}
pub fn toNodeBuffer(this: MarkedArrayBuffer, ctx: js.JSContextRef) js.JSObjectRef {
return JSValue.createBufferWithCtx(ctx, this.buffer.byteSlice(), this.buffer.ptr, MarkedArrayBuffer_deallocator).asObjectRef();
}
pub fn toJSObjectRef(this: MarkedArrayBuffer, ctx: js.JSContextRef, exception: js.ExceptionRef) js.JSObjectRef {
if (!this.buffer.value.isEmptyOrUndefinedOrNull()) {
return this.buffer.value.asObjectRef();
}
if (this.buffer.byte_len == 0) {
return js.JSObjectMakeTypedArray(
ctx,
this.buffer.typed_array_type.toC(),
0,
exception,
);
}
return js.JSObjectMakeTypedArrayWithBytesNoCopy(
ctx,
this.buffer.typed_array_type.toC(),
this.buffer.ptr,
this.buffer.byte_len,
MarkedArrayBuffer_deallocator,
this.buffer.ptr,
exception,
);
}
pub const toJS = toJSObjectRef;
};
// expensive heap reference-counted string type
// only use this for big strings
// like source code
// not little ones
pub const RefString = struct {
ptr: [*]const u8 = undefined,
len: usize = 0,
hash: Hash = 0,
impl: bun.WTF.StringImpl,
allocator: std.mem.Allocator,
ctx: ?*anyopaque = null,
onBeforeDeinit: ?*const Callback = null,
pub const Hash = u32;
pub const Map = std.HashMap(Hash, *JSC.RefString, IdentityContext(Hash), 80);
pub fn toJS(this: *RefString, global: *JSC.JSGlobalObject) JSValue {
return bun.String.init(this.impl).toJS(global);
}
pub const Callback = fn (ctx: *anyopaque, str: *RefString) void;
pub fn computeHash(input: []const u8) u32 {
return std.hash.XxHash32.hash(0, input);
}
pub fn slice(this: *RefString) []const u8 {
this.ref();
return this.leak();
}
pub fn ref(this: *RefString) void {
this.impl.ref();
}
pub fn leak(this: RefString) []const u8 {
@setRuntimeSafety(false);
return this.ptr[0..this.len];
}
pub fn deref(this: *RefString) void {
this.impl.deref();
}
pub export fn RefString__free(this: *anyopaque, _: *anyopaque, _: u32) void {
bun.cast(*RefString, this).deinit();
}
pub fn deinit(this: *RefString) void {
if (this.onBeforeDeinit) |onBeforeDeinit| {
onBeforeDeinit(this.ctx.?, this);
}
this.allocator.free(this.leak());
this.allocator.destroy(this);
}
};
comptime {
std.testing.refAllDecls(RefString);
}
pub export fn MarkedArrayBuffer_deallocator(bytes_: *anyopaque, _: *anyopaque) void {
const mimalloc = @import("../allocators/mimalloc.zig");
// zig's memory allocator interface won't work here
// mimalloc knows the size of things
// but we don't
// if (comptime Environment.allow_assert) {
// std.debug.assert(mimalloc.mi_check_owned(bytes_) or
// mimalloc.mi_heap_check_owned(JSC.VirtualMachine.get().arena.heap.?, bytes_));
// }
mimalloc.mi_free(bytes_);
}
pub export fn BlobArrayBuffer_deallocator(_: *anyopaque, blob: *anyopaque) void {
// zig's memory allocator interface won't work here
// mimalloc knows the size of things
// but we don't
var store = bun.cast(*JSC.WebCore.Blob.Store, blob);
store.deref();
}
const Expect = Test.Expect;
const DescribeScope = Test.DescribeScope;
const TestScope = Test.TestScope;
const NodeFS = JSC.Node.NodeFS;
const TextEncoder = WebCore.TextEncoder;
const TextDecoder = WebCore.TextDecoder;
const HTMLRewriter = JSC.Cloudflare.HTMLRewriter;
const Element = JSC.Cloudflare.Element;
const Comment = JSC.Cloudflare.Comment;
const TextChunk = JSC.Cloudflare.TextChunk;
const DocType = JSC.Cloudflare.DocType;
const EndTag = JSC.Cloudflare.EndTag;
const DocEnd = JSC.Cloudflare.DocEnd;
const AttributeIterator = JSC.Cloudflare.AttributeIterator;
const Blob = JSC.WebCore.Blob;
const Server = JSC.API.Server;
const SSLServer = JSC.API.SSLServer;
const DebugServer = JSC.API.DebugServer;
const DebugSSLServer = JSC.API.DebugSSLServer;
const SHA1 = JSC.API.Bun.Crypto.SHA1;
const MD5 = JSC.API.Bun.Crypto.MD5;
const MD4 = JSC.API.Bun.Crypto.MD4;
const SHA224 = JSC.API.Bun.Crypto.SHA224;
const SHA512 = JSC.API.Bun.Crypto.SHA512;
const SHA384 = JSC.API.Bun.Crypto.SHA384;
const SHA256 = JSC.API.Bun.Crypto.SHA256;
const SHA512_256 = JSC.API.Bun.Crypto.SHA512_256;
const MD5_SHA1 = JSC.API.Bun.Crypto.MD5_SHA1;
const FFI = JSC.FFI;
pub const JSPropertyNameIterator = struct {
array: js.JSPropertyNameArrayRef,
count: u32,
i: u32 = 0,
pub fn next(this: *JSPropertyNameIterator) ?js.JSStringRef {
if (this.i >= this.count) return null;
const i = this.i;
this.i += 1;
return js.JSPropertyNameArrayGetNameAtIndex(this.array, i);
}
};
pub const DOMEffect = struct {
reads: [4]ID = std.mem.zeroes([4]ID),
writes: [4]ID = std.mem.zeroes([4]ID),
pub const top = DOMEffect{
.reads = .{ ID.Heap, ID.Heap, ID.Heap, ID.Heap },
.writes = .{ ID.Heap, ID.Heap, ID.Heap, ID.Heap },
};
pub fn forRead(read: ID) DOMEffect {
return DOMEffect{
.reads = .{ read, ID.Heap, ID.Heap, ID.Heap },
.writes = .{ ID.Heap, ID.Heap, ID.Heap, ID.Heap },
};
}
pub fn forWrite(read: ID) DOMEffect {
return DOMEffect{
.writes = .{ read, ID.Heap, ID.Heap, ID.Heap },
.reads = .{ ID.Heap, ID.Heap, ID.Heap, ID.Heap },
};
}
pub const pure = DOMEffect{};
pub fn isPure(this: DOMEffect) bool {
return this.reads[0] == ID.InvalidAbstractHeap and this.writes[0] == ID.InvalidAbstractHeap;
}
pub const ID = enum(u8) {
InvalidAbstractHeap = 0,
World,
Stack,
Heap,
Butterfly_publicLength,
Butterfly_vectorLength,
GetterSetter_getter,
GetterSetter_setter,
JSCell_cellState,
JSCell_indexingType,
JSCell_structureID,
JSCell_typeInfoFlags,
JSObject_butterfly,
JSPropertyNameEnumerator_cachedPropertyNames,
RegExpObject_lastIndex,
NamedProperties,
IndexedInt32Properties,
IndexedDoubleProperties,
IndexedContiguousProperties,
IndexedArrayStorageProperties,
DirectArgumentsProperties,
ScopeProperties,
TypedArrayProperties,
/// Used to reflect the fact that some allocations reveal object identity */
HeapObjectCount,
RegExpState,
MathDotRandomState,
JSDateFields,
JSMapFields,
JSSetFields,
JSWeakMapFields,
JSWeakSetFields,
JSInternalFields,
InternalState,
CatchLocals,
Absolute,
/// DOMJIT tells the heap range with the pair of integers. */
DOMState,
/// Use this for writes only, to indicate that this may fire watchpoints. Usually this is never directly written but instead we test to see if a node clobbers this; it just so happens that you have to write world to clobber it. */
Watchpoint_fire,
/// Use these for reads only, just to indicate that if the world got clobbered, then this operation will not work. */
MiscFields,
/// Use this for writes only, just to indicate that hoisting the node is invalid. This works because we don't hoist anything that has any side effects at all. */
SideState,
};
};
fn DOMCallArgumentType(comptime Type: type) []const u8 {
const ChildType = if (@typeInfo(Type) == .Pointer) std.meta.Child(Type) else Type;
return switch (ChildType) {
i8, u8, i16, u16, i32 => "JSC::SpecInt32Only",
u32, i64, u64 => "JSC::SpecInt52Any",
f64 => "JSC::SpecDoubleReal",
bool => "JSC::SpecBoolean",
JSC.JSString => "JSC::SpecString",
JSC.JSUint8Array => "JSC::SpecUint8Array",
else => @compileError("Unknown DOM type: " ++ @typeName(Type)),
};
}
fn DOMCallArgumentTypeWrapper(comptime Type: type) []const u8 {
const ChildType = if (@typeInfo(Type) == .Pointer) std.meta.Child(Type) else Type;
return switch (ChildType) {
i32 => "int32_t",
f64 => "double",
u64 => "uint64_t",
i64 => "int64_t",
bool => "bool",
JSC.JSString => "JSC::JSString*",
JSC.JSUint8Array => "JSC::JSUint8Array*",
else => @compileError("Unknown DOM type: " ++ @typeName(Type)),
};
}
fn DOMCallResultType(comptime Type: type) []const u8 {
const ChildType = if (@typeInfo(Type) == .Pointer) std.meta.Child(Type) else Type;
return switch (ChildType) {
i32 => "JSC::SpecInt32Only",
bool => "JSC::SpecBoolean",
JSC.JSString => "JSC::SpecString",
JSC.JSUint8Array => "JSC::SpecUint8Array",
JSC.JSCell => "JSC::SpecCell",
u52, i52 => "JSC::SpecInt52Any",
f64 => "JSC::SpecDoubleReal",
else => "JSC::SpecHeapTop",
};
}
pub fn DOMCall(
comptime class_name: string,
comptime Container: type,
comptime functionName: string,
comptime ResultType: type,
comptime dom_effect: DOMEffect,
) type {
return extern struct {
const className = class_name;
pub const is_dom_call = true;
const Slowpath = @field(Container, functionName);
const SlowpathType = @TypeOf(@field(Container, functionName));
pub const shim = JSC.Shimmer(className, functionName, @This());
pub const name = class_name ++ "__" ++ functionName;
// Zig doesn't support @frameAddress(1)
// so we have to add a small wrapper fujnction
pub fn slowpath(
globalObject: *JSC.JSGlobalObject,
thisValue: JSC.JSValue,
arguments_ptr: [*]const JSC.JSValue,
arguments_len: usize,
) callconv(.C) JSValue {
return @call(.auto, @field(Container, functionName), .{
globalObject,
thisValue,
arguments_ptr[0..arguments_len],
});
}
pub const fastpath = @field(Container, functionName ++ "WithoutTypeChecks");
pub const Fastpath = @TypeOf(fastpath);
pub const Arguments = std.meta.ArgsTuple(Fastpath);
pub const Export = shim.exportFunctions(.{
.slowpath = slowpath,
.fastpath = fastpath,
});
pub fn put(globalObject: *JSC.JSGlobalObject, value: JSValue) void {
shim.cppFn("put", .{ globalObject, value });
}
pub const effect = dom_effect;