const require_errors = require('../../types/errors.cjs');
const require_utils = require('./utils.cjs');

//#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]() : require_utils.emptyInputReader();
		const transformStream = new TransformStream();
		const outputWriter = transformStream.writable.getWriter();
		const { writeHead, head } = require_utils.captureHead();
		response.process({
			inputReader,
			outputWriter,
			writeHead,
			abortSignal: event.signal
		}).catch((e) => {
			const error = require_errors.ensureError(e);
			(require_utils.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
exports.fetcher = fetcher;