Skip to content

Commit 9c19de6

Browse files
committed
feat(json-rpc): support streamable responses
1 parent 7fee14d commit 9c19de6

1 file changed

Lines changed: 21 additions & 1 deletion

File tree

src/utils/json-rpc.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ export function defineJsonRpcHandler<
163163
// Processes a single JSON-RPC request.
164164
const processRequest = async (
165165
req: JsonRpcRequest,
166-
): Promise<JsonRpcResponse | undefined> => {
166+
): Promise<JsonRpcResponse | ReadableStream | undefined> => {
167167
// Validate the request object.
168168
if (req.jsonrpc !== "2.0" || typeof req.method !== "string") {
169169
return createJsonRpcError(
@@ -189,6 +189,17 @@ export function defineJsonRpcHandler<
189189
try {
190190
const result = await handler({ jsonrpc, id, method, params }, event);
191191

192+
if (isBatch && result instanceof ReadableStream) {
193+
throw new HTTPError({
194+
status: 400,
195+
message: "Streaming responses are not supported in batch requests.",
196+
});
197+
}
198+
199+
if (result instanceof ReadableStream) {
200+
return result;
201+
}
202+
192203
// For notifications, we don't send a response.
193204
if (id !== undefined && id !== null) {
194205
return { jsonrpc: "2.0", id, result };
@@ -224,6 +235,15 @@ export function defineJsonRpcHandler<
224235
(r): r is JsonRpcResponse => r !== undefined,
225236
);
226237

238+
if (
239+
!isBatch &&
240+
finalResponses.length === 1 &&
241+
finalResponses[0] instanceof ReadableStream
242+
) {
243+
event.res.headers.set("Content-Type", "text/event-stream");
244+
return finalResponses[0];
245+
}
246+
227247
event.res.headers.set("Content-Type", "application/json");
228248

229249
// If it was a batch request but contained only notifications, send 202 Accepted.

0 commit comments

Comments
 (0)