import { ensureError } from "../../types/errors.js";
import { captureHead, emptyInputReader, tryCreateContextualLogger } from "./utils.js";

//#region src/endpoint/handlers/fetch.ts
function fetcher(handler) {
	return { fetch: (event, ...extraArgs) => {
		const url = event.url;
		const headers = Object.fromEntries(event.headers.entries());
		const response = handler.handle({
			url,
			headers,
			extraArgs
		});
		const inputReader = event.body ? event.body[Symbol.asyncIterator]() : emptyInputReader();
		const transformStream = new TransformStream();
		const outputWriter = transformStream.writable.getWriter();
		const { writeHead, head } = captureHead();
		response.process({
			inputReader,
			outputWriter,
			writeHead,
			abortSignal: event.signal
		}).catch((e) => {
			const error = ensureError(e);
			(tryCreateContextualLogger(handler.endpoint.loggerTransport, url, headers) ?? handler.endpoint.rlog).error("Unexpected error: " + (error.stack ?? error.message));
		});
		return head.then((h) => new Response(transformStream.readable, {
			status: h.statusCode,
			headers: h.headers
		}));
	} };
}

//#endregion
export { fetcher };
//# sourceMappingURL=fetch.js.map