forked from CodebuffAI/codebuff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb-scraper.ts
More file actions
65 lines (58 loc) · 1.94 KB
/
Copy pathweb-scraper.ts
File metadata and controls
65 lines (58 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { ensureUrlProtocol } from '@codebuff/common/util/string'
import { closeXml } from '@codebuff/common/util/xml'
import { logger } from './utils/logger'
// Global cache for scraped web pages
const scrapedPagesCache: Record<string, string> = {}
export async function scrapeWebPage(url: string) {
// Check if the page is already in the cache
if (scrapedPagesCache[url] !== undefined) {
return scrapedPagesCache[url]
}
try {
let content = ''
const fullUrl = ensureUrlProtocol(url)
if (fullUrl.startsWith('https://raw.githubusercontent.com/')) {
const response = await fetch(url)
content = await response.text()
} else {
const response = await fetch(`https://r.jina.ai/${url}`)
content = await response.text()
}
// Store the scraped content in the cache
scrapedPagesCache[url] = content
return content
} catch (error) {
logger.error(
{
errorMessage: error instanceof Error ? error.message : String(error),
errorStack: error instanceof Error ? error.stack : undefined,
url,
},
'Failed to scrape web page',
)
scrapedPagesCache[url] = ''
return ''
}
}
export function parseUrlsFromContent(content: string): string[] {
const urlRegex = /https?:\/\/[^\s]+/g
return content.match(urlRegex) || []
}
const MAX_SCRAPED_CONTENT_LENGTH = 75_000
export async function getScrapedContentBlocks(urls: string[]) {
const blocks: string[] = []
for (const url of urls) {
const scrapedContent = await scrapeWebPage(url)
const truncatedScrapedContent =
scrapedContent.length > MAX_SCRAPED_CONTENT_LENGTH
? scrapedContent.slice(0, MAX_SCRAPED_CONTENT_LENGTH) +
'[...TRUNCATED: WEB PAGE CONTENT TOO LONG...]'
: scrapedContent
if (truncatedScrapedContent) {
blocks.push(
`<web_scraped_content url="${url}">\n${truncatedScrapedContent}\n${closeXml('web_scraped_content')}`,
)
}
}
return blocks
}