// CI-stable tests for transformReadableStreamWithRouter behavior.
//
// These exercise the deterministic side-effects of the SSR memory fix
// (TanStack/router#7402) without relying on GC, timing of real I/O, or
// process.memoryUsage(). On-demand backpressure/external-memory
// assertions live in transformStreamBackpressure.perf.test.ts.
import { PassThrough, Readable } from 'node:stream'
import { describe, expect, test, vi } from 'vitest'
import { createMemoryHistory } from '@tanstack/history'
import { BaseRootRoute, BaseRoute } from '../src'
import { GLOBAL_TSR } from '../src/ssr/constants'
import {
HYDRATION_SCRIPT_BOUNDARY_BYTES,
HydrationScriptOutputState,
MAX_HYDRATION_OUTPUT_CHUNK_BYTES,
} from '../src/ssr/hydrationScripts'
import {
createSsrStreamResponse,
replaceSsrResponse,
} from '../src/ssr/handlerCallback'
import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server'
import {
transformHtmlStringWithRouter,
transformPipeableStreamWithRouter,
transformReadableStreamWithRouter,
} from '../src/ssr/transformStreamWithRouter'
import {
DOCUMENT_CLOSE_BYTES,
SCRIPT_CLOSE,
} from '../src/ssr/htmlBoundaryScanner'
import { createTestRouter } from './routerTestUtils'
import type { RouterManagedTag } from '../src/manifest'
import type { HydrationScriptOutput } from '../src/ssr/hydrationScripts'
const decoder = new TextDecoder()
const DOCUMENT_CLOSE = decoder.decode(DOCUMENT_CLOSE_BYTES)
const HYDRATION_SCRIPT_BOUNDARY_SUFFIX = decoder.decode(
HYDRATION_SCRIPT_BOUNDARY_BYTES,
)
const HYDRATION_SCRIPT_BOUNDARY_SOURCE =
`document.currentScript.remove()` +
HYDRATION_SCRIPT_BOUNDARY_SUFFIX.slice(0, -SCRIPT_CLOSE.length)
const SCRIPT_BARRIER_HTML = ``
function internalSplitOffsets(value: string) {
return Array.from({ length: value.length - 1 }, (_, index) => index + 1)
}
type FakeHydrationScripts = {
reserveFastPath: (output?: HydrationScriptOutput) => boolean
claimOutput: () => HydrationScriptOutput
liftBarrier: () => void
isInitialTaken: () => boolean
startSerializationTimeout: (timeoutMs: number) => void
}
type FakeServerSsr = {
hydrationScripts: FakeHydrationScripts
setRenderFinished: () => void
onCleanup: (listener: () => void) => void
cleanup: () => void
}
type MakeRouterOptions = Partial> &
Partial
type FakeRouter = {
serverSsr?: FakeServerSsr
}
type FakeHydrationRecord = {
bytes: Uint8Array
offset: number
}
function makeRouter(opts: MakeRouterOptions = {}): {
router: FakeRouter
cleanupCalls: { count: number }
claimCalls: { count: number }
emitHydrationRecord: (record: string) => void
emitScriptBatch: (parts: ReadonlyArray) => void
finishSerialization: () => void
failHydrationOutput: (error: unknown) => void
} {
const cleanupCalls = { count: 0 }
const claimCalls = { count: 0 }
const cleanupListeners: Array<() => void> = []
let cleanedUp = false
let producerDone = false
let claimed = false
let failure: unknown
let activeRecord: FakeHydrationRecord | undefined
const records: Array = []
let listener: (() => void) | undefined
let state: HydrationScriptOutput['state'] = HydrationScriptOutputState.Waiting
let serializationTimeout: ReturnType | undefined
const encoder = new TextEncoder()
function updateState() {
const nextState =
failure !== undefined
? HydrationScriptOutputState.Failed
: activeRecord
? HydrationScriptOutputState.Active
: records.length > 0
? HydrationScriptOutputState.Ready
: producerDone
? HydrationScriptOutputState.Done
: HydrationScriptOutputState.Waiting
if (state !== nextState) {
state = nextState
listener?.()
}
}
const output: HydrationScriptOutput = {
get state() {
return state
},
get error() {
return failure
},
pullChunk() {
if (state === HydrationScriptOutputState.Ready) {
activeRecord = records.shift()!
} else if (state !== HydrationScriptOutputState.Active) {
throw new Error('Fake hydration output is not ready')
}
const record = activeRecord!
const end = Math.min(
record.offset + MAX_HYDRATION_OUTPUT_CHUNK_BYTES,
record.bytes.length,
)
const chunk = record.bytes.subarray(record.offset, end)
record.offset = end
if (end === record.bytes.length) {
activeRecord = undefined
}
updateState()
return chunk
},
subscribe(onChange) {
if (listener) {
throw new Error('Fake hydration output already has a subscriber')
}
listener = onChange
return () => {
if (listener === onChange) {
listener = undefined
}
}
},
}
const {
reserveFastPath = () => false,
claimOutput = () => {
claimCalls.count++
if (claimed) {
throw new Error('Fake hydration output already has a consumer')
}
claimed = true
return output
},
liftBarrier = () => {},
isInitialTaken = () => true,
startSerializationTimeout = (timeoutMs: number) => {
if (
producerDone ||
failure !== undefined ||
serializationTimeout !== undefined
) {
return
}
serializationTimeout = setTimeout(() => {
serializationTimeout = undefined
failure = new Error('Serialization timeout after app render finished')
console.error('Serialization timeout after app render finished')
updateState()
}, timeoutMs)
},
...serverSsrOverrides
} = opts
const router: FakeRouter = {
serverSsr: {
hydrationScripts: {
reserveFastPath,
claimOutput,
liftBarrier,
isInitialTaken,
startSerializationTimeout,
},
setRenderFinished: () => {},
onCleanup: (cleanupListener: () => void) => {
if (cleanedUp) {
return
}
cleanupListeners.push(cleanupListener)
},
cleanup: () => {
if (cleanedUp) {
return
}
cleanedUp = true
cleanupCalls.count++
if (serializationTimeout !== undefined) {
clearTimeout(serializationTimeout)
serializationTimeout = undefined
}
records.length = 0
activeRecord = undefined
failure = undefined
listener = undefined
state = HydrationScriptOutputState.Done
// Mirror the real implementation: snapshot + clear, then notify.
const pendingCleanupListeners = cleanupListeners.slice()
cleanupListeners.length = 0
for (const cleanupListener of pendingCleanupListeners) {
cleanupListener()
}
router.serverSsr = undefined
},
...serverSsrOverrides,
},
}
function emitHydrationRecord(record: string) {
records.push({
bytes: encoder.encode(record),
offset: 0,
})
updateState()
}
return {
router,
cleanupCalls,
claimCalls,
emitHydrationRecord,
emitScriptBatch: (parts) => emitHydrationRecord(renderScriptBatch(parts)),
finishSerialization: () => {
producerDone = true
if (serializationTimeout !== undefined) {
clearTimeout(serializationTimeout)
serializationTimeout = undefined
}
updateState()
},
failHydrationOutput: (error) => {
failure = error
updateState()
},
}
}
function makeManualUpstream(): {
stream: ReadableStream
push: (s: string) => void
close: () => void
error: (reason: unknown) => void
cancelled: { value: boolean; reason: unknown }
} {
let controllerRef: ReadableStreamDefaultController | undefined
const cancelled = { value: false, reason: undefined as unknown }
const encoder = new TextEncoder()
const stream = new ReadableStream({
start(c) {
controllerRef = c
},
cancel(reason) {
cancelled.value = true
cancelled.reason = reason
},
})
return {
stream,
push: (s) => controllerRef!.enqueue(encoder.encode(s)),
close: () => controllerRef!.close(),
error: (reason) => controllerRef!.error(reason),
cancelled,
}
}
async function readAll(s: ReadableStream): Promise {
const reader = s.getReader()
const decoder = new TextDecoder()
let out = ''
for (;;) {
const { done, value } = await reader.read()
if (done) {
break
}
out += decoder.decode(value, { stream: true })
}
return out + decoder.decode()
}
async function readAllBytes(
stream: ReadableStream,
): Promise {
const reader = stream.getReader()
const chunks: Array = []
for (;;) {
const { done, value } = await reader.read()
if (done) {
break
}
chunks.push(Buffer.from(value))
}
return Buffer.concat(chunks)
}
async function readAllPipeableChunks(stream: Readable): Promise> {
const chunks: Array = []
for await (const chunk of stream) {
chunks.push(Buffer.from(chunk))
}
return chunks
}
async function readAllPipeableBytes(stream: Readable): Promise {
return Buffer.concat(await readAllPipeableChunks(stream))
}
function makeLargeStringRecord(prefix: string, suffix: string) {
return (
prefix +
'x'.repeat(
MAX_HYDRATION_OUTPUT_CHUNK_BYTES - 1 - Buffer.byteLength(prefix),
) +
'π' +
'ζΌ’x'.repeat(20_000) +
suffix
)
}
// Yield to the microtask queue a few times so async stream operations can
// drain. Avoids reliance on real timers.
async function flush(n = 5) {
for (let i = 0; i < n; i++) {
await Promise.resolve()
}
}
function createIssuePayload() {
return 'x'.repeat(17 * 1024 * 1024)
}
function createDeferred() {
let resolve!: (value: T) => void
let reject!: (reason?: unknown) => void
const promise = new Promise((res, rej) => {
resolve = res
reject = rej
})
return { promise, resolve, reject }
}
function createControlledStream() {
let controller!: ReadableStreamDefaultController
const stream = new ReadableStream({
start(c) {
controller = c
},
})
return { stream, controller }
}
function renderManagedScript(tag: RouterManagedTag) {
const attrs = tag.attrs ?? {}
const id = attrs.id ? ` id="${attrs.id}"` : ''
const className = attrs.className ? ` class="${attrs.className}"` : ''
const nonce = attrs.nonce ? ` nonce="${attrs.nonce}"` : ''
const streamPart =
'data-tsr-stream-part' in attrs ? ' data-tsr-stream-part=""' : ''
return ``
}
function renderManagedScripts(tags: Array) {
return tags.map(renderManagedScript).join('')
}
function renderInitialScripts(scripts: {
before: Array
boundary: RouterManagedTag
}) {
return renderManagedScripts([...scripts.before, scripts.boundary])
}
function renderScriptBatch(parts: ReadonlyArray) {
return ``
}
function createRealSsrRouter(dehydratedData: Record) {
const rootRoute = new BaseRootRoute({})
const indexRoute = new BaseRoute({
getParentRoute: () => rootRoute,
path: '/',
component: () => null,
})
return createTestRouter({
routeTree: rootRoute.addChildren([indexRoute]),
history: createMemoryHistory({ initialEntries: ['/'] }),
isServer: true,
dehydrate: () => dehydratedData,
})
}
describe('transformReadableStreamWithRouter β real SSR scripts', () => {
test('uses pass-through after Scripts takes all eager hydration scripts', async () => {
const router = createRealSsrRouter({ eager: 'loader-data' })
attachRouterServerSsrUtils({ router, manifest: undefined })
await router.load()
await router.serverSsr!.dehydrate()
// This is the server-side work performed by during rendering.
const initialScripts = router.serverSsr!.takeInitialHydrationScriptTags()
expect(initialScripts).toBeDefined()
const serverSsr = router.serverSsr!
const setRenderFinished = vi.spyOn(serverSsr, 'setRenderFinished')
const upstream = makeManualUpstream()
const html = `app${renderInitialScripts(
initialScripts!,
)}`
const output = transformReadableStreamWithRouter(router, upstream.stream)
// Pass-through reservation must not require render completion in advance.
expect(setRenderFinished).not.toHaveBeenCalled()
upstream.push(html)
upstream.close()
await expect(readAll(output)).resolves.toBe(html)
expect(setRenderFinished).toHaveBeenCalledOnce()
expect(router.serverSsr).toBeUndefined()
})
test('flushes stream-end scripts before body close when serialization finishes before transform starts', async () => {
const streamed = createDeferred()
const router = createRealSsrRouter({ streamed: streamed.promise })
attachRouterServerSsrUtils({ router, manifest: undefined })
await router.load()
await router.serverSsr!.dehydrate()
const initialScripts = router.serverSsr!.takeInitialHydrationScriptTags()
expect(initialScripts).toBeDefined()
const barrierScript = initialScripts!.boundary
expect(barrierScript.attrs).not.toHaveProperty('id')
expect(barrierScript).toBeDefined()
const initialHtml = renderInitialScripts(initialScripts!)
expect(initialHtml).toContain(`${GLOBAL_TSR}.router=`)
expect(initialHtml).not.toContain(`${GLOBAL_TSR}.e()`)
streamed.resolve('done')
await flush(20)
const upstream = makeManualUpstream()
const output = transformReadableStreamWithRouter(
router as any,
upstream.stream as any,
)
upstream.push(`app${initialHtml}`)
upstream.close()
const html = await readAll(output as any)
expect(html).toContain(`${GLOBAL_TSR}.router=`)
expect(html).toContain(`${GLOBAL_TSR}.e()`)
expect(html.indexOf(`${GLOBAL_TSR}.e()`)).toBeLessThan(
html.indexOf('