import{assert}from"./assert.js";import{debugError,helper}from"./helper.js";export class HTTPRequest{constructor(e,t,r,n,o,s){this._failureText=null,this._response=null,this._fromMemoryCache=!1,this._interceptionHandled=!1,this._headers={},this._client=e,this._requestId=o.requestId,this._isNavigationRequest=o.requestId===o.loaderId&&"Document"===o.type,this._interceptionId=r,this._allowInterception=n,this._url=o.request.url,this._resourceType=o.type.toLowerCase(),this._method=o.request.method,this._postData=o.request.postData,this._frame=t,this._redirectChain=s;for(const i of Object.keys(o.request.headers))this._headers[i.toLowerCase()]=o.request.headers[i]}url(){return this._url}resourceType(){return this._resourceType}method(){return this._method}postData(){return this._postData}headers(){return this._headers}response(){return this._response}frame(){return this._frame}isNavigationRequest(){return this._isNavigationRequest}redirectChain(){return this._redirectChain.slice()}failure(){return this._failureText?{errorText:this._failureText}:null}async continue(e={}){if(this._url.startsWith("data:"))return;assert(this._allowInterception,"Request Interception is not enabled!"),assert(!this._interceptionHandled,"Request is already handled!");const{url:t,method:r,postData:n,headers:o}=e;this._interceptionHandled=!0;const s=n?Buffer.from(n).toString("base64"):void 0;await this._client.send("Fetch.continueRequest",{requestId:this._interceptionId,url:t,method:r,postData:s,headers:o?headersArray(o):void 0}).catch((e=>{debugError(e)}))}async respond(e){if(this._url.startsWith("data:"))return;assert(this._allowInterception,"Request Interception is not enabled!"),assert(!this._interceptionHandled,"Request is already handled!"),this._interceptionHandled=!0;const t=e.body&&helper.isString(e.body)?Buffer.from(e.body):e.body||null,r={};if(e.headers)for(const n of Object.keys(e.headers))r[n.toLowerCase()]=e.headers[n];e.contentType&&(r["content-type"]=e.contentType),t&&!("content-length"in r)&&(r["content-length"]=String(Buffer.byteLength(t))),await this._client.send("Fetch.fulfillRequest",{requestId:this._interceptionId,responseCode:e.status||200,responsePhrase:STATUS_TEXTS[e.status||200],responseHeaders:headersArray(r),body:t?t.toString("base64"):void 0}).catch((e=>{debugError(e)}))}async abort(e="failed"){if(this._url.startsWith("data:"))return;const t=errorReasons[e];assert(t,"Unknown error code: "+e),assert(this._allowInterception,"Request Interception is not enabled!"),assert(!this._interceptionHandled,"Request is already handled!"),this._interceptionHandled=!0,await this._client.send("Fetch.failRequest",{requestId:this._interceptionId,errorReason:t}).catch((e=>{debugError(e)}))}}const errorReasons={aborted:"Aborted",accessdenied:"AccessDenied",addressunreachable:"AddressUnreachable",blockedbyclient:"BlockedByClient",blockedbyresponse:"BlockedByResponse",connectionaborted:"ConnectionAborted",connectionclosed:"ConnectionClosed",connectionfailed:"ConnectionFailed",connectionrefused:"ConnectionRefused",connectionreset:"ConnectionReset",internetdisconnected:"InternetDisconnected",namenotresolved:"NameNotResolved",timedout:"TimedOut",failed:"Failed"};function headersArray(e){const t=[];for(const r in e)Object.is(e[r],void 0)||t.push({name:r,value:e[r]+""});return t}const STATUS_TEXTS={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};