UNPKG

get-it

Version:

Generic HTTP request library for node, browsers and workers

2 lines (1 loc) 16.5 kB
import{c as e}from"./_chunks-es/createRequester.js";import t from"decompress-response";import{g as o}from"./_chunks-es/_commonjsHelpers.js";import r from"url";import s from"http";import n from"https";import i,{Readable as a}from"stream";import c from"assert";import{r as u,N as h,p}from"./_chunks-es/node-request-error.js";import d from"querystring";import*as l from"tunnel-agent";var f,m,y,_={exports:{}},g=/* @__PURE__ */o(function(){if(y)return _.exports;y=1;var e,t,o,a=r,h=a.URL,p=s,d=n,l=i.Writable,g=c,b=function(){return m||(m=1,f=function(){if(!e){try{e=u()("follow-redirects")}catch{}"function"!=typeof e&&(e=function(){})}e.apply(null,arguments)}),f;var e}();e=typeof process<"u",t=typeof window<"u"&&typeof document<"u",o=M(Error.captureStackTrace),!e&&(t||!o)&&console.warn("The follow-redirects package should be excluded from browser builds.");var R=!1;try{g(new h(""))}catch(e){R="ERR_INVALID_URL"===e.code}var v=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],w=["abort","aborted","connect","error","socket","timeout"],x=/* @__PURE__ */Object.create(null);w.forEach(function(e){x[e]=function(t,o,r){this._redirectable.emit(e,t,o,r)}});var q=P("ERR_INVALID_URL","Invalid URL",TypeError),E=P("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),O=P("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",E),T=P("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),L=P("ERR_STREAM_WRITE_AFTER_END","write after end"),k=l.prototype.destroy||C;function j(e,t){l.call(this),this._sanitizeOptions(e),this._options=e,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],t&&this.on("response",t);var o=this;this._onNativeResponse=function(e){try{o._processResponse(e)}catch(e){o.emit("error",e instanceof E?e:new E({cause:e}))}},this._performRequest()}function B(e){var t={maxRedirects:21,maxBodyLength:10485760},o={};return Object.keys(e).forEach(function(r){var s=r+":",n=o[s]=e[r],i=t[r]=Object.create(n);Object.defineProperties(i,{request:{value:function(e,r,n){return h&&e instanceof h?e=$(e):A(e)?e=$(H(e)):(n=r,r=S(e),e={protocol:s}),M(r)&&(n=r,r=null),(r=Object.assign({maxRedirects:t.maxRedirects,maxBodyLength:t.maxBodyLength},e,r)).nativeProtocols=o,!A(r.host)&&!A(r.hostname)&&(r.hostname="::1"),g.equal(r.protocol,s,"protocol mismatch"),b("options",r),new j(r,n)},configurable:!0,enumerable:!0,writable:!0},get:{value:function(e,t,o){var r=i.request(e,t,o);return r.end(),r},configurable:!0,enumerable:!0,writable:!0}})}),t}function C(){}function H(e){var t;if(R)t=new h(e);else if(!A((t=S(a.parse(e))).protocol))throw new q({input:e});return t}function S(e){if(/^\[/.test(e.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(e.hostname))throw new q({input:e.href||e});if(/^\[/.test(e.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(e.host))throw new q({input:e.href||e});return e}function $(e,t){var o=t||{};for(var r of v)o[r]=e[r];return o.hostname.startsWith("[")&&(o.hostname=o.hostname.slice(1,-1)),""!==o.port&&(o.port=Number(o.port)),o.path=o.search?o.pathname+o.search:o.pathname,o}function U(e,t){var o;for(var r in t)e.test(r)&&(o=t[r],delete t[r]);return null===o||typeof o>"u"?void 0:String(o).trim()}function P(e,t,o){function r(o){M(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,o||{}),this.code=e,this.message=this.cause?t+": "+this.cause.message:t}return r.prototype=new(o||Error),Object.defineProperties(r.prototype,{constructor:{value:r,enumerable:!1},name:{value:"Error ["+e+"]",enumerable:!1}}),r}function z(e,t){for(var o of w)e.removeListener(o,x[o]);e.on("error",C),e.destroy(t)}function A(e){return"string"==typeof e||e instanceof String}function M(e){return"function"==typeof e}return j.prototype=Object.create(l.prototype),j.prototype.abort=function(){z(this._currentRequest),this._currentRequest.abort(),this.emit("abort")},j.prototype.destroy=function(e){return z(this._currentRequest,e),k.call(this,e),this},j.prototype.write=function(e,t,o){if(this._ending)throw new L;if(!(A(e)||"object"==typeof(r=e)&&"length"in r))throw new TypeError("data should be a string, Buffer or Uint8Array");var r;M(t)&&(o=t,t=null),0!==e.length?this._requestBodyLength+e.length<=this._options.maxBodyLength?(this._requestBodyLength+=e.length,this._requestBodyBuffers.push({data:e,encoding:t}),this._currentRequest.write(e,t,o)):(this.emit("error",new T),this.abort()):o&&o()},j.prototype.end=function(e,t,o){if(M(e)?(o=e,e=t=null):M(t)&&(o=t,t=null),e){var r=this,s=this._currentRequest;this.write(e,t,function(){r._ended=!0,s.end(null,null,o)}),this._ending=!0}else this._ended=this._ending=!0,this._currentRequest.end(null,null,o)},j.prototype.setHeader=function(e,t){this._options.headers[e]=t,this._currentRequest.setHeader(e,t)},j.prototype.removeHeader=function(e){delete this._options.headers[e],this._currentRequest.removeHeader(e)},j.prototype.setTimeout=function(e,t){var o=this;function r(t){t.setTimeout(e),t.removeListener("timeout",t.destroy),t.addListener("timeout",t.destroy)}function s(t){o._timeout&&clearTimeout(o._timeout),o._timeout=setTimeout(function(){o.emit("timeout"),n()},e),r(t)}function n(){o._timeout&&(clearTimeout(o._timeout),o._timeout=null),o.removeListener("abort",n),o.removeListener("error",n),o.removeListener("response",n),o.removeListener("close",n),t&&o.removeListener("timeout",t),o.socket||o._currentRequest.removeListener("socket",s)}return t&&this.on("timeout",t),this.socket?s(this.socket):this._currentRequest.once("socket",s),this.on("socket",r),this.on("abort",n),this.on("error",n),this.on("response",n),this.on("close",n),this},["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(e){j.prototype[e]=function(t,o){return this._currentRequest[e](t,o)}}),["aborted","connection","socket"].forEach(function(e){Object.defineProperty(j.prototype,e,{get:function(){return this._currentRequest[e]}})}),j.prototype._sanitizeOptions=function(e){if(e.headers||(e.headers={}),e.host&&(e.hostname||(e.hostname=e.host),delete e.host),!e.pathname&&e.path){var t=e.path.indexOf("?");t<0?e.pathname=e.path:(e.pathname=e.path.substring(0,t),e.search=e.path.substring(t))}},j.prototype._performRequest=function(){var e=this._options.protocol,t=this._options.nativeProtocols[e];if(!t)throw new TypeError("Unsupported protocol "+e);if(this._options.agents){var o=e.slice(0,-1);this._options.agent=this._options.agents[o]}var r=this._currentRequest=t.request(this._options,this._onNativeResponse);for(var s of(r._redirectable=this,w))r.on(s,x[s]);if(this._currentUrl=/^\//.test(this._options.path)?a.format(this._options):this._options.path,this._isRedirect){var n=0,i=this,c=this._requestBodyBuffers;!function e(t){if(r===i._currentRequest)if(t)i.emit("error",t);else if(n<c.length){var o=c[n++];r.finished||r.write(o.data,o.encoding,e)}else i._ended&&r.end()}()}},j.prototype._processResponse=function(e){var t=e.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:e.headers,statusCode:t});var o=e.headers.location;if(!o||!1===this._options.followRedirects||t<300||t>=400)return e.responseUrl=this._currentUrl,e.redirects=this._redirects,this.emit("response",e),void(this._requestBodyBuffers=[]);if(z(this._currentRequest),e.destroy(),++this._redirectCount>this._options.maxRedirects)throw new O;var r,s=this._options.beforeRedirect;s&&(r=Object.assign({Host:e.req.getHeader("host")},this._options.headers));var n=this._options.method;((301===t||302===t)&&"POST"===this._options.method||303===t&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],U(/^content-/i,this._options.headers));var i,c,u=U(/^host$/i,this._options.headers),p=H(this._currentUrl),d=u||p.host,l=/^\w+:/.test(o)?this._currentUrl:a.format(Object.assign(p,{host:d})),f=(i=o,c=l,R?new h(i,c):H(a.resolve(c,i)));if(b("redirecting to",f.href),this._isRedirect=!0,$(f,this._options),(f.protocol!==p.protocol&&"https:"!==f.protocol||f.host!==d&&!function(e,t){g(A(e)&&A(t));var o=e.length-t.length-1;return o>0&&"."===e[o]&&e.endsWith(t)}(f.host,d))&&U(/^(?:(?:proxy-)?authorization|cookie)$/i,this._options.headers),M(s)){var m={headers:e.headers,statusCode:t},y={url:l,method:n,headers:r};s(this._options,m,y),this._sanitizeOptions(this._options)}this._performRequest()},_.exports=B({http:p,https:d}),_.exports.wrap=B,_.exports}());function b(e){return Object.keys(e||{}).reduce((t,o)=>(t[o.toLowerCase()]=e[o],t),{})}function R(e){return e.replace(/^\.*/,".").toLowerCase()}function v(e){const t=e.trim().toLowerCase(),o=t.split(":",2);return{hostname:R(o[0]),port:o[1],hasPort:t.indexOf(":")>-1}}const w=["protocol","slashes","auth","host","port","hostname","hash","search","query","pathname","path","href"],x=["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"],q=["proxy-authorization"],E=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe,O="node",T=(e,t,o,r,s)=>({body:s,url:o,method:r,headers:e.headers,statusCode:e.statusCode||0,statusMessage:e.statusMessage||"",remoteAddress:t}),L=(e,o)=>{const{options:i}=e,c=Object.assign({},r.parse(i.url));if("function"==typeof fetch&&i.fetch){const t=new AbortController,r=e.applyMiddleware("finalizeOptions",{...c,method:i.method,headers:{..."object"==typeof i.fetch&&i.fetch.headers?b(i.fetch.headers):{},...b(i.headers)},maxRedirects:i.maxRedirects}),s={credentials:i.withCredentials?"include":"omit",..."object"==typeof i.fetch?i.fetch:{},method:r.method,headers:r.headers,body:i.body,signal:t.signal},n=e.applyMiddleware("interceptRequest",void 0,{adapter:O,context:e});if(n){const e=setTimeout(o,0,null,n);return{abort:()=>clearTimeout(e)}}const a=fetch(i.url,s);return e.applyMiddleware("onRequest",{options:i,adapter:O,request:a,context:e}),a.then(async e=>{const t=i.rawBody?e.body:await e.text(),r={};e.headers.forEach((e,t)=>{r[t]=e}),o(null,{body:t,url:e.url,method:i.method,headers:r,statusCode:e.status,statusMessage:e.statusText})}).catch(e=>{"AbortError"!=e.name&&o(e)}),{abort:()=>t.abort()}}const u=E(i.body)?"stream":typeof i.body;if("undefined"!==u&&"stream"!==u&&"string"!==u&&!Buffer.isBuffer(i.body))throw new Error(`Request body must be a string, buffer or stream, got ${u}`);const f={};i.bodySize?f["content-length"]=i.bodySize:i.body&&"stream"!==u&&(f["content-length"]=Buffer.byteLength(i.body));let m=!1;const y=(e,t)=>!m&&o(e,t);e.channels.abort.subscribe(()=>{m=!0});let _=Object.assign({},c,{method:i.method,headers:Object.assign({},b(i.headers),f),maxRedirects:i.maxRedirects});const L=function(e){const t=typeof e.proxy>"u"?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=R(e.hostname||"");return t.split(",").map(v).some(e=>{const t=r.indexOf(e.hostname),s=t>-1&&t===r.length-e.hostname.length;return e.hasPort?o===e.port&&s:s})}(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}(r.parse(e.url)):e.proxy;return"string"==typeof t?r.parse(t):t||null}(i),k=L&&function(e){return typeof e.tunnel<"u"?!!e.tunnel:"https:"===r.parse(e.url).protocol}(i),j=e.applyMiddleware("interceptRequest",void 0,{adapter:O,context:e});if(j){const e=setImmediate(y,null,j);return{abort:()=>clearImmediate(e)}}if(0!==i.maxRedirects&&(_.maxRedirects=i.maxRedirects||5),L&&k?_=function(e={},t){const o=Object.assign({},e),r=x.concat(o.proxyHeaderWhiteList||[]).map(e=>e.toLowerCase()),s=q.concat(o.proxyHeaderExclusiveList||[]).map(e=>e.toLowerCase()),n=(i=o.headers,a=r,Object.keys(i).filter(e=>-1!==a.indexOf(e.toLowerCase())).reduce((e,t)=>(e[t]=i[t],e),{}));var i,a;n.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===s.indexOf(t.toLowerCase())&&(e[t]=o.headers[t]),e),{});const c=function(e,t){const o=function(e){return w.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 l[r]}(o,t),u=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,n);return o.agent=c(u),o}(_,L):L&&!k&&(_=function(e,t,o){const s=e.headers||{},n=Object.assign({},e,{headers:s});return s.host=s.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||"hostname"in o&&o.hostname||n.hostname||"").replace(/:\d+/,""),n.port=o.port?`${o.port}`:n.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=r.format(t),n}(_,c,L)),!k&&L&&L.auth&&!_.headers["proxy-authorization"]){const[e,t]="string"==typeof L.auth?L.auth.split(":").map(e=>d.unescape(e)):[L.auth.username,L.auth.password],o=Buffer.from(`${e}:${t}`,"utf8").toString("base64");_.headers["proxy-authorization"]=`Basic ${o}`}const B=function(e,t,o){const r="https:"===e.protocol,i=0===e.maxRedirects?{http:s,https:n}:{http:g.http,https:g.https};if(!t||o)return r?i.https:i.http;let a=443===t.port;return t.protocol&&(a=/^https:?/.test(t.protocol)),a?i.https:i.http}(_,L,k);"function"==typeof i.debug&&L&&i.debug("Proxying using %s",_.agent?"tunnel agent":`${_.host}:${_.port}`);const C="HEAD"!==_.method;let H;C&&!_.headers["accept-encoding"]&&!1!==i.compress&&(_.headers["accept-encoding"]=typeof Bun<"u"?"gzip, deflate":"br, gzip, deflate");const S=e.applyMiddleware("finalizeOptions",_),$=B.request(S,o=>{const r=o.complete&&0===o.readableLength,s=C?t(o):o;H=s;const n=e.applyMiddleware("onHeaders",s,{headers:o.headers,adapter:O,context:e}),a="responseUrl"in o?o.responseUrl:i.url,c=s.socket?.remoteAddress;if(i.stream)return y(null,T(s,c,a,_.method,n)),void process.nextTick(()=>{if(!n.readableFlowing){if(r||o.complete&&0===o.readableLength&&!o.readableFlowing)return void n.resume();o.complete&&o.readableFlowing&&n.once("readable",()=>{if(n.readableFlowing)return;const e=n.read(1);null===e?n.resume():n.unshift(e)})}});!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 y(e);const o=i.rawBody?t:t.toString(),r=T(s,c,a,_.method,o);return y(null,r)})});function U(e){H&&H.destroy(e),$.destroy(e)}$.once("socket",e=>{e.once("error",U),$.once("response",t=>{t.once("end",()=>{e.removeListener("error",U)})})}),$.once("error",e=>{H||y(new h(e,$))}),i.timeout&&function(e,t){if(e.timeoutTimer)return e;const o=isNaN(t)?t:{socket:t,connect:t},r=e.getHeader("host"),s=r?" to "+r:"";function n(){e.timeoutTimer&&(clearTimeout(e.timeoutTimer),e.timeoutTimer=null)}function i(t){if(n(),void 0!==o.socket){const r=()=>{const e=new Error("Socket timed out on request"+s);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"+s);t.code="ETIMEDOUT",e.destroy(t)},o.connect)),e.on("socket",function(e){e.connecting?e.once("connect",()=>i(e)):i(e)}),e.on("error",n)}($,i.timeout);const{bodyStream:P,progress:z}=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=p({time:32,length:o});return{bodyStream:(t?e.body:a.from(e.body)).pipe(r),progress:r}}(i);return e.applyMiddleware("onRequest",{options:i,adapter:O,request:$,context:e,progress:z}),P?P.pipe($):$.end(i.body),{abort:()=>$.abort()}},k=(t=[],o=L)=>e(t,o),j="node";export{O as adapter,j as environment,k as getIt};//# sourceMappingURL=index.js.map