import{SSE_KEEPALIVE_INTERVAL_MS as u}from"../constants.js";const s="text/event-stream",d=`: keepalive

`;function p(t){const[a,r,o]=t;if(a!==200)return!1;const e=typeof r=="object"&&r!==null?r:o;if(!e||typeof e!="object")return!1;if(!Array.isArray(e)){for(const[n,i]of Object.entries(e))if(n.toLowerCase()==="content-type")return String(i).toLowerCase().includes(s);return!1}if(e.length&&Array.isArray(e[0]))return e.some(([n,i])=>String(n).toLowerCase()==="content-type"&&String(i).toLowerCase().includes(s));for(let n=0;n+1<e.length;n+=2)if(String(e[n]).toLowerCase()==="content-type"&&String(e[n+1]).toLowerCase().includes(s))return!0;return!1}function S(t,a=u){let r,o=!1;const e=()=>{o=!0,r&&(clearInterval(r),r=void 0)},n=()=>!t.writableEnded&&!t.destroyed,i=()=>{o||r||(r=setInterval(()=>{if(!n()){e();return}try{t.write(d)}catch{e()}},a),r.unref?.())};t.once("finish",e),t.once("close",e),t.once("error",e);const c=t.writeHead.bind(t);return t.writeHead=function(...f){t.writeHead=c;const l=c(...f);if(!o&&p(f)){try{t.flushHeaders()}catch{}i()}return l},{stop:e}}export{S as attachSseKeepalive};
