"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeRequestContext = exports.getRequestId = exports.getRequestContext = exports.runWithRequestId = exports.withRequestContext = void 0;
const async_hooks_1 = require("async_hooks");
const crypto_1 = require("crypto");
const storage = new async_hooks_1.AsyncLocalStorage();
/**
 * Run `fn` inside a fresh request context. Use ONLY at request entry edges
 * (HTTP handlers, CLI command dispatch, daemon inbound boundaries).
 *
 * Never call from shared/reused infrastructure — that would leak the requestId
 * to unrelated callers. Listeners that need to inherit context MUST be
 * registered inside the `als.run()` callback.
 */
function withRequestContext(ctx, fn) {
    return storage.run(ctx, fn);
}
exports.withRequestContext = withRequestContext;
/**
 * Convenience wrapper that mints a fresh UUID requestId and runs `fn` under it.
 * Returns the requestId so callers can echo it back via response headers.
 */
function runWithRequestId(fn) {
    const requestId = (0, crypto_1.randomUUID)();
    const result = withRequestContext({ requestId }, fn);
    return { requestId, result };
}
exports.runWithRequestId = runWithRequestId;
/** Read the active request context, or `undefined` if not inside one. */
function getRequestContext() {
    return storage.getStore();
}
exports.getRequestContext = getRequestContext;
/** Read just the active requestId, or `undefined` if not inside a context. */
function getRequestId() {
    return storage.getStore()?.requestId;
}
exports.getRequestId = getRequestId;
/**
 * Merge any active request context into the supplied context object,
 * preferring explicit keys on the input. Existing `requestId` on `extra` wins
 * (callers may explicitly override; e.g., for cross-daemon correlation).
 */
function mergeRequestContext(extra) {
    const ctx = storage.getStore();
    if (!ctx)
        return extra;
    return { ...ctx, ...extra };
}
exports.mergeRequestContext = mergeRequestContext;
//# sourceMappingURL=log-context.js.map