File size: 7,441 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/**
 * 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(/<script[\s\S]*?<\/script>/gi, "")
    .replace(/<style[\s\S]*?<\/style>/gi, "")
    .replace(/<nav[\s\S]*?<\/nav>/gi, "")
    .replace(/<header[\s\S]*?<\/header>/gi, "")
    .replace(/<footer[\s\S]*?<\/footer>/gi, "")
    .replace(/<aside[\s\S]*?<\/aside>/gi, "")
    .replace(/<[^>]+>/g, " ")
    .replace(/&nbsp;/g, " ")
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&mdash;/g, "—")
    .replace(/&ndash;/g, "–")
    .replace(/&hellip;/g, "…")
    .replace(/\s+/g, " ")
    .trim();
}

/**
 * Extract the <title> 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 };