7e0b8aa4d1
Since we're always using `ReadableStream`, we should just get rid of `ResultPiper`. This also lets us replace things like `bufferedReadFromReadableStream` with a `TransformStream` that does the same thing, so that it's `TransformStream`s all the way down. Finally, we can get rid of the one-off call to `renderToReadableStream` and just use `renderToStream` whenever we're rendering a concurrent tree.
66 lines
1.4 KiB
TypeScript
66 lines
1.4 KiB
TypeScript
import type { ServerResponse } from 'http'
|
|
|
|
export default class RenderResult {
|
|
_result: string | ReadableStream
|
|
|
|
constructor(response: string | ReadableStream) {
|
|
this._result = response
|
|
}
|
|
|
|
toUnchunkedString(): string {
|
|
if (typeof this._result !== 'string') {
|
|
throw new Error(
|
|
'invariant: dynamic responses cannot be unchunked. This is a bug in Next.js'
|
|
)
|
|
}
|
|
return this._result
|
|
}
|
|
|
|
pipe(res: ServerResponse): Promise<void> {
|
|
if (typeof this._result === 'string') {
|
|
throw new Error(
|
|
'invariant: static responses cannot be piped. This is a bug in Next.js'
|
|
)
|
|
}
|
|
const response = this._result
|
|
const flush =
|
|
typeof (res as any).flush === 'function'
|
|
? () => (res as any).flush()
|
|
: () => {}
|
|
|
|
return (async () => {
|
|
const reader = response.getReader()
|
|
let fatalError = false
|
|
|
|
try {
|
|
while (true) {
|
|
const { done, value } = await reader.read()
|
|
|
|
if (done) {
|
|
res.end()
|
|
return
|
|
}
|
|
|
|
fatalError = true
|
|
res.write(value)
|
|
flush()
|
|
}
|
|
} catch (err) {
|
|
if (fatalError) {
|
|
res.destroy(err as any)
|
|
}
|
|
throw err
|
|
}
|
|
})()
|
|
}
|
|
|
|
isDynamic(): boolean {
|
|
return typeof this._result !== 'string'
|
|
}
|
|
|
|
static fromStatic(value: string): RenderResult {
|
|
return new RenderResult(value)
|
|
}
|
|
|
|
static empty = RenderResult.fromStatic('')
|
|
}
|