import{normalizeMimeType as h,unescapeServerVariables as p}from"../../utils.js";import{MediaTypes as c}from"../../../constants.js";import e from"./targets/index.js";import m from"./helpers/reducer.js";import{queryString as b}from"../../../utils/index.js";import{urlParse as j}from"../../../utils/url.js";class D{request;constructor(a){const r={...a};this.request=this.prepare({...r,httpVersion:r.httpVersion||"HTTP/1.1",queryString:r.queryString||[],headers:r.headers||[],cookies:r.cookies||[],postData:r.postData?{...r.postData,jsonObj:void 0,paramsObj:void 0}:void 0,bodySize:0,headersSize:0,queryObj:{},headersObj:{},cookiesObj:{},allHeaders:{},uriObj:{},fullUrl:"",pathParameters:r.pathParameters||{},serverVariables:r.serverVariables||{}})}prepare(a){if(a.queryString&&a.queryString.length&&(a.queryObj=a.queryString.reduce(m,{})),a.headers&&a.headers.length){const i=/^HTTP\/2/;a.headersObj=a.headers.reduce(function(t,s){let n=s.name;return a.httpVersion.match(i)&&(n=n.toLowerCase()),t[n]=s.value,t},{})}a.cookies&&a.cookies.length&&(a.cookiesObj=a.cookies.reduceRight(function(i,t){return i[t.name]=t.value,i},{}));const r=a.cookies.map(function(i){return encodeURIComponent(i.name)+"="+encodeURIComponent(i.value)});if(r.length&&(a.allHeaders.cookie=r.join("; ")),a.postData)switch(h(a.postData.mimeType)){case"multipart/mixed":case"multipart/related":case c.MULTIPART:case"multipart/alternative":break;case c.URL_ENCODED:a.postData?.params?.length>0&&(a.postData.paramsObj=a.postData.params.reduce(m,{}),a.postData.text=b.stringify(a.postData.paramsObj));break;case"text/json":case"text/x-json":case c.JSON:case"application/x-json":if(a.postData.text)try{a.postData.jsonObj=JSON.parse(a.postData.text)}catch{a.postData.mimeType="text/plain"}break}if(a.allHeaders=Object.assign(a.allHeaders,a.headersObj),a.uriObj=j(a.url,!0),!a.uriObj)return{...a,uriObj:{protocol:"",path:"",queryObj:{},query:{}}};if(a.queryObj)for(const[i,t]of Object.entries(a.queryObj))a.uriObj.searchParams.has(i,t)||a.uriObj.searchParams.set(i,t);a.uriObj.query=Object.fromEntries(a.uriObj.searchParams.entries()),a.queryObj=a.uriObj.query,a.uriObj.path=a.uriObj.pathname=p(a.uriObj.pathname);const o=new URL(a.uriObj.toString());return o.search="",a.url=p(o.toString()),a.uriObj.search&&(a.uriObj.path=a.uriObj.pathname+"?"+a.uriObj.search),a.fullUrl=p(a.uriObj.toString()),a}convert(a,r,o){!o&&r&&(o=r);const i=this._matchTarget(a,r);if(i){const t=i(this.request,o,{target:a,client:r});return t.length===1?t[0]:t}throw new Error("Cannot match target")}_matchTarget(a,r){return Object.prototype.hasOwnProperty.call(e,a)?typeof r=="string"&&typeof e[a][r]=="function"?e[a][r]:e[a][e[a].info.default]:!1}}export{D as HTTPSnippet};
