UNPKG

2.92 kBJavaScriptView Raw
1var T=Object.create,u=Object.defineProperty,w=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty,C=Object.getOwnPropertyNames,P=Object.getOwnPropertyDescriptor;var R=s=>u(s,"__esModule",{value:!0});var j=(s,t,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of C(t))!q.call(s,r)&&r!=="default"&&u(s,r,{get:()=>t[r],enumerable:!(e=P(t,r))||e.enumerable});return s},i=s=>j(R(u(s!=null?T(w(s)):{},"default",s&&s.__esModule&&"default"in s?{get:()=>s.default,enumerable:!0}:{value:s,enumerable:!0})),s);var f=i(require("path")),m=i(require("http")),b=i(require("https")),g=i(require("querystring")),y=i(require("url"));var p=class{constructor(t){this.coreRes=t;this.body=Buffer.alloc(0);this.headers=t.headers,this.statusCode=t.statusCode}_addChunk(t){this.body=Buffer.concat([this.body,t])}json(){return JSON.parse(this.body)}text(){return this.body.toString("utf-8")}};var c=class{constructor(t,e="GET"){this.httpMethod=e;this.data=null;this.sendDataAs=null;this.reqHeaders={};this.coreOptions={};return this.url=typeof t=="string"?new y.URL(t):t,this}query(t,e){return typeof t=="object"?Object.keys(t).forEach(r=>{this.url.searchParams.append(r,t[r])}):this.url.searchParams.append(t,e),this}path(t){return this.url.pathname=(0,f.join)(this.url.pathname,t),this}body(t,e){return this.sendDataAs=typeof t=="object"&&!e&&!Buffer.isBuffer(t)?"json":e?e.toLowerCase():"buffer",this.data=this.sendDataAs==="form"?(0,g.stringify)(t):this.sendDataAs==="json"?JSON.stringify(t):t,this}header(t,e){return typeof t=="object"?Object.keys(t).forEach(r=>{this.reqHeaders[r.toLowerCase()]=t[r]}):this.reqHeaders[t.toLowerCase()]=e,this}method(t){return this.httpMethod=t,this}timeout(t){return this.coreOptions.timeout=t,this}option(t,e){return this.coreOptions[t]=e,this}async json(){return(await this.send()).json()}async raw(){return(await this.send()).body}async text(){return(await this.send()).text()}send(){return new Promise((t,e)=>{this.data&&(!this.reqHeaders.hasOwnProperty("content-type")&&["json","form"].includes(this.sendDataAs)&&(this.reqHeaders["content-type"]=this.sendDataAs==="json"?"application/json":"application/x-www-form-urlencoded"),this.reqHeaders.hasOwnProperty("content-length")||(this.reqHeaders["content-length"]=Buffer.byteLength(this.data)));let r={protocol:this.url.protocol,host:this.url.hostname,port:this.url.port,path:this.url.pathname+this.url.search,method:this.httpMethod,headers:this.reqHeaders,...this.coreOptions},o,l=n=>{let a=n,d=new p(n);a.on("error",h=>{e(h)}),a.on("aborted",()=>{e(new Error("Server aborted request"))}),a.on("data",h=>{d._addChunk(h)}),a.on("end",()=>{t(d)})};if(this.url.protocol==="http:")o=m.default.request(r,l);else if(this.url.protocol==="https:")o=b.default.request(r,l);else throw new Error(`Bad URL protocol: ${this.url.protocol}`);o.on("error",n=>{e(n)}),this.data&&o.write(this.data),o.end()})}};module.exports=(s,t="GET")=>new c(s,t);