import '../assert_dev_env.js';
/**
 * Cross-process Server-Sent Events transport.
 *
 * Opens a real streaming `fetch` against a spawned test binary's SSE
 * endpoint, threading the session cookie captured by the sibling
 * `FetchTransport` so the stream authenticates as the same account, then
 * delegates frame parsing to the shared `create_sse_frame_reader`. Uses only
 * built-in streaming `fetch` + `TextDecoder` — no extra dep.
 *
 * Mirrors how `ws_transport.ts` is the cross-process counterpart to the
 * in-process WS harness; the in-process SSE route suite
 * (`../sse_round_trip.ts`) shares the same `create_sse_frame_reader` over a
 * Hono `Response.body`.
 *
 * @module
 */
import { create_sse_frame_reader } from './sse_frame_reader.js';
/**
 * Open a real-HTTP SSE stream pinned to `options.base_url` + `sse_path`.
 *
 * Resolves once the response headers arrive and the body is a
 * `text/event-stream`; rejects if the connect is refused (non-2xx status,
 * wrong content type, missing body) so the test surfaces the real cause
 * rather than hanging.
 *
 * @throws Error if the connect fails (status, content type, or no body).
 */
export const create_sse_transport = async (options) => {
    const { base_url, sse_path, cookies, origin, default_timeout_ms } = options;
    const url = `${base_url}${sse_path}`;
    const headers = {
        Accept: 'text/event-stream',
        Origin: origin ?? base_url,
    };
    if (cookies.length > 0)
        headers.Cookie = cookies.join('; ');
    const res = await fetch(url, { method: 'GET', headers });
    if (!res.ok) {
        throw new Error(`SSE connect to ${url} failed: status ${res.status}`);
    }
    const content_type = res.headers.get('Content-Type');
    if (!content_type?.includes('text/event-stream')) {
        throw new Error(`SSE connect to ${url}: unexpected Content-Type ${content_type}`);
    }
    if (!res.body) {
        throw new Error(`SSE connect to ${url}: response has no body`);
    }
    const { read_frame, wait_for_close, cancel } = create_sse_frame_reader(res.body.getReader(), default_timeout_ms);
    return { read_frame, wait_for_close, close: cancel };
};
