UNPKG

get-it

Version:

Generic HTTP request library for node, browsers and workers

2 lines (1 loc) 8.46 kB
import{Agent as e}from"http";import{Agent as t}from"https";import{g as s}from"./_chunks-es/_commonjsHelpers.js";import{p as r,v as n}from"./_chunks-es/_commonjsHelpers.js";import{r as o,p as i,N as c}from"./_chunks-es/node-request-error.js";import a from"is-retry-allowed";const u=/^https:/i;function p(s){const r=new e(s),n=new t(s),o={http:r,https:n};return{finalizeOptions:e=>{if(e.agent)return e;if(e.maxRedirects>0)return{...e,agents:o};const t=u.test(e.href||e.protocol);return{...e,agent:t?n:r}}}}const l=/^\//,d=/\/$/;function f(e){const t=e.replace(d,"");return{processOptions:e=>{if(/^https?:\/\//i.test(e.url))return e;const s=[t,e.url.replace(l,"")].join("/");return Object.assign({},e,{url:s})}}}var b=/* @__PURE__ */s(o());const h=["cookie","authorization"],m=Object.prototype.hasOwnProperty;function y(e={}){const t=e.verbose,s=e.namespace||"get-it",r=b(s),n=e.log||r,o=n===r&&!b.enabled(s);let i=0;return{processOptions:e=>(e.debug=n,e.requestId=e.requestId||++i,e),onRequest:s=>{if(o||!s)return s;const r=s.options;if(n("[%s] HTTP %s %s",r.requestId,r.method,r.url),t&&r.body&&"string"==typeof r.body&&n("[%s] Request body: %s",r.requestId,r.body),t&&r.headers){const t=!1===e.redactSensitiveHeaders?r.headers:((e,t)=>{const s={};for(const r in e)m.call(e,r)&&(s[r]=t.indexOf(r.toLowerCase())>-1?"<redacted>":e[r]);return s})(r.headers,h);n("[%s] Request headers: %s",r.requestId,JSON.stringify(t,null,2))}return s},onResponse:(e,s)=>{if(o||!e)return e;const r=s.options.requestId;return n("[%s] Response code: %s %s",r,e.statusCode,e.statusMessage),t&&e.body&&n("[%s] Response body: %s",r,function(e){return-1!==(e.headers["content-type"]||"").toLowerCase().indexOf("application/json")?function(e){try{const t="string"==typeof e?JSON.parse(e):e;return JSON.stringify(t,null,2)}catch{return e}}(e.body):e.body}(e)),e},onError:(e,t)=>{const s=t.options.requestId;return e?(n("[%s] ERROR: %s",s,e.message),e):(n("[%s] Error encountered, but handled by an earlier middleware",s),e)}}}function g(e,t={}){return{processOptions:s=>{const r=s.headers||{};return s.headers=t.override?Object.assign({},r,e):Object.assign({},e,r),s}}}class O extends Error{response;request;constructor(e,t){super();const s=e.url.length>400?`${e.url.slice(0,399)}…`:e.url;let r=`${e.method}-request to ${s} resulted in `;r+=`HTTP ${e.statusCode} ${e.statusMessage}`,this.message=r.trim(),this.response=e,this.request=t.options}}function w(){return{onResponse:(e,t)=>{if(!(e.statusCode>=400))return e;throw new O(e,t)}}}function j(e={}){if("function"!=typeof e.inject)throw new Error("`injectResponse` middleware requires a `inject` function");return{interceptRequest:function(t,s){const r=e.inject(s,t);if(!r)return t;const n=s.context.options;return{body:"",url:n.url,method:n.method,headers:{},statusCode:200,statusMessage:"OK",...r}}}}const R=typeof Buffer>"u"?()=>!1:e=>Buffer.isBuffer(e);function q(e){return"[object Object]"===Object.prototype.toString.call(e)}function E(e){if(!1===q(e))return!1;const t=e.constructor;if(void 0===t)return!0;const s=t.prototype;return!(!1===q(s)||!1===s.hasOwnProperty("isPrototypeOf"))}const x=["boolean","string","number"];function C(){return{processOptions:e=>{const t=e.body;return!t||"function"==typeof t.pipe||R(t)||-1===x.indexOf(typeof t)&&!Array.isArray(t)&&!E(t)?e:Object.assign({},e,{body:JSON.stringify(e.body),headers:Object.assign({},e.headers,{"Content-Type":"application/json"})})}}}function T(e){return{onResponse:s=>{const r=s.headers["content-type"]||"",n=e&&e.force||-1!==r.indexOf("application/json");return s.body&&r&&n?Object.assign({},s,{body:t(s.body)}):s},processOptions:e=>Object.assign({},e,{headers:Object.assign({Accept:"application/json"},e.headers)})};function t(e){try{return JSON.parse(e)}catch(e){throw e.message=`Failed to parsed response body as JSON: ${e.message}`,e}}}function k(e={}){if(!e.ca)throw new Error('Required mtls option "ca" is missing');if(!e.cert)throw new Error('Required mtls option "cert" is missing');if(!e.key)throw new Error('Required mtls option "key" is missing');return{finalizeOptions:t=>{if(function(e){return"object"==typeof e&&null!==e&&!("protocol"in e)}(t))return t;const s={cert:e.cert,key:e.key,ca:e.ca};return Object.assign({},t,s)}}}let v={};typeof globalThis<"u"?v=globalThis:typeof window<"u"?v=window:typeof global<"u"?v=global:typeof self<"u"&&(v=self);var S=v;function N(e={}){const t=e.implementation||S.Observable;if(!t)throw new Error("`Observable` is not available in global scope, and no implementation was passed");return{onReturn:(e,s)=>new t(t=>(e.error.subscribe(e=>t.error(e)),e.progress.subscribe(e=>t.next(Object.assign({type:"progress"},e))),e.response.subscribe(e=>{t.next(Object.assign({type:"response"},e)),t.complete()}),e.request.publish(s),()=>e.abort.publish()))}}function $(e){return t=>({stage:e,percent:t.percentage,total:t.length,loaded:t.transferred,lengthComputable:!(0===t.length&&0===t.percentage)})}function _(){let e=!1;const t=$("download"),s=$("upload");return{onHeaders:(e,s)=>{const r=i({time:32});return r.on("progress",e=>s.context.channels.progress.publish(t(e))),e.pipe(r)},onRequest:t=>{t.progress&&t.progress.on("progress",r=>{e=!0,t.context.channels.progress.publish(s(r))})},onResponse:(t,r)=>(!e&&typeof r.options.body<"u"&&r.channels.progress.publish(s({length:0,transferred:0,percentage:100})),t)}}const A=(e={})=>{const t=e.implementation||Promise;if(!t)throw new Error("`Promise` is not available in global scope, and no implementation was passed");return{onReturn:(s,r)=>new t((t,n)=>{const o=r.options.cancelToken;o&&o.promise.then(e=>{s.abort.publish(e),n(e)}),s.error.subscribe(n),s.response.subscribe(s=>{t(e.onlyBody?s.body:s)}),setTimeout(()=>{try{s.request.publish(r)}catch(e){n(e)}},0)})}};class P{__CANCEL__=!0;message;constructor(e){this.message=e}toString(){return"Cancel"+(this.message?`: ${this.message}`:"")}}class I{promise;reason;constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t=null;this.promise=new Promise(e=>{t=e}),e(e=>{this.reason||(this.reason=new P(e),t(this.reason))})}static source=()=>{let e;return{token:new I(t=>{e=t}),cancel:e}}}function H(e){if(!(!1===e||e&&e.host))throw new Error("Proxy middleware takes an object of host, port and auth properties");return{processOptions:t=>Object.assign({proxy:e},t)}}A.Cancel=P,A.CancelToken=I,A.isCancel=e=>!(!e||!e?.__CANCEL__);var J=(e,t,s)=>!("GET"!==s.method&&"HEAD"!==s.method||e.response&&e.response.statusCode)&&a(e);function M(e){return 100*Math.pow(2,e)+100*Math.random()}const z=(e={})=>(e=>{const t=e.maxRetries||5,s=e.retryDelay||M,r=e.shouldRetry;return{onError:(e,n)=>{const o=n.options,i=o.maxRetries||t,c=o.retryDelay||s,a=o.shouldRetry||r,u=o.attemptNumber||0;if(null!==(p=o.body)&&"object"==typeof p&&"function"==typeof p.pipe||!a(e,u,o)||u>=i)return e;var p;const l=Object.assign({},n,{options:Object.assign({},o,{attemptNumber:u+1})});return setTimeout(()=>n.channels.request.publish(l),c(u)),null}}})({shouldRetry:J,...e});function L(e){const t=new URLSearchParams,s=(e,r)=>{const n=r instanceof Set?Array.from(r):r;if(Array.isArray(n))if(n.length)for(const t in n)s(`${e}[${t}]`,n[t]);else t.append(`${e}[]`,"");else if("object"==typeof n&&null!==n)for(const[t,r]of Object.entries(n))s(`${e}[${t}]`,r);else t.append(e,n)};for(const[t,r]of Object.entries(e))s(t,r);return t.toString()}function B(){return{processOptions:e=>{const t=e.body;return t&&"function"!=typeof t.pipe&&!R(t)&&E(t)?{...e,body:L(e.body),headers:{...e.headers,"Content-Type":"application/x-www-form-urlencoded"}}:e}}}z.shouldRetry=J;const D=(F=p,function(e={}){const{maxRetries:t=3,ms:s=1e3,maxFree:r=256}=e,{finalizeOptions:n}=F({keepAlive:!0,keepAliveMsecs:s,maxFreeSockets:r});return{finalizeOptions:n,onError:(e,s)=>{if(("GET"===s.options.method||"POST"===s.options.method)&&e instanceof c&&"ECONNRESET"===e.code&&e.request.reusedSocket){const e=s.options.attemptNumber||0;if(e<t){const t=Object.assign({},s,{options:Object.assign({},s.options,{attemptNumber:e+1})});return setImmediate(()=>s.channels.request.publish(t)),null}}return e}}});var F;export{P as Cancel,I as CancelToken,p as agent,f as base,y as debug,g as headers,w as httpErrors,j as injectResponse,C as jsonRequest,T as jsonResponse,D as keepAlive,k as mtls,N as observable,r as processOptions,_ as progress,A as promise,H as proxy,z as retry,B as urlEncoded,n as validateOptions};//# sourceMappingURL=middleware.js.map