Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions apps/sim/connectors/website/crawl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { mapSettledWithConcurrency } from '@sim/utils/concurrency'
import {
scopedPage,
type WebsiteDiscovery,
type WebsitePage,
type WebsiteScope,
} from '@/connectors/website/sitemap'

/** Pages read at once while crawling, bounding the load a sync puts on one site. */
const CRAWL_CONCURRENCY = 4

/**
* What reading one page told the crawl: whether the page belongs in the listing (with the hash of
* its text, the listing's change indicator), and the links it offers. A page the site no longer
* serves, or that is not an HTML page, is not listed.
*/
export interface CrawledPage {
listed: boolean
contentHash?: string
links: string[]
/** Where the page's relative links resolve: its final URL after redirects, or its `<base>`. */
base?: string
/** The page exists but could not be read, so the links it holds are unknown. */
unreadable?: boolean
}

interface CrawlLimits {
maxPages: number
maxDepth: number
/**
* Ends the crawl: reads in flight are cancelled and none start after it, and what the crawl found
* by then is a truncated listing.
*/
signal: AbortSignal
/** Stops the crawl once this many pages are listed, when only some are needed. */
maxListed?: number
}

/**
* Discovers a site's pages by following links breadth-first from the configured URL: each
* in-scope page is read once, never deeper than `maxDepth` links from the start, and no more pages
* are queued than `maxPages`. A crawl cut by the page cap or its signal is truncated, and one
* where a page could not be read is incomplete, so neither lets an unlisted page read as removed.
* A configured URL outside the include paths is still read for its links, but not listed: `read`
* receives the scope a page and its redirects must stay within.
*/
export async function crawlSitePages(
scope: WebsiteScope,
read: (page: WebsitePage, signal: AbortSignal, within: WebsiteScope) => Promise<CrawledPage>,
limits: CrawlLimits
): Promise<WebsiteDiscovery> {
// Relative links resolve against the URL a page is finally served at, as a browser's would.
const seed = (within: WebsiteScope) =>
scopedPage(scope.site.baseUrl, within) ?? scopedPage(`${scope.site.baseUrl}/`, within)
const listedStart = seed(scope)
const startScope = listedStart ? scope : { ...scope, include: [] }
const start = listedStart ?? seed(startScope)
if (!start)
throw new Error(
'The website URL is excluded by the configured paths or disallowed by robots.txt'
)
const pages: WebsitePage[] = []
const seen = new Set([start.url])
let level = [start]
let truncated = false
let incomplete = false
for (let depth = 0; level.length; depth++) {
const next: WebsitePage[] = []
for (let offset = 0; offset < level.length; offset += CRAWL_CONCURRENCY) {
if (limits.signal.aborted) return { pages, truncated: true, incomplete }
const batch = level.slice(offset, offset + CRAWL_CONCURRENCY)
const results = await mapSettledWithConcurrency(batch, CRAWL_CONCURRENCY, (page) =>
read(page, limits.signal, depth === 0 ? startScope : scope)
)
for (const [index, result] of results.entries()) {
const page = batch[index]
if (!page) continue
if (result.status === 'rejected' || result.value.unreadable) {
incomplete = true
continue
}
if (result.value.listed && (depth > 0 || listedStart))
pages.push({ ...page, contentHash: result.value.contentHash })
if (limits.maxListed && pages.length >= limits.maxListed)
return { pages, truncated: true, incomplete }
if (depth >= limits.maxDepth) continue
const before = seen.size
for (const link of result.value.links) {
const found = scopedPage(link, scope, result.value.base ?? page.url)
if (!found || seen.has(found.url)) continue
if (seen.size >= limits.maxPages) {
truncated = true
break
}
seen.add(found.url)
next.push(found)
}
// A start page that leads nowhere is more likely unread (a client-rendered site) than a
// site of one page, so it does not prove the site's other pages are gone.
if (depth === 0 && seen.size === before && !truncated) incomplete = true
}
}
level = next
}
return { pages, truncated, incomplete }
}
32 changes: 30 additions & 2 deletions apps/sim/connectors/website/meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@ export const WEBSITE_DEFAULT_MAX_PAGES = 500
/** Hard ceiling on the configurable `maxPages` value. */
export const WEBSITE_MAX_PAGES_LIMIT = 5000

/** Links followed from the website URL when crawling, unless `maxDepth` says otherwise. */
export const WEBSITE_DEFAULT_MAX_DEPTH = 3

/** Hard ceiling on the configurable `maxDepth` value. */
export const WEBSITE_MAX_DEPTH_LIMIT = 10

