import { ServerSentEventStream } from "@std/http";
import { call, createChannel, each, spawn } from "effection";
import { drive } from "./server.js";
export function sse(op) {
    return function* (request) {
        let body = new ServerSentEventStream();
        let response = new Response(body.readable, {
            headers: {
                "content-type": "text/event-stream",
                "cache-control": "no-cache",
            },
        });
        return yield* drive(response, function* () {
            let writer = body.writable.getWriter();
            let write = (message) => call(() => writer.write(message));
            let messages = createChannel();
            yield* spawn(function* () {
                for (let message of yield* each(messages)) {
                    yield* write(message);
                    yield* each.next();
                }
            });
            try {
                let result = yield* op({ request, send: messages.send });
                yield* write(result);
            }
            finally {
                yield* close(writer);
            }
        });
    };
}
function* close(writer) {
    try {
        yield* call(() => writer.close());
    }
    catch (error) {
        if (!error?.message?.match(/stream is closed/)) {
            throw error;
        }
    }
}
//# sourceMappingURL=sse.js.map