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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
|
const std = @import("std");
const Api = @import("../../api/schema.zig").Api;
const bun = @import("bun");
const RequestContext = @import("../../http.zig").RequestContext;
const MimeType = @import("../../http.zig").MimeType;
const ZigURL = @import("../../url.zig").URL;
const HTTPClient = @import("bun").HTTP;
const NetworkThread = HTTPClient.NetworkThread;
const AsyncIO = NetworkThread.AsyncIO;
const JSC = @import("bun").JSC;
const js = JSC.C;
const Method = @import("../../http/method.zig").Method;
const FetchHeaders = JSC.FetchHeaders;
const ObjectPool = @import("../../pool.zig").ObjectPool;
const SystemError = JSC.SystemError;
const Output = @import("bun").Output;
const MutableString = @import("bun").MutableString;
const strings = @import("bun").strings;
const string = @import("bun").string;
const default_allocator = @import("bun").default_allocator;
const FeatureFlags = @import("bun").FeatureFlags;
const ArrayBuffer = @import("../base.zig").ArrayBuffer;
const Properties = @import("../base.zig").Properties;
const NewClass = @import("../base.zig").NewClass;
const d = @import("../base.zig").d;
const castObj = @import("../base.zig").castObj;
const getAllocator = @import("../base.zig").getAllocator;
const JSPrivateDataPtr = @import("../base.zig").JSPrivateDataPtr;
const GetJSPrivateData = @import("../base.zig").GetJSPrivateData;
const Environment = @import("../../env.zig");
const ZigString = JSC.ZigString;
const IdentityContext = @import("../../identity_context.zig").IdentityContext;
const JSPromise = JSC.JSPromise;
const JSValue = JSC.JSValue;
const JSError = JSC.JSError;
const JSGlobalObject = JSC.JSGlobalObject;
const NullableAllocator = @import("../../nullable_allocator.zig").NullableAllocator;
const VirtualMachine = JSC.VirtualMachine;
const Task = JSC.Task;
const JSPrinter = bun.js_printer;
const picohttp = @import("bun").picohttp;
const StringJoiner = @import("../../string_joiner.zig");
const uws = @import("bun").uws;
const Blob = JSC.WebCore.Blob;
const InlineBlob = JSC.WebCore.InlineBlob;
const AnyBlob = JSC.WebCore.AnyBlob;
const InternalBlob = JSC.WebCore.InternalBlob;
const Response = JSC.WebCore.Response;
const Request = JSC.WebCore.Request;
// https://developer.mozilla.org/en-US/docs/Web/API/Body
pub const Body = struct {
init: Init = Init{ .headers = null, .status_code = 200 },
value: Value, // = Value.empty,
pub inline fn len(this: *const Body) Blob.SizeType {
return this.value.size();
}
pub fn slice(this: *const Body) []const u8 {
return this.value.slice();
}
pub fn use(this: *Body) Blob {
return this.value.use();
}
pub fn clone(this: *Body, globalThis: *JSGlobalObject) Body {
return Body{
.init = this.init.clone(globalThis),
.value = this.value.clone(globalThis),
};
}
pub fn writeFormat(this: *const Body, formatter: *JSC.Formatter, writer: anytype, comptime enable_ansi_colors: bool) !void {
const Writer = @TypeOf(writer);
try formatter.writeIndent(Writer, writer);
try writer.writeAll("bodyUsed: ");
formatter.printAs(.Boolean, Writer, writer, JSC.JSValue.jsBoolean(this.value == .Used), .BooleanObject, enable_ansi_colors);
formatter.printComma(Writer, writer, enable_ansi_colors) catch unreachable;
try writer.writeAll("\n");
// if (this.init.headers) |headers| {
// try formatter.writeIndent(Writer, writer);
// try writer.writeAll("headers: ");
// try headers.leak().writeFormat(formatter, writer, comptime enable_ansi_colors);
// try writer.writeAll("\n");
// }
try formatter.writeIndent(Writer, writer);
try writer.writeAll("status: ");
formatter.printAs(.Double, Writer, writer, JSC.JSValue.jsNumber(this.init.status_code), .NumberObject, enable_ansi_colors);
if (this.value == .Blob) {
try formatter.printComma(Writer, writer, enable_ansi_colors);
try writer.writeAll("\n");
try formatter.writeIndent(Writer, writer);
try this.value.Blob.writeFormat(formatter, writer, enable_ansi_colors);
} else if (this.value == .InternalBlob) {
try formatter.printComma(Writer, writer, enable_ansi_colors);
try writer.writeAll("\n");
try formatter.writeIndent(Writer, writer);
try Blob.writeFormatForSize(this.value.size(), writer, enable_ansi_colors);
} else if (this.value == .Locked) {
if (this.value.Locked.readable) |stream| {
try formatter.printComma(Writer, writer, enable_ansi_colors);
try writer.writeAll("\n");
try formatter.writeIndent(Writer, writer);
formatter.printAs(.Object, Writer, writer, stream.value, stream.value.jsType(), enable_ansi_colors);
}
}
}
pub fn deinit(this: *Body, _: std.mem.Allocator) void {
if (this.init.headers) |headers| {
this.init.headers = null;
headers.deref();
}
this.value.deinit();
}
pub const Init = struct {
headers: ?*FetchHeaders = null,
status_code: u16,
method: Method = Method.GET,
pub fn clone(this: Init, _: *JSGlobalObject) Init {
var that = this;
var headers = this.headers;
if (headers) |head| {
that.headers = head.cloneThis();
}
return that;
}
pub fn init(allocator: std.mem.Allocator, ctx: *JSGlobalObject, response_init: JSC.JSValue, js_type: JSC.JSValue.JSType) !?Init {
var result = Init{ .status_code = 200 };
if (!response_init.isCell())
return null;
if (js_type == .DOMWrapper) {
// fast path: it's a Request object or a Response object
// we can skip calling JS getters
if (response_init.as(Request)) |req| {
if (req.headers) |headers| {
result.headers = headers.cloneThis();
}
result.method = req.method;
return result;
}
if (response_init.as(Response)) |req| {
return req.body.init.clone(ctx);
}
}
if (response_init.fastGet(ctx, .headers)) |headers| {
if (headers.as(FetchHeaders)) |orig| {
result.headers = orig.cloneThis();
} else {
result.headers = FetchHeaders.createFromJS(ctx.ptr(), headers);
}
}
if (response_init.fastGet(ctx, .status)) |status_value| {
const number = status_value.to(i32);
if (100 <= number and number < 1000)
result.status_code = @truncate(u16, @intCast(u32, number));
}
if (response_init.fastGet(ctx, .method)) |method_value| {
var method_str = method_value.toSlice(ctx, allocator);
defer method_str.deinit();
if (method_str.len > 0) {
result.method = Method.which(method_str.slice()) orelse .GET;
}
}
return result;
}
};
pub const PendingValue = struct {
promise: ?JSValue = null,
readable: ?JSC.WebCore.ReadableStream = null,
// writable: JSC.WebCore.Sink
global: *JSGlobalObject,
task: ?*anyopaque = null,
/// runs after the data is available.
onReceiveValue: ?*const fn (ctx: *anyopaque, value: *Value) void = null,
/// conditionally runs when requesting data
/// used in HTTP server to ignore request bodies unless asked for it
onStartBuffering: ?*const fn (ctx: *anyopaque) void = null,
onStartStreaming: ?*const fn (ctx: *anyopaque) JSC.WebCore.DrainResult = null,
deinit: bool = false,
action: Action = Action.none,
pub fn toAnyBlob(this: *PendingValue) ?AnyBlob {
if (this.promise != null)
return null;
return this.toAnyBlobAllowPromise();
}
pub fn toAnyBlobAllowPromise(this: *PendingValue) ?AnyBlob {
var stream = if (this.readable != null) &this.readable.? else return null;
if (stream.toAnyBlob(this.global)) |blob| {
this.readable = null;
return blob;
}
return null;
}
pub fn setPromise(value: *PendingValue, globalThis: *JSC.JSGlobalObject, action: Action) JSValue {
value.action = action;
if (value.readable) |readable| {
// switch (readable.ptr) {
// .JavaScript
// }
switch (action) {
.getText, .getJSON, .getBlob, .getArrayBuffer => {
switch (readable.ptr) {
.Blob => unreachable,
else => {},
}
value.promise = switch (action) {
.getJSON => globalThis.readableStreamToJSON(readable.value),
.getArrayBuffer => globalThis.readableStreamToArrayBuffer(readable.value),
.getText => globalThis.readableStreamToText(readable.value),
.getBlob => globalThis.readableStreamToBlob(readable.value),
else => unreachable,
};
value.promise.?.ensureStillAlive();
readable.value.unprotect();
// js now owns the memory
value.readable = null;
return value.promise.?;
},
.none => {},
}
}
{
var promise = JSC.JSPromise.create(globalThis);
const promise_value = promise.asValue(globalThis);
value.promise = promise_value;
if (value.onStartBuffering) |onStartBuffering| {
value.onStartBuffering = null;
onStartBuffering(value.task.?);
}
return promise_value;
}
}
pub const Action = enum {
none,
getText,
getJSON,
getArrayBuffer,
getBlob,
};
};
/// This is a duplex stream!
pub const Value = union(Tag) {
Blob: Blob,
/// Single-use Blob
/// Avoids a heap allocation.
InternalBlob: InternalBlob,
/// Single-use Blob that stores the bytes in the Value itself.
// InlineBlob: InlineBlob,
Locked: PendingValue,
Used: void,
Empty: void,
Error: JSValue,
pub fn toBlobIfPossible(this: *Value) void {
if (this.* != .Locked)
return;
if (this.Locked.toAnyBlob()) |blob| {
this.* = switch (blob) {
.Blob => .{ .Blob = blob.Blob },
.InternalBlob => .{ .InternalBlob = blob.InternalBlob },
// .InlineBlob => .{ .InlineBlob = blob.InlineBlob },
};
}
}
pub fn size(this: *const Value) Blob.SizeType {
return switch (this.*) {
.Blob => this.Blob.size,
.InternalBlob => @truncate(Blob.SizeType, this.InternalBlob.sliceConst().len),
// .InlineBlob => @truncate(Blob.SizeType, this.InlineBlob.sliceConst().len),
else => 0,
};
}
pub fn estimatedSize(this: *const Value) usize {
return switch (this.*) {
.InternalBlob => this.InternalBlob.sliceConst().len,
// .InlineBlob => this.InlineBlob.sliceConst().len,
else => 0,
};
}
pub fn createBlobValue(data: []u8, allocator: std.mem.Allocator, was_string: bool) Value {
// if (data.len <= InlineBlob.available_bytes) {
// var _blob = InlineBlob{
// .bytes = undefined,
// .was_string = was_string,
// .len = @truncate(InlineBlob.IntSize, data.len),
// };
// @memcpy(&_blob.bytes, data.ptr, data.len);
// allocator.free(data);
// return Value{
// .InlineBlob = _blob,
// };
// }
return Value{
.InternalBlob = InternalBlob{
.bytes = std.ArrayList(u8).fromOwnedSlice(allocator, data),
.was_string = was_string,
},
};
}
pub const Tag = enum {
Blob,
InternalBlob,
// InlineBlob,
Locked,
Used,
Empty,
Error,
};
// pub const empty = Value{ .Empty = void{} };
pub fn toReadableStream(this: *Value, globalThis: *JSGlobalObject) JSValue {
JSC.markBinding(@src());
switch (this.*) {
.Used, .Empty => {
return JSC.WebCore.ReadableStream.empty(globalThis);
},
.InternalBlob,
.Blob,
// .InlineBlob,
=> {
var blob = this.use();
defer blob.detach();
blob.resolveSize();
const value = JSC.WebCore.ReadableStream.fromBlob(globalThis, &blob, blob.size);
this.* = .{
.Locked = .{
.readable = JSC.WebCore.ReadableStream.fromJS(value, globalThis).?,
.global = globalThis,
},
};
this.Locked.readable.?.value.protect();
return value;
},
.Locked => {
var locked = &this.Locked;
if (locked.readable) |readable| {
return readable.value;
}
var drain_result: JSC.WebCore.DrainResult = .{
.estimated_size = 0,
};
if (locked.onStartStreaming) |drain| {
locked.onStartStreaming = null;
drain_result = drain(locked.task.?);
}
if (drain_result == .empty or drain_result == .aborted) {
this.* = .{ .Empty = void{} };
return JSC.WebCore.ReadableStream.empty(globalThis);
}
var reader = bun.default_allocator.create(JSC.WebCore.ByteStream.Source) catch unreachable;
reader.* = .{
.context = undefined,
.globalThis = globalThis,
};
reader.context.setup();
if (drain_result == .estimated_size) {
reader.context.highWaterMark = @truncate(Blob.SizeType, drain_result.estimated_size);
reader.context.size_hint = @truncate(Blob.SizeType, drain_result.estimated_size);
} else if (drain_result == .owned) {
reader.context.buffer = drain_result.owned.list;
reader.context.size_hint = @truncate(Blob.SizeType, drain_result.owned.size_hint);
}
locked.readable = .{
.ptr = .{ .Bytes = &reader.context },
.value = reader.toJS(globalThis),
};
locked.readable.?.value.protect();
return locked.readable.?.value;
},
else => unreachable,
}
}
pub fn fromJS(globalThis: *JSGlobalObject, value: JSValue) ?Value {
value.ensureStillAlive();
if (value.isEmptyOrUndefinedOrNull()) {
return Body.Value{
.Empty = void{},
};
}
const js_type = value.jsType();
if (js_type.isStringLike()) {
var str = value.getZigString(globalThis);
if (str.len == 0) {
return Body.Value{
.Empty = {},
};
}
// if (str.is16Bit()) {
// if (str.maxUTF8ByteLength() < InlineBlob.available_bytes or
// (str.len <= InlineBlob.available_bytes and str.utf8ByteLength() <= InlineBlob.available_bytes))
// {
// var blob = InlineBlob{
// .was_string = true,
// .bytes = undefined,
// .len = 0,
// };
// if (comptime Environment.allow_assert) {
// std.debug.assert(str.utf8ByteLength() <= InlineBlob.available_bytes);
// }
// const result = strings.copyUTF16IntoUTF8(
// blob.bytes[0..blob.bytes.len],
// []const u16,
// str.utf16SliceAligned(),
// );
// blob.len = @intCast(InlineBlob.IntSize, result.written);
// std.debug.assert(@as(usize, result.read) == str.len);
// std.debug.assert(@as(usize, result.written) <= InlineBlob.available_bytes);
// return Body.Value{
// .InlineBlob = blob,
// };
// }
// } else {
// if (str.maxUTF8ByteLength() <= InlineBlob.available_bytes or
// (str.len <= InlineBlob.available_bytes and str.utf8ByteLength() <= InlineBlob.available_bytes))
// {
// var blob = InlineBlob{
// .was_string = true,
// .bytes = undefined,
// .len = 0,
// };
// if (comptime Environment.allow_assert) {
// std.debug.assert(str.utf8ByteLength() <= InlineBlob.available_bytes);
// }
// const result = strings.copyLatin1IntoUTF8(
// blob.bytes[0..blob.bytes.len],
// []const u8,
// str.slice(),
// );
// blob.len = @intCast(InlineBlob.IntSize, result.written);
// std.debug.assert(@as(usize, result.read) == str.len);
// std.debug.assert(@as(usize, result.written) <= InlineBlob.available_bytes);
// return Body.Value{
// .InlineBlob = blob,
// };
// }
// }
var buffer = str.toOwnedSlice(bun.default_allocator) catch {
globalThis.vm().throwError(globalThis, ZigString.static("Failed to clone string").toErrorInstance(globalThis));
return null;
};
return Body.Value{
.InternalBlob = .{
.bytes = std.ArrayList(u8).fromOwnedSlice(bun.default_allocator, buffer),
.was_string = true,
},
};
}
if (js_type.isTypedArray()) {
if (value.asArrayBuffer(globalThis)) |buffer| {
var bytes = buffer.byteSlice();
if (bytes.len == 0) {
return Body.Value{
.Empty = {},
};
}
// if (bytes.len <= InlineBlob.available_bytes) {
// return Body.Value{
// .InlineBlob = InlineBlob.init(bytes),
// };
// }
return Body.Value{
.InternalBlob = .{
.bytes = std.ArrayList(u8){
.items = bun.default_allocator.dupe(u8, bytes) catch {
globalThis.vm().throwError(globalThis, ZigString.static("Failed to clone ArrayBufferView").toErrorInstance(globalThis));
return null;
},
.capacity = bytes.len,
.allocator = bun.default_allocator,
},
.was_string = false,
},
};
}
}
if (js_type == .DOMWrapper) {
if (value.as(Blob)) |blob| {
return Body.Value{
.Blob = blob.dupe(),
};
}
}
value.ensureStillAlive();
if (JSC.WebCore.ReadableStream.fromJS(value, globalThis)) |readable| {
switch (readable.ptr) {
.Blob => |blob| {
var result: Value = .{
.Blob = Blob.initWithStore(blob.store, globalThis),
};
blob.store.ref();
readable.done();
if (!blob.done) {
blob.done = true;
blob.deinit();
}
return result;
},
else => {},
}
return Body.Value.fromReadableStream(readable, globalThis);
}
return Body.Value{
.Blob = Blob.get(globalThis, value, true, false) catch |err| {
if (err == error.InvalidArguments) {
globalThis.throwInvalidArguments("Expected an Array", .{});
return null;
}
globalThis.throwInvalidArguments("Invalid Body object", .{});
return null;
},
};
}
pub fn fromReadableStream(readable: JSC.WebCore.ReadableStream, globalThis: *JSGlobalObject) Value {
if (readable.isLocked(globalThis)) {
return .{ .Error = ZigString.init("Cannot use a locked ReadableStream").toErrorInstance(globalThis) };
}
readable.value.protect();
return .{
.Locked = .{
.readable = readable,
.global = globalThis,
},
};
}
pub fn resolve(to_resolve: *Value, new: *Value, global: *JSGlobalObject) void {
if (to_resolve.* == .Locked) {
var locked = &to_resolve.Locked;
if (locked.readable) |readable| {
readable.done();
locked.readable = null;
}
if (locked.onReceiveValue) |callback| {
locked.onReceiveValue = null;
callback(locked.task.?, new);
return;
}
if (locked.promise) |promise_| {
const promise = promise_.asAnyPromise().?;
locked.promise = null;
switch (locked.action) {
.getText => {
switch (new.*) {
.InternalBlob,
// .InlineBlob,
=> {
var blob = new.useAsAnyBlob();
promise.resolve(global, blob.toString(global, .transfer));
},
else => {
var blob = new.use();
promise.resolve(global, blob.toString(global, .transfer));
},
}
},
.getJSON => {
var blob = new.useAsAnyBlob();
const json_value = blob.toJSON(global, .share);
blob.detach();
if (json_value.isAnyError()) {
promise.reject(global, json_value);
} else {
promise.resolve(global, json_value);
}
},
.getArrayBuffer => {
var blob = new.useAsAnyBlob();
promise.resolve(global, blob.toArrayBuffer(global, .transfer));
},
else => {
var ptr = bun.default_allocator.create(Blob) catch unreachable;
ptr.* = new.use();
ptr.allocator = bun.default_allocator;
promise.resolve(global, ptr.toJS(global));
},
}
JSC.C.JSValueUnprotect(global, promise_.asObjectRef());
}
}
}
pub fn slice(this: *const Value) []const u8 {
return switch (this.*) {
.Blob => this.Blob.sharedView(),
.InternalBlob => this.InternalBlob.sliceConst(),
// .InlineBlob => this.InlineBlob.sliceConst(),
else => "",
};
}
pub fn use(this: *Value) Blob {
this.toBlobIfPossible();
switch (this.*) {
.Blob => {
var new_blob = this.Blob;
std.debug.assert(new_blob.allocator == null); // owned by Body
this.* = .{ .Used = {} };
return new_blob;
},
.InternalBlob => {
var new_blob = Blob.init(
this.InternalBlob.toOwnedSlice(),
// we will never resize it from here
// we have to use the default allocator
// even if it was actually allocated on a different thread
bun.default_allocator,
JSC.VirtualMachine.get().global,
);
if (this.InternalBlob.was_string) {
new_blob.content_type = MimeType.text.value;
}
this.* = .{ .Used = {} };
return new_blob;
},
// .InlineBlob => {
// const cloned = this.InlineBlob.bytes;
// const new_blob = Blob.create(
// cloned[0..this.InlineBlob.len],
// bun.default_allocator,
// JSC.VirtualMachine.get().global,
// this.InlineBlob.was_string,
// );
// this.* = .{ .Used = {} };
// return new_blob;
// },
else => {
return Blob.initEmpty(undefined);
},
}
}
pub fn tryUseAsAnyBlob(this: *Value) ?AnyBlob {
const any_blob: AnyBlob = switch (this.*) {
.Blob => AnyBlob{ .Blob = this.Blob },
.InternalBlob => AnyBlob{ .InternalBlob = this.InternalBlob },
// .InlineBlob => AnyBlob{ .InlineBlob = this.InlineBlob },
.Locked => this.Locked.toAnyBlobAllowPromise() orelse return null,
else => return null,
};
this.* = .{ .Used = {} };
return any_blob;
}
pub fn useAsAnyBlob(this: *Value) AnyBlob {
const any_blob: AnyBlob = switch (this.*) {
.Blob => .{ .Blob = this.Blob },
.InternalBlob => .{ .InternalBlob = this.InternalBlob },
// .InlineBlob => .{ .InlineBlob = this.InlineBlob },
.Locked => this.Locked.toAnyBlobAllowPromise() orelse AnyBlob{ .Blob = .{} },
else => .{ .Blob = Blob.initEmpty(undefined) },
};
this.* = .{ .Used = {} };
return any_blob;
}
pub fn toErrorInstance(this: *Value, error_instance: JSC.JSValue, global: *JSGlobalObject) void {
if (this.* == .Locked) {
var locked = this.Locked;
locked.deinit = true;
if (locked.promise) |promise| {
if (promise.asAnyPromise()) |internal| {
internal.reject(global, error_instance);
}
JSC.C.JSValueUnprotect(global, promise.asObjectRef());
locked.promise = null;
}
if (locked.readable) |readable| {
readable.done();
locked.readable = null;
}
this.* = .{ .Error = error_instance };
if (locked.onReceiveValue) |onReceiveValue| {
locked.onReceiveValue = null;
onReceiveValue(locked.task.?, this);
}
return;
}
this.* = .{ .Error = error_instance };
}
pub fn toErrorString(this: *Value, comptime err: string, global: *JSGlobalObject) void {
var error_str = ZigString.init(err);
var error_instance = error_str.toErrorInstance(global);
return this.toErrorInstance(error_instance, global);
}
pub fn toError(this: *Value, err: anyerror, global: *JSGlobalObject) void {
var error_str = ZigString.init(std.fmt.allocPrint(
bun.default_allocator,
"Error reading file {s}",
.{@errorName(err)},
) catch unreachable);
error_str.mark();
var error_instance = error_str.toErrorInstance(global);
return this.toErrorInstance(error_instance, global);
}
pub fn deinit(this: *Value) void {
const tag = @as(Tag, this.*);
if (tag == .Locked) {
if (!this.Locked.deinit) {
this.Locked.deinit = true;
if (this.Locked.readable) |*readable| {
readable.done();
}
}
return;
}
if (tag == .InternalBlob) {
this.InternalBlob.clearAndFree();
this.* = Value{ .Empty = {} }; //Value.empty;
}
if (tag == .Blob) {
this.Blob.deinit();
this.* = Value{ .Empty = {} }; //Value.empty;
}
if (tag == .Error) {
JSC.C.JSValueUnprotect(VirtualMachine.get().global, this.Error.asObjectRef());
}
}
pub fn clone(this: *Value, globalThis: *JSC.JSGlobalObject) Value {
if (this.* == .InternalBlob) {
var internal_blob = this.InternalBlob;
this.* = .{
.Blob = Blob.init(
internal_blob.toOwnedSlice(),
internal_blob.bytes.allocator,
globalThis,
),
};
}
// if (this.* == .InlineBlob) {
// return this.*;
// }
if (this.* == .Blob) {
return Value{ .Blob = this.Blob.dupe() };
}
return Value{ .Empty = {} };
}
};
pub fn @"404"(_: js.JSContextRef) Body {
return Body{
.init = Init{
.headers = null,
.status_code = 404,
},
.value = Value{ .Empty = {} }, //Value.empty,
};
}
pub fn @"200"(_: js.JSContextRef) Body {
return Body{
.init = Init{
.status_code = 200,
},
.value = Value{ .Empty = {} }, //Value.empty,
};
}
pub fn extract(
globalThis: *JSGlobalObject,
value: JSValue,
) ?Body {
return extractBody(
globalThis,
value,
false,
JSValue.zero,
.Cell,
);
}
pub fn extractWithInit(
globalThis: *JSGlobalObject,
value: JSValue,
init: JSValue,
init_type: JSValue.JSType,
) ?Body {
return extractBody(
globalThis,
value,
true,
init,
init_type,
);
}
// https://github.com/WebKit/webkit/blob/main/Source/WebCore/Modules/fetch/FetchBody.cpp#L45
inline fn extractBody(
globalThis: *JSGlobalObject,
value: JSValue,
comptime has_init: bool,
init: JSValue,
init_type: JSC.JSValue.JSType,
) ?Body {
var body = Body{
.value = Value{ .Empty = {} },
.init = Init{ .headers = null, .status_code = 200 },
};
var allocator = getAllocator(globalThis);
if (comptime has_init) {
if (Init.init(allocator, globalThis, init, init_type)) |maybeInit| {
if (maybeInit) |init_| {
body.init = init_;
}
} else |_| {}
}
body.value = Value.fromJS(globalThis, value) orelse return null;
if (body.value == .Blob)
std.debug.assert(body.value.Blob.allocator == null); // owned by Body
return body;
}
};
pub fn BodyMixin(comptime Type: type) type {
return struct {
pub fn getText(
this: *Type,
globalThis: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
var value: *Body.Value = this.getBodyValue();
if (value.* == .Used) {
return handleBodyAlreadyUsed(globalThis);
}
if (value.* == .Locked) {
return value.Locked.setPromise(globalThis, .getText);
}
var blob = value.useAsAnyBlob();
return JSC.JSPromise.wrap(globalThis, blob.toString(globalThis, .transfer));
}
pub fn getBody(
this: *Type,
globalThis: *JSC.JSGlobalObject,
) callconv(.C) JSValue {
var body: *Body.Value = this.getBodyValue();
if (body.* == .Used) {
// TODO: make this closed
return JSC.WebCore.ReadableStream.empty(globalThis);
}
return body.toReadableStream(globalThis);
}
pub fn getBodyUsed(
this: *Type,
_: *JSC.JSGlobalObject,
) callconv(.C) JSValue {
return JSValue.jsBoolean(this.getBodyValue().* == .Used);
}
pub fn getJSON(
this: *Type,
globalObject: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
var value: *Body.Value = this.getBodyValue();
if (value.* == .Used) {
return handleBodyAlreadyUsed(globalObject);
}
if (value.* == .Locked) {
return value.Locked.setPromise(globalObject, .getJSON);
}
var blob = value.useAsAnyBlob();
return JSC.JSPromise.wrap(globalObject, blob.toJSON(globalObject, .share));
}
fn handleBodyAlreadyUsed(globalObject: *JSC.JSGlobalObject) JSValue {
return JSC.JSPromise.rejectedPromiseValue(
globalObject,
ZigString.static("Body already used").toErrorInstance(globalObject),
);
}
pub fn getArrayBuffer(
this: *Type,
globalObject: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
var value: *Body.Value = this.getBodyValue();
if (value.* == .Used) {
return handleBodyAlreadyUsed(globalObject);
}
if (value.* == .Locked) {
return value.Locked.setPromise(globalObject, .getArrayBuffer);
}
var blob: AnyBlob = value.useAsAnyBlob();
return JSC.JSPromise.wrap(globalObject, blob.toArrayBuffer(globalObject, .transfer));
}
pub fn getBlob(
this: *Type,
globalObject: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
var value: *Body.Value = this.getBodyValue();
if (value.* == .Used) {
return handleBodyAlreadyUsed(globalObject);
}
if (value.* == .Locked) {
return value.Locked.setPromise(globalObject, .getBlob);
}
var blob = value.use();
var ptr = getAllocator(globalObject).create(Blob) catch unreachable;
ptr.* = blob;
blob.allocator = getAllocator(globalObject);
return JSC.JSPromise.resolvedPromiseValue(globalObject, ptr.toJS(globalObject));
}
};
}
|