-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathfetch.test.ts
2076 lines (1889 loc) · 64 KB
/
fetch.test.ts
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
import { AnyFunction, serve, ServeOptions, Server, sleep, TCPSocketListener } from "bun";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "bun:test";
import { chmodSync, readFileSync, rmSync, writeFileSync } from "fs";
import { bunEnv, bunExe, gc, isWindows, tls, tmpdirSync, withoutAggressiveGC } from "harness";
import { mkfifo } from "mkfifo";
import net from "net";
import { join } from "path";
import { gzipSync } from "zlib";
const tmp_dir = tmpdirSync();
const fixture = readFileSync(join(import.meta.dir, "fetch.js.txt"), "utf8").replaceAll("\r\n", "\n");
const fetchFixture3 = join(import.meta.dir, "fetch-leak-test-fixture-3.js");
const fetchFixture4 = join(import.meta.dir, "fetch-leak-test-fixture-4.js");
let server: Server;
function startServer({ fetch, ...options }: ServeOptions) {
server = serve({
...options,
fetch,
port: 0,
});
}
afterEach(() => {
server?.stop?.(true);
});
afterAll(() => {
rmSync(tmp_dir, { force: true, recursive: true });
});
const payload = new Uint8Array(1024 * 1024 * 2);
crypto.getRandomValues(payload);
it("new Request(invalid url) throws", () => {
expect(() => new Request("http")).toThrow();
expect(() => new Request("")).toThrow();
expect(() => new Request("http://[::1")).toThrow();
expect(() => new Request("https://[::1")).toThrow();
expect(() => new Request("!")).toThrow();
});
describe("fetch data urls", () => {
it("basic", async () => {
var url =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
var res = await fetch(url);
expect(res.status).toBe(200);
expect(res.statusText).toBe("OK");
expect(res.ok).toBe(true);
var blob = await res.blob();
expect(blob.size).toBe(85);
expect(blob.type).toBe("image/png");
});
it("percent encoded", async () => {
var url = "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D";
var res = await fetch(url);
expect(res.status).toBe(200);
expect(res.statusText).toBe("OK");
expect(res.ok).toBe(true);
var blob = await res.blob();
expect(blob.size).toBe(13);
expect(blob.type).toBe("text/plain;charset=utf-8");
expect(blob.text()).resolves.toBe("Hello, World!");
});
it("percent encoded (invalid)", async () => {
var url = "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3";
expect(async () => {
await fetch(url);
}).toThrow("failed to fetch the data URL");
});
it("plain text", async () => {
var url = "data:,Hello%2C%20World!";
var res = await fetch(url);
expect(res.status).toBe(200);
expect(res.statusText).toBe("OK");
expect(res.ok).toBe(true);
var blob = await res.blob();
expect(blob.size).toBe(13);
expect(blob.type).toBe("text/plain;charset=utf-8");
expect(blob.text()).resolves.toBe("Hello, World!");
url = "data:,helloworld!";
res = await fetch(url);
expect(res.status).toBe(200);
expect(res.statusText).toBe("OK");
expect(res.ok).toBe(true);
blob = await res.blob();
expect(blob.size).toBe(11);
expect(blob.type).toBe("text/plain;charset=utf-8");
expect(blob.text()).resolves.toBe("helloworld!");
});
it("unstrict parsing of invalid URL characters", async () => {
var url = "data:application/json,{%7B%7D}";
var res = await fetch(url);
expect(res.status).toBe(200);
expect(res.statusText).toBe("OK");
expect(res.ok).toBe(true);
var blob = await res.blob();
expect(blob.size).toBe(4);
expect(blob.type).toBe("application/json;charset=utf-8");
expect(blob.text()).resolves.toBe("{{}}");
});
it("unstrict parsing of double percent characters", async () => {
var url = "data:application/json,{%%7B%7D%%}%%";
var res = await fetch(url);
expect(res.status).toBe(200);
expect(res.statusText).toBe("OK");
expect(res.ok).toBe(true);
var blob = await res.blob();
expect(blob.size).toBe(9);
expect(blob.type).toBe("application/json;charset=utf-8");
expect(blob.text()).resolves.toBe("{%{}%%}%%");
});
it("data url (invalid)", async () => {
var url = "data:Hello%2C%20World!";
expect(async () => {
await fetch(url);
}).toThrow("failed to fetch the data URL");
});
it("emoji", async () => {
var url = "data:,😀";
var res = await fetch(url);
expect(res.status).toBe(200);
expect(res.statusText).toBe("OK");
expect(res.ok).toBe(true);
var blob = await res.blob();
expect(blob.size).toBe(4);
expect(blob.type).toBe("text/plain;charset=utf-8");
expect(blob.text()).resolves.toBe("😀");
});
it("should work with Request", async () => {
var req = new Request("data:,Hello%2C%20World!");
var res = await fetch(req);
expect(res.status).toBe(200);
expect(res.statusText).toBe("OK");
expect(res.ok).toBe(true);
var blob = await res.blob();
expect(blob.size).toBe(13);
expect(blob.type).toBe("text/plain;charset=utf-8");
expect(blob.text()).resolves.toBe("Hello, World!");
req = new Request("data:,😀");
res = await fetch(req);
expect(res.status).toBe(200);
expect(res.statusText).toBe("OK");
expect(res.ok).toBe(true);
blob = await res.blob();
expect(blob.size).toBe(4);
expect(blob.type).toBe("text/plain;charset=utf-8");
expect(blob.text()).resolves.toBe("😀");
});
it("should work with Request (invalid)", async () => {
var req = new Request("data:Hello%2C%20World!");
expect(async () => {
await fetch(req);
}).toThrow("failed to fetch the data URL");
req = new Request("data:Hello%345632");
expect(async () => {
await fetch(req);
}).toThrow("failed to fetch the data URL");
});
});
describe("AbortSignal", () => {
beforeEach(() => {
startServer({
async fetch(request) {
if (request.url.endsWith("/nodelay")) {
return new Response("Hello");
}
if (request.url.endsWith("/stream")) {
const reader = request.body!.getReader();
const body = new ReadableStream({
async pull(controller) {
if (!reader) controller.close();
const { done, value } = await reader.read();
// When no more data needs to be consumed, close the stream
if (done) {
controller.close();
return;
}
// Enqueue the next data chunk into our target stream
controller.enqueue(value);
},
});
return new Response(body);
}
if (request.method.toUpperCase() === "POST") {
const body = await request.text();
return new Response(body);
}
await sleep(15);
return new Response("Hello");
},
});
});
afterEach(() => {
server?.stop?.(true);
});
it("AbortError", async () => {
const controller = new AbortController();
const signal = controller.signal;
expect(async () => {
async function manualAbort() {
await sleep(1);
controller.abort();
}
await Promise.all([fetch(server.url, { signal: signal }).then(res => res.text()), manualAbort()]);
}).toThrow(new DOMException("The operation was aborted."));
});
it("AbortAfterFinish", async () => {
const controller = new AbortController();
const signal = controller.signal;
await fetch(`http://127.0.0.1:${server.port}/nodelay`, { signal: signal }).then(async res =>
expect(await res.text()).toBe("Hello"),
);
controller.abort();
});
it("AbortErrorWithReason", async () => {
const controller = new AbortController();
const signal = controller.signal;
expect(async () => {
async function manualAbort() {
await sleep(10);
controller.abort(new Error("My Reason"));
}
await Promise.all([fetch(server.url, { signal: signal }).then(res => res.text()), manualAbort()]);
}).toThrow("My Reason");
});
it("AbortErrorEventListener", async () => {
const controller = new AbortController();
const signal = controller.signal;
signal.addEventListener("abort", ev => {
const target = ev.currentTarget!;
expect(target).toBeDefined();
expect(target.aborted).toBe(true);
expect(target.reason).toBeDefined();
expect(target.reason!.name).toBe("AbortError");
});
expect(async () => {
async function manualAbort() {
await sleep(10);
controller.abort();
}
await Promise.all([fetch(server.url, { signal: signal }).then(res => res.text()), manualAbort()]);
}).toThrow(new DOMException("The operation was aborted."));
});
it("AbortErrorWhileUploading", async () => {
const controller = new AbortController();
expect(async () => {
await fetch(`http://localhost:${server.port}`, {
method: "POST",
body: new ReadableStream({
pull(event_controller) {
event_controller.enqueue(new Uint8Array([1, 2, 3, 4]));
//this will abort immediately should abort before connected
controller.abort();
},
}),
signal: controller.signal,
});
}).toThrow(new DOMException("The operation was aborted."));
});
it("TimeoutError", async () => {
const signal = AbortSignal.timeout(10);
try {
using server = Bun.serve({
port: 0,
async fetch() {
await Bun.sleep(100);
return new Response("Hello");
},
});
await fetch(server.url, { signal: signal }).then(res => res.text());
expect.unreachable();
} catch (ex: any) {
expect(ex.name).toBe("TimeoutError");
}
});
it("Request", async () => {
const controller = new AbortController();
const signal = controller.signal;
async function manualAbort() {
await sleep(10);
controller.abort();
}
try {
const request = new Request(server.url, { signal });
await Promise.all([fetch(request).then(res => res.text()), manualAbort()]);
expect(() => {}).toThrow();
} catch (ex: any) {
expect(ex.name).toBe("AbortError");
}
});
});
describe("Headers", () => {
it(".toJSON", () => {
const headers = new Headers({
"content-length": "123",
"content-type": "text/plain",
"x-another-custom-header": "Hello World",
"x-custom-header": "Hello World",
});
expect(JSON.stringify(headers.toJSON(), null, 2)).toBe(
JSON.stringify(Object.fromEntries(headers.entries()), null, 2),
);
});
it(".getSetCookie() with object", () => {
const headers = new Headers({
"content-length": "123",
"content-type": "text/plain",
"x-another-custom-header": "Hello World",
"x-custom-header": "Hello World",
"Set-Cookie": "foo=bar; Path=/; HttpOnly",
});
expect(headers.count).toBe(5);
expect(headers.getAll("set-cookie")).toEqual(["foo=bar; Path=/; HttpOnly"]);
});
it("presence of content-encoding header(issue #5668)", async () => {
startServer({
fetch(req) {
const content = gzipSync(JSON.stringify({ message: "Hello world" }));
return new Response(content, {
status: 200,
headers: {
"content-encoding": "gzip",
"content-type": "application/json",
},
});
},
});
const result = await fetch(`http://${server.hostname}:${server.port}/`);
const value = result.headers.get("content-encoding");
const body = await result.json();
expect(value).toBe("gzip");
expect(body).toBeDefined();
expect(body.message).toBe("Hello world");
});
it(".getSetCookie() with array", () => {
const headers = new Headers([
["content-length", "123"],
["content-type", "text/plain"],
["x-another-custom-header", "Hello World"],
["x-custom-header", "Hello World"],
["Set-Cookie", "foo=bar; Path=/; HttpOnly"],
["Set-Cookie", "foo2=bar2; Path=/; HttpOnly"],
]);
expect(headers.count).toBe(6);
expect(headers.getAll("set-cookie")).toEqual(["foo=bar; Path=/; HttpOnly", "foo2=bar2; Path=/; HttpOnly"]);
});
it("Set-Cookies init", () => {
const headers = new Headers([
["Set-Cookie", "foo=bar"],
["Set-Cookie", "bar=baz"],
["X-bun", "abc"],
["X-bun", "def"],
]);
const actual = [...headers];
expect(actual).toEqual([
["x-bun", "abc, def"],
["set-cookie", "foo=bar"],
["set-cookie", "bar=baz"],
]);
expect([...headers.values()]).toEqual(["abc, def", "foo=bar", "bar=baz"]);
});
it("Set-Cookies toJSON", () => {
const headers = new Headers([
["Set-Cookie", "foo=bar"],
["Set-Cookie", "bar=baz"],
["X-bun", "abc"],
["X-bun", "def"],
]).toJSON();
expect(headers).toEqual({
"x-bun": "abc, def",
"set-cookie": ["foo=bar", "bar=baz"],
});
});
it("Headers append multiple", () => {
const headers = new Headers([
["Set-Cookie", "foo=bar"],
["X-bun", "foo"],
]);
headers.append("Set-Cookie", "bar=baz");
headers.append("x-bun", "bar");
const actual = [...headers];
// we do not preserve the order
// which is kind of bad
expect(actual).toEqual([
["x-bun", "foo, bar"],
["set-cookie", "foo=bar"],
["set-cookie", "bar=baz"],
]);
});
it("append duplicate set cookie key", () => {
const headers = new Headers([["Set-Cookie", "foo=bar"]]);
headers.append("set-Cookie", "foo=baz");
headers.append("Set-cookie", "baz=bar");
const actual = [...headers];
expect(actual).toEqual([
["set-cookie", "foo=bar"],
["set-cookie", "foo=baz"],
["set-cookie", "baz=bar"],
]);
});
it("set duplicate cookie key", () => {
const headers = new Headers([["Set-Cookie", "foo=bar"]]);
headers.set("set-Cookie", "foo=baz");
headers.set("set-cookie", "bar=qat");
const actual = [...headers];
expect(actual).toEqual([["set-cookie", "bar=qat"]]);
});
it("should include set-cookie headers in array", () => {
const headers = new Headers();
headers.append("Set-Cookie", "foo=bar");
headers.append("Content-Type", "text/plain");
const actual = [...headers];
expect(actual).toEqual([
["content-type", "text/plain"],
["set-cookie", "foo=bar"],
]);
});
});
describe("fetch", () => {
const urls = [
"https://example.com",
"http://example.com",
new URL("https://example.com"),
new Request({ url: "https://example.com" }),
{ toString: () => "https://example.com" } as string,
];
for (let url of urls) {
gc();
let name: string;
if (url instanceof URL) {
name = "URL: " + url;
} else if (url instanceof Request) {
name = "Request: " + url.url;
} else if (url.hasOwnProperty("toString")) {
name = "Object: " + url.toString();
} else {
name = url as string;
}
it(name, async () => {
gc();
const response = await fetch(url, { verbose: true });
gc();
const text = await response.text();
gc();
expect(fixture).toBe(text);
});
}
it('redirect: "manual"', async () => {
startServer({
fetch(req) {
return new Response(null, {
status: 302,
headers: {
Location: "https://example.com",
},
});
},
});
const response = await fetch(`http://${server.hostname}:${server.port}`, {
redirect: "manual",
});
expect(response.status).toBe(302);
expect(response.headers.get("location")).toBe("https://example.com");
expect(response.redirected).toBe(false); // not redirected
});
it('redirect: "follow"', async () => {
startServer({
fetch(req) {
return new Response(null, {
status: 302,
headers: {
Location: "https://example.com",
},
});
},
});
const response = await fetch(`http://${server.hostname}:${server.port}`, {
redirect: "follow",
});
expect(response.status).toBe(200);
expect(response.headers.get("location")).toBe(null);
expect(response.redirected).toBe(true);
});
it('redirect: "error" #2819', async () => {
startServer({
fetch(req) {
return new Response(null, {
status: 302,
headers: {
Location: "https://example.com",
},
});
},
});
try {
const response = await fetch(`http://${server.hostname}:${server.port}`, {
redirect: "error",
});
expect(response).toBeUndefined();
} catch (err: any) {
expect(err.code).toBe("UnexpectedRedirect");
}
});
it("should properly redirect to another port #7793", async () => {
var socket: net.Server | null = null;
try {
using server = Bun.serve({
port: 0,
tls,
fetch() {
return new Response("Hello, world!");
},
});
socket = net.createServer(socket => {
socket.on("data", () => {
// we redirect and close the connection here
socket.end(`HTTP/1.1 301 Moved Permanently\r\nLocation: ${server?.url}\r\nConnection: close\r\n\r\n`);
});
});
const { promise, resolve, reject } = Promise.withResolvers();
socket.on("error", reject);
socket.listen(0, "localhost", async () => {
const url = server?.url.href;
const http_url = server?.url.href.replace("https://", "http://");
try {
await fetch(http_url, { tls: { rejectUnauthorized: false } });
} catch {}
const response = await fetch(url, { tls: { rejectUnauthorized: false } }).then(res => res.text());
resolve(response);
});
expect(await promise).toBe("Hello, world!");
} finally {
socket?.close();
}
});
it("provide body", async () => {
startServer({
fetch(req) {
return new Response(req.body);
},
hostname: "localhost",
});
// POST with body
const url = `http://${server.hostname}:${server.port}`;
const response = await fetch(url, { method: "POST", body: "buntastic" });
expect(response.status).toBe(200);
expect(await response.text()).toBe("buntastic");
});
["GET", "HEAD", "OPTIONS"].forEach(method =>
it(`fail on ${method} with body`, async () => {
const url = `http://${server.hostname}:${server.port}`;
expect(async () => {
await fetch(url, { body: "buntastic" });
}).toThrow("fetch() request with GET/HEAD/OPTIONS method cannot have body.");
}),
);
it("content length is inferred", async () => {
startServer({
fetch(req) {
return new Response(req.headers.get("content-length"));
},
hostname: "localhost",
});
// POST with body
const url = `http://${server.hostname}:${server.port}`;
const response = await fetch(url, { method: "POST", body: "buntastic" });
expect(response.status).toBe(200);
expect(await response.text()).toBe("9");
const response2 = await fetch(url, { method: "POST", body: "" });
expect(response2.status).toBe(200);
expect(await response2.text()).toBe("0");
});
it("should work with ipv6 localhost", async () => {
using server = Bun.serve({
port: 0,
fetch(req) {
return new Response("Pass!");
},
});
let res = await fetch(`http://[::1]:${server.port}`);
expect(await res.text()).toBe("Pass!");
res = await fetch(`http://[::]:${server.port}/`);
expect(await res.text()).toBe("Pass!");
res = await fetch(`http://[0:0:0:0:0:0:0:1]:${server.port}/`);
expect(await res.text()).toBe("Pass!");
res = await fetch(`http://[0000:0000:0000:0000:0000:0000:0000:0001]:${server.port}/`);
expect(await res.text()).toBe("Pass!");
});
});
it("simultaneous HTTPS fetch", async () => {
const urls = ["https://example.com", "https://www.example.com"];
for (let batch = 0; batch < 4; batch++) {
const promises = new Array(20);
for (let i = 0; i < 20; i++) {
promises[i] = fetch(urls[i % 2]);
}
const result = await Promise.all(promises);
expect(result.length).toBe(20);
for (let i = 0; i < 20; i++) {
expect(result[i].status).toBe(200);
expect(await result[i].text()).toBe(fixture);
}
}
});
it("website with tlsextname", async () => {
// irony
await fetch("https://bun.sh", { method: "HEAD" });
});
function testBlobInterface(blobbyConstructor: { (..._: any[]): any }, hasBlobFn?: boolean) {
for (let withGC of [false, true]) {
for (let jsonObject of [
{ hello: true },
{
hello: "😀 😃 😄 😁 😆 😅 😂 🤣 🥲 ☺️ 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😗 😙 😚 😋 😛 😝 😜 🤪 🤨 🧐 🤓 😎 🥸 🤩 🥳",
},
]) {
it(`${jsonObject.hello === true ? "latin1" : "utf16"} json${withGC ? " (with gc) " : ""}`, async () => {
if (withGC) gc();
var response = blobbyConstructor(JSON.stringify(jsonObject));
if (withGC) gc();
expect(JSON.stringify(await response.json())).toBe(JSON.stringify(jsonObject));
if (withGC) gc();
});
it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> json${
withGC ? " (with gc) " : ""
}`, async () => {
if (withGC) gc();
var response = blobbyConstructor(new TextEncoder().encode(JSON.stringify(jsonObject)));
if (withGC) gc();
expect(JSON.stringify(await response.json())).toBe(JSON.stringify(jsonObject));
if (withGC) gc();
});
it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> invalid json${
withGC ? " (with gc) " : ""
}`, async () => {
if (withGC) gc();
var response = blobbyConstructor(
new TextEncoder().encode(JSON.stringify(jsonObject) + " NOW WE ARE INVALID JSON"),
);
if (withGC) gc();
var failed = false;
try {
await response.json();
} catch (e) {
failed = true;
}
expect(failed).toBe(true);
if (withGC) gc();
});
it(`${jsonObject.hello === true ? "latin1" : "utf16"} text${withGC ? " (with gc) " : ""}`, async () => {
if (withGC) gc();
var response = blobbyConstructor(JSON.stringify(jsonObject));
if (withGC) gc();
expect(await response.text()).toBe(JSON.stringify(jsonObject));
if (withGC) gc();
});
it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> text${
withGC ? " (with gc) " : ""
}`, async () => {
if (withGC) gc();
var response = blobbyConstructor(new TextEncoder().encode(JSON.stringify(jsonObject)));
if (withGC) gc();
expect(await response.text()).toBe(JSON.stringify(jsonObject));
if (withGC) gc();
});
it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer${withGC ? " (with gc) " : ""}`, async () => {
if (withGC) gc();
var response = blobbyConstructor(JSON.stringify(jsonObject));
if (withGC) gc();
const bytes = new TextEncoder().encode(JSON.stringify(jsonObject));
if (withGC) gc();
const compare = new Uint8Array(await response.arrayBuffer());
if (withGC) gc();
withoutAggressiveGC(() => {
for (let i = 0; i < compare.length; i++) {
if (withGC) gc();
expect(compare[i]).toBe(bytes[i]);
if (withGC) gc();
}
});
if (withGC) gc();
});
it(`${jsonObject.hello === true ? "latin1" : "utf16"} bytes${withGC ? " (with gc) " : ""}`, async () => {
if (withGC) gc();
var response = blobbyConstructor(JSON.stringify(jsonObject));
if (withGC) gc();
const bytes = new TextEncoder().encode(JSON.stringify(jsonObject));
if (withGC) gc();
const compare = await response.bytes();
if (withGC) gc();
withoutAggressiveGC(() => {
for (let i = 0; i < compare.length; i++) {
if (withGC) gc();
expect(compare[i]).toBe(bytes[i]);
if (withGC) gc();
}
});
if (withGC) gc();
});
it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> arrayBuffer${
withGC ? " (with gc) " : ""
}`, async () => {
if (withGC) gc();
var response = blobbyConstructor(new TextEncoder().encode(JSON.stringify(jsonObject)));
if (withGC) gc();
const bytes = new TextEncoder().encode(JSON.stringify(jsonObject));
if (withGC) gc();
const compare = new Uint8Array(await response.arrayBuffer());
if (withGC) gc();
withoutAggressiveGC(() => {
for (let i = 0; i < compare.length; i++) {
if (withGC) gc();
expect(compare[i]).toBe(bytes[i]);
if (withGC) gc();
}
});
if (withGC) gc();
});
it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> bytes${
withGC ? " (with gc) " : ""
}`, async () => {
if (withGC) gc();
var response = blobbyConstructor(new TextEncoder().encode(JSON.stringify(jsonObject)));
if (withGC) gc();
const bytes = new TextEncoder().encode(JSON.stringify(jsonObject));
if (withGC) gc();
const compare = await response.bytes();
if (withGC) gc();
withoutAggressiveGC(() => {
for (let i = 0; i < compare.length; i++) {
if (withGC) gc();
expect(compare[i]).toBe(bytes[i]);
if (withGC) gc();
}
});
if (withGC) gc();
});
hasBlobFn &&
it(`${jsonObject.hello === true ? "latin1" : "utf16"} blob${withGC ? " (with gc) " : ""}`, async () => {
if (withGC) gc();
const text = JSON.stringify(jsonObject);
var response = blobbyConstructor(text);
if (withGC) gc();
const size = new TextEncoder().encode(text).byteLength;
if (withGC) gc();
const blobed = await response.blob();
if (withGC) gc();
expect(blobed instanceof Blob).toBe(true);
if (withGC) gc();
expect(blobed.size).toBe(size);
if (withGC) gc();
expect(blobed.type).toBe("text/plain;charset=utf-8");
const out = await blobed.text();
expect(out).toBe(text);
if (withGC) gc();
await new Promise(resolve => setTimeout(resolve, 1));
if (withGC) gc();
expect(out).toBe(text);
const first = await blobed.arrayBuffer();
const initial = first[0];
first[0] = 254;
const second = await blobed.arrayBuffer();
expect(second[0]).toBe(initial);
expect(first[0]).toBe(254);
});
}
}
}
describe("Bun.file", () => {
let count = 0;
testBlobInterface(data => {
const blob = new Blob([data]);
const buffer = Bun.peek(blob.arrayBuffer()) as ArrayBuffer;
const path = join(tmp_dir, `tmp-${count++}.bytes`);
writeFileSync(path, buffer);
const file = Bun.file(path);
expect(blob.size).toBe(file.size);
expect(file.lastModified).toBeGreaterThan(0);
return file;
});
// this test uses libc.so or dylib so we skip on windows
it.skipIf(isWindows)("size is Infinity on a fifo", () => {
const path = join(tmp_dir, "test-fifo");
mkfifo(path);
const { size } = Bun.file(path);
expect(size).toBe(Infinity);
});
const method = ["arrayBuffer", "text", "json", "bytes"] as const;
function forEachMethod(fn: (m: (typeof method)[number]) => any, skip?: AnyFunction) {
for (const m of method) {
(skip ? it.skip : it)(m, fn(m));
}
}
// on Windows the creator of the file will be able to read from it so this test is disabled on it
describe.skipIf(isWindows)("bad permissions throws", () => {
const path = join(tmp_dir, "my-new-file");
beforeAll(async () => {
await Bun.write(path, "hey");
chmodSync(path, 0x000);
});
forEachMethod(m => () => {
const file = Bun.file(path);
expect(async () => await file[m]()).toThrow("Permission denied");
});
afterAll(() => {
rmSync(path, { force: true });
});
});
describe("non-existent file throws", () => {
const path = join(tmp_dir, "does-not-exist");
forEachMethod(m => async () => {
const file = Bun.file(path);
expect(async () => await file[m]()).toThrow("No such file or directory");
});
});
});
describe("Blob", () => {
testBlobInterface(data => new Blob([data]));
it("should have expected content type", async () => {
var response = new Response("<div>hello</div>", {
headers: {
"content-type": "multipart/form-data;boundary=boundary",
},
});
expect((await response.blob()).type).toBe("multipart/form-data;boundary=boundary");
response = new Response("<div>hello</div>", {
headers: {
"content-type": "text/html; charset=utf-8",
},
});
expect((await response.blob()).type).toBe("text/html;charset=utf-8");
response = new Response("<div>hello</div>", {
headers: {
"content-type": "octet/stream",
},
});
expect((await response.blob()).type).toBe("octet/stream");
response = new Response("<div>hello</div>", {
headers: {
"content-type": "text/plain;charset=utf-8",
},
});
expect((await response.blob()).type).toBe("text/plain;charset=utf-8");
});
var blobConstructorValues = [
["123", "456"],
["123", 456],
["123", "456", "789"],
["123", 456, 789],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 9])],
[Uint8Array.from([1, 2, 3, 4]), "5678", 9],
[new Blob([Uint8Array.from([1, 2, 3, 4])]), "5678", 9],
[
new Blob([
new TextEncoder().encode(
"😀 😃 😄 😁 😆 😅 😂 🤣 🥲 ☺️ 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😗 😙 😚 😋 😛 😝 😜 🤪 🤨 🧐 🤓 😎 🥸 🤩 🥳",
),
]),
],
[
new TextEncoder().encode(
"😀 😃 😄 😁 😆 😅 😂 🤣 🥲 ☺️ 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😗 😙 😚 😋 😛 😝 😜 🤪 🤨 🧐 🤓 😎 🥸 🤩 🥳",
),
],
] as any[];
var expected = [
"123456",
"123456",
"123456789",
"123456789",
"123456789",
"\x01\x02\x03\x04\x05\x06\x07\t",
"\x01\x02\x03\x0456789",
"\x01\x02\x03\x0456789",
"😀 😃 😄 😁 😆 😅 😂 🤣 🥲 ☺️ 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😗 😙 😚 😋 😛 😝 😜 🤪 🤨 🧐 🤓 😎 🥸 🤩 🥳",
"😀 😃 😄 😁 😆 😅 😂 🤣 🥲 ☺️ 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😗 😙 😚 😋 😛 😝 😜 🤪 🤨 🧐 🤓 😎 🥸 🤩 🥳",
];
it(`blobConstructorValues`, async () => {
for (let i = 0; i < blobConstructorValues.length; i++) {
var response = new Blob(blobConstructorValues[i]);
const res = await response.text();
if (res !== expected[i]) {
throw new Error(
`Failed: ${expected[i].split("").map(a => a.charCodeAt(0))}, received: ${res
.split("")
.map(a => a.charCodeAt(0))}`,
);
}
expect(res).toBe(expected[i]);
}
});
for (let withGC of [false, true]) {
it(`Blob.slice() ${withGC ? " with gc" : ""}`, async () => {