export const CORRELATION_ID_HEADER="X-Correlation-ID";export const CORRELATION_ID_ALIASES=["X-Request-ID","X-Trace-ID","X-Transaction-ID"];const CORRELATION_ID_PATTERN=/^req_\d{13}_[a-f0-9]{8}$/;export function generateCorrelationId(){return`req_${Date.now()}_${generateRandomHex(8)}`}export function validateCorrelationId(r){return"string"==typeof r&&CORRELATION_ID_PATTERN.test(r)}export function parseCorrelationId(r){if(!validateCorrelationId(r))return null;const e=r.split("_");return{prefix:e[0]??"req",timestamp:parseInt(e[1]??"0",10),random:e[2]??""}}export function attachCorrelationId(r,e){const t=e??generateCorrelationId();if(!validateCorrelationId(t))throw new Error(`Invalid correlation ID format: ${t}. Expected format: req_{timestamp}_{random}`);return r instanceof Headers?r.set("X-Correlation-ID",t):r["X-Correlation-ID"]=t,r}export function extractCorrelationId(r){const e=r instanceof Headers?r.get("X-Correlation-ID"):r["X-Correlation-ID"];if(e&&validateCorrelationId(e))return e;for(const e of CORRELATION_ID_ALIASES){const t=r instanceof Headers?r.get(e):r[e];if(t&&validateCorrelationId(t))return t}}export function getOrCreateCorrelationId(r){if(!r)return generateCorrelationId();return extractCorrelationId(r)??generateCorrelationId()}export function createCorrelationIdFromTimestamp(r,e){const t=e??generateRandomHex(8);if(!/^[a-f0-9]{8}$/.test(t))throw new Error(`Invalid random component: ${t}. Expected 8 hex characters`);return`req_${r}_${t}`}export function getCorrelationIdAge(r){const e=parseCorrelationId(r);if(!e)return null;return Date.now()-e.timestamp}export function isCorrelationIdExpired(r,e=3e5){const t=getCorrelationIdAge(r);return null!==t&&t>e}function generateRandomHex(r){const e=Math.ceil(r/2);if("undefined"!=typeof crypto&&crypto.getRandomValues){const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("").substring(0,r)}try{return require("node:crypto").randomBytes(e).toString("hex").substring(0,r)}catch{throw new Error("Cryptographic random generation unavailable. Install crypto polyfill or use environment with crypto support.")}}export function correlationIdMiddleware(){return(r,e,t)=>{const o=getOrCreateCorrelationId(r.headers);r.correlationId=o,e.setHeader("X-Correlation-ID",o),"function"==typeof t&&t()}}