'use client' import { isServer } from '@tanstack/react-query' import { useServerInsertedHTML } from 'next/navigation' import * as React from 'react' import { htmlEscapeJsonString } from './htmlescape' const serializedSymbol = Symbol('serialized') interface DataTransformer { serialize: (object: any) => any deserialize: (object: any) => any } type Serialized = unknown & { [serializedSymbol]: TData } interface TypedDataTransformer { serialize: (obj: TData) => Serialized deserialize: (obj: Serialized) => TData } interface HydrationStreamContext { id: string stream: { /** * **Server method** * Push a new entry to the stream * Will be ignored on the client */ push: (...shape: Array) => void } } export interface HydrationStreamProviderProps { children: React.ReactNode /** * Optional transformer to serialize/deserialize the data * Example devalue, superjson et al */ transformer?: DataTransformer /** * **Client method** * Called in the browser when new entries are received */ onEntries: (entries: Array) => void /** * **Server method** * onFlush is called on the server when the cache is flushed */ onFlush?: () => Array /** * A nonce that'll allow the inline script to be executed when Content Security Policy is enforced */ nonce?: string } export function createHydrationStreamProvider() { const context = React.createContext>( null as any, ) /** * 1. (Happens on server): `useServerInsertedHTML()` is called **on the server** whenever a `Suspense`-boundary completes * - This means that we might have some new entries in the cache that needs to be flushed * - We pass these to the client by inserting a `