File size: 3,164 Bytes
52c6f5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
export interface StreamChunk {
	type: "chunk" | "done" | "error";
	content?: string;
	error?: string;
}

export class StreamReader {
	private decoder = new TextDecoder();
	private buffer = "";

	constructor(private response: Response) {
		if (!response.body) {
			throw new Error("Response has no body");
		}
	}

	async *read(): AsyncGenerator<StreamChunk, void, unknown> {
		const reader = this.response.body!.getReader();

		try {
			while (true) {
				const { done, value } = await reader.read();
				if (done) break;

				this.buffer += this.decoder.decode(value, { stream: true });
				const lines = this.buffer.split("\n");
				this.buffer = lines.pop() || "";

				for (const line of lines) {
					if (line.startsWith("data: ")) {
						const data = line.slice(6).trim();
						if (!data) continue;

						try {
							const parsed = JSON.parse(data) as StreamChunk;
							yield parsed;
							if (parsed.type === "done") return;
						} catch {
							// Ignore malformed JSON
						}
					}
				}
			}
		} finally {
			reader.releaseLock();
		}
	}

	static async fromFetch(url: string, options?: RequestInit): Promise<StreamReader> {
		const response = await fetch(url, options);
		if (!response.ok) {
			const error = await response.json();
			throw new Error(error.error || "Request failed");
		}
		return new StreamReader(response);
	}
}

export class StreamWriter {
	private encoder = new TextEncoder();
	private controller?: ReadableStreamDefaultController<Uint8Array>;
	public readonly stream: ReadableStream<Uint8Array>;

	constructor() {
		this.stream = new ReadableStream({
			start: controller => {
				this.controller = controller;
			},
		});
	}

	write(chunk: StreamChunk): void {
		if (!this.controller) {
			return;
		}

		try {
			const data = JSON.stringify(chunk);
			this.controller.enqueue(this.encoder.encode(`data: ${data}\n\n`));
		} catch {
			// Controller might be closed
		}
	}

	writeChunk(content: string): void {
		this.write({ type: "chunk", content });
	}

	writeError(error: string): void {
		this.write({ type: "error", error });
	}

	end(): void {
		if (!this.controller) return;
		try {
			this.write({ type: "done" });
			this.controller.close();
		} catch {
			// Controller might already be closed
		}
		this.controller = undefined;
	}

	error(error: Error): void {
		if (!this.controller) return;
		try {
			this.writeError(error.message);
			this.controller.close();
		} catch {
			// Controller might already be closed
		}
		this.controller = undefined;
	}

	createResponse(): Response {
		return new Response(this.stream, {
			headers: {
				"Content-Type": "text/event-stream",
				"Cache-Control": "no-cache",
				"Connection": "keep-alive",
			},
		});
	}
}

export async function streamFromAsyncIterable<T>(
	iterable: AsyncIterable<T>,
	transform: (item: T) => StreamChunk,
): Promise<ReadableStream<Uint8Array>> {
	const writer = new StreamWriter();

	(async () => {
		try {
			for await (const item of iterable) {
				writer.write(transform(item));
			}
			writer.end();
		} catch (error) {
			writer.error(error instanceof Error ? error : new Error(String(error)));
		}
	})();

	return writer.stream;
}