import{Bs as e,Gs as t,Vs as n,zs as r}from"./config-DY0eCr1t.js";import{i}from"./logger-B2mMW1MJ.js";import{n as a}from"./proxy-env-CB7CLgvT.js";import{t as o}from"./fetch-timeout-Cz6GuU_c.js";import{EnvHttpProxyAgent as s}from"undici";const c={STRICT:`strict`,TRUSTED_ENV_PROXY:`trusted_env_proxy`},l=new Set([`accept`,`accept-encoding`,`accept-language`,`cache-control`,`content-language`,`content-type`,`if-match`,`if-modified-since`,`if-none-match`,`if-unmodified-since`,`pragma`,`range`,`user-agent`]);function u(e){return{...e,mode:c.STRICT}}function d(e){return{...e,mode:c.TRUSTED_ENV_PROXY}}function f(e){return e.mode?e.mode:e.proxy===`env`&&e.dangerouslyAllowEnvProxyWithoutPinnedDns===!0?c.TRUSTED_ENV_PROXY:c.STRICT}function p(e){return e===301||e===302||e===303||e===307||e===308}function m(e){if(!e?.headers)return e;let t=new Headers(e.headers),n=new Headers;for(let[e,r]of t.entries())l.has(e.toLowerCase())&&n.set(e,r);return{...e,headers:n}}function h(e){let{timeoutMs:t,signal:n}=e;if(!t&&!n)return{signal:void 0,cleanup:()=>{}};if(!t)return{signal:n,cleanup:()=>{}};let r=new AbortController,i=setTimeout(r.abort.bind(r),t),a=o(r);return n&&(n.aborted?r.abort():n.addEventListener(`abort`,a,{once:!0})),{signal:r.signal,cleanup:()=>{clearTimeout(i),n&&n.removeEventListener(`abort`,a)}}}async function g(o){let l=o.fetchImpl??globalThis.fetch;if(!l)throw Error(`fetch is not available`);let u=typeof o.maxRedirects==`number`&&Number.isFinite(o.maxRedirects)?Math.max(0,Math.floor(o.maxRedirects)):3,d=f(o),{signal:g,cleanup:_}=h({timeoutMs:o.timeoutMs,signal:o.signal}),v=!1,y=async t=>{v||(v=!0,_(),await e(t??void 0))},b=new Set,x=o.url,S=o.init?{...o.init}:void 0,C=0;for(;;){let f;try{f=new URL(x)}catch{throw await y(),Error(`Invalid URL: must be http or https`)}if(![`http:`,`https:`].includes(f.protocol))throw await y(),Error(`Invalid URL: must be http or https`);let h=null;try{let r=await t(f.hostname,{lookupFn:o.lookupFn,policy:o.policy});d===c.TRUSTED_ENV_PROXY&&a()?h=new s:o.pinDns!==!1&&(h=n(r));let i={...S?{...S}:{},redirect:`manual`,...h?{dispatcher:h}:{},...g?{signal:g}:{}},_=await l(f.toString(),i);if(p(_.status)){let t=_.headers.get(`location`);if(!t)throw await y(h),Error(`Redirect missing location header (${_.status})`);if(C+=1,C>u)throw await y(h),Error(`Too many redirects (limit: ${u})`);let n=new URL(t,f),r=n.toString();if(b.has(r))throw await y(h),Error(`Redirect loop detected`);n.origin!==f.origin&&(S=m(S)),b.add(r),_.body?.cancel(),await e(h),x=r;continue}return{response:_,finalUrl:x,release:async()=>y(h)}}catch(e){throw e instanceof r&&i(`security: blocked URL fetch (${o.auditContext??`url-fetch`}) target=${f.origin}${f.pathname} reason=${e.message}`),await y(h),e}}}export{u as n,d as r,g as t};