/** Client-safe metadata for the website connector: its setup fields, auth and tags. */
export const websiteConnectorMeta: ConnectorMeta = {
id: 'website',
name: 'Website',
description: 'Sync the pages of a website from its sitemap',
description: 'Sync the pages of a website from its sitemap or by following its links',
version: '1.0.0',
icon: WebsiteIcon,

Expand All @@ -36,7 +42,21 @@ export const websiteConnectorMeta: ConnectorMeta = {
placeholder: 'https://www.example.com',
required: true,
description:
'Pages are discovered from the sitemaps the site lists in robots.txt, or its sitemap.xml. Only pages on this host and under this path are synced, and robots.txt rules are honored.',
'Only pages on this host and under this path are synced, and robots.txt rules (including Crawl-delay) are honored.',
},
{
id: 'discovery',
title: 'Page Discovery',
type: 'dropdown',
required: false,
options: [
{ label: 'Sitemap, or follow links when there is none', id: 'auto' },
{ label: 'Sitemap only', id: 'sitemap' },
{ label: 'Follow links from the website URL', id: 'links' },
],
placeholder: 'Sitemap, or follow links when there is none',
description:
'Sitemaps come from robots.txt or sitemap.xml. Following links starts at the website URL and reads each page once, up to the link depth.',
},
{
id: 'sitemapUrl',
Expand All @@ -63,6 +83,14 @@ export const websiteConnectorMeta: ConnectorMeta = {
required: false,
description: 'Comma-separated path prefixes never to sync; * matches any characters.',
},
{
id: 'maxDepth',
title: 'Max Link Depth',
type: 'short-input',
placeholder: `e.g. 2 (default: ${WEBSITE_DEFAULT_MAX_DEPTH}, max: ${WEBSITE_MAX_DEPTH_LIMIT})`,
required: false,
description: 'How many links away from the website URL a crawl reads pages',
},
{
id: 'maxPages',
title: 'Max Pages',
Expand Down
35 changes: 32 additions & 3 deletions apps/sim/connectors/website/page.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { decodePage, robotsHeaderNoindex } from '@/connectors/website/page'
import { decodePage, extractPageText, robotsDirectives } from '@/connectors/website/page'

const html = (head: string, text: string) => `<html><head>${head}</head><body>${text}</body></html>`

Expand Down Expand Up @@ -44,7 +44,36 @@ describe('website page decoding', () => {

describe('X-Robots-Tag', () => {
it('honors an unqualified noindex after another crawler’s directive in a repeated header', () => {
expect(robotsHeaderNoindex('otherbot: noindex, noindex')).toBe(true)
expect(robotsHeaderNoindex('otherbot: noindex')).toBe(false)
expect(robotsDirectives('otherbot: noindex, noindex').noindex).toBe(true)
expect(robotsDirectives('otherbot: noindex').noindex).toBe(false)
})

it('reads nofollow and none as forbidding links, for this crawler only', () => {
expect(robotsDirectives('simbot: nofollow')).toEqual({ noindex: false, nofollow: true })
expect(robotsDirectives('none')).toEqual({ noindex: true, nofollow: true })
expect(robotsDirectives('otherbot: none').nofollow).toBe(false)
expect(robotsDirectives('simbot: noindex nofollow')).toEqual({ noindex: true, nofollow: true })
})
})

describe('robots meta tag', () => {
const links = (content: string) =>
extractPageText(html(`<meta name="robots" content="${content}">`, '<a href="/next">Next</a>'))
it('never reads a valued directive’s value as a directive', () => {
expect(links('max-image-preview:none')).toMatchObject({ noindex: false, links: ['/next'] })
})

it('skips only links whose rel holds the nofollow token', () => {
const page = extractPageText(
html(
'',
'<a rel="external-nofollow" href="/kept">Kept</a><a rel="external nofollow" href="/dropped">Dropped</a>'
)
)
expect(page.links).toEqual(['/kept'])
})

it('reads directives separated by spaces as well as commas', () => {
expect(links('noindex nofollow')).toMatchObject({ noindex: true, links: [] })
})
})
77 changes: 58 additions & 19 deletions apps/sim/connectors/website/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ export interface WebsitePageText {
text: string
/** The page asks not to be indexed (`noindex` or `none` in its robots meta tag). */
noindex: boolean
/**
* The links a crawl may follow from the page, as written (relative or absolute): none when the
* page asks not to be followed, and never a link marked `rel="nofollow"`.
*/
links: string[]
/** The page's first `<base href>`, as written, which relative links resolve against. */
baseHref?: string
}

/**
Expand All @@ -26,20 +33,40 @@ export interface WebsitePageText {
export function extractPageText(html: string): WebsitePageText {
assertHtmlStringWithinLimits(html)
const $ = cheerio.load(html)
const directives = $(`meta[name="robots" i], meta[name="${WEBSITE_CRAWLER_TOKEN}" i]`)
.map((_, element) => $(element).attr('content') ?? '')
.get()
.join(',')
const directives = robotsDirectives(
$(`meta[name="robots" i], meta[name="${WEBSITE_CRAWLER_TOKEN}" i]`)
.map((_, element) => $(element).attr('content') ?? '')
.get()
.join(',')
)
const title =
$('meta[property="og:title"]').attr('content')?.trim() ||
$('title').first().text().trim() ||
$('h1').first().text().trim()
// Read before page chrome is dropped: navigation is where most of a site's links live.
const links = directives.nofollow
? []
: $('a[href], area[href]')
.filter(
(_, element) =>
!($(element).attr('rel') ?? '').toLowerCase().split(/\s+/).includes('nofollow')
)
.map((_, element) => $(element).attr('href') ?? '')
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
.get()
.filter(Boolean)
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
$(CHROME_SELECTOR).remove()
const region = ['main', 'article'].find((selector) => $(selector).length > 0) ?? 'body'
const regionText = loadedHtmlToStructuredText($, region)
// A client-rendered page leaves <main>/<article> empty; fall back to the body.
const text = regionText || region === 'body' ? regionText : loadedHtmlToStructuredText($)
return { title, text, noindex: /\b(noindex|none)\b/i.test(directives) }
const baseHref = $('base[href]').first().attr('href')?.trim()
return {
title,
text,
noindex: directives.noindex,
links,
...(baseHref ? { baseHref } : {}),
}
}

const META_TAG = /<meta\s[^>]*>/gi
Expand Down Expand Up @@ -105,23 +132,35 @@ const VALUED_DIRECTIVES = new Set([
'max-video-preview',
])

/** What a page's robots directives ask of this crawler. */
export interface RobotsDirectives {
/** `noindex` or `none`: leave the page out of the index. */
noindex: boolean
/** `nofollow` or `none`: do not follow the page's links. */
nofollow: boolean
}

/**
* Whether an `X-Robots-Tag` header asks this crawler not to index the page: `noindex` or `none`,
* either unqualified or after this crawler's name (`SimBot: noindex`). Only a directive right
* after another crawler's name is left to that crawler. Repeated headers arrive joined by commas,
* which hides where one ends, so a crawler name never carries over to the directives after it:
* an unqualified `noindex` is never mistaken for another crawler's.
* The directives a robots `<meta>` tag's content or an `X-Robots-Tag` header gives this crawler:
* each directive, either unqualified or after this crawler's name
* (`SimBot: noindex`). Only a directive right after another crawler's name is left to that
* crawler, and a valued directive (`max-image-preview: none`) is never read as its value.
* Repeated headers arrive joined by commas, which hides where one ends, so a crawler name never
* carries over to the directives after it: an unqualified `noindex` is never mistaken for another
* crawler's.
*/
export function robotsHeaderNoindex(value: string | null): boolean {
if (!value) return false
export function robotsDirectives(value: string | null | undefined): RobotsDirectives {
const token = WEBSITE_CRAWLER_TOKEN.toLowerCase()
return value.split(',').some((part) => {
let directive = part.trim().toLowerCase()
const directives = (value ?? '').split(',').flatMap((part) => {
const directive = part.trim().toLowerCase()
const named = /^([\w-]+)\s*:\s*(.*)$/.exec(directive)
if (named && !VALUED_DIRECTIVES.has(named[1])) {
if (named[1] !== token) return false
directive = named[2]
}
return directive === 'noindex' || directive === 'none'
// Some pages separate directives with spaces (`noindex nofollow`) rather than commas.
if (!named) return directive.split(/\s+/)
if (VALUED_DIRECTIVES.has(named[1])) return []
return named[1] === token ? named[2].split(/\s+/) : []
})
return {
noindex: directives.some((directive) => directive === 'noindex' || directive === 'none'),
nofollow: directives.some((directive) => directive === 'nofollow' || directive === 'none'),
}
}
9 changes: 9 additions & 0 deletions apps/sim/connectors/website/robots.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,13 @@ describe('robots.txt rules for the website connector', () => {
const rules = Array.from({ length: 1001 }, (_, index) => `Disallow: /p${index}`)
expect(() => parseRobots(['User-agent: *', ...rules].join('\n'))).toThrow('more than')
})

it('takes the Crawl-delay of the applied group, capped so a site cannot stall a sync', () => {
expect(parseRobots('User-agent: *\nCrawl-delay: 1.5\nDisallow: /x').crawlDelayMs).toBe(1500)
expect(parseRobots('User-agent: *\nCrawl-delay: 3600').crawlDelayMs).toBe(10_000)
expect(
parseRobots('User-agent: *\nCrawl-delay: 5\n\nUser-agent: SimBot\nDisallow: /x').crawlDelayMs
).toBe(0)
expect(parseRobots('User-agent: *\nCrawl-delay: soon').crawlDelayMs).toBe(0)
})
})
Loading