import { AsyncIteratorClass } from '@standard-server/shared' import { once } from './function' import { isPlainObject } from './object' import { promiseWithResolvers } from './promise' import type { StartSpanOptions } from './tracing' import { recordSpanError, runInSpanContext, startSpan } from './tracing' import type { Promisable } from './types' import type { ThrowableError } from './types' export function replicateReadableStream( stream: ReadableStream, count: number, ): ReadableStream[] { if (count <= 0) { return [] } const replicated: ReadableStream[] = [] let pending = stream for (let index = 0; index < count - 1; index++) { const [replica, remainder] = pending.tee() replicated.push(replica) pending = remainder } replicated.push(pending) return replicated } export type ReadableStreamReadResult = | { done: false; value: T } | { done: true; value?: T | undefined } export interface WrapReadableStreamOptions { /** * Any call to the original stream reader will be executed inside this function. * Useful when you want execution to happen within a specific context, * such as AsyncLocalStorage. */ runWith?: ((run: () => Promise) => Promisable) | undefined mapResult?: | ((result: ReadableStreamReadResult) => Promisable>) | undefined mapError?: ((error: ThrowableError) => Promisable) | undefined onError?: ((error: ThrowableError) => Promisable) | undefined /** * Guaranteed to execute exactly once after the stream finishes or is cancelled. */ onFinish?: (() => Promisable) | undefined } export function wrapReadableStream( stream: ReadableStream, { runWith, mapResult, mapError, onError, onFinish }: WrapReadableStreamOptions, ): NoInfer> { runWith ??= (run) => run() const reader = once(() => stream.getReader()) const finish = once(async () => onFinish?.()) // TODO: return new ReadableStream( { async pull(controller) { let result: ReadableStreamReadResult try { const readResult = await runWith(() => reader().read()) result = mapResult ? await mapResult(readResult) : (readResult as ReadableStreamReadResult) } catch (error) { try { await onError?.(error as ThrowableError) controller.error(mapError ? await mapError(error as ThrowableError) : error) } finally { await finish() } return } if (result.done) { controller.close() await finish() } else { controller.enqueue(result.value) } }, async cancel(reason) { try { try { await runWith(() => reader().cancel(reason)) } catch (error) { await onError?.(error as ThrowableError) throw error } } finally { await finish() } }, }, { highWaterMark: 0 }, ) } export function traceReadableStream( options: StartSpanOptions | string, stream: ReadableStream, ): ReadableStream { const getSpan = once(() => startSpan(options)) return wrapReadableStream(stream, { runWith: (run) => runInSpanContext(getSpan(), run), mapResult(result) { getSpan()?.addEvent(result.done ? 'closed' : 'enqueued') return result }, onError(error) { recordSpanError(getSpan(), error) }, onFinish() { getSpan()?.end() }, }) } /** * Converts a {@link ReadableStream} into an {@link AsyncIteratorClass}. * * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration} */ export function streamToAsyncIteratorObject( stream: ReadableStream, { signal }: { signal?: AbortSignal | undefined } = {}, ): AsyncIteratorClass { const reader = stream.getReader() let cancelledBySignal = false return new AsyncIteratorClass( async () => { if (signal?.aborted) { cancelledBySignal = true throw signal.reason } if (!signal) { return reader.read() as Promise> } const { promise, reject } = promiseWithResolvers() const onAbort = () => reject(signal.reason) signal.addEventListener('abort', onAbort, { once: true }) try { return await Promise.race([ reader.read() as Promise>, promise.catch(async (reason) => { cancelledBySignal = true throw reason }), ]) } finally { signal.removeEventListener('abort', onAbort) } }, async ({ kind, error }) => { if (kind === 'cancelled' || (kind === 'error' && cancelledBySignal)) { await reader.cancel(error) } }, ) } /** * Converts an `AsyncIterator` into a `ReadableStream`. */ export function asyncIteratorToStream(iterator: AsyncIterator): ReadableStream { return createIteratorStream(iterator, (value) => value) } /** * Converts an `AsyncIterator` into a `ReadableStream`, ensuring that * all emitted object values are *unproxied* before enqueuing. * * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration} */ export function asyncIteratorToUnproxiedDataStream( iterator: AsyncIterator, ): ReadableStream { return createIteratorStream(iterator, (value) => isPlainObject(value) ? { ...value } : Array.isArray(value) ? (value.map((i) => i) as T) // use .map instead of ... to deal with sparse arrays : value, ) } function createIteratorStream( iterator: AsyncIterator, map: (value: T) => T, ): ReadableStream { return new ReadableStream( { async pull(controller) { const { done, value } = await iterator.next() if (done) { controller.close() } else { controller.enqueue(map(value)) } }, async cancel() { await iterator.return?.() }, }, { highWaterMark: 0 }, ) }