diff --git a/apps/sim/connectors/website/crawl.ts b/apps/sim/connectors/website/crawl.ts
new file mode 100644
index 00000000000..9175f95baa4
--- /dev/null
+++ b/apps/sim/connectors/website/crawl.ts
@@ -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?: 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,
+ limits: CrawlLimits
+): Promise {
+ // 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 }
+}
diff --git a/apps/sim/connectors/website/meta.ts b/apps/sim/connectors/website/meta.ts
index 614013f14f1..4749eb71afb 100644
--- a/apps/sim/connectors/website/meta.ts
+++ b/apps/sim/connectors/website/meta.ts
@@ -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,
@@ -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',
@@ -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',
diff --git a/apps/sim/connectors/website/page.test.ts b/apps/sim/connectors/website/page.test.ts
index c8d216c8abf..b119135b496 100644
--- a/apps/sim/connectors/website/page.test.ts
+++ b/apps/sim/connectors/website/page.test.ts
@@ -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) => `${head}${text}`
@@ -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(``, 'Next'))
+ 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(
+ '',
+ 'KeptDropped'
+ )
+ )
+ expect(page.links).toEqual(['/kept'])
+ })
+
+ it('reads directives separated by spaces as well as commas', () => {
+ expect(links('noindex nofollow')).toMatchObject({ noindex: true, links: [] })
})
})
diff --git a/apps/sim/connectors/website/page.ts b/apps/sim/connectors/website/page.ts
index 60a4624fa99..725baa3b959 100644
--- a/apps/sim/connectors/website/page.ts
+++ b/apps/sim/connectors/website/page.ts
@@ -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 ``, as written, which relative links resolve against. */
+ baseHref?: string
}
/**
@@ -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') ?? '')
+ .get()
+ .filter(Boolean)
$(CHROME_SELECTOR).remove()
const region = ['main', 'article'].find((selector) => $(selector).length > 0) ?? 'body'
const regionText = loadedHtmlToStructuredText($, region)
// A client-rendered page leaves / 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 = /]*>/gi
@@ -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 `` 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'),
+ }
}
diff --git a/apps/sim/connectors/website/robots.test.ts b/apps/sim/connectors/website/robots.test.ts
index 7614e81af46..1d599bebb40 100644
--- a/apps/sim/connectors/website/robots.test.ts
+++ b/apps/sim/connectors/website/robots.test.ts
@@ -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)
+ })
})
diff --git a/apps/sim/connectors/website/robots.ts b/apps/sim/connectors/website/robots.ts
index ef1ac461f7c..eb691c50f30 100644
--- a/apps/sim/connectors/website/robots.ts
+++ b/apps/sim/connectors/website/robots.ts
@@ -11,8 +11,20 @@ interface RobotsRule {
export interface RobotsPolicy {
allows(path: string): boolean
sitemaps: string[]
+ /** The pause the site asks for between requests, in milliseconds, capped; 0 when none. */
+ crawlDelayMs: number
}
+/** One `User-agent` group: the crawlers it names, its rules, and its Crawl-delay in seconds. */
+interface RobotsGroup {
+ agents: string[]
+ rules: RobotsRule[]
+ delaySeconds?: number
+}
+
+/** The longest pause between requests a site's Crawl-delay may impose. */
+const MAX_CRAWL_DELAY_MS = 10_000
+
/**
* A URL path in one canonical form, so `/%70rivate` and `/private`, or `/café` and `/caf%C3%A9`,
* compare equal: escapes of unreserved characters are decoded, other escapes uppercased, and
@@ -70,9 +82,9 @@ const MAX_ROBOTS_RULES = 1000
* groups when none does. The longest matching rule decides, and Allow wins a tie.
*/
export function parseRobots(body: string): RobotsPolicy {
- const groups: { agents: string[]; rules: RobotsRule[] }[] = []
+ const groups: RobotsGroup[] = []
const sitemaps: string[] = []
- let current: { agents: string[]; rules: RobotsRule[] } | undefined
+ let current: RobotsGroup | undefined
let readingAgents = false
for (const raw of body.split(/\r\n|\r|\n/)) {
const line = raw.replace(/#.*$/, '').trim()
@@ -95,6 +107,11 @@ export function parseRobots(body: string): RobotsPolicy {
continue
}
readingAgents = false
+ if (current && field === 'crawl-delay') {
+ const seconds = Number(value)
+ if (Number.isFinite(seconds) && seconds > 0) current.delaySeconds = seconds
+ continue
+ }
if (!current || (field !== 'allow' && field !== 'disallow')) continue
if (!value) continue
current.rules.push({
@@ -106,15 +123,16 @@ export function parseRobots(body: string): RobotsPolicy {
}
const token = WEBSITE_CRAWLER_TOKEN.toLowerCase()
const named = groups.filter((group) => group.agents.includes(token))
- const rules = (
- named.length ? named : groups.filter((group) => group.agents.includes('*'))
- ).flatMap((group) => group.rules)
+ const applied = named.length ? named : groups.filter((group) => group.agents.includes('*'))
+ const rules = applied.flatMap((group) => group.rules)
+ const delaySeconds = Math.max(0, ...applied.map((group) => group.delaySeconds ?? 0))
if (rules.length > MAX_ROBOTS_RULES)
throw new Error(
`robots.txt applies ${rules.length} rules to this crawler, more than the ${MAX_ROBOTS_RULES} it evaluates`
)
return {
sitemaps,
+ crawlDelayMs: Math.min(Math.round(delaySeconds * 1000), MAX_CRAWL_DELAY_MS),
allows(rawPath) {
const path = normalizePath(rawPath)
let decision: RobotsRule | undefined
@@ -133,4 +151,4 @@ export function parseRobots(body: string): RobotsPolicy {
}
/** A site without robots.txt allows everything and declares no sitemaps. */
-export const ALLOW_ALL_ROBOTS: RobotsPolicy = { sitemaps: [], allows: () => true }
+export const ALLOW_ALL_ROBOTS: RobotsPolicy = { sitemaps: [], crawlDelayMs: 0, allows: () => true }
diff --git a/apps/sim/connectors/website/sitemap.ts b/apps/sim/connectors/website/sitemap.ts
index 7580b4bc8dc..f8fc715c2ff 100644
--- a/apps/sim/connectors/website/sitemap.ts
+++ b/apps/sim/connectors/website/sitemap.ts
@@ -47,6 +47,8 @@ export interface WebsitePage {
path: string
/** The sitemap's ``, as an ISO timestamp, when it gives a valid one. */
lastModified?: string
+ /** The hash of the text a crawl read from the page, its change indicator when it has no date. */
+ contentHash?: string
}
/** The pages one discovery found, and why they may not be all the site has. */
@@ -166,9 +168,13 @@ function readSitemapEntries(
return closed && !implied && isSitemap() ? 'complete' : 'invalid'
}
-/** The page a sitemap location names, when it is a page within the configured scope. */
-export function scopedPage(location: string, scope: WebsiteScope): WebsitePage | null {
- const url = siteUrl(location, `${scope.site.origin}/`, scope.site)
+/** The page a location names, resolved against `base`, when it is a page within the scope. */
+export function scopedPage(
+ location: string,
+ scope: WebsiteScope,
+ base = `${scope.site.origin}/`
+): WebsitePage | null {
+ const url = siteUrl(location, base, scope.site)
if (!url) return null
url.hash = ''
const path = normalizePath(url.pathname).replace(/\/+$/, '') || '/'
diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts
index f798c255207..705ba73d561 100644
--- a/apps/sim/connectors/website/website.integration.ts
+++ b/apps/sim/connectors/website/website.integration.ts
@@ -29,6 +29,10 @@ let robotsToWww = false
let hung: ServerResponse[] = []
let wwwRequests: IncomingMessage[] = []
let undeclared: 'html' | 'text' | undefined
+let crawlDelay = ''
+let lockedLink = false
+let extraLinks = ''
+const pageRequests: { path: string; at: number }[] = []
let faqBody = '
Original answer.
'
/** More `` entries than one sitemap may list, all disallowed, between two listed pages. */
@@ -55,7 +59,37 @@ const siteServer = createServer((request, response) => {
if (request.headers.host?.startsWith('www.')) wwwRequests.push(request)
const path = new URL(request.url ?? '/', site).pathname
if (/^\/child-\d+\.xml$/.test(path)) return send(200, 'application/xml', '')
+ if (!/\.(xml|gz|txt)$/.test(path)) pageRequests.push({ path, at: Date.now() })
switch (path) {
+ case '/':
+ return send(
+ 200,
+ 'text/html',
+ `Home