Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
Implement JavaScript-only base href handling (ENG-2302) (#1756)
devin-ai-integration[bot]de1bc96aa000
diff --git a/apps/api/sharedLibs/html-transformer/src/lib.rs b/apps/api/sharedLibs/html-transformer/src/lib.rsindex 4018746bc..f2f49d5ba 100644--- a/apps/api/sharedLibs/html-transformer/src/lib.rs+++ b/apps/api/sharedLibs/html-transformer/src/lib.rs@@ -5,6 +5,23 @@ use serde::Deserialize;use serde_json::Value;use url::Url;+/// Extracts base href from HTML+///+/// # Safety+/// Input must be a C HTML string. Output will be a string. Output string must be freed with free_string.+#[no_mangle]+pub unsafe extern "C" fn extract_base_href(html: *const libc::c_char) -> *mut libc::c_char {+ let html = unsafe { CStr::from_ptr(html) }.to_str().unwrap();++ let document = parse_html().one(html);++ let base_href = document.select("base[href]").unwrap().next()+ .and_then(|base| base.attributes.borrow().get("href").map(|x| x.to_string()))+ .unwrap_or_else(|| String::new());++ CString::new(base_href).unwrap().into_raw()+}+/// Extracts links from HTML////// # Safetydiff --git a/apps/api/src/lib/__tests__/html-transformer.test.ts b/apps/api/src/lib/__tests__/html-transformer.test.tsindex 6d312c489..4eecff330 100644--- a/apps/api/src/lib/__tests__/html-transformer.test.ts+++ b/apps/api/src/lib/__tests__/html-transformer.test.ts@@ -94,6 +94,99 @@ describe("HTML Transformer", () => {expect(links).toContain("https://valid.com");// Other links should be filtered out or handled appropriately});++ it("should handle base href for relative links", async () => {+ const html = `+ <html>+ <head>+ <base href="/" />+ </head>+ <body>+ <a href="page.php">Page</a>+ <a href="/absolute">Absolute</a>+ <a href="https://external.com">External</a>+ </body>+ </html>+ `;+ const links = await extractLinks(html);+ expect(links).toContain("page.php");+ expect(links).toContain("/absolute");+ expect(links).toContain("https://external.com");+ });++ it("should handle relative base href", async () => {+ const html = `+ <html>+ <head>+ <base href="../" />+ </head>+ <body>+ <a href="page.php">Page</a>+ </body>+ </html>+ `;+ const links = await extractLinks(html);+ expect(links).toContain("page.php");+ });++ it("should handle absolute base href", async () => {+ const html = `+ <html>+ <head>+ <base href="https://cdn.example.com/" />+ </head>+ <body>+ <a href="assets/style.css">CSS</a>+ </body>+ </html>+ `;+ const links = await extractLinks(html);+ expect(links).toContain("assets/style.css");+ });++ it("should use first base href when multiple exist", async () => {+ const html = `+ <html>+ <head>+ <base href="/" />+ <base href="/other/" />+ </head>+ <body>+ <a href="page.php">Page</a>+ </body>+ </html>+ `;+ const links = await extractLinks(html);+ expect(links).toContain("page.php");+ });++ it("should fallback to page URL when no base href", async () => {+ const html = `+ <html>+ <body>+ <a href="page.php">Page</a>+ </body>+ </html>+ `;+ const links = await extractLinks(html);+ expect(links).toContain("page.php");+ });++ it("should handle malformed base href gracefully", async () => {+ const html = `+ <html>+ <head>+ <base href="" />+ <base />+ </head>+ <body>+ <a href="page.php">Page</a>+ </body>+ </html>+ `;+ const links = await extractLinks(html);+ expect(links).toContain("page.php");+ });});describe("extractMetadata", () => {diff --git a/apps/api/src/lib/html-transformer.ts b/apps/api/src/lib/html-transformer.tsindex b089ccc64..b1f58f826 100644--- a/apps/api/src/lib/html-transformer.ts+++ b/apps/api/src/lib/html-transformer.ts@@ -21,6 +21,7 @@ type TransformHtmlOptions = {class RustHTMLTransformer {private static instance: RustHTMLTransformer;private _extractLinks: KoffiFunction;+ private _extractBaseHref: KoffiFunction;private _extractMetadata: KoffiFunction;private _transformHtml: KoffiFunction;private _freeString: KoffiFunction;@@ -32,6 +33,7 @@ class RustHTMLTransformer {const cstn = "CString:" + crypto.randomUUID();const freedResultString = koffi.disposable(cstn, "string", this._freeString);this._extractLinks = lib.func("extract_links", freedResultString, ["string"]);+ this._extractBaseHref = lib.func("extract_base_href", freedResultString, ["string"]);this._extractMetadata = lib.func("extract_metadata", freedResultString, ["string"]);this._transformHtml = lib.func("transform_html", freedResultString, ["string"]);this._getInnerJSON = lib.func("get_inner_json", freedResultString, ["string"]);@@ -61,6 +63,18 @@ class RustHTMLTransformer {});}+ public async extractBaseHref(html: string): Promise<string> {+ return new Promise<string>((resolve, reject) => {+ this._extractBaseHref.async(html, (err: Error, res: string) => {+ if (err) {+ reject(err);+ } else {+ resolve(res);+ }+ });+ });+ }+public async extractMetadata(html: string): Promise<any> {return new Promise<string[]>((resolve, reject) => {this._extractMetadata.async(html, (err: Error, res: string) => {@@ -117,6 +131,17 @@ export async function extractLinks(return await converter.extractLinks(html);}+export async function extractBaseHref(+ html: string | null | undefined,+): Promise<string> {+ if (!html) {+ return "";+ }++ const converter = await RustHTMLTransformer.getInstance();+ return await converter.extractBaseHref(html);+}+export async function extractMetadata(html: string | null | undefined,): Promise<any> {diff --git a/apps/api/src/scraper/scrapeURL/lib/__tests__/extractLinks.test.ts b/apps/api/src/scraper/scrapeURL/lib/__tests__/extractLinks.test.tsnew file mode 100644index 000000000..c1430ea0f--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/lib/__tests__/extractLinks.test.ts@@ -0,0 +1,64 @@+import { extractLinks } from "../extractLinks";++describe("extractLinks integration", () => {+ it("should resolve relative links with base href correctly", async () => {+ const html = `+ <html>+ <head>+ <base href="/" />+ </head>+ <body>+ <a href="page.php">Page</a>+ <a href="/absolute">Absolute</a>+ <a href="https://external.com">External</a>+ </body>+ </html>+ `;+ const links = await extractLinks(html, "https://example.org/foo/bar");+ expect(links).toContain("https://example.org/page.php");+ expect(links).toContain("https://example.org/absolute");+ expect(links).toContain("https://external.com");+ });++ it("should resolve relative base href against page URL", async () => {+ const html = `+ <html>+ <head>+ <base href="../" />+ </head>+ <body>+ <a href="page.php">Page</a>+ </body>+ </html>+ `;+ const links = await extractLinks(html, "https://example.org/foo/bar");+ expect(links).toContain("https://example.org/page.php");+ });++ it("should handle absolute base href", async () => {+ const html = `+ <html>+ <head>+ <base href="https://cdn.example.com/" />+ </head>+ <body>+ <a href="assets/style.css">CSS</a>+ </body>+ </html>+ `;+ const links = await extractLinks(html, "https://example.org/foo/bar");+ expect(links).toContain("https://cdn.example.com/assets/style.css");+ });++ it("should fallback to page URL when no base href", async () => {+ const html = `+ <html>+ <body>+ <a href="page.php">Page</a>+ </body>+ </html>+ `;+ const links = await extractLinks(html, "https://example.org/foo/bar");+ expect(links).toContain("https://example.org/foo/page.php");+ });+});diff --git a/apps/api/src/scraper/scrapeURL/lib/extractLinks.ts b/apps/api/src/scraper/scrapeURL/lib/extractLinks.tsindex 48117ae76..da98fc2d9 100644--- a/apps/api/src/scraper/scrapeURL/lib/extractLinks.ts+++ b/apps/api/src/scraper/scrapeURL/lib/extractLinks.ts@@ -1,39 +1,56 @@// TODO: refactorimport { load } from "cheerio"; // rustifiedimport { logger } from "../../../lib/logger";-import { extractLinks as _extractLinks } from "../../../lib/html-transformer";+import { extractLinks as _extractLinks, extractBaseHref as _extractBaseHref } from "../../../lib/html-transformer";++function resolveUrlWithBaseHref(href: string, baseUrl: string, baseHref: string): string {+ let resolutionBase = baseUrl;++ if (baseHref) {+ try {+ new URL(baseHref);+ resolutionBase = baseHref;+ } catch {+ try {+ resolutionBase = new URL(baseHref, baseUrl).href;+ } catch {+ resolutionBase = baseUrl;+ }+ }+ }++ try {+ if (href.startsWith("http://") || href.startsWith("https://")) {+ return href;+ } else if (href.startsWith("mailto:")) {+ return href;+ } else if (href.startsWith("#")) {+ return '';+ } else {+ return new URL(href, resolutionBase).href;+ }+ } catch (error) {+ logger.error(+ `Failed to construct URL for href: ${href} with base: ${resolutionBase}`,+ { error },+ );+ return '';+ }+}async function extractLinksRust(html: string, baseUrl: string): Promise<string[]> {const hrefs = await _extractLinks(html);-+ const baseHref = await _extractBaseHref(html);const links: string[] = [];hrefs.forEach(href => {href = href.trim();- try {- if (href.startsWith("http://") || href.startsWith("https://")) {- // Absolute URL, add as is- links.push(href);- } else if (href.startsWith("/")) {- // Relative URL starting with '/', append to origin- links.push(new URL(href, baseUrl).href);- } else if (!href.startsWith("#") && !href.startsWith("mailto:")) {- // Relative URL not starting with '/', append to base URL- links.push(new URL(href, baseUrl).href);- } else if (href.startsWith("mailto:")) {- // mailto: links, add as is- links.push(href);- }- // Fragment-only links (#) are ignored- } catch (error) {- logger.error(- `Failed to construct URL for href: ${href} with base: ${baseUrl}`,- { error },- );+ const resolvedUrl = resolveUrlWithBaseHref(href, baseUrl, baseHref);+ if (resolvedUrl) {+ links.push(resolvedUrl);}});- // Remove duplicates and returnreturn [...new Set(links)];}@@ -48,36 +65,19 @@ export async function extractLinks(html: string, baseUrl: string): Promise<strin}const $ = load(html);+ const baseHref = $('base[href]').first().attr('href') || '';const links: string[] = [];$("a").each((_, element) => {let href = $(element).attr("href");if (href) {href = href.trim();- try {- if (href.startsWith("http://") || href.startsWith("https://")) {- // Absolute URL, add as is- links.push(href);- } else if (href.startsWith("/")) {- // Relative URL starting with '/', append to origin- links.push(new URL(href, baseUrl).href);- } else if (!href.startsWith("#") && !href.startsWith("mailto:")) {- // Relative URL not starting with '/', append to base URL- links.push(new URL(href, baseUrl).href);- } else if (href.startsWith("mailto:")) {- // mailto: links, add as is- links.push(href);- }- // Fragment-only links (#) are ignored- } catch (error) {- logger.error(- `Failed to construct URL for href: ${href} with base: ${baseUrl}`,- { error },- );+ const resolvedUrl = resolveUrlWithBaseHref(href, baseUrl, baseHref);+ if (resolvedUrl) {+ links.push(resolvedUrl);}}});- // Remove duplicates and returnreturn [...new Set(links)];}