/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { BrowserCrawler } from "./BrowserCrawler.ts"; import { RequestQueue } from "../queue/RequestQueue.ts"; import { BxcDB } from "../db/BxcDB.ts"; import { redis } from "bun"; import { extractStructuredData } from "../google/fetch.ts"; import { generateOpenApiSchema } from "../utils/openapi.ts"; import { getEmbedding } from "../utils/vector.ts"; import { ensureCrawlMarkdown } from "./markdown-fallback.ts"; export interface AutonomousCrawlerOptions { requestQueueName?: string; allowedDomains?: string[]; /** Motifs d'URL (RegExp source) à ne jamais enfiler. */ excludePatterns?: string[]; maxDepth?: number; maxRequests?: number; /** Lower bound for the adaptive request worker pool (default: 2). */ minConcurrency?: number; /** Upper bound for the adaptive request worker pool (default: 20). */ maxConcurrency?: number; /** Attempts after the initial request before sending a URL to the dead-letter queue (default: 3). */ maxRetries?: number; redisTtl?: number; // In seconds, default: 86400 (24h) profile?: "static" | "http" | "fast" | "stealth" | "max"; daemon?: boolean; proxyPool?: string[]; } export class AutonomousCrawler { private requestQueue: RequestQueue; private db: BxcDB; private allowedDomains?: string[]; private exclude: RegExp[]; private maxDepth: number; private maxRequests: number; private minConcurrency?: number; private maxConcurrency?: number; private redisTtl: number; private profile: "static" | "http" | "fast" | "stealth" | "max"; private daemon: boolean; private proxyPool?: string[]; private activeCrawler?: BrowserCrawler; private isRunning = false; constructor(opts: AutonomousCrawlerOptions = {}) { this.requestQueue = RequestQueue.open(opts.requestQueueName ?? "bxc-autonomous-crawler", { maxRetries: opts.maxRetries, }); this.db = new BxcDB(); this.allowedDomains = opts.allowedDomains; this.exclude = (opts.excludePatterns ?? []).map((motif) => new RegExp(motif)); this.maxDepth = opts.maxDepth ?? 5; this.maxRequests = opts.maxRequests ?? Infinity; this.minConcurrency = opts.minConcurrency; this.maxConcurrency = opts.maxConcurrency; this.redisTtl = opts.redisTtl ?? 86400; // 24h this.profile = opts.profile ?? "stealth"; this.daemon = opts.daemon ?? false; this.proxyPool = opts.proxyPool; } /** * Run the crawler. If URLs are specified, enqueue them. */ async run(initialUrls?: string[]): Promise { if (this.isRunning) return; this.isRunning = true; if (initialUrls && initialUrls.length > 0) { const prepared = initialUrls.map((url) => { return { url, opts: { userData: { depth: 0 } } }; }); this.requestQueue.addRequests(prepared); } // Periodic background recovery task to handle crashed or killed workers const recoveryInterval = setInterval(() => { try { const recovered = this.requestQueue.recoverStaleLocks(); if (recovered > 0) { console.log(`[crawler-recovery] Auto-recovered ${recovered} stale locked requests from queue.`); } } catch (err) { console.error("[crawler-recovery] Stale lock recovery error:", err); } }, 60000); this.activeCrawler = new BrowserCrawler({ requestQueue: this.requestQueue, profile: this.profile, minConcurrency: this.minConcurrency, maxConcurrency: this.maxConcurrency, maxRequestsPerCrawl: this.maxRequests, daemon: this.daemon, proxyPool: this.proxyPool, requestHandler: async (context) => { const { request, page, response, enqueueLinks, pushData, log } = context; const depth = (request.userData?.depth as number) ?? 0; log(`Crawling url: ${request.url} at depth ${depth}`); const url = request.url; // Check Redis Cache first to bypass heavy crawling if possible const cached = await redis.get(`bxc:cache:url:${url}`); if (cached) { log(`Cache hit for: ${url}. Skipping scrape.`); try { const parsed = JSON.parse(cached); // Push cached data await pushData({ url, title: parsed.title, depth, status: parsed.status, openapi: parsed.openapi, cached: true }); } catch {} return; } // Handle Sitemap XML files const isSitemap = url.endsWith(".xml") || url.includes("sitemap"); if (isSitemap) { log(`Parsing sitemap: ${url}`); const sitemapHtml = await page.content(); const cheerio = require("cheerio"); const $ = cheerio.load(sitemapHtml, { xmlMode: true }); const locUrls: string[] = []; $("loc").each((_: any, el: any) => { const locText = $(el).text().trim(); if (locText) locUrls.push(locText); }); log(`Found ${locUrls.length} links in sitemap.`); let filtered = locUrls; if (this.allowedDomains && this.allowedDomains.length > 0) { filtered = locUrls.filter((l) => { try { const hostname = new URL(l).hostname; return this.allowedDomains!.some( (d) => hostname === d || hostname.endsWith("." + d) ); } catch { return false; } }); } if (filtered.length > 0) { this.requestQueue.addRequests( filtered.map((l) => ({ url: l, opts: { userData: { depth } } })) ); } await redis.set(`bxc:cache:url:${url}`, JSON.stringify({ title: "Sitemap", status: 200 }), "EX", 3600); return; } // 1. Capture the page and its structured metadata before normalizing text. const html = await page.content(); const browserMarkdown = await page.markdown(); const title = await page.title(); const structured = await extractStructuredData(html); const markdown = ensureCrawlMarkdown({ html, markdown: browserMarkdown, title, description: structured.description, url, }); // 2. Generate OpenAPI Schema const openapi = generateOpenApiSchema({ url, title, description: structured.description || undefined, markdown, structuredData: structured, tables: structured.tables, feedItems: structured.feedItems, timestamp: new Date().toISOString() }); // 3. Generate Semantic / Vector Embedding log(`Generating embedding for: ${url}`); const vector = await getEmbedding(markdown, "passage"); // 4. Save to SQLite database const metadata = { title, depth, canonical: structured.canonical, openGraph: structured.openGraph, twitter: structured.twitter }; this.db.saveScrape(url, this.profile, response.status, html, metadata, markdown, structured, openapi, vector); // 5. Cache in Redis const redisKey = `bxc:cache:url:${url}`; const redisValue = JSON.stringify({ url, title, status: response.status, markdown, structured, openapi, vector, timestamp: new Date().toISOString() }); await redis.set(redisKey, redisValue, "EX", this.redisTtl); log(`Cached url + vector in Redis: ${url}`); // 6. Recursively enqueue links if depth < this.maxDepth if (depth < this.maxDepth) { await enqueueLinks({ selector: "a[href]", allowedDomains: this.allowedDomains, exclude: this.exclude, userData: { depth: depth + 1 } }); } // Push to Crawlee-like dataset await pushData({ url, title, depth, status: response.status, openapi, vector }); } }); try { await this.activeCrawler.run(); } finally { clearInterval(recoveryInterval); this.isRunning = false; } } stop(): void { this.isRunning = false; this.activeCrawler?.stop(); } stats() { return this.requestQueue.stats(); } replayFailed(): number { return this.requestQueue.replayFailed(); } deadLetterQueue() { return this.requestQueue.deadLetterQueue(); } }