import { parseSseStream } from "@steipete/summarize-core/runtime";
export async function* parseOpenAiSseJsonStream(body) {
    for await (const message of parseSseStream(body)) {
        if (message.event === "__comment__")
            continue;
        const data = message.data.trim();
        if (!data)
            continue;
        if (data === "[DONE]")
            return;
        const parsed = JSON.parse(data);
        if (parsed && typeof parsed === "object") {
            yield parsed;
        }
    }
}
export function createOpenAiSseError(event) {
    const asRecord = (value) => value && typeof value === "object" ? value : null;
    const directError = asRecord(event.error);
    const responseError = asRecord(asRecord(event.response)?.error);
    const details = responseError ?? directError ?? event;
    const rawCode = details.code ?? details.type ?? event.code;
    const code = typeof rawCode === "string" ? rawCode : null;
    const message = typeof details.message === "string"
        ? details.message
        : typeof event.message === "string"
            ? event.message
            : "OpenAI stream failed.";
    const error = new Error(message);
    if (code)
        error.code = code;
    return error;
}
export function createDeferredUsage() {
    let resolve = () => { };
    const promise = new Promise((nextResolve) => {
        resolve = nextResolve;
    });
    return { promise, resolve };
}
//# sourceMappingURL=sse.js.map