import { ensureError } from "../../types/errors.js";
import { 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();
		response.process({
			inputReader,
			outputWriter,
			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 Promise.resolve(new Response(transformStream.readable, {
			status: response.statusCode,
			headers: response.headers
		}));
	} };
}

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