Elffuss BraidHub

kikocis/continue public

16439cbc6ccd · 5.3 KiBRawPermalink
1import { RequestOptions } from "@continuedev/config-types";
2import * as followRedirects from "follow-redirects";
3import { HttpProxyAgent } from "http-proxy-agent";
4import { HttpsProxyAgent } from "https-proxy-agent";
5import { BodyInit, RequestInit, Response } from "node-fetch";
6import { getAgentOptions } from "./getAgentOptions.js";
7import fetch from "./node-fetch-patch.js";
8import { getProxyFromEnv, shouldBypassProxy } from "./util.js";
9
10const { http, https } = (followRedirects as any).default;
11
12function 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
56async 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
76function logError(error: unknown) {
77 console.log("=== FETCH ERROR ===");
78 console.log(`Error: ${error}`);
79 console.log("===================");
80}
81
82export 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 = getAgentOptions(requestOptions);
93
94 // Get proxy from options or environment variables
95 let proxy = requestOptions?.proxy;
96 if (!proxy) {
97 proxy = getProxyFromEnv(url.protocol);
98 }
99
100 // Check if should bypass proxy based on requestOptions or NO_PROXY env var
101 const shouldBypass =
102 requestOptions?.noProxy?.includes(url.hostname) ||
103 shouldBypassProxy(url.hostname);
104
105 // Create agent
106 const protocol = url.protocol === "https:" ? https : http;
107 const agent =
108 proxy && !shouldBypass
109 ? protocol === https
110 ? new HttpsProxyAgent(proxy, agentOptions)
111 : new HttpProxyAgent(proxy, agentOptions)
112 : new protocol.Agent(agentOptions);
113
114 let headers: { [key: string]: string } = {};
115 for (const [key, value] of Object.entries(init?.headers || {})) {
116 headers[key] = value as string;
117 }
118 headers = {
119 ...headers,
120 ...requestOptions?.headers,
121 };
122
123 // Replace localhost with 127.0.0.1
124 if (url.hostname === "localhost") {
125 url.hostname = "127.0.0.1";
126 }
127
128 // add extra body properties if provided
129 let updatedBody: string | undefined = undefined;
130 try {
131 if (requestOptions?.extraBodyProperties && typeof init?.body === "string") {
132 const parsedBody = JSON.parse(init.body);
133 updatedBody = JSON.stringify({
134 ...parsedBody,
135 ...requestOptions.extraBodyProperties,
136 });
137 }
138 } catch (e) {
139 console.log("Unable to parse HTTP request body: ", e);
140 }
141
142 const finalBody = updatedBody ?? init?.body;
143 const method = init?.method || "GET";
144
145 // Verbose logging for debugging - log request details
146 if (process.env.VERBOSE_FETCH) {
147 logRequest(method, url, headers, finalBody, proxy, shouldBypass);
148 }
149
150 // fetch the request with the provided options
151 try {
152 const resp = await fetch(url, {
153 ...init,
154 body: finalBody,
155 headers: headers,
156 agent: agent,
157 });
158
159 // Verbose logging for debugging - log response details
160 if (process.env.VERBOSE_FETCH) {
161 await logResponse(resp);
162 }
163
164 if (!resp.ok) {
165 const requestId = resp.headers.get("x-request-id");
166 if (requestId) {
167 console.log(`Request ID: ${requestId}, Status: ${resp.status}`);
168 }
169 }
170
171 return resp;
172 } catch (error) {
173 // Verbose logging for errors
174 if (process.env.VERBOSE_FETCH) {
175 logError(error);
176 }
177
178 if (error instanceof Error && error.name === "AbortError") {
179 // Return a Response object that streamResponse etc can handle
180 return new Response(null, {
181 status: 499, // Client Closed Request
182 statusText: "Client Closed Request",
183 });
184 }
185 throw error;
186 }
187}