import { useEffect } from "react";
function startSse(url, onMessage, onCompleted) {
    const chunks = [];
    const sse = new EventSource(url);
    sse.addEventListener("message", ev => {
        const data = JSON.parse(ev.data);
        if (data) {
            chunks.push(data);
            onMessage(chunks.join(''));
        }
    });
    sse.addEventListener("close", (ev) => {
        sse.close();
        const msg = JSON.parse(ev.data);
        onCompleted(msg);
    });
    return () => {
        sse.close();
    };
}
export function useEventSource(url, onMessage, onCompleted) {
    useEffect(() => {
        if (typeof url === 'function') {
            url().then(url => startSse(url, onMessage, onCompleted));
        }
        else {
            startSse(url, onMessage, onCompleted);
        }
    }, [url]);
}
//# sourceMappingURL=useEventSource.js.map