forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathReactFlightDOMEdge-test.js
933 lines (819 loc) · 27.7 KB
/
ReactFlightDOMEdge-test.js
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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment
*/
'use strict';
// Polyfills for test environment
global.ReadableStream =
require('web-streams-polyfill/ponyfill/es6').ReadableStream;
global.TextEncoder = require('util').TextEncoder;
global.TextDecoder = require('util').TextDecoder;
global.Blob = require('buffer').Blob;
if (typeof File === 'undefined' || typeof FormData === 'undefined') {
global.File = require('buffer').File || require('undici').File;
global.FormData = require('undici').FormData;
}
// Patch for Edge environments for global scope
global.AsyncLocalStorage = require('async_hooks').AsyncLocalStorage;
// Don't wait before processing work on the server.
// TODO: we can replace this with FlightServer.act().
global.setTimeout = cb => cb();
let serverExports;
let clientExports;
let webpackMap;
let webpackModules;
let webpackModuleLoading;
let React;
let ReactServer;
let ReactDOMServer;
let ReactServerDOMServer;
let ReactServerDOMClient;
let use;
function normalizeCodeLocInfo(str) {
return (
str &&
str.replace(/^ +(?:at|in) ([\S]+)[^\n]*/gm, function (m, name) {
return ' in ' + name + (/\d/.test(m) ? ' (at **)' : '');
})
);
}
describe('ReactFlightDOMEdge', () => {
beforeEach(() => {
jest.resetModules();
// Simulate the condition resolution
jest.mock('react', () => require('react/react.react-server'));
jest.mock('react-server-dom-webpack/server', () =>
require('react-server-dom-webpack/server.edge'),
);
const WebpackMock = require('./utils/WebpackMock');
serverExports = WebpackMock.serverExports;
clientExports = WebpackMock.clientExports;
webpackMap = WebpackMock.webpackMap;
webpackModules = WebpackMock.webpackModules;
webpackModuleLoading = WebpackMock.moduleLoading;
ReactServer = require('react');
ReactServerDOMServer = require('react-server-dom-webpack/server');
jest.resetModules();
__unmockReact();
jest.unmock('react-server-dom-webpack/server');
jest.mock('react-server-dom-webpack/client', () =>
require('react-server-dom-webpack/client.edge'),
);
React = require('react');
ReactDOMServer = require('react-dom/server.edge');
ReactServerDOMClient = require('react-server-dom-webpack/client');
use = React.use;
});
function passThrough(stream) {
// Simulate more realistic network by splitting up and rejoining some chunks.
// This lets us test that we don't accidentally rely on particular bounds of the chunks.
return new ReadableStream({
async start(controller) {
const reader = stream.getReader();
let prevChunk = new Uint8Array(0);
function push() {
reader.read().then(({done, value}) => {
if (done) {
controller.enqueue(prevChunk);
prevChunk = new Uint8Array(0);
controller.close();
return;
}
const chunk = new Uint8Array(prevChunk.length + value.length);
chunk.set(prevChunk, 0);
chunk.set(value, prevChunk.length);
if (chunk.length > 50) {
controller.enqueue(chunk.subarray(0, chunk.length - 50));
prevChunk = chunk.subarray(chunk.length - 50);
} else {
// Wait to see if we get some more bytes to join in.
prevChunk = chunk;
// Flush if we don't get any more.
(async function flushAfterAFewTasks() {
for (let i = 0; i < 10; i++) {
await i;
}
if (prevChunk.byteLength > 0) {
controller.enqueue(prevChunk);
}
prevChunk = new Uint8Array(0);
})();
}
push();
});
}
push();
},
});
}
async function readResult(stream) {
const reader = stream.getReader();
let result = '';
while (true) {
const {done, value} = await reader.read();
if (done) {
return result;
}
result += Buffer.from(value).toString('utf8');
}
}
async function readByteLength(stream) {
const reader = stream.getReader();
let length = 0;
while (true) {
const {done, value} = await reader.read();
if (done) {
return length;
}
length += value.byteLength;
}
}
it('should allow an alternative module mapping to be used for SSR', async () => {
function ClientComponent() {
return <span>Client Component</span>;
}
// The Client build may not have the same IDs as the Server bundles for the same
// component.
const ClientComponentOnTheClient = clientExports(ClientComponent);
const ClientComponentOnTheServer = clientExports(ClientComponent);
// In the SSR bundle this module won't exist. We simulate this by deleting it.
const clientId = webpackMap[ClientComponentOnTheClient.$$id].id;
delete webpackModules[clientId];
// Instead, we have to provide a translation from the client meta data to the SSR
// meta data.
const ssrMetadata = webpackMap[ClientComponentOnTheServer.$$id];
const translationMap = {
[clientId]: {
'*': ssrMetadata,
},
};
function App() {
return <ClientComponentOnTheClient />;
}
const stream = ReactServerDOMServer.renderToReadableStream(
<App />,
webpackMap,
);
const response = ReactServerDOMClient.createFromReadableStream(stream, {
ssrManifest: {
moduleMap: translationMap,
moduleLoading: webpackModuleLoading,
},
});
function ClientRoot() {
return use(response);
}
const ssrStream = await ReactDOMServer.renderToReadableStream(
<ClientRoot />,
);
const result = await readResult(ssrStream);
expect(result).toEqual('<span>Client Component</span>');
});
it('should encode long string in a compact format', async () => {
const testString = '"\n\t'.repeat(500) + '🙃';
const testString2 = 'hello'.repeat(400);
const stream = ReactServerDOMServer.renderToReadableStream({
text: testString,
text2: testString2,
});
const [stream1, stream2] = passThrough(stream).tee();
const serializedContent = await readResult(stream1);
// The content should be compact an unescaped
expect(serializedContent.length).toBeLessThan(4000);
expect(serializedContent).not.toContain('\\n');
expect(serializedContent).not.toContain('\\t');
expect(serializedContent).not.toContain('\\"');
expect(serializedContent).toContain('\t');
const result = await ReactServerDOMClient.createFromReadableStream(
stream2,
{
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
},
);
// Should still match the result when parsed
expect(result.text).toBe(testString);
expect(result.text2).toBe(testString2);
});
it('should encode repeated objects in a compact format by deduping', async () => {
const obj = {
this: {is: 'a large objected'},
with: {many: 'properties in it'},
};
const props = {root: <div>{new Array(30).fill(obj)}</div>};
const stream = ReactServerDOMServer.renderToReadableStream(props);
const [stream1, stream2] = passThrough(stream).tee();
const serializedContent = await readResult(stream1);
expect(serializedContent.length).toBeLessThan(1100);
const result = await ReactServerDOMClient.createFromReadableStream(
stream2,
{
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
},
);
// TODO: Cyclic references currently cause a Lazy wrapper which is not ideal.
const resultElement = result.root._init(result.root._payload);
// Should still match the result when parsed
expect(resultElement).toEqual(props.root);
expect(resultElement.props.children[5]).toBe(
resultElement.props.children[10],
); // two random items are the same instance
});
it('should execute repeated server components only once', async () => {
const str = 'this is a long return value';
let timesRendered = 0;
function ServerComponent() {
timesRendered++;
return str;
}
const element = <ServerComponent />;
// Hardcoded list to avoid the key warning
const children = (
<>
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
</>
);
const resolvedChildren = new Array(30).fill(str);
const stream = ReactServerDOMServer.renderToReadableStream(children);
const [stream1, stream2] = passThrough(stream).tee();
const serializedContent = await readResult(stream1);
expect(serializedContent.length).toBeLessThan(410);
expect(timesRendered).toBeLessThan(5);
const model = await ReactServerDOMClient.createFromReadableStream(stream2, {
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
});
// Use the SSR render to resolve any lazy elements
const ssrStream = await ReactDOMServer.renderToReadableStream(model);
// Should still match the result when parsed
const result = await readResult(ssrStream);
expect(result).toEqual(resolvedChildren.join('<!-- -->'));
});
it('should execute repeated host components only once', async () => {
const div = <div>this is a long return value</div>;
let timesRendered = 0;
function ServerComponent() {
timesRendered++;
return div;
}
const element = <ServerComponent />;
// Hardcoded list to avoid the key warning
const children = (
<>
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
{element}
</>
);
const resolvedChildren = new Array(30).fill(
'<div>this is a long return value</div>',
);
const stream = ReactServerDOMServer.renderToReadableStream(children);
const [stream1, stream2] = passThrough(stream).tee();
const serializedContent = await readResult(stream1);
expect(serializedContent.length).toBeLessThan(__DEV__ ? 590 : 400);
expect(timesRendered).toBeLessThan(5);
const model = await ReactServerDOMClient.createFromReadableStream(stream2, {
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
});
// Use the SSR render to resolve any lazy elements
const ssrStream = await ReactDOMServer.renderToReadableStream(model);
// Should still match the result when parsed
const result = await readResult(ssrStream);
expect(result).toEqual(resolvedChildren.join(''));
});
it('should execute repeated server components in a compact form', async () => {
async function ServerComponent({recurse}) {
if (recurse > 0) {
return <ServerComponent recurse={recurse - 1} />;
}
return <div>Fin</div>;
}
const stream = ReactServerDOMServer.renderToReadableStream(
<ServerComponent recurse={20} />,
);
const serializedContent = await readResult(stream);
const expectedDebugInfoSize = __DEV__ ? 300 * 20 : 0;
expect(serializedContent.length).toBeLessThan(150 + expectedDebugInfoSize);
});
// @gate enableBinaryFlight
it('should be able to serialize any kind of typed array', async () => {
const buffer = new Uint8Array([
123, 4, 10, 5, 100, 255, 244, 45, 56, 67, 43, 124, 67, 89, 100, 20,
]).buffer;
const buffers = [
buffer,
new Int8Array(buffer, 1),
new Uint8Array(buffer, 2),
new Uint8ClampedArray(buffer, 2),
new Int16Array(buffer, 2),
new Uint16Array(buffer, 2),
new Int32Array(buffer, 4),
new Uint32Array(buffer, 4),
new Float32Array(buffer, 4),
new Float64Array(buffer, 0),
new BigInt64Array(buffer, 0),
new BigUint64Array(buffer, 0),
new DataView(buffer, 3),
];
const stream = passThrough(
ReactServerDOMServer.renderToReadableStream(buffers),
);
const result = await ReactServerDOMClient.createFromReadableStream(stream, {
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
});
expect(result).toEqual(buffers);
});
// @gate enableBinaryFlight
it('should be able to serialize a blob', async () => {
const bytes = new Uint8Array([
123, 4, 10, 5, 100, 255, 244, 45, 56, 67, 43, 124, 67, 89, 100, 20,
]);
const blob = new Blob([bytes, bytes], {
type: 'application/x-test',
});
const stream = passThrough(
ReactServerDOMServer.renderToReadableStream(blob),
);
const result = await ReactServerDOMClient.createFromReadableStream(stream, {
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
});
expect(result instanceof Blob).toBe(true);
expect(result.size).toBe(bytes.length * 2);
expect(await result.arrayBuffer()).toEqual(await blob.arrayBuffer());
});
// @gate enableBinaryFlight
it('can transport FormData (blobs)', async () => {
const bytes = new Uint8Array([
123, 4, 10, 5, 100, 255, 244, 45, 56, 67, 43, 124, 67, 89, 100, 20,
]);
const blob = new Blob([bytes, bytes], {
type: 'application/x-test',
});
const formData = new FormData();
formData.append('hi', 'world');
formData.append('file', blob, 'filename.test');
expect(formData.get('file') instanceof File).toBe(true);
expect(formData.get('file').name).toBe('filename.test');
const stream = passThrough(
ReactServerDOMServer.renderToReadableStream(formData),
);
const result = await ReactServerDOMClient.createFromReadableStream(stream, {
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
});
expect(result instanceof FormData).toBe(true);
expect(result.get('hi')).toBe('world');
const resultBlob = result.get('file');
expect(resultBlob instanceof Blob).toBe(true);
expect(resultBlob.name).toBe('blob'); // We should not pass through the file name for security.
expect(resultBlob.size).toBe(bytes.length * 2);
expect(await resultBlob.arrayBuffer()).toEqual(await blob.arrayBuffer());
});
it('can pass an async import that resolves later to an outline object like a Map', async () => {
let resolve;
const promise = new Promise(r => (resolve = r));
const asyncClient = clientExports(promise);
// We await the value on the servers so it's an async value that the client should wait for
const awaitedValue = await asyncClient;
const map = new Map();
map.set('value', awaitedValue);
const stream = passThrough(
ReactServerDOMServer.renderToReadableStream(map, webpackMap),
);
// Parsing the root blocks because the module hasn't loaded yet
const resultPromise = ReactServerDOMClient.createFromReadableStream(
stream,
{
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
},
);
// Afterwards we finally resolve the module value so it's available on the client
resolve('hello');
const result = await resultPromise;
expect(result instanceof Map).toBe(true);
expect(result.get('value')).toBe('hello');
});
// @gate enableFlightReadableStream
it('can pass an async import to a ReadableStream while enqueuing in order', async () => {
let resolve;
const promise = new Promise(r => (resolve = r));
const asyncClient = clientExports(promise);
// We await the value on the servers so it's an async value that the client should wait for
const awaitedValue = await asyncClient;
const s = new ReadableStream({
start(c) {
c.enqueue('hello');
c.enqueue(awaitedValue);
c.enqueue('!');
c.close();
},
});
const stream = passThrough(
ReactServerDOMServer.renderToReadableStream(s, webpackMap),
);
const result = await ReactServerDOMClient.createFromReadableStream(stream, {
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
});
const reader = result.getReader();
expect(await reader.read()).toEqual({value: 'hello', done: false});
const readPromise = reader.read();
// We resolve this after we've already received the '!' row.
await resolve('world');
expect(await readPromise).toEqual({value: 'world', done: false});
expect(await reader.read()).toEqual({value: '!', done: false});
expect(await reader.read()).toEqual({value: undefined, done: true});
});
// @gate enableFlightReadableStream
it('can pass an async import a AsyncIterable while allowing peaking at future values', async () => {
let resolve;
const promise = new Promise(r => (resolve = r));
const asyncClient = clientExports(promise);
const multiShotIterable = {
async *[Symbol.asyncIterator]() {
yield 'hello';
// We await the value on the servers so it's an async value that the client should wait for
yield await asyncClient;
yield '!';
},
};
const stream = passThrough(
ReactServerDOMServer.renderToReadableStream(
multiShotIterable,
webpackMap,
),
);
// Parsing the root blocks because the module hasn't loaded yet
const result = await ReactServerDOMClient.createFromReadableStream(stream, {
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
});
const iterator = result[Symbol.asyncIterator]();
expect(await iterator.next()).toEqual({value: 'hello', done: false});
const readPromise = iterator.next();
// While the previous promise didn't resolve yet, we should be able to peak at the next value
// by iterating past it.
expect(await iterator.next()).toEqual({value: '!', done: false});
// We resolve the previous row after we've already received the '!' row.
await resolve('world');
expect(await readPromise).toEqual({value: 'world', done: false});
expect(await iterator.next()).toEqual({value: undefined, done: true});
});
// @gate enableFlightReadableStream
it('should ideally dedupe objects inside async iterables but does not yet', async () => {
const obj = {
this: {is: 'a large objected'},
with: {many: 'properties in it'},
};
const iterable = {
async *[Symbol.asyncIterator]() {
for (let i = 0; i < 30; i++) {
yield obj;
}
},
};
const stream = ReactServerDOMServer.renderToReadableStream({
iterable,
});
const [stream1, stream2] = passThrough(stream).tee();
const serializedContent = await readResult(stream1);
// TODO: Ideally streams should dedupe objects but because we never outline the objects
// they end up not having a row to reference them nor any of its nested objects.
// expect(serializedContent.length).toBeLessThan(400);
expect(serializedContent.length).toBeGreaterThan(400);
const result = await ReactServerDOMClient.createFromReadableStream(
stream2,
{
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
},
);
const items = [];
const iterator = result.iterable[Symbol.asyncIterator]();
let entry;
while (!(entry = await iterator.next()).done) {
items.push(entry.value);
}
// Should still match the result when parsed
expect(items.length).toBe(30);
// TODO: These should be the same
// expect(items[5]).toBe(items[10]); // two random items are the same instance
expect(items[5]).toEqual(items[10]);
});
it('warns if passing a this argument to bind() of a server reference', async () => {
const ServerModule = serverExports({
greet: function () {},
});
const ServerModuleImportedOnClient = {
greet: ReactServerDOMClient.createServerReference(
ServerModule.greet.$$id,
async function (ref, args) {},
),
};
expect(() => {
ServerModule.greet.bind({}, 'hi');
}).toErrorDev(
'Cannot bind "this" of a Server Action. Pass null or undefined as the first argument to .bind().',
{withoutStack: true},
);
expect(() => {
ServerModuleImportedOnClient.greet.bind({}, 'hi');
}).toErrorDev(
'Cannot bind "this" of a Server Action. Pass null or undefined as the first argument to .bind().',
{withoutStack: true},
);
});
// @gate enableFlightReadableStream && enableBinaryFlight
it('should supports ReadableStreams with typed arrays', async () => {
const buffer = new Uint8Array([
123, 4, 10, 5, 100, 255, 244, 45, 56, 67, 43, 124, 67, 89, 100, 20,
]).buffer;
const buffers = [
buffer,
new Int8Array(buffer, 1),
new Uint8Array(buffer, 2),
new Uint8ClampedArray(buffer, 2),
new Int16Array(buffer, 2),
new Uint16Array(buffer, 2),
new Int32Array(buffer, 4),
new Uint32Array(buffer, 4),
new Float32Array(buffer, 4),
new Float64Array(buffer, 0),
new BigInt64Array(buffer, 0),
new BigUint64Array(buffer, 0),
new DataView(buffer, 3),
];
// This is not a binary stream, it's a stream that contain binary chunks.
const s = new ReadableStream({
start(c) {
for (let i = 0; i < buffers.length; i++) {
c.enqueue(buffers[i]);
}
c.close();
},
});
const stream = ReactServerDOMServer.renderToReadableStream(s, {});
const [stream1, stream2] = passThrough(stream).tee();
const result = await ReactServerDOMClient.createFromReadableStream(
stream1,
{
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
},
);
expect(await readByteLength(stream2)).toBeLessThan(300);
const streamedBuffers = [];
const reader = result.getReader();
let entry;
while (!(entry = await reader.read()).done) {
streamedBuffers.push(entry.value);
}
expect(streamedBuffers).toEqual(buffers);
});
// @gate enableFlightReadableStream && enableBinaryFlight
it('should support BYOB binary ReadableStreams', async () => {
const buffer = new Uint8Array([
123, 4, 10, 5, 100, 255, 244, 45, 56, 67, 43, 124, 67, 89, 100, 20,
]).buffer;
const buffers = [
new Int8Array(buffer, 1),
new Uint8Array(buffer, 2),
new Uint8ClampedArray(buffer, 2),
new Int16Array(buffer, 2),
new Uint16Array(buffer, 2),
new Int32Array(buffer, 4),
new Uint32Array(buffer, 4),
new Float32Array(buffer, 4),
new Float64Array(buffer, 0),
new BigInt64Array(buffer, 0),
new BigUint64Array(buffer, 0),
new DataView(buffer, 3),
];
// This a binary stream where each chunk ends up as Uint8Array.
const s = new ReadableStream({
type: 'bytes',
start(c) {
for (let i = 0; i < buffers.length; i++) {
c.enqueue(buffers[i]);
}
c.close();
},
});
const stream = ReactServerDOMServer.renderToReadableStream(s, {});
const [stream1, stream2] = passThrough(stream).tee();
const result = await ReactServerDOMClient.createFromReadableStream(
stream1,
{
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
},
);
expect(await readByteLength(stream2)).toBeLessThan(300);
const streamedBuffers = [];
const reader = result.getReader({mode: 'byob'});
let entry;
while (!(entry = await reader.read(new Uint8Array(10))).done) {
expect(entry.value instanceof Uint8Array).toBe(true);
streamedBuffers.push(entry.value);
}
// The streamed buffers might be in different chunks and in Uint8Array form but
// the concatenated bytes should be the same.
expect(streamedBuffers.flatMap(t => Array.from(t))).toEqual(
buffers.flatMap(c =>
Array.from(new Uint8Array(c.buffer, c.byteOffset, c.byteLength)),
),
);
});
it('supports async server component debug info as the element owner in DEV', async () => {
function Container({children}) {
return children;
}
const promise = Promise.resolve(true);
async function Greeting({firstName}) {
// We can't use JSX here because it'll use the Client React.
const child = ReactServer.createElement(
'span',
null,
'Hello, ' + firstName,
);
// Yield the synchronous pass
await promise;
// We should still be able to track owner using AsyncLocalStorage.
return ReactServer.createElement(Container, null, child);
}
const model = {
greeting: ReactServer.createElement(Greeting, {firstName: 'Seb'}),
};
const stream = ReactServerDOMServer.renderToReadableStream(
model,
webpackMap,
);
const rootModel = await ReactServerDOMClient.createFromReadableStream(
stream,
{
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
},
);
const ssrStream = await ReactDOMServer.renderToReadableStream(
rootModel.greeting,
);
const result = await readResult(ssrStream);
expect(result).toEqual('<span>Hello, Seb</span>');
// Resolve the React Lazy wrapper which must have resolved by now.
const lazyWrapper = rootModel.greeting;
const greeting = lazyWrapper._init(lazyWrapper._payload);
// We've rendered down to the span.
expect(greeting.type).toBe('span');
if (__DEV__) {
const greetInfo = expect.objectContaining({
name: 'Greeting',
env: 'Server',
owner: null,
});
expect(lazyWrapper._debugInfo).toEqual([
greetInfo,
expect.objectContaining({
name: 'Container',
env: 'Server',
owner: greetInfo,
}),
]);
// The owner that created the span was the outer server component.
// We expect the debug info to be referentially equal to the owner.
expect(greeting._owner).toBe(lazyWrapper._debugInfo[0]);
} else {
expect(lazyWrapper._debugInfo).toBe(undefined);
expect(greeting._owner).toBe(
gate(flags => flags.disableStringRefs) ? undefined : null,
);
}
});
// @gate __DEV__ && enableOwnerStacks
it('can get the component owner stacks asynchronously', async () => {
let stack;
function Foo() {
return ReactServer.createElement(Bar, null);
}
function Bar() {
return ReactServer.createElement(
'div',
null,
ReactServer.createElement(Baz, null),
);
}
const promise = Promise.resolve(0);
async function Baz() {
await promise;
stack = ReactServer.captureOwnerStack();
return ReactServer.createElement('span', null, 'hi');
}
const stream = ReactServerDOMServer.renderToReadableStream(
ReactServer.createElement(
'div',
null,
ReactServer.createElement(Foo, null),
),
webpackMap,
);
await readResult(stream);
expect(normalizeCodeLocInfo(stack)).toBe(
'\n in Bar (at **)' + '\n in Foo (at **)',
);
});
});