Open History to see the last commit
1import { ByokMissingError, isByokMissingBody } from '@tanstack/ai/byok'
2import {
3 createResponseStreamTextDecoder,
4 getResponseStreamReader,
5} from './response-stream'
6import { parseSseDataLine } from './sse-utils'
7import type { StreamChunk } from '@tanstack/ai/client'
8
9/**
10 * Read lines from a stream (newline-delimited)
11 */
12async function* readStreamLines(
13 reader: ReadableStreamDefaultReader<Uint8Array>,
14 abortSignal?: AbortSignal,
15): AsyncGenerator<string> {
16 try {
17 const decoder = createResponseStreamTextDecoder()
18 let buffer = ''
19
20 while (!abortSignal?.aborted) {
21 const { done, value } = await reader.read()
22 if (done) break
23
24 buffer += decoder.decode(value, { stream: true })
25 const lines = buffer.split('\n')
26
27 buffer = lines.pop() || ''
28
29 for (const line of lines) {
30 if (line.trim()) {
31 yield line
32 }
33 }
34 }
35
36 if (buffer.trim()) {
37 yield buffer
38 }
39 } finally {
40 try {
41 // Custom cancellation hooks must not delay errors or iterator return.
42 void reader.cancel().catch(() => {})
43 } catch {
44 // Preserve the original error if cancellation throws synchronously.
45 }
46 reader.releaseLock()
47 }
48}
49
50/**
51 * Parse a Response body as Server-Sent Events, yielding StreamChunks.
52 *
53 * Used by GenerationClient to parse SSE Responses returned from fetchers
54 * (e.g., TanStack Start server functions using `toServerSentEventsResponse()`).
55 */
56export async function* parseSSEResponse(
57 response: Response,
58 abortSignal?: AbortSignal,
59): AsyncGenerator<StreamChunk> {
60 if (!response.ok) {
61 if (response.status === 401) {
62 const body: unknown = await response
63 .clone()
64 .json()
65 .catch(() => null)
66 if (isByokMissingBody(body)) {
67 throw new ByokMissingError(body.error.provider)
68 }
69 }
70 throw new Error(
71 `HTTP error! status: ${response.status} ${response.statusText}`,
72 )
73 }
74
75 const reader = getResponseStreamReader(response)
76
77 for await (const line of readStreamLines(reader, abortSignal)) {
78 const data = parseSseDataLine(line)
79
80 try {
81 const parsed: StreamChunk = JSON.parse(data)
82 yield parsed
83 } catch (parseError) {
84 console.warn('Failed to parse SSE chunk:', data)
85 }
86 }
87}