import { __esmMin } from "../../../_virtual/_rolldown/runtime.js";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/utils/logger/context.ts
/**
* Logger Context
* Context tracking and propagation for structured logging
*/
/**
* Run *fn* with merged async log context. Propagates through async/await (Node AsyncLocalStorage).
* Nested calls merge over the parent context (shallow per key).
*/
function runWithLogContext(context, fn) {
	const parent = logContextStorage.getStore();
	const merged = parent ? mergeContext(parent.ctx, context) : { ...context };
	return logContextStorage.run({ ctx: { ...merged } }, fn);
}
/** Current async log context, if any. */
function getAsyncLogContext() {
	return logContextStorage.getStore()?.ctx;
}
/**
* Shallow-merge fields into the current async log context (e.g. set sessionId after parsing a body).
* No-op when not inside {@link runWithLogContext}.
*/
function updateAsyncLogContext(partial) {
	const ref = logContextStorage.getStore();
	if (ref) ref.ctx = mergeContext(ref.ctx, partial);
}
/** Keys injected from async context into log records (used by logger mixin). */
function getAsyncLogCorrelationKeys() {
	return ASYNC_LOG_CORRELATION_KEYS;
}
function inboundCorrelationMetadataFromAsyncLogContext() {
	const ctx = getAsyncLogContext();
	if (!ctx) return void 0;
	const meta = {};
	for (const key of INBOUND_METADATA_FROM_ASYNC) {
		const v = ctx[key];
		if (v !== void 0 && v !== "") meta[key] = v;
	}
	return Object.keys(meta).length > 0 ? meta : void 0;
}
/**
* Merge two contexts
*/
function mergeContext(base, additional) {
	return {
		...base,
		...additional
	};
}
/**
* Store context for a request ID
*/
function setRequestContext(requestId, context) {
	contextStore.set(requestId, context);
}
/**
* Get context for a request ID
*/
function getRequestContext(requestId) {
	return contextStore.get(requestId);
}
/**
* Clear context for a request ID
*/
function clearRequestContext(requestId) {
	contextStore.delete(requestId);
}
/**
* Create a child logger with additional context
* This is a placeholder for the actual implementation
*/
function withContext(logger, context) {
	return logger.withContext(context);
}
var contextStore, ASYNC_LOG_CORRELATION_KEYS, logContextStorage, INBOUND_METADATA_FROM_ASYNC;
var init_context = __esmMin((() => {
	contextStore = /* @__PURE__ */ new Map();
	ASYNC_LOG_CORRELATION_KEYS = [
		"requestId",
		"sessionId",
		"userId",
		"correlationId"
	];
	logContextStorage = new AsyncLocalStorage();
	INBOUND_METADATA_FROM_ASYNC = [
		"requestId",
		"correlationId",
		"userId"
	];
}));
//#endregion
init_context();
export { clearRequestContext, getAsyncLogContext, getAsyncLogCorrelationKeys, getRequestContext, inboundCorrelationMetadataFromAsyncLogContext, init_context, mergeContext, runWithLogContext, setRequestContext, updateAsyncLogContext, withContext };

//# sourceMappingURL=context.js.map