@@ -104,7 +104,10 @@ export function transformStreamWithRouter(
104104 let timeoutHandle : NodeJS . Timeout
105105
106106 const finalPassThrough = createPassthrough ( ( ) => {
107- stopListeningToInjectedHtml ?.( )
107+ if ( stopListeningToInjectedHtml ) {
108+ stopListeningToInjectedHtml ( )
109+ stopListeningToInjectedHtml = undefined
110+ }
108111 clearTimeout ( timeoutHandle )
109112 } )
110113 const textDecoder = new TextDecoder ( )
@@ -134,34 +137,36 @@ export function transformStreamWithRouter(
134137 let processingCount = 0
135138
136139 // Process any already-injected HTML
137- router . serverSsr ! . injectedHtml . forEach ( ( promise ) => {
138- handleInjectedHtml ( promise )
139- } )
140+ handleInjectedHtml ( )
140141
141142 // Listen for any new injected HTML
142- stopListeningToInjectedHtml = router . subscribe ( 'onInjectedHtml' , ( e ) => {
143- handleInjectedHtml ( e . promise )
144- } )
145-
146- function handleInjectedHtml ( promise : Promise < string > ) {
147- processingCount ++
148-
149- promise
150- . then ( ( html ) => {
151- if ( isAppRendering ) {
152- routerStreamBuffer += html
153- } else {
154- finalPassThrough . write ( html )
155- }
156- } )
157- . catch ( injectedHtmlDonePromise . reject )
158- . finally ( ( ) => {
159- processingCount --
143+ stopListeningToInjectedHtml = router . subscribe (
144+ 'onInjectedHtml' ,
145+ handleInjectedHtml ,
146+ )
160147
161- if ( ! isAppRendering && processingCount === 0 ) {
162- injectedHtmlDonePromise . resolve ( )
163- }
164- } )
148+ function handleInjectedHtml ( ) {
149+ router . serverSsr ! . injectedHtml . forEach ( ( promise ) => {
150+ processingCount ++
151+
152+ promise
153+ . then ( ( html ) => {
154+ if ( isAppRendering ) {
155+ routerStreamBuffer += html
156+ } else {
157+ finalPassThrough . write ( html )
158+ }
159+ } )
160+ . catch ( injectedHtmlDonePromise . reject )
161+ . finally ( ( ) => {
162+ processingCount --
163+
164+ if ( ! isAppRendering && processingCount === 0 ) {
165+ injectedHtmlDonePromise . resolve ( )
166+ }
167+ } )
168+ } )
169+ router . serverSsr ! . injectedHtml = [ ]
165170 }
166171
167172 injectedHtmlDonePromise
@@ -176,7 +181,12 @@ export function transformStreamWithRouter(
176181 console . error ( 'Error reading routerStream:' , err )
177182 finalPassThrough . destroy ( err )
178183 } )
179- . finally ( ( ) => stopListeningToInjectedHtml ?.( ) )
184+ . finally ( ( ) => {
185+ if ( stopListeningToInjectedHtml ) {
186+ stopListeningToInjectedHtml ( )
187+ stopListeningToInjectedHtml = undefined
188+ }
189+ } )
180190
181191 // Transform the appStream
182192 readStream ( appStream , {
0 commit comments