const require_components = require('../components.cjs');
const require_logger_transport = require('../../logging/logger_transport.cjs');
const require_logger = require('../../logging/logger.cjs');
const require_user_agent = require('../../user_agent.cjs');

//#region src/endpoint/handlers/utils.ts
function tryCreateContextualLogger(loggerTransport, url, headers, additionalContext) {
	try {
		const path = new URL(url, "https://example.com").pathname;
		const parsed = require_components.parseUrlComponents(path);
		if (parsed.type !== "invoke") return;
		const invocationId = invocationIdFromHeaders(headers);
		return require_logger.createLogger(loggerTransport, require_logger_transport.LogSource.SYSTEM, new require_logger_transport.LoggerContext(invocationId, parsed.componentName, parsed.handlerName, void 0, void 0, additionalContext));
	} catch {
		return;
	}
}
function invocationIdFromHeaders(headers) {
	const invocationIdHeader = headers["x-restate-invocation-id"];
	return typeof invocationIdHeader === "string" ? invocationIdHeader : Array.isArray(invocationIdHeader) ? invocationIdHeader[0] ?? "unknown id" : "unknown id";
}
function errorResponse(code, message) {
	return simpleResponse(code, {
		"content-type": "application/json",
		"x-restate-server": require_user_agent.X_RESTATE_SERVER
	}, new TextEncoder().encode(JSON.stringify({ message })));
}
function simpleResponse(statusCode, headers, body) {
	return { async process({ inputReader, outputWriter, writeHead }) {
		writeHead(statusCode, headers);
		while (true) {
			const { done } = await inputReader.next();
			if (done) break;
		}
		await outputWriter.write(body);
		await outputWriter.close();
	} };
}
function emptyInputReader() {
	return (async function* () {})()[Symbol.asyncIterator]();
}
/**
* Bundles a `writeHead` callback with a Promise that resolves once the head
* is committed. Used by adapters (fetch, lambda) that need to observe the
* head commit from outside the `process()` call.
*/
function captureHead() {
	const { promise, resolve } = Promise.withResolvers();
	return {
		writeHead: (statusCode, headers) => {
			resolve({
				statusCode,
				headers: { ...headers }
			});
		},
		head: promise
	};
}

//#endregion
exports.captureHead = captureHead;
exports.emptyInputReader = emptyInputReader;
exports.errorResponse = errorResponse;
exports.invocationIdFromHeaders = invocationIdFromHeaders;
exports.simpleResponse = simpleResponse;
exports.tryCreateContextualLogger = tryCreateContextualLogger;