diff --git a/packages/react-client/src/ReactFlightClient.js b/packages/react-client/src/ReactFlightClient.js index 1ffd5dcee7a0..8dd5b64d5df5 100644 --- a/packages/react-client/src/ReactFlightClient.js +++ b/packages/react-client/src/ReactFlightClient.js @@ -1021,14 +1021,28 @@ type InitializationReference = { path: Array, isDebug?: boolean, // DEV-only }; -type InitializationHandler = { +type PendingInitializationHandler = { parent: null | InitializationHandler, chunk: null | BlockedChunk, value: any, - reason: any, + // The controller of a stream whose chunk is blocked on its debug info. Null + // for every other model. + reason: null | FlightStreamController, deps: number, - errored: boolean, + errored: false, }; +type ErroredInitializationHandler = { + parent: null | InitializationHandler, + chunk: null | BlockedChunk, + value: null, + // The error the handler was rejected with. + reason: mixed, + deps: number, + errored: true, +}; +type InitializationHandler = + | PendingInitializationHandler + | ErroredInitializationHandler; let initializingHandler: null | InitializationHandler = null; let initializingChunk: null | BlockedChunk = null; let isInitializingDebugInfo: boolean = false; @@ -1144,46 +1158,104 @@ function initializeModelChunk(chunk: ResolvedModelChunk): void { try { const value: T = parseModel(response, resolvedModel); - // Invoke any listeners added while resolving this model. I.e. cyclic - // references. This may or may not fully resolve the model depending on - // if they were blocked. - const resolveListeners = cyclicChunk.value; - if (resolveListeners !== null) { - cyclicChunk.value = null; - cyclicChunk.reason = null; - for (let i = 0; i < resolveListeners.length; i++) { - const listener = resolveListeners[i]; - if (typeof listener === 'function') { - listener(value); - } else { - fulfillReference(response, listener, value, cyclicChunk); + const handler = initializingHandler; + if (handler !== null) { + if (handler.errored) { + // The handler errored during the parse, so `cyclicChunk` errors with + // the same reason. `triggerErrorOnChunk` also rejects the references + // that nested parses queued on `cyclicChunk` during the parse. No value + // will arrive for them. `initializeDebugChunk` can have errored + // `cyclicChunk` before the parse. That error stays. + if ((cyclicChunk as any).status === BLOCKED) { + triggerErrorOnChunk(response, cyclicChunk, handler.reason); } + return; } + // Record on the handler which chunk it completes, and with what value, + // before the listeners below are examined. `resolveBlockedCycle` walks + // from a reference to its handler and on to that handler's chunk. A cycle + // that closes through `cyclicChunk` is only found once `handler.chunk` is + // `cyclicChunk`. + handler.value = value; + handler.chunk = cyclicChunk; } - if (initializingHandler !== null) { - if (initializingHandler.errored) { - throw initializingHandler.reason; + + const listeners = cyclicChunk.value; + const rejectListeners = cyclicChunk.reason; + cyclicChunk.value = null; + cyclicChunk.reason = null; + if (listeners !== null) { + // These listeners were added to `cyclicChunk` while its model was + // parsing. They come from models that were parsed nested inside that + // parse and that pointed back at `cyclicChunk`. They fall in two groups. + // + // A reference whose handler is transitively waiting on `cyclicChunk` is a + // cycle. Neither side can complete before the other, so one of them has + // to accept the value as it is now. The reference receives the current + // object, and the outstanding references fill it in place. + // + // Every other listener waits. Its handler is not waiting on + // `cyclicChunk`, so it can receive the value once the model has resolved + // its own references, like any reference into a blocked chunk does. + // Handing it the value now would complete that handler with an object + // that still has references outstanding. Function listeners have no + // handler and always wait. + let cyclic: null | Array = null; + let deferred: null | Array mixed)> = null; + for (let i = 0; i < listeners.length; i++) { + const listener = listeners[i]; + if ( + typeof listener !== 'function' && + resolveBlockedCycle(cyclicChunk, listener) !== null + ) { + if (cyclic === null) { + cyclic = []; + } + cyclic.push(listener); + // A reference is queued for rejection as the same object that is + // queued for resolution. It is fulfilled below, so its rejection + // entry goes. + if (rejectListeners !== null) { + const rejectionIdx = rejectListeners.indexOf(listener); + if (rejectionIdx !== -1) { + rejectListeners.splice(rejectionIdx, 1); + } + } + } else { + if (deferred === null) { + deferred = []; + } + deferred.push(listener); + } } - if (initializingHandler.deps > 0) { - // We discovered new dependencies on modules that are not yet resolved. - // We have to keep the BLOCKED state until they're resolved. - initializingHandler.value = value; - initializingHandler.chunk = cyclicChunk; - return; + // Put the deferred listeners back on `cyclicChunk` before any cyclic + // reference is fulfilled. Fulfilling one can complete `cyclicChunk`, and + // completion wakes what is queued on it at that moment. + if (deferred !== null) { + cyclicChunk.value = deferred; + cyclicChunk.reason = rejectListeners; + } + if (cyclic !== null) { + for (let i = 0; i < cyclic.length; i++) { + fulfillReference(response, cyclic[i], value, cyclicChunk); + } } } - if (__DEV__) { - // Only a blocked chunk receives debug info, so release the set here. - cyclicChunk._receivedDebugInfo = null; - } - const initializedChunk: InitializedChunk = chunk as any; - initializedChunk.status = INITIALIZED; - initializedChunk.value = value; - initializedChunk.reason = null; - if (__DEV__) { - processChunkDebugInfo(response, initializedChunk, value); + if ((cyclicChunk as any).status !== BLOCKED) { + // Fulfilling a cyclic reference completed `cyclicChunk`, or failed and + // errored it. A failure rejects the reference's handler. The rejection + // reaches `cyclicChunk`, directly or through the cycle, because + // `handler.chunk` is set. + return; + } + if (handler !== null && handler.deps > 0) { + // The model references chunks that have not resolved yet. `cyclicChunk` + // stays BLOCKED, with the deferred listeners queued on it, until the last + // of those resolves. + return; } + initializeBlockedChunk(response, cyclicChunk, value, null); } catch (error) { const erroredChunk: ErroredChunk = chunk as any; erroredChunk.status = ERRORED; @@ -1622,6 +1694,58 @@ function getWeakChunk(response: Response, id: number): SomeChunk { return chunk; } +// Moves a blocked chunk to INITIALIZED and wakes whatever is waiting on it. The +// other `initialize*Chunk` functions start from a resolved chunk and parse it. +// This one starts from a chunk whose model is already parsed and whose +// references have all resolved. +function initializeBlockedChunk( + response: Response, + chunk: BlockedChunk, + value: T, + reason: InitializedChunk['reason'], +): void { + const resolveListeners = chunk.value; + if (__DEV__) { + // Only a blocked chunk receives debug info, so release the set here. + chunk._receivedDebugInfo = null; + } + const initializedChunk: InitializedChunk = chunk as any; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + initializedChunk.reason = reason; + if (resolveListeners !== null) { + wakeChunk(response, resolveListeners, value, initializedChunk); + } else if (__DEV__) { + processChunkDebugInfo(response, initializedChunk, value); + } +} + +// Initializes the handler's chunk once the handler has no references left to +// wait on. `handler.chunk` is null while the handler's model is still parsing. +// `initializeModelChunk` handles that case when the parse ends. +function initializeChunkIfUnblocked( + response: Response, + handler: InitializationHandler, +): void { + if (handler.deps !== 0 || handler.errored) { + return; + } + const chunk = handler.chunk; + if (chunk === null) { + return; + } + // `BlockedChunk` is the chunk's type at the time the handler recorded it. + // The chunk can have errored since, or a cyclic reference can have completed + // it, so its status is read again here. + if ((chunk as SomeChunk).status !== BLOCKED) { + return; + } + // `handler.reason` is the controller of a stream whose chunk was blocked on + // its debug info, and null otherwise. It becomes the initialized chunk's + // `reason` either way. + initializeBlockedChunk(response, chunk, handler.value, handler.reason); +} + function fulfillReference( response: Response, reference: InitializationReference, @@ -1809,29 +1933,7 @@ function fulfillReference( } handler.deps--; - - if (handler.deps === 0) { - const chunk = handler.chunk; - if (chunk === null || chunk.status !== BLOCKED) { - return; - } - const resolveListeners = chunk.value; - if (__DEV__) { - // Only a blocked chunk receives debug info, so release the set here. - chunk._receivedDebugInfo = null; - } - const initializedChunk: InitializedChunk = chunk as any; - initializedChunk.status = INITIALIZED; - initializedChunk.value = handler.value; - initializedChunk.reason = handler.reason; // Used by streaming chunks - if (resolveListeners !== null) { - wakeChunk(response, resolveListeners, handler.value, initializedChunk); - } else { - if (__DEV__) { - processChunkDebugInfo(response, initializedChunk, handler.value); - } - } - } + initializeChunkIfUnblocked(response, handler); } function rejectReference( @@ -1846,9 +1948,10 @@ function rejectReference( return; } const blockedValue = handler.value; - handler.errored = true; - handler.value = null; - handler.reason = error; + const erroredHandler: ErroredInitializationHandler = handler as any; + erroredHandler.errored = true; + erroredHandler.value = null; + erroredHandler.reason = error; const chunk = handler.chunk; if (chunk === null || chunk.status !== BLOCKED) { return; @@ -2067,25 +2170,7 @@ function loadServerReference, T>( } handler.deps--; - - if (handler.deps === 0) { - const chunk = handler.chunk; - if (chunk === null || chunk.status !== BLOCKED) { - return; - } - const resolveListeners = chunk.value; - const initializedChunk: InitializedChunk = chunk as any; - initializedChunk.status = INITIALIZED; - initializedChunk.value = handler.value; - initializedChunk.reason = null; - if (resolveListeners !== null) { - wakeChunk(response, resolveListeners, handler.value, initializedChunk); - } else { - if (__DEV__) { - processChunkDebugInfo(response, initializedChunk, handler.value); - } - } - } + initializeChunkIfUnblocked(response, handler); } function reject(error: mixed): void { @@ -2096,9 +2181,10 @@ function loadServerReference, T>( return; } const blockedValue = handler.value; - handler.errored = true; - handler.value = null; - handler.reason = error; + const erroredHandler: ErroredInitializationHandler = handler as any; + erroredHandler.errored = true; + erroredHandler.value = null; + erroredHandler.reason = error; const chunk = handler.chunk; if (chunk === null || chunk.status !== BLOCKED) { return; @@ -2284,9 +2370,11 @@ function getOutlinedModel( // This is an error. Instead of erroring directly, we're going to encode this on // an initialization handler so that we can catch it at the nearest Element. if (initializingHandler) { - initializingHandler.errored = true; - initializingHandler.value = null; - initializingHandler.reason = referencedChunk.reason; + const erroredHandler: ErroredInitializationHandler = + initializingHandler as any; + erroredHandler.errored = true; + erroredHandler.value = null; + erroredHandler.reason = referencedChunk.reason; } else { initializingHandler = { parent: null, @@ -2393,9 +2481,11 @@ function getOutlinedModel( // This is an error. Instead of erroring directly, we're going to encode this on // an initialization handler so that we can catch it at the nearest Element. if (initializingHandler) { - initializingHandler.errored = true; - initializingHandler.value = null; - initializingHandler.reason = chunk.reason; + const erroredHandler: ErroredInitializationHandler = + initializingHandler as any; + erroredHandler.errored = true; + erroredHandler.value = null; + erroredHandler.reason = chunk.reason; } else { initializingHandler = { parent: null, diff --git a/packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMBrowser-test.js b/packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMBrowser-test.js index 7c84c2a2e6c2..fbd5fb55c806 100644 --- a/packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMBrowser-test.js +++ b/packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMBrowser-test.js @@ -3717,4 +3717,79 @@ describe('ReactFlightDOMBrowser', () => { expect(taskWhileRendering).toBe('\n"use client"'); }); }); + + it('rejects a value that waits on a row that fails to parse', async () => { + const foo = {}; + const x = {}; + // The server outlines a Set into its own row, and that row refers to foo by + // id. The client parses the Set's row nested inside foo's row, and queues a + // reference from the Set's row back onto foo's row. x is a member of the + // Set, so a later reference to x is a path into the Set's row that does not + // go through foo's row. + const bar = new Set([foo, x]); + foo.bar = bar; + // The server cannot serialize a function, so the row it outlines for + // `foo.broken` is an error row. foo's row refers to that error row. + foo.broken = new Set([() => {}]); + const object = { + foo: Promise.resolve(foo), + x: Promise.resolve(x), + }; + + const stream = await serverAct(() => + ReactServerDOMServer.renderToReadableStream(object, webpackMap, { + onError() {}, + }), + ); + // Error rows come last in the stream. The client parses foo's row when foo + // is first read, so the whole stream is delivered as one Uint8Array to make + // sure the error row has been processed by then. + const reader = stream.getReader(); + const parts = []; + for (;;) { + const {done, value} = await reader.read(); + if (done) { + break; + } + parts.push(value); + } + const total = parts.reduce((sum, part) => sum + part.byteLength, 0); + const bytes = new Uint8Array(total); + let offset = 0; + for (let i = 0; i < parts.length; i++) { + bytes.set(parts[i], offset); + offset += parts[i].byteLength; + } + + const response = await ReactServerDOMClient.createFromReadableStream( + new ReadableStream({ + start(controller) { + controller.enqueue(bytes); + controller.close(); + }, + }), + ); + + // Reading foo first parses foo's row, and the nested Set row along with it. + // The Set row then waits on foo's row, and foo's row fails on the error + // row. The client must reject the reference the Set row queued on foo's + // row, so that the Set row errors as well and x errors with the Set row. + const fooError = await Promise.resolve(response.foo).then( + () => null, + error => error, + ); + expect(fooError).toBeInstanceOf(Error); + if (__DEV__) { + expect(fooError.message).toContain( + 'Functions cannot be passed directly to Client Components', + ); + } + // The error object travels by identity from the error row into every row it + // errors, so x rejects with the same object that rejected foo. + const xError = await Promise.resolve(response.x).then( + () => null, + error => error, + ); + expect(xError).toBe(fooError); + }); }); diff --git a/packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMNode-test.js b/packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMNode-test.js index 88e3dcef2bf7..48162d3629c7 100644 --- a/packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMNode-test.js +++ b/packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMNode-test.js @@ -30,6 +30,7 @@ let Stream; let use; let assertConsoleErrorDev; let serverAct; +let getDebugInfo; // We test pass-through without encoding strings but it should work without it too. const streamOptions = { @@ -77,6 +78,10 @@ describe('ReactFlightDOMNode', () => { const InternalTestUtils = require('internal-test-utils'); assertConsoleErrorDev = InternalTestUtils.assertConsoleErrorDev; + getDebugInfo = InternalTestUtils.getDebugInfo.bind(null, { + ignoreProps: false, + useFixedTime: true, + }); }); function filterStackFrame(filename, functionName) { @@ -204,6 +209,28 @@ describe('ReactFlightDOMNode', () => { return {delayedStream, resolveDelayedStream}; } + // Runs an action that makes a Node stream emit, and flushes the ticks inside + // the act scope so that act sees the work the delivery triggers. Node streams + // hand data over through `process.nextTick`, which the fake timers mock. + function actOnStream(action: () => mixed): Promise { + return serverAct(() => { + action(); + jest.runAllTicks(); + }); + } + + // The Node client resolves client references through a server consumer + // manifest, which maps each client module id to the module the SSR bundle + // loads for it. These tests use the same module on both sides. + function createIdentityServerConsumerManifest(...clientReferences) { + const moduleMap = {}; + for (let i = 0; i < clientReferences.length; i++) { + const metadata = webpackMap[clientReferences[i].$$id]; + moduleMap[metadata.id] = {'*': metadata}; + } + return {moduleMap, moduleLoading: webpackModuleLoading}; + } + it('should support web streams in node', async () => { function Text({children}) { return {children}; @@ -980,10 +1007,10 @@ describe('ReactFlightDOMNode', () => { // The concrete location may change as this test is updated. // Just make sure they still point at React.use(p2) (gate(flags => flags.enableAsyncDebugInfo) - ? '\n at SharedComponent (./ReactFlightDOMNode-test.js:838:7)' + ? '\n at SharedComponent (./ReactFlightDOMNode-test.js:865:7)' : '') + - '\n at ServerComponent (file://./ReactFlightDOMNode-test.js:860:26)' + - '\n at App (file://./ReactFlightDOMNode-test.js:877:25)', + '\n at ServerComponent (file://./ReactFlightDOMNode-test.js:887:26)' + + '\n at App (file://./ReactFlightDOMNode-test.js:904:25)', ); } else { expect(ownerStack).toBeNull(); @@ -1567,12 +1594,12 @@ describe('ReactFlightDOMNode', () => { '\n' + ' in Dynamic' + (gate(flags => flags.enableAsyncDebugInfo) - ? ' (file://ReactFlightDOMNode-test.js:1441:27)\n' + ? ' (file://ReactFlightDOMNode-test.js:1468:27)\n' : '\n') + ' in body\n' + ' in html\n' + - ' in App (file://ReactFlightDOMNode-test.js:1454:25)\n' + - ' in ClientRoot (ReactFlightDOMNode-test.js:1529:16)', + ' in App (file://ReactFlightDOMNode-test.js:1481:25)\n' + + ' in ClientRoot (ReactFlightDOMNode-test.js:1556:16)', ); } else { expect( @@ -1581,7 +1608,7 @@ describe('ReactFlightDOMNode', () => { '\n' + ' in body\n' + ' in html\n' + - ' in ClientRoot (ReactFlightDOMNode-test.js:1529:16)', + ' in ClientRoot (ReactFlightDOMNode-test.js:1556:16)', ); } @@ -1591,8 +1618,8 @@ describe('ReactFlightDOMNode', () => { normalizeCodeLocInfo(ownerStack, {preserveLocation: true}), ).toBe( '\n' + - ' in Dynamic (file://ReactFlightDOMNode-test.js:1441:27)\n' + - ' in App (file://ReactFlightDOMNode-test.js:1454:25)', + ' in Dynamic (file://ReactFlightDOMNode-test.js:1468:27)\n' + + ' in App (file://ReactFlightDOMNode-test.js:1481:25)', ); } else { expect( @@ -1600,7 +1627,7 @@ describe('ReactFlightDOMNode', () => { ).toBe( '' + '\n' + - ' in App (file://ReactFlightDOMNode-test.js:1454:25)', + ' in App (file://ReactFlightDOMNode-test.js:1481:25)', ); } } else { @@ -1757,7 +1784,7 @@ describe('ReactFlightDOMNode', () => { normalizeCodeLocInfo(componentStack, {preserveLocation: true}), ).toBe( '\n' + - ' in ClientDynamic (ReactFlightDOMNode-test.js:1704:9)\n' + + ' in ClientDynamic (ReactFlightDOMNode-test.js:1731:9)\n' + ' in Suspense\n' + ' in body\n' + ' in html\n' + @@ -1768,7 +1795,7 @@ describe('ReactFlightDOMNode', () => { normalizeCodeLocInfo(componentStack, {preserveLocation: true}), ).toBe( '\n' + - ' in ClientDynamic (ReactFlightDOMNode-test.js:1704:9)\n' + + ' in ClientDynamic (ReactFlightDOMNode-test.js:1731:9)\n' + ' in Suspense\n' + ' in body\n' + ' in html\n' + @@ -1781,10 +1808,10 @@ describe('ReactFlightDOMNode', () => { '\n' + gate(flags => flags.enableAsyncDebugInfo - ? ' at ClientDynamic (./ReactFlightDOMNode-test.js:1705:9)\n' + ? ' at ClientDynamic (./ReactFlightDOMNode-test.js:1732:9)\n' : '', ) + - ' at ClientRoot (./ReactFlightDOMNode-test.js:1718:21)', + ' at ClientRoot (./ReactFlightDOMNode-test.js:1745:21)', ); } else { expect(ownerStack).toBeNull(); @@ -2485,4 +2512,191 @@ describe('ReactFlightDOMNode', () => { expect(getEventListeners(composite, 'abort')).toHaveLength(0); }); + + // @gate __DEV__ + it('does not expose a debug-tree element whose props still hold an unresolved reference', async () => { + // Regression test for facebook/react#37361. + // + // A server component element sits in its parent's componentInfo. Its props + // object is shared with its own componentInfo, so the debug channel + // outlines the props into a separate row. The client parses the props row + // nested inside the parent's componentInfo row, and registers the element's + // reference to the props row while that parse is still running. + // + // The client must not hand the element the props object at that point. The + // props row still waits on a client module reference, and the element is + // not part of that wait, so the lazy that wraps the element has to stay + // pending until the props row completes. An element initialized early + // carries the null placeholder where `ClientModule` belongs, which is what + // DevTools reads. In DEV its props are also frozen, so the module write + // that lands later throws, and the response rejects. + // + // The Suspense boundary inside PassthroughServerComponent keeps + // PassthroughServerComponent's componentInfo on row 0 and moves + // AsyncServerComponent's to the outlined row. Row 0 then resolves before + // the module loads, and the element is observable through the root's debug + // info while its props row is still waiting. + const received = []; + let resolveClientModuleChunk; + const ClientModule = clientExports( + {label: 'module'}, + '43', + '/client-module.js', + new Promise(resolve => (resolveClientModuleChunk = resolve)), + ); + const ClientComponent = clientExports(function ClientComponent(props) { + received.push({ + module: + props.module === null + ? 'null' + : props.module === undefined + ? 'undefined' + : 'object', + shared: + props.shared === null + ? 'null' + : props.shared === undefined + ? 'undefined' + : 'object', + }); + return React.createElement('span', null, 'client'); + }); + + const shared = {}; + const longText = 'a'.repeat(4000); + + let resolveIo; + async function AsyncServerComponent(props) { + await new Promise(resolve => { + resolveIo = resolve; + }); + return ReactServer.createElement( + 'div', + null, + longText, + ReactServer.createElement(ClientComponent, { + shared: props.shared, + module: props.ClientModule, + }), + ); + } + + function PassthroughServerComponent({children}) { + return ReactServer.createElement( + ReactServer.Suspense, + {fallback: 'loading'}, + children, + ); + } + + function App() { + return ReactServer.createElement(PassthroughServerComponent, { + shared, + children: ReactServer.createElement(AsyncServerComponent, { + shared, + ClientModule, + }), + }); + } + + let debugText = ''; + const rscStream = await serverAct(() => + ReactServerDOMServer.renderToPipeableStream( + ReactServer.createElement(App, null), + webpackMap, + { + debugChannel: new Stream.Writable({ + write(chunk, encoding, callback) { + debugText += Buffer.from(chunk).toString('utf8'); + callback(); + }, + }), + }, + ), + ); + + const rscChunks = []; + rscStream.pipe( + new Stream.Writable({ + write(chunk, encoding, callback) { + rscChunks.push(Buffer.from(chunk)); + callback(); + }, + }), + ); + await actOnStream(() => resolveIo('io')); + + const debugReadable = new Stream.PassThrough(streamOptions); + const rscReadable = new Stream.PassThrough(streamOptions); + const response = ReactServerDOMClient.createFromNodeStream( + rscReadable, + createIdentityServerConsumerManifest(ClientComponent, ClientModule), + {debugChannel: debugReadable}, + ); + + function ClientRoot() { + return use(response); + } + + // The SSR render runs ClientComponent, which records the props it receives. + const ssrErrors = []; + const ssrStream = ReactDOMServer.renderToPipeableStream( + React.createElement(ClientRoot), + { + onError(error) { + ssrErrors.push(String(error).slice(0, 80)); + }, + }, + ); + await actOnStream(() => + ssrStream.pipe(new Stream.PassThrough(streamOptions)), + ); + + const debugRows = debugText.split('\n'); + for (let i = 0; i < debugRows.length; i++) { + if (debugRows[i].length > 0) { + await actOnStream(() => debugReadable.write(debugRows[i] + '\n')); + } + } + await actOnStream(() => debugReadable.end()); + + for (let i = 0; i < rscChunks.length; i++) { + await actOnStream(() => rscReadable.write(rscChunks[i])); + } + await actOnStream(() => rscReadable.end()); + + // Row 0 resolves before the module loads, because the boundary keeps + // AsyncServerComponent's blocked debug chain off it. + await expect(response).resolves.toBeDefined(); + const root = await response; + + // DevTools reads the element from the componentInfo's `children`, through + // the payload of the lazy that wraps it. The status is recorded here and + // asserted after the module resolves, so that a regression fails on the + // frozen-props error first. + const passthroughInfo = getDebugInfo(root).find( + entry => entry.name === 'PassthroughServerComponent', + ); + const asyncServerElementLazy = passthroughInfo.props.children; + const payloadStatusBeforeModule = asyncServerElementLazy._payload.status; + + await actOnStream(() => resolveClientModuleChunk()); + + // Without the fix, the element was initialized before the module arrived, + // and writing the module into its frozen props throws. The SSR render + // reports the error. + expect(ssrErrors).toEqual([]); + expect(received).toEqual([{module: 'object', shared: 'object'}]); + + // An element initialized before the module arrived carries the null + // placeholder that DevTools reads, whether or not the write throws. The + // lazy must not have resolved while its props row was waiting. + expect(payloadStatusBeforeModule).not.toBe('fulfilled'); + + // Resolve the lazy the way a renderer does. It holds the module now. + const asyncServerElement = asyncServerElementLazy._init( + asyncServerElementLazy._payload, + ); + expect(asyncServerElement.props.ClientModule).toEqual({label: 'module'}); + }); });