forked from cloudflare/miniflare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.spec.ts
1276 lines (1213 loc) · 40.4 KB
/
http.spec.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 assert from "assert";
import http from "http";
import { text } from "stream/consumers";
import { ReadableStream, TransformStream, WritableStream } from "stream/web";
import { URL } from "url";
import {
Body,
IncomingRequestCfProperties,
Request,
Response,
_getBodyLength,
_getURLList,
_isByteStream,
createCompatFetch,
fetch,
logResponse,
withImmutableHeaders,
withInputGating,
withStringFormDataFiles,
withWaitUntil,
} from "@miniflare/core";
import {
Compatibility,
InputGate,
LogLevel,
NoOpLog,
RequestContext,
} from "@miniflare/shared";
import {
TestLog,
triggerPromise,
useServer,
utf8Decode,
utf8Encode,
waitsForInputGate,
waitsForOutputGate,
} from "@miniflare/shared-test";
import { WebSocketPair } from "@miniflare/web-sockets";
import test, { Macro } from "ava";
import {
Request as BaseRequest,
Response as BaseResponse,
BodyMixin,
File,
FormData,
Headers,
fetch as baseFetch,
} from "undici";
// @ts-expect-error filling out all properties is annoying
const cf: IncomingRequestCfProperties = { country: "GB" };
async function byobReadFirstChunk(body: ReadableStream<Uint8Array> | null) {
assert(body);
const reader = body.getReader({ mode: "byob" });
const result = await reader.read(new Uint8Array(32));
return utf8Decode(result.value);
}
test('Headers: getAll: throws if key not "Set-Cookie"', (t) => {
const headers = new Headers();
// @ts-expect-error getAll is added to the Headers prototype by importing
// @miniflare/core
t.throws(() => headers.getAll("set-biscuit"), {
instanceOf: TypeError,
message: 'getAll() can only be used with the header name "Set-Cookie".',
});
});
test("Headers: getAll: returns empty array if no headers", (t) => {
const headers = new Headers();
// @ts-expect-error getAll is added to the Headers prototype by importing
// @miniflare/core
t.deepEqual(headers.getAll("Set-Cookie"), []);
});
test("Headers: getAll: returns separated Set-Cookie values", (t) => {
const headers = new Headers();
const cookie1 = "key1=value1; Expires=Mon, 18 Oct 2021 17:45:00 GMT";
const cookie2 = "key2=value2";
const cookie3 = "key3=value3; Max-Age=3600";
headers.append("Set-Cookie", cookie1);
headers.append("Set-Cookie", cookie2);
headers.append("Set-Cookie", cookie3);
t.is(headers.get("set-Cookie"), [cookie1, cookie2, cookie3].join(", "));
// @ts-expect-error getAll is added to the Headers prototype by importing
// @miniflare/core
t.deepEqual(headers.getAll("set-CoOkiE"), [cookie1, cookie2, cookie3]);
});
test("_isByteStream: determines if a ReadableStream is a byte stream", (t) => {
const regularStream = new ReadableStream({
pull(controller) {
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.close();
},
});
const byteStream = new ReadableStream({
type: "bytes",
pull(controller) {
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.close();
},
});
t.false(_isByteStream(regularStream));
t.true(_isByteStream(byteStream));
});
// These tests also implicitly test withInputGating
test("Body: body isn't input gated by default", async (t) => {
const inputGate = new InputGate();
const [openTrigger, openPromise] = triggerPromise<void>();
await inputGate.runWith(async () => {
// noinspection ES6MissingAwait
void inputGate.runWithClosed(() => openPromise);
const body = new Body(new BaseResponse("body")).body;
assert(body);
// @ts-expect-error @types/node stream/consumers doesn't accept ReadableStream
t.is(await text(body), "body");
});
openTrigger();
});
test("Body: body returns null with null body", (t) => {
const body = new Body(new BaseResponse(null));
t.is(body.body, null);
});
test("Body: same body instance is always returned", (t) => {
const body = new Body(new BaseResponse("body"));
t.not(body.body, null);
t.is(body.body, body.body);
});
test("Body: reuses byte stream if not input gated", (t) => {
const bodyStream = new ReadableStream({
type: "bytes",
pull(controller) {
controller.enqueue(utf8Encode("chunk"));
controller.close();
},
});
let res = new Response(bodyStream);
t.is(res.body, bodyStream);
res = withInputGating(new Response(bodyStream));
t.not(res.body, bodyStream);
});
test("Body: body isn't locked until read from", async (t) => {
const res = new Response("body");
// noinspection SuspiciousTypeOfGuard
t.true(res instanceof Body);
// noinspection SuspiciousTypeOfGuard
assert(res.body instanceof ReadableStream);
// Access property that doesn't read any data
t.false(res.body.locked);
// Check we can still clone the body
const clone = res.clone();
t.is(await clone.text(), "body");
});
test("Body: can pause, resume and cancel body stream", async (t) => {
const chunks = ["123", "456", "789"];
const bodyStream = new ReadableStream({
pull(controller) {
const chunk = chunks.shift();
if (chunk) {
controller.enqueue(utf8Encode(chunk));
} else {
controller.close();
}
},
});
const { body } = new Response(bodyStream);
assert(body);
let reader = body.getReader();
let result = await reader.read();
t.false(result.done);
t.is(utf8Decode(result.value), "123");
reader.releaseLock();
reader = body.getReader();
result = await reader.read();
t.false(result.done);
t.is(utf8Decode(result.value), "456");
await reader.cancel(new Error("Cancelled!"));
result = await reader.read();
t.true(result.done);
t.is(result.value, undefined);
reader.releaseLock();
reader = body.getReader();
result = await reader.read();
t.true(result.done);
t.is(result.value, undefined);
});
test("Body: throws on string chunks", async (t) => {
const inputStream = new ReadableStream({
start(controller) {
controller.enqueue("I'm a string");
controller.close();
},
});
const { body } = new Response(inputStream);
assert(body);
await t.throwsAsync(body.getReader().read(), {
instanceOf: TypeError,
message:
"This TransformStream is being used as a byte stream, " +
"but received a string on its writable side. " +
"If you wish to write a string, you'll probably want to " +
"explicitly UTF-8-encode it with TextEncoder.",
});
});
test("Body: throws on non-ArrayBuffer/ArrayBufferView chunks", async (t) => {
const inputStream = new ReadableStream({
start(controller) {
controller.enqueue(42);
controller.close();
},
});
const { body } = new Response(inputStream);
assert(body);
await t.throwsAsync(body.getReader().read(), {
instanceOf: TypeError,
message:
"This TransformStream is being used as a byte stream, " +
"but received an object of non-ArrayBuffer/ArrayBufferView " +
"type on its writable side.",
});
});
const inputGatedBodyMacro: Macro<[(body: ReadableStream) => Promise<any>]> =
async (t, closure) => {
const res = withInputGating(new Body(new BaseResponse("body")));
// @ts-expect-error res.body is a ReadableStream
const body: ReadableStream = res.body;
await waitsForInputGate(t, () => closure(body));
};
inputGatedBodyMacro.title = (providedTitle) =>
`Body: body.${providedTitle}() applies input gating`;
test("getReader", inputGatedBodyMacro, (body) => body.getReader().read());
test("pipeTrough", inputGatedBodyMacro, (body) =>
body.pipeThrough(new TransformStream()).getReader().read()
);
test("pipeTo", inputGatedBodyMacro, (body) =>
body.pipeTo(new WritableStream())
);
test("tee", inputGatedBodyMacro, (body) => body.tee()[0].getReader().read());
test("values", inputGatedBodyMacro, (body) => body.values().next());
test("[Symbol.asyncIterator]", inputGatedBodyMacro, (body) =>
body[Symbol.asyncIterator]().next()
);
const inputGatedConsumerMacro: Macro<
[key: Exclude<keyof BodyMixin, "body" | "bodyUsed">, res?: BaseResponse]
> = async (t, key, res = new BaseResponse('{"key": "value"}')) => {
// Check result is not input gated by default
const inputGate = new InputGate();
const [openTrigger, openPromise] = triggerPromise<void>();
await inputGate.runWith(async () => {
// noinspection ES6MissingAwait
void inputGate.runWithClosed(() => openPromise);
const body = new Body(res.clone());
t.not(await body?.[key](), undefined);
});
openTrigger();
// Check input gating can be enabled
await waitsForInputGate(t, async () => {
const body = withInputGating(new Body(res));
await body?.[key]();
});
};
inputGatedConsumerMacro.title = (providedTitle, key) =>
`Body: ${key}() applies input gating`;
test(inputGatedConsumerMacro, "arrayBuffer");
test(inputGatedConsumerMacro, "blob");
test(
inputGatedConsumerMacro,
"formData",
new BaseResponse("key=value", {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
})
);
test(inputGatedConsumerMacro, "json");
test(inputGatedConsumerMacro, "text");
test("Body: formData: parses regular form data fields", async (t) => {
// Check with application/x-www-form-urlencoded Content-Type
let body = new Body(
new BaseResponse("key1=value1&key2=value2", {
headers: { "content-type": "application/x-www-form-urlencoded" },
})
);
let formData = await body.formData();
t.is(formData.get("key1"), "value1");
t.is(formData.get("key2"), "value2");
// Check with multipart/form-data Content-Type
body = new Body(
new BaseResponse(
[
"--boundary",
'Content-Disposition: form-data; name="key1"',
"",
"multipart value1",
"--boundary",
'Content-Disposition: form-data; name="key2"',
"",
"multipart value2",
"--boundary",
'Content-Disposition: form-data; name="key2"',
"",
"second value2",
"--boundary--",
].join("\r\n"),
{ headers: { "content-type": 'multipart/form-data;boundary="boundary"' } }
)
);
formData = await body.formData();
t.is(formData.get("key1"), "multipart value1");
t.deepEqual(formData.getAll("key2"), ["multipart value2", "second value2"]);
});
test("Body: formData: parses files as File objects by default", async (t) => {
const body = new Body(
new BaseResponse(
[
"--boundary",
'Content-Disposition: form-data; name="key"; filename="test.txt"',
"Content-Type: text/plain",
"",
"file contents",
"--boundary--",
].join("\r\n"),
{ headers: { "content-type": 'multipart/form-data;boundary="boundary"' } }
)
);
const formData = await body.formData();
const file = formData.get("key");
assert(file instanceof File);
t.is(await file.text(), "file contents");
t.is(file.name, "test.txt");
});
test("Body: formData: parses files as strings if option set", async (t) => {
let body = new Body(
new BaseResponse(
[
"--boundary",
'Content-Disposition: form-data; name="key"; filename="test.txt"',
"Content-Type: text/plain",
"",
"file contents",
"--boundary--",
].join("\r\n"),
{ headers: { "content-type": 'multipart/form-data;boundary="boundary"' } }
)
);
body = withStringFormDataFiles(body);
const formData = await body.formData();
t.is(formData.get("key"), "file contents");
});
test("Body: formData: respects Content-Transfer-Encoding header for base64 encoded files", async (t) => {
let body = new Body(
new BaseResponse(
[
"--boundary",
'Content-Disposition: form-data; name="key"; filename="test.txt"',
"Content-Transfer-Encoding: base64",
"Content-Type: text/plain",
"",
"dGVzdA==", // test
"--boundary--",
].join("\r\n"),
{ headers: { "content-type": 'multipart/form-data;boundary="boundary"' } }
)
);
body = withStringFormDataFiles(body);
const formData = await body.formData();
t.is(formData.get("key"), "test");
});
test("Request: constructing from BaseRequest doesn't create new BaseRequest unless required", (t) => {
// Check properties of Request are same as BaseRequest if not RequestInit passed
const controller = new AbortController();
const base = new BaseRequest("http://localhost", {
method: "POST",
keepalive: true,
headers: { "Content-Type": "text/html" },
body: "<p>test</p>",
redirect: "follow",
integrity: "sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=",
signal: controller.signal,
});
let req = new Request(base);
// Headers wouldn't be the same instance if cloned
t.is(req.headers, base.headers);
// Bodies are different, as we create a readable byte stream for each Request
// @ts-expect-error our bodies are typed ReadableStream
t.not(req.body, base.body);
t.is(req.cache, base.cache);
t.is(req.credentials, base.credentials);
t.is(req.destination, base.destination);
t.is(req.integrity, base.integrity);
t.is(req.method, base.method);
t.is(req.cache, base.cache);
t.is(req.mode, base.mode);
t.is(req.redirect, base.redirect);
t.is(req.cache, base.cache);
t.is(req.referrerPolicy, base.referrerPolicy);
t.is(req.url, base.url);
t.is(req.keepalive, base.keepalive);
t.is(req.signal, base.signal);
// Check new BaseRequest created if RequestInit passed
req = new Request(base, {
method: "PATCH",
});
// Should be different as new instance created
// @ts-expect-error our bodies are typed ReadableStream
t.not(req.body, base.body);
t.is(req.method, "PATCH");
});
test("Request: can construct new Request from existing Request", async (t) => {
const req = new Request("http://localhost", {
method: "POST",
body: "body",
cf,
});
const req2 = new Request(req);
// Should be different as new instance created
t.not(req2.headers, req.headers);
t.not(req2.body, req.body);
t.not(req2.cf, req.cf);
t.is(req2.method, "POST");
t.is(await req2.text(), "body");
t.deepEqual(req2.cf, cf);
});
test("Request: supports non-standard properties", (t) => {
const req = new Request("http://localhost", {
method: "POST",
cf,
});
t.is(req.method, "POST");
t.deepEqual(req.cf, cf);
// Check cf has been cloned
t.not(req.cf, cf);
});
test("Request: doesn't detach ArrayBuffers", async (t) => {
// Check with ArrayBuffer
const buffer = utf8Encode("test1").buffer;
let req = new Request("http://localhost", { method: "POST", body: buffer });
t.is(await text(req.body as any), "test1");
req = new Request("http://localhost", { method: "POST", body: buffer });
t.is(await text(req.body as any), "test1");
// Check with Uint8Array
const array = utf8Encode("test2");
req = new Request("http://localhost", { method: "POST", body: array });
t.is(await text(req.body as any), "test2");
req = new Request("http://localhost", { method: "POST", body: array });
t.is(await text(req.body as any), "test2");
});
test("Request: clones non-standard properties", (t) => {
const req = new Request("http://localhost", {
method: "POST",
cf,
});
const req2 = req.clone();
t.is(req2.method, "POST");
t.deepEqual(req2.cf, cf);
t.not(req2.cf, req.cf);
// Check prototype correct and clone still clones non-standard properties
t.is(Object.getPrototypeOf(req2), Request.prototype);
const req3 = req2.clone();
t.is(req3.method, "POST");
t.deepEqual(req3.cf, cf);
t.not(req3.cf, req2.cf);
});
test("Request: can be input gated", async (t) => {
const req = withInputGating(
new Request("http://localhost", { method: "POST", body: "body" })
);
// noinspection SuspiciousTypeOfGuard
t.true(req instanceof Body);
await waitsForInputGate(t, () => req.text());
});
test("Request: clone retains input gated option", async (t) => {
const req = withInputGating(
new Request("http://localhost", { method: "POST", body: "body" })
);
const clone = req.clone();
await waitsForInputGate(t, () => clone.text());
});
test("Request: clone retains form data file parsing option", async (t) => {
const formData = new FormData();
formData.append("file", new File(["test"], "test.txt"));
// Implicitly testing FormData body encoding here too
let req = new Request("https://host", { method: "POST", body: formData });
let clone = req.clone();
let resFormData = await clone.formData();
const file = resFormData.get("file");
assert(file instanceof File);
t.is(await file.text(), "test");
t.is(file.name, "test.txt");
req = new Request("https://host", { method: "POST", body: formData });
req = withStringFormDataFiles(req);
clone = req.clone();
resFormData = await clone.formData();
t.is(resFormData.get("file"), "test");
});
test("Request: Object.keys() returns getters", async (t) => {
const req = new Request("http://localhost", {
headers: { "X-Key": "value " },
});
const keys = Object.keys(req);
const expectedKeys = [
"body",
"bodyUsed",
"headers",
"cf",
"signal",
"redirect",
"url",
"method",
];
t.deepEqual(keys.sort(), expectedKeys.sort());
});
test("Request: can mutate forbidden headers after construction", async (t) => {
// From https://github.com/nodejs/undici/blob/cd566ccf65c18b8405793a752247f3e350a50fcf/lib/fetch/constants.js#L3-L24
const forbiddenHeaderNames = [
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"cookie",
"cookie2",
"date",
"dnt",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"via",
];
const req = new Request("http://localhost");
for (const header of forbiddenHeaderNames) {
req.headers.set(header, "value");
t.is(req.headers.get(header), "value");
}
// Check this still works on a clone
const req2 = req.clone();
for (const header of forbiddenHeaderNames) {
t.is(req2.headers.get(header), "value");
req2.headers.set(header, "value2");
t.is(req2.headers.get(header), "value2");
}
});
test("Request: can use byob reader for body", async (t) => {
const { body } = new Request("https://a", { method: "POST", body: "body" });
assert(body);
const reader = body.getReader({ mode: "byob" });
const result = await reader.read(new Uint8Array(32));
t.is(utf8Decode(result.value), "body");
});
test("Request: can use byob reader when cloning", async (t) => {
let req = new Request("https://a", { method: "POST", body: "body" });
let clone = req.clone();
t.is(await byobReadFirstChunk(req.body), "body");
t.is(await byobReadFirstChunk(clone.body), "body");
// Check reading the clone first too
req = new Request("https://a", { method: "POST", body: "body" });
clone = req.clone();
t.is(await byobReadFirstChunk(clone.body), "body");
t.is(await byobReadFirstChunk(req.body), "body");
});
test("withImmutableHeaders: makes Request's headers immutable", (t) => {
const req = new Request("http://localhost");
req.headers.set("X-Key", "value");
t.is(withImmutableHeaders(req), req);
t.throws(() => req.headers.set("X-Key", "new"), {
instanceOf: TypeError,
message: "immutable",
});
t.is(req.headers.get("X-Key"), "value");
// Check clone still has immutable headers
const clone = req.clone();
t.throws(() => clone.headers.set("X-Key", "new"), {
instanceOf: TypeError,
message: "immutable",
});
t.is(clone.headers.get("X-Key"), "value");
});
test("Response.redirect: creates redirect response", (t) => {
let res = Response.redirect("http://localhost/", 307);
// noinspection SuspiciousTypeOfGuard
t.true(res instanceof Response);
t.is(res.headers.get("Location"), "http://localhost/");
// Check status defaults to 302
res = Response.redirect("http://localhost/");
t.is(res.status, 302);
t.is(res.headers.get("Location"), "http://localhost/");
});
test("Response: constructing from BaseResponse doesn't create new BaseResponse unless required", async (t) => {
const base = new BaseResponse("<p>test</p>", {
status: 404,
statusText: "Not Found",
headers: { "Content-Type": "text/html" },
});
let res = new Response(base.body, base);
// Headers wouldn't be the same if cloned
t.is(res.headers, base.headers);
// Bodies are different, as we create a readable byte stream for each Request
// @ts-expect-error our bodies are typed ReadableStream
t.not(res.body, base.body);
t.is(res.status, base.status);
t.is(res.ok, base.ok);
t.is(res.statusText, base.statusText);
t.is(res.url, base.url);
t.is(res.redirected, base.redirected);
// Check new BaseResponse created if different body passed
res = new Response("<p>new</p>", base);
// Should be different as new instance created
// @ts-expect-error our bodies are typed ReadableStream
t.not(res.body, base.body);
t.is(await res.text(), "<p>new</p>");
});
test("Response: can construct new Response from existing Response", async (t) => {
const res = new Response("<p>test</p>", {
status: 404,
headers: { "Content-Type": "text/html" },
});
const res2 = new Response(res.body, res);
// Should be different as new instance created
t.not(res2.headers, res.headers);
t.is(res2.status, 404);
t.is(await res2.text(), "<p>test</p>");
});
test("Response: supports non-standard properties", (t) => {
const pair = new WebSocketPair();
const res = new Response(null, {
encodeBody: "manual",
status: 101,
webSocket: pair["0"],
headers: { "X-Key": "value" },
});
t.is(res.encodeBody, "manual");
t.is(res.status, 101);
t.is(res.webSocket, pair[0]);
t.is(res.headers.get("X-Key"), "value");
});
test("Response: encodeBody defaults to auto", (t) => {
const res = new Response(null);
t.is(res.encodeBody, "auto");
});
test("Response: requires status 101 for WebSocket response", (t) => {
const pair = new WebSocketPair();
t.throws(() => new Response(null, { webSocket: pair["0"] }), {
instanceOf: RangeError,
message: "Responses with a WebSocket must have status code 101.",
});
});
test("Response: only allows status 101 for WebSocket response", (t) => {
t.throws(() => new Response(null, { status: 101 }), {
instanceOf: RangeError,
message:
"Failed to construct 'Response': The status provided (101) is outside the range [200, 599].",
});
});
test("Response: allows empty string for null body", (t) => {
for (const nullBodyStatus of [204, 205, 304]) {
const res = new Response("", { status: nullBodyStatus });
t.is(res.status, nullBodyStatus);
t.is(res.body, null, nullBodyStatus.toString());
}
});
test("Response: doesn't detach ArrayBuffers", async (t) => {
// https://github.com/cloudflare/miniflare/issues/171
// Check with ArrayBuffer
const buffer = utf8Encode("test1").buffer;
let res = new Response(buffer);
t.is(await text(res.body as any), "test1");
res = new Response(buffer);
t.is(await text(res.body as any), "test1");
// Check with Uint8Array
const array = utf8Encode("test2");
res = new Response(array);
t.is(await text(res.body as any), "test2");
res = new Response(array);
t.is(await text(res.body as any), "test2");
});
test("Response: clones non-standard properties", async (t) => {
const res = new Response("body", { encodeBody: "manual" });
const waitUntil = [1, "2", true];
withWaitUntil(res, Promise.resolve(waitUntil));
t.is(await res.waitUntil(), waitUntil);
const res2 = res.clone();
t.is(res2.encodeBody, "manual");
t.is(await res2.waitUntil(), waitUntil);
// Check prototype correct and clone still clones non-standard properties
t.is(Object.getPrototypeOf(res2), Response.prototype);
const res3 = res2.clone();
t.is(res3.encodeBody, "manual");
t.is(await res3.waitUntil(), waitUntil);
t.is(await res.text(), "body");
t.is(await res2.text(), "body");
t.is(await res3.text(), "body");
});
test("Response: constructing from Response copies non-standard properties", (t) => {
const pair = new WebSocketPair();
const res = new Response("body1", {
encodeBody: "manual",
status: 101,
webSocket: pair["0"],
});
const res2 = new Response("body2", res);
t.is(res2.encodeBody, "manual");
t.is(res2.status, 101);
t.is(res2.webSocket, pair["0"]);
});
test("Response: fails to clone WebSocket response", (t) => {
const pair = new WebSocketPair();
const res = new Response(null, {
status: 101,
webSocket: pair["0"],
});
t.throws(() => res.clone(), {
instanceOf: TypeError,
message: "Cannot clone a response to a WebSocket handshake.",
});
});
test("Response: can be input gated", async (t) => {
const res = withInputGating(new Response("body"));
// noinspection SuspiciousTypeOfGuard
t.true(res instanceof Body);
await waitsForInputGate(t, () => res.text());
});
test("Response: clone retains input gated option", async (t) => {
const res = withInputGating(new Response("body"));
const clone = res.clone();
await waitsForInputGate(t, () => clone.text());
});
test("Response: clone retains form data file parsing option", async (t) => {
const formData = new FormData();
formData.append("file", new File(["test"], "test.txt"));
// Implicitly testing FormData body encoding here too
let res = new Response(formData);
let clone = res.clone();
let resFormData = await clone.formData();
const file = resFormData.get("file");
assert(file instanceof File);
t.is(await file.text(), "test");
t.is(file.name, "test.txt");
res = new Response(formData);
res = withStringFormDataFiles(res);
clone = res.clone();
resFormData = await clone.formData();
t.is(resFormData.get("file"), "test");
});
test("Response: clones null body", async (t) => {
const res = new Response(null, { status: 201 });
const clone = res.clone();
t.is(clone.body, null);
});
test("Response: Object.keys() returns getters", async (t) => {
const res = new Response("body", { headers: { "X-Key": "value " } });
const keys = Object.keys(res);
const expectedKeys = [
"body",
"bodyUsed",
"headers",
"encodeBody",
"webSocket",
"url",
"redirected",
"ok",
"statusText",
"status",
];
t.deepEqual(keys.sort(), expectedKeys.sort());
});
test("Response: can mutate forbidden headers after construction", async (t) => {
// From https://github.com/nodejs/undici/blob/cd566ccf65c18b8405793a752247f3e350a50fcf/lib/fetch/constants.js#L61
const forbiddenResponseHeaderNames = ["set-cookie", "set-cookie2"];
const res = new Response("body");
for (const header of forbiddenResponseHeaderNames) {
res.headers.set(header, "value");
t.is(res.headers.get(header), "value");
}
// Check this still works on a clone
const res2 = res.clone();
for (const header of forbiddenResponseHeaderNames) {
t.is(res2.headers.get(header), "value");
res2.headers.set(header, "value2");
t.is(res2.headers.get(header), "value2");
}
});
test("Response: can use byob reader for body", async (t) => {
const { body } = new Response("body");
assert(body);
const reader = body.getReader({ mode: "byob" });
const result = await reader.read(new Uint8Array(32));
t.is(utf8Decode(result.value), "body");
});
test("Response: can use byob reader when cloning", async (t) => {
let res = new Response("body");
let clone = res.clone();
t.is(await byobReadFirstChunk(res.body), "body");
t.is(await byobReadFirstChunk(clone.body), "body");
// Check reading the clone first too
res = new Response("body");
clone = res.clone();
t.is(await byobReadFirstChunk(clone.body), "body");
t.is(await byobReadFirstChunk(res.body), "body");
});
test("Response: type throws with unimplemented error", async (t) => {
const res = new Response();
t.throws(() => res.type, {
instanceOf: Error,
message:
"Failed to get the 'type' property on 'Response': the property is not implemented.",
});
});
test("withWaitUntil: adds wait until to (Base)Response", async (t) => {
const waitUntil = [1];
let res = new Response("body");
t.is(withWaitUntil(res, Promise.resolve(waitUntil)), res);
t.is(await res.waitUntil(), waitUntil);
const baseWaitUntil = [2];
const baseRes = new BaseResponse("body");
res = withWaitUntil(baseRes, Promise.resolve(baseWaitUntil));
t.is(await res.waitUntil(), baseWaitUntil);
});
function redirectingServerListener(
req: http.IncomingMessage,
res: http.ServerResponse
) {
const { searchParams } = new URL(req.url ?? "", "http://localhost");
const n = parseInt(searchParams.get("n") ?? "0");
if (n > 0) {
res.writeHead(302, { Location: `/?n=${n - 1}`, "Set-Cookie": `n=${n}` });
} else {
res.writeHead(200);
}
res.end();
}
test("_getURLList: extracts URL list from Response", async (t) => {
const upstream = (await useServer(t, redirectingServerListener)).http;
const url = new URL("/?n=3", upstream);
const res = await baseFetch(url);
const urlList = _getURLList(res);
t.deepEqual(urlList?.map(String), [
`${upstream.origin}/?n=3`,
`${upstream.origin}/?n=2`,
`${upstream.origin}/?n=1`,
`${upstream.origin}/?n=0`,
]);
});
test("_getBodyLength: extracts actual Response Content-Length", async (t) => {
let res = new Response("body", { headers: { "Content-Length": "100" } });
t.is(_getBodyLength(res), 4);
res = new Response(new Uint8Array([1, 2, 3]));
t.is(_getBodyLength(res), 3);
res = new Response(null);
t.is(_getBodyLength(res), undefined);
res = new Response(new ReadableStream(), {
headers: { "Content-Length": "50" },
});
t.is(_getBodyLength(res), undefined);
});
test("fetch: can fetch from existing Request", async (t) => {
const upstream = (await useServer(t, (req, res) => res.end("upstream"))).http;
const req = new Request(upstream);
const res = await fetch(req);
t.is(await res.text(), "upstream");
});
test("fetch: gives a null body for upstream null body status codes", async (t) => {
const upstream = (
await useServer(t, (req, res) => {
res.statusCode = 304;
res.end();
})
).http;
const req = new Request(upstream);
const res = await fetch(req);
t.is(res.status, 304);
t.is(await res.text(), "");
});
test("fetch: increments subrequest count", async (t) => {
const upstream = (await useServer(t, (req, res) => res.end("upstream"))).http;
const ctx = new RequestContext();
await ctx.runWith(() => fetch(upstream));
t.is(ctx.subrequests, 1);
});
test("fetch: increments subrequest count for each redirect", async (t) => {
const upstream = (await useServer(t, redirectingServerListener)).http;
const url = new URL("/?n=3", upstream);
const ctx = new RequestContext();
await ctx.runWith(() => fetch(url));
t.is(ctx.subrequests, 4);
});
test("fetch: waits for output gate to open before fetching", async (t) => {
let fetched = false;
const upstream = (
await useServer(t, (req, res) => {
fetched = true;
res.end("upstream");
})
).http;
await waitsForOutputGate(
t,
() => fetch(upstream),
() => fetched
);
});
test("fetch: removes Host and CF-Connecting-IP headers from Request", async (t) => {
const upstream = (
await useServer(t, (req, res) => res.end(JSON.stringify(req.headers)))
).http;
const res = await fetch(upstream, {
headers: {
Host: "miniflare.dev",
"CF-Connecting-IP": "127.0.0.1",
"X-Real-IP": "127.0.0.1",
},
});
const headers = await res.json();
t.like(headers, {
host: upstream.host,
"x-real-ip": "127.0.0.1",
});
});
test("fetch: removes Content-Length 0 from body-less requests", async (t) => {
// Should remove content-length: 0 from certain methods because undici sees it
// as an error: https://github.com/cloudflare/miniflare/issues/193
const upstream = (
await useServer(t, (req, res) => res.end(JSON.stringify(req.headers)))
).http;
const res = await fetch(upstream, {
method: "DELETE",
headers: {
"Content-Length": "0"
},
});
const headers = await res.json();
t.like(headers, {
host: upstream.host,
});
});
test("fetch: removes default fetch headers from Request unless explicitly added", async (t) => {
// Should remove accept, accept-language, sec-fetch-mode, and user-agent
// headers unless explicitly added: https://github.com/cloudflare/miniflare/issues/139
const upstream = (
await useServer(t, (req, res) => res.end(JSON.stringify(req.headers)))
).http;
function removeExpected(headers: any): any {
delete headers["accept-encoding"];
delete headers["connection"];
delete headers["host"];
delete headers["mf-loop"];
return headers;
}
// Check with no additional headers
let res = await fetch(upstream, { headers: { "CF-Ray": "ray1" } });
t.deepEqual(removeExpected(await res.json()), { "cf-ray": "ray1" });
// Check with single additional header