get-it
Version:
Generic HTTP request library for node, browsers and workers
2 lines (1 loc) • 9.87 kB
JavaScript
;var e=require("decompress-response"),t=require("follow-redirects"),o=require("http"),r=require("https"),n=require("progress-stream"),s=require("querystring"),c=require("stream"),a=require("url"),u=require("tunnel-agent");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function p(e){if(e&&"object"==typeof e&&"default"in e)return e;var t=/* @__PURE__ */Object.create(null);return e&&Object.keys(e).forEach((function(o){if("default"!==o){var r=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,r.get?r:{enumerable:!0,get:function(){return e[o]}})}})),t.default=e,Object.freeze(t)}var d=/* @__PURE__ */i(e),h=/* @__PURE__ */i(t),l=/* @__PURE__ */i(o),f=/* @__PURE__ */i(r),m=/* @__PURE__ */i(n),y=/* @__PURE__ */i(s),b=/* @__PURE__ */i(a),g=/* @__PURE__ */p(u);const x=!(typeof navigator>"u")&&"ReactNative"===navigator.product,w={timeout:x?6e4:12e4};function O(e){return decodeURIComponent(e.replace(/\+/g," "))}function v(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const t=Number(e);return isNaN(t)?v(w.timeout):{connect:t,socket:t}}const R=/^https?:\/\//i;function q(e){return Object.keys(e||{}).reduce(((t,o)=>(t[o.toLowerCase()]=e[o],t)),{})}function P(e){return e.replace(/^\.*/,".").toLowerCase()}function T(e){const t=e.trim().toLowerCase(),o=t.split(":",2);return{hostname:P(o[0]),port:o[1],hasPort:t.indexOf(":")>-1}}const j=["protocol","slashes","auth","host","port","hostname","hash","search","query","pathname","path","href"],C=["accept","accept-charset","accept-encoding","accept-language","accept-ranges","cache-control","content-encoding","content-language","content-location","content-md5","content-range","content-type","connection","date","expect","max-forwards","pragma","referer","te","user-agent","via"],L=["proxy-authorization"],E=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe,S="node";class $ extends Error{request;code;constructor(e,t){super(e.message),this.request=t,this.code=e.code}}const k=(e,t,o,r)=>({body:r,url:t,method:o,headers:e.headers,statusCode:e.statusCode,statusMessage:e.statusMessage});exports.N=$,exports.a=S,exports.h=(e,t)=>{const{options:o}=e,r=Object.assign({},b.default.parse(o.url));if("function"==typeof fetch&&o.fetch){const n=new AbortController,s=e.applyMiddleware("finalizeOptions",{...r,method:o.method,headers:{..."object"==typeof o.fetch&&o.fetch.headers?q(o.fetch.headers):{},...q(o.headers)},maxRedirects:o.maxRedirects}),c={credentials:o.withCredentials?"include":"omit",..."object"==typeof o.fetch?o.fetch:{},method:s.method,headers:s.headers,body:o.body,signal:n.signal},a=e.applyMiddleware("interceptRequest",void 0,{adapter:S,context:e});if(a){const e=setTimeout(t,0,null,a);return{abort:()=>clearTimeout(e)}}const u=fetch(o.url,c);return e.applyMiddleware("onRequest",{options:o,adapter:S,request:u,context:e}),u.then((async e=>{const r=o.rawBody?e.body:await e.text(),n={};e.headers.forEach(((e,t)=>{n[t]=e})),t(null,{body:r,url:e.url,method:o.method,headers:n,statusCode:e.status,statusMessage:e.statusText})})).catch((e=>{"AbortError"!=e.name&&t(e)})),{abort:()=>n.abort()}}const n=E(o.body)?"stream":typeof o.body;if("undefined"!==n&&"stream"!==n&&"string"!==n&&!Buffer.isBuffer(o.body))throw new Error(`Request body must be a string, buffer or stream, got ${n}`);const s={};o.bodySize?s["content-length"]=o.bodySize:o.body&&"stream"!==n&&(s["content-length"]=Buffer.byteLength(o.body));let a=!1;const u=(e,o)=>!a&&t(e,o);e.channels.abort.subscribe((()=>{a=!0}));let i=Object.assign({},r,{method:o.method,headers:Object.assign({},q(o.headers),s),maxRedirects:o.maxRedirects});const p=function(e){let t;return t=e.hasOwnProperty("proxy")?e.proxy:function(e){const t=process.env.NO_PROXY||process.env.no_proxy||"";return"*"===t||""!==t&&function(e,t){const o=e.port||("https:"===e.protocol?"443":"80"),r=P(e.hostname);return t.split(",").map(T).some((e=>{const t=r.indexOf(e.hostname),n=t>-1&&t===r.length-e.hostname.length;return e.hasPort?o===e.port&&n:n}))}(e,t)?null:"http:"===e.protocol?process.env.HTTP_PROXY||process.env.http_proxy||null:"https:"===e.protocol&&(process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy)||null}(b.default.parse(e.url)),"string"==typeof t?b.default.parse(t):t}(o),x=p&&function(e){return typeof e.tunnel<"u"?!!e.tunnel:"https:"===b.default.parse(e.url).protocol}(o),w=e.applyMiddleware("interceptRequest",void 0,{adapter:S,context:e});if(w){const e=setImmediate(u,null,w);return{abort:()=>clearImmediate(e)}}if(0!==o.maxRedirects&&(i.maxRedirects=o.maxRedirects||5),p&&x?i=function(e={},t){const o=Object.assign({},e),r=C.concat(o.proxyHeaderWhiteList||[]).map((e=>e.toLowerCase())),n=L.concat(o.proxyHeaderExclusiveList||[]).map((e=>e.toLowerCase())),s=(c=o.headers,a=r,Object.keys(c).filter((e=>-1!==a.indexOf(e.toLowerCase()))).reduce(((e,t)=>(e[t]=c[t],e)),{}));var c,a;s.host=function(e){const t=e.port,o=e.protocol;let r=`${e.hostname}:`;return r+=t||("https:"===o?"443":"80"),r}(o),o.headers=Object.keys(o.headers||{}).reduce(((e,t)=>(-1===n.indexOf(t.toLowerCase())&&(e[t]=o.headers[t]),e)),{});const u=function(e,t){const o=function(e){return j.reduce(((t,o)=>(t[o]=e[o],t)),{})}(e),r=function(e,t){return`${"https:"===e.protocol?"https":"http"}Over${"https:"===t.protocol?"Https":"Http"}`}(o,t);return g[r]}(o,t),i=function(e,t,o){return{proxy:{host:t.hostname,port:+t.port,proxyAuth:t.auth,headers:o},headers:e.headers,ca:e.ca,cert:e.cert,key:e.key,passphrase:e.passphrase,pfx:e.pfx,ciphers:e.ciphers,rejectUnauthorized:e.rejectUnauthorized,secureOptions:e.secureOptions,secureProtocol:e.secureProtocol}}(o,t,s);return o.agent=u(i),o}(i,p):p&&!x&&(i=function(e,t,o){const r=e.headers||{},n=Object.assign({},e,{headers:r});return r.host=r.host||function(e){const t=e.port||("https:"===e.protocol?"443":"80");return`${e.hostname}:${t}`}(t),n.protocol=o.protocol||n.protocol,n.hostname=o.host.replace(/:\d+/,""),n.port=o.port,n.host=function(e){let t=e.host;return e.port&&("80"===e.port&&"http:"===e.protocol||"443"===e.port&&"https:"===e.protocol)&&(t=e.hostname),t}(Object.assign({},t,o)),n.href=`${n.protocol}//${n.host}${n.path}`,n.path=b.default.format(t),n}(i,r,p)),!x&&p&&p.auth&&!i.headers["proxy-authorization"]){const[e,t]=p.auth.username?[p.auth.username,p.auth.password]:p.auth.split(":").map((e=>y.default.unescape(e))),o=Buffer.from(`${e}:${t}`,"utf8").toString("base64");i.headers["proxy-authorization"]=`Basic ${o}`}const O=function(e,t,o){const r="https:"===e.protocol,n=0===e.maxRedirects?{http:l.default,https:f.default}:{http:h.default.http,https:h.default.https};if(!t||o)return r?n.https:n.http;let s=443===t.port;return t.protocol&&(s=/^https:?/.test(t.protocol)),s?n.https:n.http}(i,p,x);"function"==typeof o.debug&&p&&o.debug("Proxying using %s",i.agent?"tunnel agent":`${i.host}:${i.port}`);const v="HEAD"!==i.method;let R;v&&!i.headers["accept-encoding"]&&!1!==o.compress&&(i.headers["accept-encoding"]=typeof Bun<"u"?"gzip, deflate":"br, gzip, deflate");const U=e.applyMiddleware("finalizeOptions",i),z=O.request(U,(t=>{const r=v?d.default(t):t;R=r;const n=e.applyMiddleware("onHeaders",r,{headers:t.headers,adapter:S,context:e}),s="responseUrl"in t?t.responseUrl:o.url;o.stream?u(null,k(r,s,i.method,n)):function(e,t){const o=[];e.on("data",(function(e){o.push(e)})),e.once("end",(function(){t&&t(null,Buffer.concat(o)),t=null})),e.once("error",(function(e){t&&t(e),t=null}))}(n,((e,t)=>{if(e)return u(e);const n=o.rawBody?t:t.toString(),c=k(r,s,i.method,n);return u(null,c)}))}));function M(e){R&&R.destroy(e),z.destroy(e)}z.once("socket",(e=>{e.once("error",M),z.once("response",(t=>{t.once("end",(()=>{e.removeListener("error",M)}))}))})),z.once("error",(e=>{R||u(new $(e,z))})),o.timeout&&function(e,t){if(e.timeoutTimer)return e;const o=isNaN(t)?t:{socket:t,connect:t},r=e.getHeader("host"),n=r?" to "+r:"";function s(){e.timeoutTimer&&(clearTimeout(e.timeoutTimer),e.timeoutTimer=null)}function c(t){if(s(),void 0!==o.socket){const r=()=>{const e=new Error("Socket timed out on request"+n);e.code="ESOCKETTIMEDOUT",t.destroy(e)};t.setTimeout(o.socket,r),e.once("response",(e=>{e.once("end",(()=>{t.removeListener("timeout",r)}))}))}}void 0!==o.connect&&(e.timeoutTimer=setTimeout((function(){const t=new Error("Connection timed out on request"+n);t.code="ETIMEDOUT",e.destroy(t)}),o.connect)),e.on("socket",(function(e){e.connecting?e.once("connect",(()=>c(e))):c(e)})),e.on("error",s)}(z,o.timeout);const{bodyStream:B,progress:H}=function(e){if(!e.body)return{};const t=E(e.body),o=e.bodySize||(t?null:Buffer.byteLength(e.body));if(!o)return t?{bodyStream:e.body}:{};const r=m.default({time:16,length:o});return{bodyStream:(t?e.body:c.Readable.from(e.body)).pipe(r),progress:r}}(o);return e.applyMiddleware("onRequest",{options:o,adapter:S,request:z,context:e,progress:H}),B?B.pipe(z):z.end(o.body),{abort:()=>z.abort()}},exports.p=function(e){const t={...w,..."string"==typeof e?{url:e}:e};if(t.timeout=v(t.timeout),t.query){const{url:e,searchParams:o}=function(e){const t=e.indexOf("?");if(-1===t)return{url:e,searchParams:new URLSearchParams};const o=e.slice(0,t),r=e.slice(t+1);if(!x)return{url:o,searchParams:new URLSearchParams(r)};if("function"!=typeof decodeURIComponent)throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const n=new URLSearchParams;for(const e of r.split("&")){const[t,o]=e.split("=");t&&n.append(O(t),O(o||""))}return{url:o,searchParams:n}}(t.url);for(const[r,n]of Object.entries(t.query)){if(void 0!==n)if(Array.isArray(n))for(const e of n)o.append(r,e);else o.append(r,n);const s=o.toString();s&&(t.url=`${e}?${s}`)}}return t.method=t.body&&!t.method?"POST":(t.method||"GET").toUpperCase(),t},exports.v=function(e){if(!R.test(e.url))throw new Error(`"${e.url}" is not a valid URL`)};//# sourceMappingURL=node-request.cjs.map