Elffuss BraidHub

kikocis/continue public

7d3a047d2016 · 2.9 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 fetch, { RequestInit, Response } from "node-fetch";
6import { getAgentOptions } from "./getAgentOptions.js";
7import { getProxyFromEnv, shouldBypassProxy } from "./util.js";
8
9const { http, https } = (followRedirects as any).default;
10
11export async function fetchwithRequestOptions(
12 url_: URL | string,
13 init?: RequestInit,
14 requestOptions?: RequestOptions,
15): Promise<Response> {
16 const url = typeof url_ === "string" ? new URL(url_) : url_;
17 if (url.host === "localhost") {
18 url.host = "127.0.0.1";
19 }
20
21 const agentOptions = getAgentOptions(requestOptions);
22
23 // Get proxy from options or environment variables
24 let proxy = requestOptions?.proxy;
25 if (!proxy) {
26 proxy = getProxyFromEnv(url.protocol);
27 }
28
29 // Check if should bypass proxy based on requestOptions or NO_PROXY env var
30 const shouldBypass =
31 requestOptions?.noProxy?.includes(url.hostname) ||
32 shouldBypassProxy(url.hostname);
33
34 // Create agent
35 const protocol = url.protocol === "https:" ? https : http;
36 const agent =
37 proxy && !shouldBypass
38 ? protocol === https
39 ? new HttpsProxyAgent(proxy, agentOptions)
40 : new HttpProxyAgent(proxy, agentOptions)
41 : new protocol.Agent(agentOptions);
42
43 let headers: { [key: string]: string } = {};
44 for (const [key, value] of Object.entries(init?.headers || {})) {
45 headers[key] = value as string;
46 }
47 headers = {
48 ...headers,
49 ...requestOptions?.headers,
50 };
51
52 // Replace localhost with 127.0.0.1
53 if (url.hostname === "localhost") {
54 url.hostname = "127.0.0.1";
55 }
56
57 // add extra body properties if provided
58 let updatedBody: string | undefined = undefined;
59 try {
60 if (requestOptions?.extraBodyProperties && typeof init?.body === "string") {
61 const parsedBody = JSON.parse(init.body);
62 updatedBody = JSON.stringify({
63 ...parsedBody,
64 ...requestOptions.extraBodyProperties,
65 });
66 }
67 } catch (e) {
68 console.log("Unable to parse HTTP request body: ", e);
69 }
70
71 // fetch the request with the provided options
72 try {
73 const resp = await fetch(url, {
74 ...init,
75 body: updatedBody ?? init?.body,
76 headers: headers,
77 agent: agent,
78 });
79
80 if (!resp.ok) {
81 const requestId = resp.headers.get("x-request-id");
82 if (requestId) {
83 console.log(`Request ID: ${requestId}, Status: ${resp.status}`);
84 }
85 }
86
87 return resp;
88 } catch (error) {
89 if (error instanceof Error && error.name === "AbortError") {
90 // Return a Response object that streamResponse etc can handle
91 return new Response(null, {
92 status: 499, // Client Closed Request
93 statusText: "Client Closed Request",
94 });
95 }
96 throw error;
97 }
98}