RotNot / src /lib /sources /wikipedia.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
4.38 kB
/**
* Wikipedia MediaWiki API client for source curation.
*
* Uses the MediaWiki Action API to search for topics and extract
* relevant content. Rate-limited to stay well within the 10K req/hr
* authenticated limit (we don't even need auth for this volume).
*
* All content from Wikipedia is licensed under CC BY-SA 4.0.
*/
const WIKIPEDIA_API = "https://en.wikipedia.org/w/api.php";
const USER_AGENT = "RotNot/1.0 (educational app; contact: github.com/CuriosityQuantified/rotnot)";
export interface WikiSearchResult {
pageId: number;
title: string;
snippet: string; // HTML snippet from search
}
export interface WikiExtract {
pageId: number;
title: string;
url: string;
extract: string; // plain-text extract (first N characters)
}
/**
* Search Wikipedia for pages matching a query.
* Returns up to `limit` results (default 3).
*/
export async function searchWikipedia(
query: string,
limit: number = 3,
): Promise<WikiSearchResult[]> {
const params = new URLSearchParams({
action: "query",
list: "search",
srsearch: query,
srlimit: String(limit),
srinfo: "totalhits",
srprop: "snippet",
format: "json",
origin: "*",
});
const response = await fetch(`${WIKIPEDIA_API}?${params}`, {
headers: { "User-Agent": USER_AGENT },
});
if (!response.ok) {
throw new Error(`Wikipedia search failed: ${response.status} ${response.statusText}`);
}
const data = await response.json();
const results = data?.query?.search ?? [];
return results.map((r: { pageid: number; title: string; snippet: string }) => ({
pageId: r.pageid,
title: r.title,
snippet: stripHtml(r.snippet),
}));
}
/**
* Fetch a plain-text extract for a Wikipedia page by title.
* Returns up to `maxChars` characters of the article's introduction.
*/
export async function getWikipediaExtract(
title: string,
maxChars: number = 3000,
): Promise<WikiExtract | null> {
const params = new URLSearchParams({
action: "query",
titles: title,
prop: "extracts|info",
exintro: "1", // intro section only
explaintext: "1", // plain text, no HTML
exchars: String(maxChars),
inprop: "url",
format: "json",
origin: "*",
});
const response = await fetch(`${WIKIPEDIA_API}?${params}`, {
headers: { "User-Agent": USER_AGENT },
});
if (!response.ok) {
throw new Error(`Wikipedia extract failed: ${response.status} ${response.statusText}`);
}
const data = await response.json();
const pages = data?.query?.pages ?? {};
const pageId = Object.keys(pages)[0];
if (!pageId || pageId === "-1") {
return null; // page not found
}
const page = pages[pageId];
if (!page.extract || page.extract.trim().length < 50) {
return null; // stub or disambiguation page
}
return {
pageId: Number(pageId),
title: page.title,
url: page.fullurl || `https://en.wikipedia.org/wiki/${encodeURIComponent(page.title.replace(/ /g, "_"))}`,
extract: page.extract.trim(),
};
}
/**
* Search for a topic and return extracts for the top matching pages.
* This is the main entry point — combines search + extract in one call.
*
* Returns up to `maxResults` extracts with substantive content.
*/
export async function fetchWikipediaSources(
topic: string,
maxResults: number = 3,
): Promise<WikiExtract[]> {
const searchResults = await searchWikipedia(topic, maxResults + 2); // fetch a few extra in case some are stubs
const extracts: WikiExtract[] = [];
for (const result of searchResults) {
if (extracts.length >= maxResults) break;
const extract = await getWikipediaExtract(result.title);
if (extract) {
extracts.push(extract);
}
}
return extracts;
}
/**
* Verify that a Wikipedia URL is still live (HEAD request).
*/
export async function verifyWikipediaUrl(url: string): Promise<boolean> {
try {
const response = await fetch(url, {
method: "HEAD",
headers: { "User-Agent": USER_AGENT },
});
return response.ok;
} catch {
return false;
}
}
/**
* Strip HTML tags from a string (used for search snippets).
*/
function stripHtml(html: string): string {
return html
.replace(/<[^>]+>/g, "")
.replace(/&quot;/g, '"')
.replace(/&amp;/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&#039;/g, "'")
.replace(/&nbsp;/g, " ");
}