/** * URL content extraction for Deep Reading. * Fetches a URL and extracts readable text content using Mozilla's Readability-inspired approach. * Falls back to basic HTML stripping if structured extraction fails. */ const USER_AGENT = "RotNot/1.0 (Deep Reading Exercise; +https://github.com/CuriosityQuantified/rotnot)"; /** Maximum characters to keep from extracted content */ const MAX_CONTENT_CHARS = 15_000; /** Minimum characters for a valid article */ const MIN_CONTENT_CHARS = 200; export interface ExtractedArticle { title: string; body: string; domain: string; wordCount: number; estimatedMinutes: number; sourceUrl: string; } /** * Strip HTML tags and decode common entities. */ function stripHtml(html: string): string { return html .replace(//gi, "") .replace(//gi, "") .replace(//gi, "") .replace(//gi, "") .replace(//gi, "") .replace(//gi, "") .replace(/<[^>]+>/g, " ") .replace(/ /g, " ") .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, '"') .replace(/'/g, "'") .replace(/—/g, "—") .replace(/–/g, "–") .replace(/…/g, "…") .replace(/\s+/g, " ") .trim(); } /** * Extract the from HTML. */ function extractTitle(html: string): string { const match = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i); if (match) return stripHtml(match[1]).trim(); // Fallback: og:title const ogMatch = html.match( /<meta\s+property=["']og:title["']\s+content=["']([^"']+)["']/i, ); if (ogMatch) return ogMatch[1].trim(); return "Untitled Article"; } /** * Extract the main content from HTML. * Uses a series of heuristics to find the article body. */ function extractContent(html: string): string { // Try <article> tag first const articleMatch = html.match(/<article[\s\S]*?>([\s\S]*?)<\/article>/i); if (articleMatch) { const text = stripHtml(articleMatch[1]); if (text.length >= MIN_CONTENT_CHARS) return text; } // Try main content area const mainMatch = html.match(/<main[\s\S]*?>([\s\S]*?)<\/main>/i); if (mainMatch) { const text = stripHtml(mainMatch[1]); if (text.length >= MIN_CONTENT_CHARS) return text; } // Try common content class patterns const contentPatterns = [ /class=["'][^"']*(?:article-body|article-content|post-content|entry-content|story-body)[^"']*["'][\s\S]*?>([\s\S]*?)<\/(?:div|section)/i, /id=["'](?:article-body|content|main-content|story)["'][\s\S]*?>([\s\S]*?)<\/(?:div|section)/i, ]; for (const pattern of contentPatterns) { const match = html.match(pattern); if (match) { const text = stripHtml(match[1]); if (text.length >= MIN_CONTENT_CHARS) return text; } } // Fallback: strip everything and take the body const bodyMatch = html.match(/<body[\s\S]*?>([\s\S]*?)<\/body>/i); if (bodyMatch) { return stripHtml(bodyMatch[1]); } return stripHtml(html); } /** * Convert extracted plain text into structured paragraphs. */ function formatAsReadableText(rawText: string): string { // Split on sentence boundaries that look like paragraph breaks // (double spaces, multiple newlines get collapsed to single space by stripHtml) const sentences = rawText.split(/(?<=[.!?])\s+/); const paragraphs: string[] = []; let currentParagraph = ""; for (const sentence of sentences) { currentParagraph += (currentParagraph ? " " : "") + sentence; // Roughly 3-5 sentences per paragraph const sentenceCount = (currentParagraph.match(/[.!?]/g) || []).length; if (sentenceCount >= 4) { paragraphs.push(currentParagraph.trim()); currentParagraph = ""; } } if (currentParagraph.trim()) { paragraphs.push(currentParagraph.trim()); } return paragraphs.join("\n\n"); } /** * Estimate reading difficulty based on text characteristics. */ function estimateDifficulty( text: string, ): "beginner" | "intermediate" | "advanced" { const words = text.split(/\s+/); const avgWordLength = words.reduce((sum, w) => sum + w.length, 0) / words.length; const sentences = text.split(/[.!?]+/).filter((s) => s.trim().length > 0); const avgSentenceLength = words.length / Math.max(sentences.length, 1); // Simple readability heuristic if (avgWordLength > 6 || avgSentenceLength > 25) return "advanced"; if (avgWordLength > 5 || avgSentenceLength > 18) return "intermediate"; return "beginner"; } /** * Fetch a URL and extract readable article content. */ export async function fetchAndExtract(url: string): Promise<ExtractedArticle> { const response = await fetch(url, { headers: { "User-Agent": USER_AGENT, Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", }, redirect: "follow", signal: AbortSignal.timeout(15_000), }); if (!response.ok) { throw new Error(`Failed to fetch URL: ${response.status} ${response.statusText}`); } const contentType = response.headers.get("content-type") ?? ""; if (!contentType.includes("text/html") && !contentType.includes("text/plain") && !contentType.includes("application/xhtml")) { throw new Error(`Unsupported content type: ${contentType}. Only HTML and text pages are supported.`); } const html = await response.text(); const title = extractTitle(html); let rawContent = extractContent(html); // Truncate if too long if (rawContent.length > MAX_CONTENT_CHARS) { // Cut at last sentence boundary before limit const truncated = rawContent.slice(0, MAX_CONTENT_CHARS); const lastSentence = truncated.lastIndexOf("."); rawContent = lastSentence > MAX_CONTENT_CHARS * 0.8 ? truncated.slice(0, lastSentence + 1) : truncated; } if (rawContent.length < MIN_CONTENT_CHARS) { throw new Error( "Could not extract enough readable content from this URL. The page may be behind a paywall, require JavaScript, or have minimal text content.", ); } const body = formatAsReadableText(rawContent); const wordCount = body.split(/\s+/).length; const estimatedMinutes = Math.max(1, Math.round(wordCount / 200)); const domain = new URL(url).hostname.replace("www.", ""); return { title, body, domain, wordCount, estimatedMinutes, sourceUrl: url, }; } /** * Create an Article-compatible object from user-pasted text. */ export function createFromText( text: string, title?: string, ): ExtractedArticle { const body = text.trim(); if (body.length < MIN_CONTENT_CHARS) { throw new Error( `Text is too short (${body.length} characters). Minimum ${MIN_CONTENT_CHARS} characters required for a meaningful reading exercise.`, ); } const truncated = body.length > MAX_CONTENT_CHARS ? body.slice(0, body.lastIndexOf(".", MAX_CONTENT_CHARS) + 1) || body.slice(0, MAX_CONTENT_CHARS) : body; const wordCount = truncated.split(/\s+/).length; const estimatedMinutes = Math.max(1, Math.round(wordCount / 200)); return { title: title?.trim() || "Custom Reading", body: truncated, domain: "Custom", wordCount, estimatedMinutes, sourceUrl: "", }; } export { MIN_CONTENT_CHARS, MAX_CONTENT_CHARS, stripHtml, extractTitle, extractContent, estimateDifficulty };