@firekid/hurl 1.0.0 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var I=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var oe=Object.prototype.hasOwnProperty;var ue=(e,r)=>{for(var t in r)I(e,t,{get:r[t],enumerable:!0})},ie=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of se(r))!oe.call(e,s)&&s!==t&&I(e,s,{get:()=>r[s],enumerable:!(n=ne(r,s))||n.enumerable});return e};var le=e=>ie(I({},"__esModule",{value:!0}),e);var Re={};ue(Re,{HurlError:()=>l,clearCache:()=>J,createInstance:()=>O,default:()=>ge});module.exports=le(Re);var l=class extends Error{constructor(r){super(r.message),this.name="HurlError",this.type=r.type,this.status=r.status,this.statusText=r.statusText,this.data=r.data,this.headers=r.headers,this.requestId=r.requestId,this.retries=r.retries??0}};function $(e){return new l({message:`HTTP ${e.status}: ${e.statusText}`,type:"HTTP_ERROR",...e})}function v(e,r){return new l({message:e,type:"NETWORK_ERROR",requestId:r})}function F(e,r){return new l({message:`Request timed out after ${e}ms`,type:"TIMEOUT_ERROR",requestId:r})}function S(e){return new l({message:"Request was aborted",type:"ABORT_ERROR",requestId:e})}function B(e,r){return new l({message:`Failed to parse response: ${e}`,type:"PARSE_ERROR",requestId:r})}async function _(e,r){let t=e.body?.getReader(),n=parseInt(e.headers.get("content-length")??"0",10);if(!t)return e.text();let s=[],i=0;for(;;){let{done:u,value:a}=await t.read();if(u)break;s.push(a),i+=a.length,r({loaded:i,total:n,percent:n>0?Math.round(i/n*100):0})}let c=new Uint8Array(i),o=0;for(let u of s)c.set(u,o),o+=u.length;return new TextDecoder().decode(c)}function P(e){let r={};return e.forEach((t,n)=>{r[n]=t}),r}async function K(e,r,t){let n=e.headers.get("content-type")??"";try{if(t){let s=await _(e,t);return n.includes("application/json")?JSON.parse(s):s}return n.includes("application/json")?await e.json():n.includes("text/")?await e.text():n.includes("application/octet-stream")||n.includes("image/")?await e.arrayBuffer():await e.text()}catch(s){throw B(s.message,r)}}function L(e,r,t,n){let s=Date.now();return{data:e,status:r.status,statusText:r.statusText,headers:P(r.headers),requestId:t,timing:{start:n,end:s,duration:s-n},fromCache:!1}}function M(e,r,t){if(t.type==="bearer"&&(e.Authorization=`Bearer ${t.token}`),t.type==="basic"){let n=btoa(`${t.username}:${t.password}`);e.Authorization=`Basic ${n}`}t.type==="apikey"&&(t.in==="query"?r[t.key]=t.value:e[t.key]=t.value)}function j(e){return e==null?null:typeof e=="number"?{count:e,delay:300,backoff:"exponential"}:e}function N(e,r,t){return t>=r.count||e.type==="ABORT_ERROR"?!1:r.on&&e.status?r.on.includes(e.status):!!(e.type==="NETWORK_ERROR"||e.type==="TIMEOUT_ERROR"||e.status&&e.status>=500)}async function G(e,r){let t=e.delay??300,n=e.backoff==="exponential"?t*Math.pow(2,r):t*(r+1);await new Promise(s=>setTimeout(s,n))}var x=new Map;function k(e,r){return r?.key??e}function W(e){let r=x.get(e);return r?Date.now()>r.expiresAt?(x.delete(e),null):{...r.response,fromCache:!0}:null}function z(e,r,t){x.set(e,{response:r,expiresAt:Date.now()+t.ttl})}function J(){x.clear()}var C=new Map;function Q(e){return C.get(e)??null}function V(e,r){C.set(e,r),r.finally(()=>C.delete(e))}function X(e,r){console.group(`[hurl] \u2192 ${r.method??"GET"} ${e}`),r.headers&&Object.keys(r.headers).length>0&&console.log("headers:",r.headers),r.query&&console.log("query:",r.query),r.body&&console.log("body:",r.body),r.timeout&&console.log("timeout:",r.timeout),r.retry&&console.log("retry:",r.retry),console.groupEnd()}function A(e){let r=e.status>=400?"\u{1F534}":e.status>=300?"\u{1F7E1}":"\u{1F7E2}";console.group(`[hurl] ${r} ${e.status} ${e.statusText} (${e.timing.duration}ms)`),console.log("requestId:",e.requestId),e.fromCache&&console.log("served from cache"),console.log("headers:",e.headers),console.log("data:",e.data),console.groupEnd()}function Y(e){console.group("[hurl] \u{1F534} Error"),console.error(e),console.groupEnd()}function ae(){return Math.random().toString(36).slice(2,10)}function ce(e,r,t){let n;if(r.startsWith("http://")||r.startsWith("https://")){if(e){let i=new URL(e).origin,c=new URL(r).origin;if(i!==c)throw new Error(`Absolute URL "${r}" does not match baseUrl origin "${i}". Pass the full URL without baseUrl, or use a path-relative URL.`)}n=r}else{if(r.startsWith("//"))throw new Error("Protocol-relative URLs are not supported. Use an explicit https:// or http:// scheme.");n=e?`${e.replace(/\/$/,"")}/${r.replace(/^\//,"")}`:r}if(!t||Object.keys(t).length===0)return n;let s=new URLSearchParams;for(let[i,c]of Object.entries(t))s.set(i,String(c));return`${n}?${s.toString()}`}function pe(e,r){let t={...r.headers,...e.headers},n=e.body;return n&&typeof n=="object"&&!(n instanceof FormData)&&!(n instanceof Blob)&&(t["Content-Type"]=t["Content-Type"]??"application/json"),t}function fe(e){if(e!=null)return e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||typeof e=="string"?e:JSON.stringify(e)}async function Z(e,r,t){let n=r.requestId??ae(),s=r.method??"GET",i=Date.now(),c=j(r.retry??t.retry),o=r.debug??t.debug??!1,u={...t.query,...r.query},a=pe(r,t),h=r.timeout??t.timeout,H=r.auth??t.auth;H&&M(a,u,H);let R=ce(t.baseUrl??"",e,Object.keys(u).length>0?u:void 0),m=r.cache??t.cache,p=!!m&&!m.bypass&&s==="GET";if(p){let d=k(R,m),T=W(d);if(T)return o&&A(T),T}let y=r.deduplicate??t.deduplicate??!1;if(y&&s==="GET"){let d=Q(R);if(d)return d}o&&X(R,{...r,method:s});let D=async d=>{let T=[],b=null,E=new AbortController;T.push(E),r.signal&&r.signal.addEventListener("abort",()=>E.abort()),h&&(b=setTimeout(()=>E.abort("timeout"),h));try{let f=await fetch(R,{method:s,headers:a,body:fe(r.body),signal:E.signal,redirect:r.followRedirects??!0?"follow":"manual"});b&&clearTimeout(b);let g=await K(f,n,r.onDownloadProgress);if(!f.ok)throw $({status:f.status,statusText:f.statusText,data:g,headers:P(f.headers),requestId:n,retries:d});let w=L(g,f,n,i);return p&&m&&z(k(R,m),w,m),o&&A(w),w}catch(f){b&&clearTimeout(b);let g;if(f instanceof l?g=f:f.name==="AbortError"?g=h&&f.message==="timeout"?F(h,n):S(n):g=v(f.message,n),g.retries=d,c&&N(g,c,d))return o&&console.log(`[hurl] retrying (${d+1}/${c.count})...`),await G(c,d),D(d+1);throw o&&Y(g),g}},U=D(0);return y&&s==="GET"&&V(R,U),U}function q(){let e=[];return{use(r){return e.push(r),()=>{let t=e.indexOf(r);t!==-1&&e.splice(t,1)}},clear(){e.length=0},getAll(){return[...e]}}}async function ee(e,r,t){let n={url:r,options:t};for(let s of e)n=await s(n.url,n.options);return n}async function re(e,r){let t=r;for(let n of e)t=await n(t);return t}async function te(e,r){let t=r;for(let n of e)t instanceof l&&(t=await n(t));return t}function O(e={}){let r={...e},t=q(),n=q(),s=q();async function i(o,u={}){let a=o,h=u,H=t.getAll(),R=n.getAll(),m=s.getAll();if(H.length>0){let p=await ee(H,o,u);a=p.url,h=p.options}try{let p=await Z(a,h,r);return R.length>0?await re(R,p):p}catch(p){if(p instanceof l&&m.length>0){let y=await te(m,p);if(!(y instanceof l))return y;throw y}throw p}}return{request:i,get(o,u){return i(o,{...u,method:"GET"})},post(o,u,a){return i(o,{...a,method:"POST",body:u})},put(o,u,a){return i(o,{...a,method:"PUT",body:u})},patch(o,u,a){return i(o,{...a,method:"PATCH",body:u})},delete(o,u){return i(o,{...u,method:"DELETE"})},head(o,u){return i(o,{...u,method:"HEAD"})},options(o,u){return i(o,{...u,method:"OPTIONS"})},all(o){return Promise.all(o)},defaults:{set(o){r={...r,...o}},get(){return{...r}},reset(){r={...e}}},interceptors:{request:{use:t.use.bind(t),clear:t.clear.bind(t)},response:{use:n.use.bind(n),clear:n.clear.bind(n)},error:{use:s.use.bind(s),clear:s.clear.bind(s)}},create(o){return O({...r,...o})},extend(o){return O({...r,...o})}}}var de=O(),ge=de;0&&(module.exports={HurlError,clearCache,createInstance});
1
+ "use strict";var O=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var oe=Object.prototype.hasOwnProperty;var ue=(e,r)=>{for(var t in r)O(e,t,{get:r[t],enumerable:!0})},ie=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of se(r))!oe.call(e,s)&&s!==t&&O(e,s,{get:()=>r[s],enumerable:!(n=ne(r,s))||n.enumerable});return e};var le=e=>ie(O({},"__esModule",{value:!0}),e);var me={};ue(me,{HurlError:()=>l,clearCache:()=>J,createInstance:()=>w,default:()=>Re});module.exports=le(me);var l=class extends Error{constructor(r){super(r.message),this.name="HurlError",this.type=r.type,this.status=r.status,this.statusText=r.statusText,this.data=r.data,this.headers=r.headers,this.requestId=r.requestId,this.retries=r.retries??0}};function $(e){return new l({message:`HTTP ${e.status}: ${e.statusText}`,type:"HTTP_ERROR",...e})}function v(e,r){return new l({message:e,type:"NETWORK_ERROR",requestId:r})}function F(e,r){return new l({message:`Request timed out after ${e}ms`,type:"TIMEOUT_ERROR",requestId:r})}function S(e){return new l({message:"Request was aborted",type:"ABORT_ERROR",requestId:e})}function B(e,r){return new l({message:`Failed to parse response: ${e}`,type:"PARSE_ERROR",requestId:r})}async function _(e,r){let t=e.body?.getReader(),n=parseInt(e.headers.get("content-length")??"0",10);if(!t)return e.text();let s=[],u=0;for(;;){let{done:i,value:c}=await t.read();if(i)break;s.push(c),u+=c.length,r({loaded:u,total:n,percent:n>0?Math.round(u/n*100):0})}let a=new Uint8Array(u),o=0;for(let i of s)a.set(i,o),o+=i.length;return new TextDecoder().decode(a)}function I(e){let r={};return e.forEach((t,n)=>{r[n]=t}),r}async function K(e,r,t,n){if(n==="HEAD"||e.status===204||e.headers.get("content-length")==="0")return null;let s=e.headers.get("content-type")??"";try{if(t){let a=await _(e,t);return s.includes("application/json")?JSON.parse(a):a}if(s.includes("application/json"))return await e.json();if(s.includes("text/"))return await e.text();if(s.includes("application/octet-stream")||s.includes("image/"))return await e.arrayBuffer();let u=await e.text();return u||null}catch(u){throw B(u.message,r)}}function L(e,r,t,n){let s=Date.now();return{data:e,status:r.status,statusText:r.statusText,headers:I(r.headers),requestId:t,timing:{start:n,end:s,duration:s-n},fromCache:!1}}function M(e,r,t){if(t.type==="bearer"&&(e.Authorization=`Bearer ${t.token}`),t.type==="basic"){let n=btoa(`${t.username}:${t.password}`);e.Authorization=`Basic ${n}`}t.type==="apikey"&&(t.in==="query"?r[t.key]=t.value:e[t.key]=t.value)}function j(e){return e==null?null:typeof e=="number"?{count:e,delay:300,backoff:"exponential"}:e}function N(e,r,t){return t>=r.count||e.type==="ABORT_ERROR"?!1:r.on&&e.status?r.on.includes(e.status):!!(e.type==="NETWORK_ERROR"||e.type==="TIMEOUT_ERROR"||e.status&&e.status>=500)}async function G(e,r){let t=e.delay??300,n=e.backoff==="exponential"?t*Math.pow(2,r):t*(r+1);await new Promise(s=>setTimeout(s,n))}var b=new Map;function P(e,r){return r?.key??e}function W(e){let r=b.get(e);return r?Date.now()>r.expiresAt?(b.delete(e),null):{...r.response,fromCache:!0}:null}function z(e,r,t){b.set(e,{response:r,expiresAt:Date.now()+t.ttl})}function J(){b.clear()}var k=new Map;function Q(e){return k.get(e)??null}function V(e,r){k.set(e,r),r.finally(()=>k.delete(e))}function X(e,r){console.group(`[hurl] \u2192 ${r.method??"GET"} ${e}`),r.headers&&Object.keys(r.headers).length>0&&console.log("headers:",r.headers),r.query&&console.log("query:",r.query),r.body&&console.log("body:",r.body),r.timeout&&console.log("timeout:",r.timeout),r.retry&&console.log("retry:",r.retry),console.groupEnd()}function C(e){let r=e.status>=400?"\u{1F534}":e.status>=300?"\u{1F7E1}":"\u{1F7E2}";console.group(`[hurl] ${r} ${e.status} ${e.statusText} (${e.timing.duration}ms)`),console.log("requestId:",e.requestId),e.fromCache&&console.log("served from cache"),console.log("headers:",e.headers),console.log("data:",e.data),console.groupEnd()}function Y(e){console.group("[hurl] \u{1F534} Error"),console.error(e),console.groupEnd()}function ae(){return Math.random().toString(36).slice(2,10)}function ce(e,r,t){let n;if(r.startsWith("http://")||r.startsWith("https://")){if(e){let u=new URL(e).origin,a=new URL(r).origin;if(u!==a)throw new Error(`Absolute URL "${r}" does not match baseUrl origin "${u}". Pass the full URL without baseUrl, or use a path-relative URL.`)}n=r}else{if(r.startsWith("//"))throw new Error("Protocol-relative URLs are not supported. Use an explicit https:// or http:// scheme.");n=e?`${e.replace(/\/$/,"")}/${r.replace(/^\//,"")}`:r}if(!t||Object.keys(t).length===0)return n;let s=new URLSearchParams;for(let[u,a]of Object.entries(t))s.set(u,String(a));return`${n}?${s.toString()}`}function pe(e,r){let t={...r.headers,...e.headers},n=e.body;return n&&typeof n=="object"&&!(n instanceof FormData)&&!(n instanceof Blob)&&(t["Content-Type"]=t["Content-Type"]??"application/json"),t}function fe(e){if(e!=null)return e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||typeof e=="string"?e:JSON.stringify(e)}function de(e,r){if(r)return!0;let t=e;return!!(t?.name==="TimeoutError"||t?.name==="AbortError"&&t?.message?.includes("timeout"))}async function Z(e,r,t){let n=r.requestId??ae(),s=r.method??"GET",u=Date.now(),a=j(r.retry??t.retry),o=r.debug??t.debug??!1,i={...t.query,...r.query},c=pe(r,t),y=r.timeout??t.timeout,T=r.auth??t.auth;T&&M(c,i,T);let R=ce(t.baseUrl??"",e,Object.keys(i).length>0?i:void 0),m=r.cache??t.cache,f=!!m&&!m.bypass&&s==="GET";if(f){let d=P(R,m),h=W(d);if(h)return o&&C(h),h}let H=r.deduplicate??t.deduplicate??!1;if(H&&s==="GET"){let d=Q(R);if(d)return d}o&&X(R,{...r,method:s});let A=async d=>{let h=null,U=!1,x=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>x.abort()),y&&(h=setTimeout(()=>{U=!0,x.abort()},y));try{let p=await fetch(R,{method:s,headers:c,body:fe(r.body),signal:x.signal,redirect:r.followRedirects??!0?"follow":"manual"});h&&clearTimeout(h);let g=await K(p,n,r.onDownloadProgress,s);if(!p.ok)throw $({status:p.status,statusText:p.statusText,data:g,headers:I(p.headers),requestId:n,retries:d});let q=L(g,p,n,u);return f&&m&&z(P(R,m),q,m),o&&C(q),q}catch(p){h&&clearTimeout(h);let g;if(p instanceof l?g=p:p.name==="AbortError"||p.name==="TimeoutError"?g=de(p,U)?F(y??0,n):S(n):g=v(p.message,n),g.retries=d,a&&N(g,a,d))return o&&console.log(`[hurl] retrying (${d+1}/${a.count})...`),await G(a,d),A(d+1);throw o&&Y(g),g}},D=A(0);return H&&s==="GET"&&V(R,D),D}function E(){let e=[];return{use(r){return e.push(r),()=>{let t=e.indexOf(r);t!==-1&&e.splice(t,1)}},clear(){e.length=0},getAll(){return[...e]}}}async function ee(e,r,t){let n={url:r,options:t};for(let s of e)n=await s(n.url,n.options);return n}async function re(e,r){let t=r;for(let n of e)t=await n(t);return t}async function te(e,r){let t=r;for(let n of e)t instanceof l&&(t=await n(t));return t}function w(e={}){let r={...e},t=E(),n=E(),s=E();async function u(o,i={}){let c=o,y=i,T=t.getAll(),R=n.getAll(),m=s.getAll();if(T.length>0){let f=await ee(T,o,i);c=f.url,y=f.options}try{let f=await Z(c,y,r);return R.length>0?await re(R,f):f}catch(f){if(f instanceof l&&m.length>0){let H=await te(m,f);if(!(H instanceof l))return H;throw H}throw f}}return{request:u,get(o,i){return u(o,{...i,method:"GET"})},post(o,i,c){return u(o,{...c,method:"POST",body:i})},put(o,i,c){return u(o,{...c,method:"PUT",body:i})},patch(o,i,c){return u(o,{...c,method:"PATCH",body:i})},delete(o,i){return u(o,{...i,method:"DELETE"})},head(o,i){return u(o,{...i,method:"HEAD"})},options(o,i){return u(o,{...i,method:"OPTIONS"})},all(o){return Promise.all(o)},defaults:{set(o){r={...r,...o}},get(){return{...r}},reset(){r={...e}}},interceptors:{request:{use:t.use.bind(t),clear:t.clear.bind(t)},response:{use:n.use.bind(n),clear:n.clear.bind(n)},error:{use:s.use.bind(s),clear:s.clear.bind(s)}},create(o){return w({...r,...o})},extend(o){return w({...r,...o})}}}var ge=w(),Re=ge;0&&(module.exports={HurlError,clearCache,createInstance});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var l=class extends Error{constructor(r){super(r.message),this.name="HurlError",this.type=r.type,this.status=r.status,this.statusText=r.statusText,this.data=r.data,this.headers=r.headers,this.requestId=r.requestId,this.retries=r.retries??0}};function U(e){return new l({message:`HTTP ${e.status}: ${e.statusText}`,type:"HTTP_ERROR",...e})}function $(e,r){return new l({message:e,type:"NETWORK_ERROR",requestId:r})}function v(e,r){return new l({message:`Request timed out after ${e}ms`,type:"TIMEOUT_ERROR",requestId:r})}function F(e){return new l({message:"Request was aborted",type:"ABORT_ERROR",requestId:e})}function S(e,r){return new l({message:`Failed to parse response: ${e}`,type:"PARSE_ERROR",requestId:r})}async function B(e,r){let t=e.body?.getReader(),n=parseInt(e.headers.get("content-length")??"0",10);if(!t)return e.text();let o=[],i=0;for(;;){let{done:u,value:a}=await t.read();if(u)break;o.push(a),i+=a.length,r({loaded:i,total:n,percent:n>0?Math.round(i/n*100):0})}let c=new Uint8Array(i),s=0;for(let u of o)c.set(u,s),s+=u.length;return new TextDecoder().decode(c)}function O(e){let r={};return e.forEach((t,n)=>{r[n]=t}),r}async function _(e,r,t){let n=e.headers.get("content-type")??"";try{if(t){let o=await B(e,t);return n.includes("application/json")?JSON.parse(o):o}return n.includes("application/json")?await e.json():n.includes("text/")?await e.text():n.includes("application/octet-stream")||n.includes("image/")?await e.arrayBuffer():await e.text()}catch(o){throw S(o.message,r)}}function K(e,r,t,n){let o=Date.now();return{data:e,status:r.status,statusText:r.statusText,headers:O(r.headers),requestId:t,timing:{start:n,end:o,duration:o-n},fromCache:!1}}function L(e,r,t){if(t.type==="bearer"&&(e.Authorization=`Bearer ${t.token}`),t.type==="basic"){let n=btoa(`${t.username}:${t.password}`);e.Authorization=`Basic ${n}`}t.type==="apikey"&&(t.in==="query"?r[t.key]=t.value:e[t.key]=t.value)}function M(e){return e==null?null:typeof e=="number"?{count:e,delay:300,backoff:"exponential"}:e}function j(e,r,t){return t>=r.count||e.type==="ABORT_ERROR"?!1:r.on&&e.status?r.on.includes(e.status):!!(e.type==="NETWORK_ERROR"||e.type==="TIMEOUT_ERROR"||e.status&&e.status>=500)}async function N(e,r){let t=e.delay??300,n=e.backoff==="exponential"?t*Math.pow(2,r):t*(r+1);await new Promise(o=>setTimeout(o,n))}var x=new Map;function I(e,r){return r?.key??e}function G(e){let r=x.get(e);return r?Date.now()>r.expiresAt?(x.delete(e),null):{...r.response,fromCache:!0}:null}function W(e,r,t){x.set(e,{response:r,expiresAt:Date.now()+t.ttl})}function re(){x.clear()}var P=new Map;function z(e){return P.get(e)??null}function J(e,r){P.set(e,r),r.finally(()=>P.delete(e))}function Q(e,r){console.group(`[hurl] \u2192 ${r.method??"GET"} ${e}`),r.headers&&Object.keys(r.headers).length>0&&console.log("headers:",r.headers),r.query&&console.log("query:",r.query),r.body&&console.log("body:",r.body),r.timeout&&console.log("timeout:",r.timeout),r.retry&&console.log("retry:",r.retry),console.groupEnd()}function k(e){let r=e.status>=400?"\u{1F534}":e.status>=300?"\u{1F7E1}":"\u{1F7E2}";console.group(`[hurl] ${r} ${e.status} ${e.statusText} (${e.timing.duration}ms)`),console.log("requestId:",e.requestId),e.fromCache&&console.log("served from cache"),console.log("headers:",e.headers),console.log("data:",e.data),console.groupEnd()}function V(e){console.group("[hurl] \u{1F534} Error"),console.error(e),console.groupEnd()}function te(){return Math.random().toString(36).slice(2,10)}function ne(e,r,t){let n;if(r.startsWith("http://")||r.startsWith("https://")){if(e){let i=new URL(e).origin,c=new URL(r).origin;if(i!==c)throw new Error(`Absolute URL "${r}" does not match baseUrl origin "${i}". Pass the full URL without baseUrl, or use a path-relative URL.`)}n=r}else{if(r.startsWith("//"))throw new Error("Protocol-relative URLs are not supported. Use an explicit https:// or http:// scheme.");n=e?`${e.replace(/\/$/,"")}/${r.replace(/^\//,"")}`:r}if(!t||Object.keys(t).length===0)return n;let o=new URLSearchParams;for(let[i,c]of Object.entries(t))o.set(i,String(c));return`${n}?${o.toString()}`}function se(e,r){let t={...r.headers,...e.headers},n=e.body;return n&&typeof n=="object"&&!(n instanceof FormData)&&!(n instanceof Blob)&&(t["Content-Type"]=t["Content-Type"]??"application/json"),t}function oe(e){if(e!=null)return e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||typeof e=="string"?e:JSON.stringify(e)}async function X(e,r,t){let n=r.requestId??te(),o=r.method??"GET",i=Date.now(),c=M(r.retry??t.retry),s=r.debug??t.debug??!1,u={...t.query,...r.query},a=se(r,t),h=r.timeout??t.timeout,H=r.auth??t.auth;H&&L(a,u,H);let R=ne(t.baseUrl??"",e,Object.keys(u).length>0?u:void 0),m=r.cache??t.cache,p=!!m&&!m.bypass&&o==="GET";if(p){let d=I(R,m),T=G(d);if(T)return s&&k(T),T}let y=r.deduplicate??t.deduplicate??!1;if(y&&o==="GET"){let d=z(R);if(d)return d}s&&Q(R,{...r,method:o});let A=async d=>{let T=[],b=null,E=new AbortController;T.push(E),r.signal&&r.signal.addEventListener("abort",()=>E.abort()),h&&(b=setTimeout(()=>E.abort("timeout"),h));try{let f=await fetch(R,{method:o,headers:a,body:oe(r.body),signal:E.signal,redirect:r.followRedirects??!0?"follow":"manual"});b&&clearTimeout(b);let g=await _(f,n,r.onDownloadProgress);if(!f.ok)throw U({status:f.status,statusText:f.statusText,data:g,headers:O(f.headers),requestId:n,retries:d});let w=K(g,f,n,i);return p&&m&&W(I(R,m),w,m),s&&k(w),w}catch(f){b&&clearTimeout(b);let g;if(f instanceof l?g=f:f.name==="AbortError"?g=h&&f.message==="timeout"?v(h,n):F(n):g=$(f.message,n),g.retries=d,c&&j(g,c,d))return s&&console.log(`[hurl] retrying (${d+1}/${c.count})...`),await N(c,d),A(d+1);throw s&&V(g),g}},D=A(0);return y&&o==="GET"&&J(R,D),D}function q(){let e=[];return{use(r){return e.push(r),()=>{let t=e.indexOf(r);t!==-1&&e.splice(t,1)}},clear(){e.length=0},getAll(){return[...e]}}}async function Y(e,r,t){let n={url:r,options:t};for(let o of e)n=await o(n.url,n.options);return n}async function Z(e,r){let t=r;for(let n of e)t=await n(t);return t}async function ee(e,r){let t=r;for(let n of e)t instanceof l&&(t=await n(t));return t}function C(e={}){let r={...e},t=q(),n=q(),o=q();async function i(s,u={}){let a=s,h=u,H=t.getAll(),R=n.getAll(),m=o.getAll();if(H.length>0){let p=await Y(H,s,u);a=p.url,h=p.options}try{let p=await X(a,h,r);return R.length>0?await Z(R,p):p}catch(p){if(p instanceof l&&m.length>0){let y=await ee(m,p);if(!(y instanceof l))return y;throw y}throw p}}return{request:i,get(s,u){return i(s,{...u,method:"GET"})},post(s,u,a){return i(s,{...a,method:"POST",body:u})},put(s,u,a){return i(s,{...a,method:"PUT",body:u})},patch(s,u,a){return i(s,{...a,method:"PATCH",body:u})},delete(s,u){return i(s,{...u,method:"DELETE"})},head(s,u){return i(s,{...u,method:"HEAD"})},options(s,u){return i(s,{...u,method:"OPTIONS"})},all(s){return Promise.all(s)},defaults:{set(s){r={...r,...s}},get(){return{...r}},reset(){r={...e}}},interceptors:{request:{use:t.use.bind(t),clear:t.clear.bind(t)},response:{use:n.use.bind(n),clear:n.clear.bind(n)},error:{use:o.use.bind(o),clear:o.clear.bind(o)}},create(s){return C({...r,...s})},extend(s){return C({...r,...s})}}}var ue=C(),Qe=ue;export{l as HurlError,re as clearCache,C as createInstance,Qe as default};
1
+ var a=class extends Error{constructor(r){super(r.message),this.name="HurlError",this.type=r.type,this.status=r.status,this.statusText=r.statusText,this.data=r.data,this.headers=r.headers,this.requestId=r.requestId,this.retries=r.retries??0}};function U(e){return new a({message:`HTTP ${e.status}: ${e.statusText}`,type:"HTTP_ERROR",...e})}function $(e,r){return new a({message:e,type:"NETWORK_ERROR",requestId:r})}function v(e,r){return new a({message:`Request timed out after ${e}ms`,type:"TIMEOUT_ERROR",requestId:r})}function F(e){return new a({message:"Request was aborted",type:"ABORT_ERROR",requestId:e})}function S(e,r){return new a({message:`Failed to parse response: ${e}`,type:"PARSE_ERROR",requestId:r})}async function B(e,r){let t=e.body?.getReader(),n=parseInt(e.headers.get("content-length")??"0",10);if(!t)return e.text();let o=[],u=0;for(;;){let{done:i,value:c}=await t.read();if(i)break;o.push(c),u+=c.length,r({loaded:u,total:n,percent:n>0?Math.round(u/n*100):0})}let l=new Uint8Array(u),s=0;for(let i of o)l.set(i,s),s+=i.length;return new TextDecoder().decode(l)}function q(e){let r={};return e.forEach((t,n)=>{r[n]=t}),r}async function _(e,r,t,n){if(n==="HEAD"||e.status===204||e.headers.get("content-length")==="0")return null;let o=e.headers.get("content-type")??"";try{if(t){let l=await B(e,t);return o.includes("application/json")?JSON.parse(l):l}if(o.includes("application/json"))return await e.json();if(o.includes("text/"))return await e.text();if(o.includes("application/octet-stream")||o.includes("image/"))return await e.arrayBuffer();let u=await e.text();return u||null}catch(u){throw S(u.message,r)}}function K(e,r,t,n){let o=Date.now();return{data:e,status:r.status,statusText:r.statusText,headers:q(r.headers),requestId:t,timing:{start:n,end:o,duration:o-n},fromCache:!1}}function L(e,r,t){if(t.type==="bearer"&&(e.Authorization=`Bearer ${t.token}`),t.type==="basic"){let n=btoa(`${t.username}:${t.password}`);e.Authorization=`Basic ${n}`}t.type==="apikey"&&(t.in==="query"?r[t.key]=t.value:e[t.key]=t.value)}function M(e){return e==null?null:typeof e=="number"?{count:e,delay:300,backoff:"exponential"}:e}function j(e,r,t){return t>=r.count||e.type==="ABORT_ERROR"?!1:r.on&&e.status?r.on.includes(e.status):!!(e.type==="NETWORK_ERROR"||e.type==="TIMEOUT_ERROR"||e.status&&e.status>=500)}async function N(e,r){let t=e.delay??300,n=e.backoff==="exponential"?t*Math.pow(2,r):t*(r+1);await new Promise(o=>setTimeout(o,n))}var b=new Map;function O(e,r){return r?.key??e}function G(e){let r=b.get(e);return r?Date.now()>r.expiresAt?(b.delete(e),null):{...r.response,fromCache:!0}:null}function W(e,r,t){b.set(e,{response:r,expiresAt:Date.now()+t.ttl})}function re(){b.clear()}var I=new Map;function z(e){return I.get(e)??null}function J(e,r){I.set(e,r),r.finally(()=>I.delete(e))}function Q(e,r){console.group(`[hurl] \u2192 ${r.method??"GET"} ${e}`),r.headers&&Object.keys(r.headers).length>0&&console.log("headers:",r.headers),r.query&&console.log("query:",r.query),r.body&&console.log("body:",r.body),r.timeout&&console.log("timeout:",r.timeout),r.retry&&console.log("retry:",r.retry),console.groupEnd()}function P(e){let r=e.status>=400?"\u{1F534}":e.status>=300?"\u{1F7E1}":"\u{1F7E2}";console.group(`[hurl] ${r} ${e.status} ${e.statusText} (${e.timing.duration}ms)`),console.log("requestId:",e.requestId),e.fromCache&&console.log("served from cache"),console.log("headers:",e.headers),console.log("data:",e.data),console.groupEnd()}function V(e){console.group("[hurl] \u{1F534} Error"),console.error(e),console.groupEnd()}function te(){return Math.random().toString(36).slice(2,10)}function ne(e,r,t){let n;if(r.startsWith("http://")||r.startsWith("https://")){if(e){let u=new URL(e).origin,l=new URL(r).origin;if(u!==l)throw new Error(`Absolute URL "${r}" does not match baseUrl origin "${u}". Pass the full URL without baseUrl, or use a path-relative URL.`)}n=r}else{if(r.startsWith("//"))throw new Error("Protocol-relative URLs are not supported. Use an explicit https:// or http:// scheme.");n=e?`${e.replace(/\/$/,"")}/${r.replace(/^\//,"")}`:r}if(!t||Object.keys(t).length===0)return n;let o=new URLSearchParams;for(let[u,l]of Object.entries(t))o.set(u,String(l));return`${n}?${o.toString()}`}function se(e,r){let t={...r.headers,...e.headers},n=e.body;return n&&typeof n=="object"&&!(n instanceof FormData)&&!(n instanceof Blob)&&(t["Content-Type"]=t["Content-Type"]??"application/json"),t}function oe(e){if(e!=null)return e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||typeof e=="string"?e:JSON.stringify(e)}function ue(e,r){if(r)return!0;let t=e;return!!(t?.name==="TimeoutError"||t?.name==="AbortError"&&t?.message?.includes("timeout"))}async function X(e,r,t){let n=r.requestId??te(),o=r.method??"GET",u=Date.now(),l=M(r.retry??t.retry),s=r.debug??t.debug??!1,i={...t.query,...r.query},c=se(r,t),y=r.timeout??t.timeout,T=r.auth??t.auth;T&&L(c,i,T);let R=ne(t.baseUrl??"",e,Object.keys(i).length>0?i:void 0),m=r.cache??t.cache,f=!!m&&!m.bypass&&o==="GET";if(f){let d=O(R,m),h=G(d);if(h)return s&&P(h),h}let H=r.deduplicate??t.deduplicate??!1;if(H&&o==="GET"){let d=z(R);if(d)return d}s&&Q(R,{...r,method:o});let C=async d=>{let h=null,D=!1,w=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>w.abort()),y&&(h=setTimeout(()=>{D=!0,w.abort()},y));try{let p=await fetch(R,{method:o,headers:c,body:oe(r.body),signal:w.signal,redirect:r.followRedirects??!0?"follow":"manual"});h&&clearTimeout(h);let g=await _(p,n,r.onDownloadProgress,o);if(!p.ok)throw U({status:p.status,statusText:p.statusText,data:g,headers:q(p.headers),requestId:n,retries:d});let x=K(g,p,n,u);return f&&m&&W(O(R,m),x,m),s&&P(x),x}catch(p){h&&clearTimeout(h);let g;if(p instanceof a?g=p:p.name==="AbortError"||p.name==="TimeoutError"?g=ue(p,D)?v(y??0,n):F(n):g=$(p.message,n),g.retries=d,l&&j(g,l,d))return s&&console.log(`[hurl] retrying (${d+1}/${l.count})...`),await N(l,d),C(d+1);throw s&&V(g),g}},A=C(0);return H&&o==="GET"&&J(R,A),A}function E(){let e=[];return{use(r){return e.push(r),()=>{let t=e.indexOf(r);t!==-1&&e.splice(t,1)}},clear(){e.length=0},getAll(){return[...e]}}}async function Y(e,r,t){let n={url:r,options:t};for(let o of e)n=await o(n.url,n.options);return n}async function Z(e,r){let t=r;for(let n of e)t=await n(t);return t}async function ee(e,r){let t=r;for(let n of e)t instanceof a&&(t=await n(t));return t}function k(e={}){let r={...e},t=E(),n=E(),o=E();async function u(s,i={}){let c=s,y=i,T=t.getAll(),R=n.getAll(),m=o.getAll();if(T.length>0){let f=await Y(T,s,i);c=f.url,y=f.options}try{let f=await X(c,y,r);return R.length>0?await Z(R,f):f}catch(f){if(f instanceof a&&m.length>0){let H=await ee(m,f);if(!(H instanceof a))return H;throw H}throw f}}return{request:u,get(s,i){return u(s,{...i,method:"GET"})},post(s,i,c){return u(s,{...c,method:"POST",body:i})},put(s,i,c){return u(s,{...c,method:"PUT",body:i})},patch(s,i,c){return u(s,{...c,method:"PATCH",body:i})},delete(s,i){return u(s,{...i,method:"DELETE"})},head(s,i){return u(s,{...i,method:"HEAD"})},options(s,i){return u(s,{...i,method:"OPTIONS"})},all(s){return Promise.all(s)},defaults:{set(s){r={...r,...s}},get(){return{...r}},reset(){r={...e}}},interceptors:{request:{use:t.use.bind(t),clear:t.clear.bind(t)},response:{use:n.use.bind(n),clear:n.clear.bind(n)},error:{use:o.use.bind(o),clear:o.clear.bind(o)}},create(s){return k({...r,...s})},extend(s){return k({...r,...s})}}}var ie=k(),Ve=ie;export{a as HurlError,re as clearCache,k as createInstance,Ve as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firekid/hurl",
3
- "version": "1.0.0",
3
+ "version": "1.0.3",
4
4
  "description": "The modern HTTP client. Axios DX. Fetch speed. Zero dependencies.",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.mjs",
@@ -14,8 +14,8 @@
14
14
  },
15
15
  "files": ["dist"],
16
16
  "scripts": {
17
- "build": "tsup src/index.ts --format cjs,esm --dts --minify --clean",
18
- "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
17
+ "build": "tsup",
18
+ "dev": "tsup --watch",
19
19
  "test": "vitest run",
20
20
  "test:watch": "vitest",
21
21
  "typecheck": "tsc --noEmit"