MCPcopy Create free account
hub / github.com/Noumena-Network/code / getWithPermittedRedirects

Function getWithPermittedRedirects

src/tools/WebFetchTool/utils.ts:275–347  ·  view source on GitHub ↗
(
  url: string,
  signal: AbortSignal,
  redirectChecker: (originalUrl: string, redirectUrl: string) => boolean,
  depth = 0,
  redirectChain: string[] = [],
)

Source from the content-addressed store, hash-verified

273}
274
275export async function getWithPermittedRedirects(
276 url: string,
277 signal: AbortSignal,
278 redirectChecker: (originalUrl: string, redirectUrl: string) => boolean,
279 depth = 0,
280 redirectChain: string[] = [],
281): Promise<FetchedResponse | RedirectInfo> {
282 if (depth > MAX_REDIRECTS) {
283 throw new Error(`Too many redirects (exceeded ${MAX_REDIRECTS})`)
284 }
285 try {
286 const response = await axios.get(url, {
287 signal,
288 timeout: FETCH_TIMEOUT_MS,
289 maxRedirects: 0,
290 responseType: 'arraybuffer',
291 maxContentLength: MAX_HTTP_CONTENT_LENGTH,
292 headers: {
293 Accept: 'text/markdown, text/html, */*',
294 'User-Agent': getWebFetchUserAgent(),
295 },
296 })
297 return Object.assign(response, { finalUrl: url, redirectChain })
298 } catch (error) {
299 if (
300 axios.isAxiosError(error) &&
301 error.response &&
302 [301, 302, 307, 308].includes(error.response.status)
303 ) {
304 const redirectLocation = error.response.headers.location
305 if (!redirectLocation) {
306 throw new Error('Redirect missing Location header')
307 }
308
309 // Resolve relative URLs against the original URL
310 const redirectUrl = new URL(redirectLocation, url).toString()
311 const nextRedirectChain = [...redirectChain, redirectUrl]
312
313 if (redirectChecker(url, redirectUrl)) {
314 // Recursively follow the permitted redirect
315 return getWithPermittedRedirects(
316 redirectUrl,
317 signal,
318 redirectChecker,
319 depth + 1,
320 nextRedirectChain,
321 )
322 } else {
323 // Return redirect information to the caller
324 return {
325 type: 'redirect',
326 originalUrl: url,
327 redirectUrl,
328 statusCode: error.response.status,
329 redirectChain: nextRedirectChain,
330 }
331 }
332 }

Callers 2

utils.test.tsFile · 0.85
getURLMarkdownContentFunction · 0.85

Calls 3

getWebFetchUserAgentFunction · 0.85
toStringMethod · 0.65
getMethod · 0.45

Tested by

no test coverage detected