// DuckDuckGo HTML search parser with rate throttling import type { SearchResult } from "./constants.js"; let lastSearchTs = 0; const MIN_INTERVAL_MS = 2000; // 2s between DDG requests export function throttleWait(): number { const now = Date.now(); const elapsed = now - lastSearchTs; return Math.max(0, MIN_INTERVAL_MS - elapsed); } export function markSearchTime(): void { lastSearchTs = Date.now(); } function decodeDDGUrl(rawUrl: string): string | null { if (!rawUrl) return null; if (rawUrl.includes("uddg=")) { const match = rawUrl.match(/uddg=([^&]+)/); if (match) return decodeURIComponent(match[1]); } if (rawUrl.startsWith("//")) return "https:" + rawUrl; if (rawUrl.startsWith("/")) return "https://duckduckgo.com" + rawUrl; return rawUrl; } function decodeHTMLEntities(str: string): string { return str .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, '"') .replace(/'/g, "'") .replace(/'/g, "'") .replace(/'/g, "'") .replace(/ /g, " ") .replace(///g, "/") // Numeric character references .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(parseInt(n, 10))) .replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16))) .trim(); } export interface ParseDiagnostics { captcha?: true; resultsFound: number; resultsSkipped: number; rawBlockCount: number; } export function parseDdgResults(html: string): { results: SearchResult[]; diagnostics: ParseDiagnostics; error?: string; } { const diagnostics: ParseDiagnostics = { resultsFound: 0, resultsSkipped: 0, rawBlockCount: 0, }; // Detect captcha if ( html.includes("anomaly-modal") || html.includes("captcha") || html.includes("botdetection") ) { return { results: [], diagnostics: { ...diagnostics, captcha: true }, error: "DuckDuckGo is showing a captcha. Try again later or use a different search method.", }; } const results: SearchResult[] = []; const seenUrls = new Set(); // Parse by result blocks — each result is wrapped in a container. // Links: TITLE // Snippets: TEXT // They share a parent result block, so we pair by extracting blocks first. const resultBlockRegex = /class="result[^"]*"[^>]*>([\s\S]*?)(?=]*class="result[^"]*"|$)/gi; const linkRegex = /]*class="result__a"[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/i; const snippetRegex = /class="result__snippet"[^>]*>([\s\S]*?)<\/a>/i; let blockMatch; while ((blockMatch = resultBlockRegex.exec(html)) !== null) { diagnostics.rawBlockCount++; const block = blockMatch[1]; const linkMatch = block.match(linkRegex); if (!linkMatch) continue; const rawUrl = linkMatch[1]; const rawTitle = linkMatch[2].replace(/<[^>]+>/g, "").trim(); const url = decodeDDGUrl(rawUrl); if (!url || seenUrls.has(url)) { if (url) diagnostics.resultsSkipped++; continue; } seenUrls.add(url); diagnostics.resultsFound++; const snippetMatch = block.match(snippetRegex); const snippet = snippetMatch ? decodeHTMLEntities(snippetMatch[1].replace(/<[^>]+>/g, "").trim()) : ""; results.push({ title: decodeHTMLEntities(rawTitle), url, snippet, }); } return { results, diagnostics }; }