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 reader.releaseLock()
41 }
42}
43
44/**
45 * Parse a Response body as Server-Sent Events, yielding StreamChunks.
46 *
47 * Used by GenerationClient to parse SSE Responses returned from fetchers
48 * (e.g., TanStack Start server functions using `toServerSentEventsResponse()`).
49 */
50export async function* parseSSEResponse(
51 response: Response,
52 abortSignal?: AbortSignal,
53): AsyncGenerator<StreamChunk> {
54 if (!response.ok) {
55 if (response.status === 401) {
56 const body: unknown = await response
57 .clone()
58 .json()
59 .catch(() => null)
60 if (isByokMissingBody(body)) {
61 throw new ByokMissingError(body.error.provider)
62 }
63 }
64 throw new Error(
65 `HTTP error! status: ${response.status} ${response.statusText}`,
66 )
67 }
68
69 const reader = getResponseStreamReader(response)
70
71 for await (const line of readStreamLines(reader, abortSignal)) {
72 const data = parseSseDataLine(line)
73
74 if (data === '[DONE]') {
75 console.warn(
76 '[@tanstack/ai-client] Received [DONE] sentinel. This is deprecated — upgrade your @tanstack/ai server package. RUN_FINISHED is the stream terminator.',
77 )
78 continue
79 }
80
81 try {
82 const parsed: StreamChunk = JSON.parse(data)
83 yield parsed
84 } catch (parseError) {
85 console.warn('Failed to parse SSE chunk:', data)
86 }
87 }
88}