| 1 | import { RequestOptions } from "@continuedev/config-types"; |
| 2 | import * as followRedirects from "follow-redirects"; |
| 3 | import { HttpProxyAgent } from "http-proxy-agent"; |
| 4 | import { HttpsProxyAgent } from "https-proxy-agent"; |
| 5 | import { BodyInit, RequestInit, Response } from "node-fetch"; |
| 6 | import { getAgentOptions } from "./getAgentOptions.js"; |
| 7 | import patchedFetch from "./node-fetch-patch.js"; |
| 8 | import { getProxy, shouldBypassProxy } from "./util.js"; |
| 9 | |
| 10 | const { http, https } = (followRedirects as any).default; |
| 11 | |
| 12 | function logRequest( |
| 13 | method: string, |
| 14 | url: URL, |
| 15 | headers: { [key: string]: string }, |
| 16 | body: BodyInit | null | undefined, |
| 17 | proxy?: string, |
| 18 | shouldBypass?: boolean, |
| 19 | ) { |
| 20 | console.log("=== FETCH REQUEST ==="); |
| 21 | console.log(`Method: ${method}`); |
| 22 | console.log(`URL: ${url.toString()}`); |
| 23 | |
| 24 | // Log headers in curl format |
| 25 | console.log("Headers:"); |
| 26 | for (const [key, value] of Object.entries(headers)) { |
| 27 | console.log(` -H '${key}: ${value}'`); |
| 28 | } |
| 29 | |
| 30 | // Log proxy information |
| 31 | if (proxy && !shouldBypass) { |
| 32 | console.log(`Proxy: ${proxy}`); |
| 33 | } |
| 34 | |
| 35 | // Log body |
| 36 | if (body) { |
| 37 | console.log(`Body: ${body}`); |
| 38 | } |
| 39 | |
| 40 | // Generate equivalent curl command |
| 41 | let curlCommand = `curl -X ${method}`; |
| 42 | for (const [key, value] of Object.entries(headers)) { |
| 43 | curlCommand += ` -H '${key}: ${value}'`; |
| 44 | } |
| 45 | if (body) { |
| 46 | curlCommand += ` -d '${body}'`; |
| 47 | } |
| 48 | if (proxy && !shouldBypass) { |
| 49 | curlCommand += ` --proxy '${proxy}'`; |
| 50 | } |
| 51 | curlCommand += ` '${url.toString()}'`; |
| 52 | console.log(`Equivalent curl: ${curlCommand}`); |
| 53 | console.log("====================="); |
| 54 | } |
| 55 | |
| 56 | async function logResponse(resp: Response) { |
| 57 | console.log("=== FETCH RESPONSE ==="); |
| 58 | console.log(`Status: ${resp.status} ${resp.statusText}`); |
| 59 | console.log("Response Headers:"); |
| 60 | resp.headers.forEach((value, key) => { |
| 61 | console.log(` ${key}: ${value}`); |
| 62 | }); |
| 63 | |
| 64 | // TODO: For streamed responses, this caused the response to be consumed and the connection would just hang open |
| 65 | // Clone response to read body without consuming it |
| 66 | // const respClone = resp.clone(); |
| 67 | // try { |
| 68 | // const responseText = await respClone.text(); |
| 69 | // console.log(`Response Body: ${responseText}`); |
| 70 | // } catch (e) { |
| 71 | // console.log("Could not read response body:", e); |
| 72 | // } |
| 73 | console.log("======================"); |
| 74 | } |
| 75 | |
| 76 | function logError(error: unknown) { |
| 77 | console.log("=== FETCH ERROR ==="); |
| 78 | console.log(`Error: ${error}`); |
| 79 | console.log("==================="); |
| 80 | } |
| 81 | |
| 82 | export async function fetchwithRequestOptions( |
| 83 | url_: URL | string, |
| 84 | init?: RequestInit, |
| 85 | requestOptions?: RequestOptions, |
| 86 | ): Promise<Response> { |
| 87 | const url = typeof url_ === "string" ? new URL(url_) : url_; |
| 88 | if (url.host === "localhost") { |
| 89 | url.host = "127.0.0.1"; |
| 90 | } |
| 91 | |
| 92 | const agentOptions = await getAgentOptions(requestOptions); |
| 93 | |
| 94 | // Get proxy from options or environment variables |
| 95 | const proxy = getProxy(url.protocol, requestOptions); |
| 96 | |
| 97 | // Check if should bypass proxy based on requestOptions or NO_PROXY env var |
| 98 | const shouldBypass = shouldBypassProxy(url.hostname, requestOptions); |
| 99 | |
| 100 | // Create agent |
| 101 | const protocol = url.protocol === "https:" ? https : http; |
| 102 | const agent = |
| 103 | proxy && !shouldBypass |
| 104 | ? protocol === https |
| 105 | ? new HttpsProxyAgent(proxy, agentOptions) |
| 106 | : new HttpProxyAgent(proxy, agentOptions) |
| 107 | : new protocol.Agent(agentOptions); |
| 108 | |
| 109 | let headers: { [key: string]: string } = {}; |
| 110 | for (const [key, value] of Object.entries(init?.headers || {})) { |
| 111 | headers[key] = value as string; |
| 112 | } |
| 113 | headers = { |
| 114 | ...headers, |
| 115 | ...requestOptions?.headers, |
| 116 | }; |
| 117 | |
| 118 | // Replace localhost with 127.0.0.1 |
| 119 | if (url.hostname === "localhost") { |
| 120 | url.hostname = "127.0.0.1"; |
| 121 | } |
| 122 | |
| 123 | // add extra body properties if provided |
| 124 | let updatedBody: string | undefined = undefined; |
| 125 | try { |
| 126 | if (requestOptions?.extraBodyProperties && typeof init?.body === "string") { |
| 127 | const parsedBody = JSON.parse(init.body); |
| 128 | updatedBody = JSON.stringify({ |
| 129 | ...parsedBody, |
| 130 | ...requestOptions.extraBodyProperties, |
| 131 | }); |
| 132 | } |
| 133 | } catch (e) { |
| 134 | console.log("Unable to parse HTTP request body: ", e); |
| 135 | } |
| 136 | |
| 137 | const finalBody = updatedBody ?? init?.body; |
| 138 | const method = init?.method || "GET"; |
| 139 | |
| 140 | // Verbose logging for debugging - log request details |
| 141 | if (process.env.VERBOSE_FETCH) { |
| 142 | logRequest(method, url, headers, finalBody, proxy, shouldBypass); |
| 143 | } |
| 144 | |
| 145 | // fetch the request with the provided options |
| 146 | try { |
| 147 | const resp = await patchedFetch(url, { |
| 148 | ...init, |
| 149 | body: finalBody, |
| 150 | headers: headers, |
| 151 | agent: agent, |
| 152 | }); |
| 153 | |
| 154 | // Verbose logging for debugging - log response details |
| 155 | if (process.env.VERBOSE_FETCH) { |
| 156 | await logResponse(resp); |
| 157 | } |
| 158 | |
| 159 | if (!resp.ok) { |
| 160 | const requestId = resp.headers.get("x-request-id"); |
| 161 | if (requestId) { |
| 162 | console.log(`Request ID: ${requestId}, Status: ${resp.status}`); |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | return resp; |
| 167 | } catch (error) { |
| 168 | // Verbose logging for errors |
| 169 | if (process.env.VERBOSE_FETCH) { |
| 170 | logError(error); |
| 171 | } |
| 172 | |
| 173 | if (error instanceof Error && error.name === "AbortError") { |
| 174 | // Return a Response object that streamResponse etc can handle |
| 175 | return new Response(null, { |
| 176 | status: 499, // Client Closed Request |
| 177 | statusText: "Client Closed Request", |
| 178 | }); |
| 179 | } |
| 180 | throw error; |
| 181 | } |
| 182 | } |