diff --git a/core/core.ts b/core/core.ts index 83f8e09d6..6ebbd385b 100644 --- a/core/core.ts +++ b/core/core.ts @@ -27,7 +27,7 @@ import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { streamDiffLines } from "./util/verticalEdit"; -import { verifyOrInstallChromium } from "./indexing/docs/crawl"; +import DocsCrawler from "./indexing/docs/DocsCrawler"; export class Core { // implements IMessenger @@ -169,7 +169,7 @@ export class Core { ); try { - verifyOrInstallChromium(); + DocsCrawler.verifyOrInstallChromium(); } catch (err) { console.debug(`Failed to install Chromium: ${err}`); } diff --git a/core/indexing/docs/crawl.test.ts b/core/indexing/docs/DocsCrawler.test.ts similarity index 86% rename from core/indexing/docs/crawl.test.ts rename to core/indexing/docs/DocsCrawler.test.ts index b6fa040da..b3c4b2593 100644 --- a/core/indexing/docs/crawl.test.ts +++ b/core/indexing/docs/DocsCrawler.test.ts @@ -1,4 +1,4 @@ -import { crawl, PageData } from "./crawl"; +import DocsCrawler, { type PageData } from "./DocsCrawler"; import preIndexedDocs from "./preIndexedDocs"; // Temporary workaround until we have better caching of Chromium @@ -15,8 +15,11 @@ describe.skip("crawl", () => { let crawlResults: PageData[]; beforeAll(async () => { + const docsCrawler = new DocsCrawler(new URL(repoUrl)); + crawlResults = []; - for await (const page of crawl(new URL(repoUrl))) { + + for await (const page of docsCrawler.crawl()) { crawlResults.push(page); } }, TIMEOUT); @@ -65,8 +68,12 @@ describe.skip("crawl", () => { for (const site of TEST_SITES) { const crawlResults: PageData[] = []; + const docsCrawler = new DocsCrawler( + new URL(site), + NUM_PAGES_TO_CRAWL, + ); - for await (const page of crawl(new URL(site), NUM_PAGES_TO_CRAWL)) { + for await (const page of docsCrawler.crawl()) { crawlResults.push(page); } @@ -94,7 +101,9 @@ describe.skip("crawl", () => { let pageFound = false; try { - for await (const page of crawl(new URL(url), 1)) { + const docsCrawler = new DocsCrawler(new URL(url), 1); + + for await (const page of docsCrawler.crawl()) { if (page.url === url) { pageFound = true; break; diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts new file mode 100644 index 000000000..3ec9554ae --- /dev/null +++ b/core/indexing/docs/DocsCrawler.ts @@ -0,0 +1,249 @@ +import { Octokit } from "@octokit/rest"; +import { URL } from "node:url"; +import { getChromiumPath, getContinueUtilsPath } from "../../util/paths"; +import { Page } from "puppeteer"; +// @ts-ignore +import PCR from "puppeteer-chromium-resolver"; +import * as fs from "fs"; + +export type PageData = { + url: string; + path: string; + content: string; +}; + +export default class DocsCrawler { + LINK_GROUP_SIZE = 2; // Controls parallelization of crawler + GITHUB_HOST = "github.com"; + MAX_REQUESTS_PER_CRAWL = 1000; + markdownRegex = new RegExp(/\.(md|mdx)$/); + octokit = new Octokit({ + auth: undefined, + }); + + static PCR_CONFIG = { + downloadPath: getContinueUtilsPath(), + }; + + constructor( + private readonly startUrl: URL, + private readonly maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL, + ) {} + + static verifyOrInstallChromium() { + if (!fs.existsSync(getChromiumPath())) { + PCR(DocsCrawler.PCR_CONFIG); + } + } + + async *crawl(): AsyncGenerator { + if (this.startUrl.host === this.GITHUB_HOST) { + yield* this.crawlGithubRepo(); + } else { + yield* this.crawlSite(); + } + } + + private async getGithubRepoDefaultBranch( + owner: string, + repo: string, + ): Promise { + const repoInfo = await this.octokit.repos.get({ + owner, + repo, + }); + + return repoInfo.data.default_branch; + } + + private async getGitHubRepoPaths( + owner: string, + repo: string, + branch: string, + ) { + const tree = await this.octokit.request( + "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", + { + owner, + repo, + tree_sha: branch, + headers: { + "X-GitHub-Api-Version": "2022-11-28", + }, + recursive: "true", + }, + ); + + const paths = tree.data.tree + .filter( + (file: any) => + file.type === "blob" && this.markdownRegex.test(file.path ?? ""), + ) + .map((file: any) => file.path); + + return paths; + } + + private async getGithubRepoFileContent( + path: string, + owner: string, + repo: string, + ) { + try { + const response = await this.octokit.repos.getContent({ + owner, + repo, + path, + headers: { + Accept: "application/vnd.github.raw+json", + }, + }); + + return response.data as unknown as string; + } catch (error) { + console.debug("Error fetching file contents:", error); + return null; + } + } + + private async *crawlGithubRepo() { + console.debug(`Crawling GitHub repo: ${this.startUrl.toString()}`); + + const urlStr = this.startUrl.toString(); + const [_, owner, repo] = this.startUrl.pathname.split("/"); + const branch = await this.getGithubRepoDefaultBranch(owner, repo); + const paths = await this.getGitHubRepoPaths(owner, repo, branch); + + for await (const path of paths) { + const content = await this.getGithubRepoFileContent(path, owner, repo); + + yield { + path, + url: urlStr, + content: content ?? "", + }; + } + } + + private stripHashFromUrl(urlStr: string) { + try { + let url = new URL(urlStr); + url.hash = ""; + return url; + } catch (err) { + console.debug(`Failed to create URL: ${err}`); + return null; + } + } + + private isValidHostAndPath(newUrl: URL, curUrl: URL) { + return ( + newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host + ); + } + + private async getLinksFromPage(page: Page, curUrl: URL) { + const links = await page.$$eval("a", (links) => links.map((a) => a.href)); + + // This additional step is due to issues getting the URL module to work + // in an $$eval command + const cleanedLinks = links + .map(this.stripHashFromUrl) + .filter( + (newUrl) => + newUrl !== null && + this.isValidHostAndPath(newUrl, curUrl) && + newUrl !== curUrl, + ) + .map((newUrl) => (newUrl as URL).href); + + const dedupedLinks = Array.from(new Set(cleanedLinks)); + + return dedupedLinks; + } + + private async getLinkGroupsFromPage(page: Page, curUrl: URL) { + const links = await this.getLinksFromPage(page, curUrl); + + const groups = links.reduce((acc, link, i) => { + const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE); + + if (!acc[groupIndex]) { + acc.push([]); + } + + acc[groupIndex].push(link); + + return acc; + }, [] as string[][]); + + return groups; + } + + private async *crawlSitePages( + page: Page, + curUrl: URL, + visitedLinks: Set = new Set(), + curRequestCount: number = 0, + ): AsyncGenerator { + if (curRequestCount >= this.maxRequestsPerCrawl) { + console.warn("Max requests per crawl reached. Stopping crawler."); + return; + } + + if (visitedLinks.has(curUrl.toString())) { + console.warn("Already visited, skipping: ", curUrl.toString()); + return; + } + + console.debug(`Crawling page: ${curUrl.toString()}`); + + await page.goto(curUrl.toString()); + + const htmlContent = await page.content(); + const linkGroups = await this.getLinkGroupsFromPage(page, curUrl); + const requestCount = curRequestCount + 1; + + visitedLinks.add(curUrl.toString()); + + yield { + path: curUrl.pathname, + url: curUrl.toString(), + content: htmlContent, + }; + + for (const linkGroup of linkGroups) { + for (const link of linkGroup) { + yield* this.crawlSitePages( + page, + new URL(link), + visitedLinks, + requestCount, + ); + } + } + } + + private async *crawlSite(): AsyncGenerator { + console.debug(`Crawling site repo: ${this.startUrl}`); + + const stats = await PCR(DocsCrawler.PCR_CONFIG); + + const browser = await stats.puppeteer.launch({ + args: [ + "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", + ], + executablePath: stats.executablePath, + }); + + const page = await browser.newPage(); + + try { + yield* this.crawlSitePages(page, this.startUrl); + } catch (e) { + console.debug("Error getting links: ", e); + } finally { + await browser.close(); + } + } +} diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index dfe9a8727..ed77f5b39 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -22,7 +22,7 @@ import { import { Telemetry } from "../../util/posthog"; import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider"; import { Article, chunkArticle, pageToArticle } from "./article"; -import { crawl } from "./crawl"; +import DocsCrawler from "./DocsCrawler"; import { runLanceMigrations, runSqliteMigrations } from "./migrations"; import { downloadFromS3, @@ -172,7 +172,7 @@ export default class DocsService { siteIndexingConfig: SiteIndexingConfig, reIndex: boolean = false, ): AsyncGenerator { - const { startUrl } = siteIndexingConfig; + const { startUrl, rootUrl } = siteIndexingConfig; const embeddingsProvider = await this.getEmbeddingsProvider(); if (this.docsIndexingQueue.has(startUrl)) { @@ -202,8 +202,10 @@ export default class DocsService { let processedPages = 0; let maxKnownPages = 1; + const docsCrawler = new DocsCrawler(new URL(startUrl)); + // Crawl pages and retrieve info as articles - for await (const page of crawl(new URL(startUrl))) { + for await (const page of docsCrawler.crawl()) { processedPages++; const article = pageToArticle(page); diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index 3c9ecca88..fef6fbb32 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -2,7 +2,7 @@ import { Readability } from "@mozilla/readability"; import { JSDOM } from "jsdom"; import { Chunk } from "../../"; import { cleanFragment, cleanHeader } from "../chunk/markdown"; -import { PageData } from "./crawl"; +import { PageData } from "./DocsCrawler"; export type ArticleComponent = { title: string; diff --git a/core/indexing/docs/crawl.ts b/core/indexing/docs/crawl.ts deleted file mode 100644 index 2bbe1f0cb..000000000 --- a/core/indexing/docs/crawl.ts +++ /dev/null @@ -1,240 +0,0 @@ -import { Octokit } from "@octokit/rest"; -import { URL } from "node:url"; -import { EventEmitter } from "events"; -import { getChromiumPath, getContinueUtilsPath } from "../../util/paths"; -import { executablePath, Page } from "puppeteer"; -// @ts-ignore -import PCR from "puppeteer-chromium-resolver"; -import * as fs from "fs"; - -export type PageData = { - url: string; - path: string; - content: string; -}; - -const MAX_TIME_TO_CRAWL = 1000 * 5; -const LINK_GROUP_SIZE = 2; // Controls parallelization of crawler -const GITHUB_HOST = "github.com"; -const MAX_REQUESTS_PER_CRAWL = 1000; -const markdownRegex = new RegExp(/\.(md|mdx)$/); -const octokit = new Octokit({ - auth: undefined, -}); - -const PCR_CONFIG = { - downloadPath: getContinueUtilsPath(), -}; - -export function verifyOrInstallChromium() { - if (!fs.existsSync(getChromiumPath())) { - PCR(PCR_CONFIG); - } -} - -async function getGithubRepoDefaultBranch( - owner: string, - repo: string, -): Promise { - const repoInfo = await octokit.repos.get({ - owner, - repo, - }); - - return repoInfo.data.default_branch; -} - -async function getGitHubRepoPaths(owner: string, repo: string, branch: string) { - const tree = await octokit.request( - "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", - { - owner, - repo, - tree_sha: branch, - headers: { - "X-GitHub-Api-Version": "2022-11-28", - }, - recursive: "true", - }, - ); - - const paths = tree.data.tree - .filter( - (file: any) => - file.type === "blob" && markdownRegex.test(file.path ?? ""), - ) - .map((file: any) => file.path); - - return paths; -} - -async function getGithubRepoFileContent( - path: string, - owner: string, - repo: string, -) { - try { - const response = await octokit.repos.getContent({ - owner, - repo, - path, - headers: { - Accept: "application/vnd.github.raw+json", - }, - }); - - return response.data as unknown as string; - } catch (error) { - console.debug("Error fetching file contents:", error); - return null; - } -} - -async function* crawlGithubRepo(url: URL) { - const urlStr = url.toString(); - const [_, owner, repo] = url.pathname.split("/"); - const branch = await getGithubRepoDefaultBranch(owner, repo); - const paths = await getGitHubRepoPaths(owner, repo, branch); - - for await (const path of paths) { - const content = await getGithubRepoFileContent(path, owner, repo); - - yield { - path, - url: urlStr, - content: content ?? "", - }; - } -} - -async function getLinksFromPage(page: Page) { - // The URL lib is not available by default in the page scope, - // so we need to expose it to the page through this fn. - await page.exposeFunction( - "getCleanedUrlFromAnchorTag", - (a: HTMLAnchorElement) => { - let url = new URL(a.href); - url.hash = ""; - return url.href; - }, - ); - - const links: string[] = await page.$$eval("a", (links) => - links.map((a) => (window as any).getCleanedUrlFromAnchorTag), - ); - - return links; -} - -async function getLinkGroups(page: Page) { - const links = await getLinksFromPage(page); - - const groups = links.reduce((acc, link, i) => { - const groupIndex = Math.floor(i / LINK_GROUP_SIZE); - - if (!acc[groupIndex]) { - acc.push([]); - } - - acc[groupIndex].push(link); - - return acc; - }, [] as string[][]); - - return groups; -} - -function shouldSkipPage(url: URL, rootUrl: URL, visitedLinks: Set) { - const hasVisitedLink = visitedLinks.has(url.toString()); - const isInvalidHostOrPath = - !url.pathname.startsWith(rootUrl.pathname) || rootUrl.host !== url.host; - - return hasVisitedLink || isInvalidHostOrPath; -} - -async function* crawlSitePages( - page: Page, - url: URL, - rootUrl: URL, - maxRequestsPerCrawl: number, - visitedLinks: Set = new Set(), - currentRequests: number = 0, -): AsyncGenerator { - if (currentRequests >= maxRequestsPerCrawl) { - console.warn("Max requests per crawl reached. Stopping crawler."); - return; - } - - if (shouldSkipPage(url, rootUrl, visitedLinks)) { - console.warn("Skipping ", url.toString()); - return; - } - - await page.goto(url.toString()); - - const htmlContent = await page.content(); - const linkGroups = await getLinkGroups(page); - const requestCount = currentRequests + 1; - - visitedLinks.add(url.toString()); - - yield { - path: url.pathname, - url: url.toString(), - content: htmlContent, - }; - - for (const linkGroup of linkGroups) { - for (const link of linkGroup) { - yield* crawlSitePages( - page, - new URL(link), - rootUrl, - maxRequestsPerCrawl, - visitedLinks, - requestCount, - ); - } - } -} - -async function* crawlSite( - startUrl: URL, - rootUrl: URL, - maxRequestsPerCrawl: number, -): AsyncGenerator { - const stats = await PCR(PCR_CONFIG); - - const browser = await stats.puppeteer.launch({ - args: [ - "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", - ], - executablePath: stats.executablePath, - // From the docs: https://pptr.dev/guides/headless-modes - // If the performance is more important for your use case, switch to chrome-headless-shell as following: - // { headless: "shell" } - headless: "shell", - }); - - const page = await browser.newPage(); - - try { - yield* crawlSitePages(page, startUrl, rootUrl, maxRequestsPerCrawl); - } catch (e) { - console.debug("Error getting links: ", e); - } finally { - await browser.close(); - } -} - -export async function* crawl( - url: URL, - maxRequestsPerCrawl: number = MAX_REQUESTS_PER_CRAWL, -): AsyncGenerator { - if (url.host === GITHUB_HOST) { - yield* crawlGithubRepo(url); - } else { - // TODO: Why both - yield* crawlSite(url, url, maxRequestsPerCrawl); - } -}