Wiki: drop the unused lookup, search and section routes

Nothing in the page or the link scanner called /api/wiki/lookup,
/api/wiki/search or /api/wiki/section. Remove the routes and what
existed only for them: readTitles and the POST allowance,
WikiClient.search and SearchHit, TTL.search, snippet(), the mock's
search/page answer, WikiClient.section and Section. WikiClient.lookup
stays (the scanner uses it), as do suggest and article.

Tests of the removed code go; input validation and off mode are now
checked on remaining routes. The mock's Eukaryote fixture gets its own
page id instead of sharing Hostile article's. README and
docs/wikipedia.md list what exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Opus 5.5 committed 2026-11-17 18:04:16 -05:00
1 parent 60d26908d6
commit 5c867b2eef
9 files changed
+24 -190

No files matched your search

+4 -68
View File
@@ -6,12 +6,11 @@
* short description, missing. 50 titles per request (the API's limit).
* senses(title) the articles a disambiguation page lists, with their descriptions.
* suggest(prefix) title autocomplete (REST search/title).
* search(query) full-text search with snippets (REST search/page; CirrusSearch syntax).
* summary(title) extract, description, thumbnail, canonical URL, revision (REST page/summary).
* { cacheOnly: true } answers from the cache alone, never the network.
* article(title) lead plus the section list; section(title, id) one section. The whole page
* is fetched once (action=parse), split at its headings, sanitised (images
* dropped), cached. { sections: true } returns every section's html too.
* article(title) lead plus the section list. The whole page is fetched once (action=parse),
* split at its headings, sanitised (images dropped), cached.
* { sections: true } returns every section's html too.
*
* Every request goes through one serial queue with a minimum spacing, priority for interactive
* calls, Retry-After / 429 / 503 / maxlag handling, and a descriptive User-Agent. Results are
@@ -24,7 +23,7 @@ import { createHash } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { dataDir, writeAtomic as write } from "./util";
import { snippet, splitArticle } from "./wikiHtml";
import { splitArticle } from "./wikiHtml";
// ---- results ----
@@ -101,17 +100,6 @@ export interface TitleSuggestion {
thumbnail: string | null;
url: string;
}
export interface SearchHit {
title: string;
pageId: number;
description: string | null;
/** Plain text of the snippet. */
snippet: string;
/** The snippet with matches in <mark>, everything else escaped. */
snippetHtml: string;
thumbnail: string | null;
url: string;
}
export interface Attribution {
title: string;
url: string;
@@ -162,12 +150,6 @@ export interface Article {
export interface FullArticle extends Article {
sections: (SectionInfo & { html: string })[];
}
export interface Section extends SectionInfo {
title: string;
revisionId: number;
html: string;
attribution: Attribution;
}
// ---- configuration ----
@@ -182,7 +164,6 @@ const TTL = {
summary: 14 * DAY,
article: 7 * DAY,
suggest: 1 * DAY,
search: 1 * DAY,
};
/** Spacing with a recognised contact in the User-Agent: 1 request/s, well under 200/min. */
const SPACING_IDENTIFIED_MS = 1000;
@@ -731,37 +712,6 @@ export class WikiClient {
});
}
/**
* Full-text search (CirrusSearch). The query may use its syntax: "quoted phrases",
* intitle:, morelike:Title, -exclusions. Only the query is sent.
*/
async search(query: string, limit = 10, o: CallOpts = {}): Promise<Result<SearchHit[]>> {
const q = query.replace(/\s+/g, " ").trim();
if (!q) return { ok: true, value: [], cached: true };
const n = clamp(limit, 1, 50);
return this.cachedSmall(`search:${n}:${q}`, TTL.search, async () => {
const r = await this.getJson(`${this.site}/w/rest.php/v1/search/page?${new URLSearchParams({ q, limit: String(n) })}`, o);
if (!r.ok) return r;
if (r.status !== 200 || !Array.isArray(r.json?.pages)) return unavailable("bad-response", `search/page answered ${r.status}`);
return {
ok: true,
cached: false,
value: r.json.pages.map((pg: any): SearchHit => {
const s = snippet(String(pg.excerpt ?? ""));
return {
title: String(pg.title),
pageId: Number(pg.id),
description: pg.description ?? null,
snippet: s.text,
snippetHtml: s.html,
thumbnail: absolute(pg.thumbnail?.url),
url: this.articleUrl(String(pg.title)),
};
}),
};
});
}
// -- summary --
/**
@@ -911,20 +861,6 @@ export class WikiClient {
return unavailable("bad-response", String(e));
}
}
/** One section, by the id from article(). */
async section(title: string, id: number, o: CallOpts = {}): Promise<Result<Section>> {
try {
const r = await this.loadArticle(title, o);
if (!r.ok) return r;
const a = r.value;
const s = id === 0 ? { id: 0, level: 1, heading: a.title, anchor: "", number: null, parent: 0, html: a.lead } : a.sections.find((x) => x.id === id);
if (!s) return { ok: false, reason: "missing", message: `“${a.title}” has no section ${id}` };
return { ...r, value: { ...s, title: a.title, revisionId: a.revisionId, attribution: this.attribution(a.title, a.revisionId, MODIFIED) } };
} catch (e) {
return unavailable("bad-response", String(e));
}
}
}
const MODIFIED = "Adapted: references, navigation boxes, infoboxes, edit links and images removed.";
-22
View File
@@ -169,28 +169,6 @@ function tidy(html: string) {
return html.replace(/\n{3,}/g, "\n\n").trim();
}
/** Search excerpts: keep the matches as <mark>, everything else as text. */
export function snippet(excerpt: string): { text: string; html: string } {
let text = "";
let html = "";
const walk = (nodes: Node[], inMatch: boolean) => {
for (const n of nodes) {
if (n.nodeName === "#text") {
const v = (n as T.TextNode).value;
text += v;
html += escapeText(v);
} else if (isEl(n)) {
const m = !inMatch && classes(n).has("searchmatch");
if (m) html += "<mark>";
walk(n.childNodes, inMatch || m);
if (m) html += "</mark>";
}
}
};
walk(parseFragment(excerpt).childNodes, false);
return { text, html };
}
function headingOf(n: Node): El | null {
if (!isEl(n)) return null;
if (/^h[2-6]$/.test(n.tagName)) return n;
+1 -20
View File
@@ -224,7 +224,7 @@ const FIXTURES: Record<string, Fixture> = {
],
},
Eukaryote: {
id: 1_200_120,
id: 1_200_122,
description: "Domain of life whose cells have nuclei",
lead: [
`The <b>eukaryotes</b> are organisms whose cells have a membrane-bound nucleus.[ref] They include all animals, plants, fungi and many single-celled organisms, the protists, and with the [[Bacteria|bacteria]] and the [[Archaea|archaea]] they make up the three domains of life. Eukaryotic cells also contain other membrane-bound compartments, such as [[Mitochondrion|mitochondria]] and the Golgi apparatus, and are typically much larger than those of prokaryotes.`,
@@ -732,24 +732,6 @@ function searchTitle(url: URL): Response {
return json({ pages: pages.slice(0, limit) });
}
/** search/page: every word of the query in the title or text; the excerpt marks the matches. */
function searchPage(url: URL): Response {
const q = (url.searchParams.get("q") ?? "").replace(/\bintitle:/gi, "").replace(/"/g, " ");
const limit = Number(url.searchParams.get("limit") ?? 10) || 10;
const words = q.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
if (!words.length) return json({ pages: [] });
const pages = Object.entries(FIXTURES).flatMap(([title, f]) => {
const text = fullText(f);
const hay = `${title}\n${text}`.toLowerCase();
if (!words.every((w) => hay.includes(w))) return [];
const sentence = text.split(/(?<=\.)\s+/).find((s) => words.some((w) => s.toLowerCase().includes(w))) ?? text.slice(0, 150);
const re = new RegExp(`(${words.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`, "giu");
const excerpt = escape(sentence).replace(re, `<span class="searchmatch">$1</span>`);
return [{ id: f.id, key: dbKey(title), title, excerpt, matched_title: null, anchor: null, description: f.description, thumbnail: null }];
});
return json({ pages: pages.slice(0, limit) });
}
function wait(ms: number, signal?: AbortSignal | null) {
return new Promise<void>((done, fail) => {
const timer = setTimeout(done, ms);
@@ -777,7 +759,6 @@ export function makeMockWikiFetch(slowMs = SLOW_MS, bulkMs = 0): typeof fetch {
const p = url.searchParams;
if (url.pathname.startsWith("/api/rest_v1/page/summary/")) return summary(url);
if (url.pathname === "/w/rest.php/v1/search/title") return searchTitle(url);
if (url.pathname === "/w/rest.php/v1/search/page") return searchPage(url);
if (url.pathname === "/w/api.php" && p.get("action") === "parse") return parse(url);
if (url.pathname === "/w/api.php" && p.get("action") === "query") return query(url);
return json({ error: { code: "badrequest", info: `The mock does not answer ${url.pathname}` } }, 400);
+3 -44
View File
@@ -1,12 +1,9 @@
/**
* HTTP routes over server/wiki.ts:
*
* GET /api/wiki/lookup?titles=A|B|C or POST { titles: string[] } (≤ 200 titles)
* GET /api/wiki/suggest?q=Brou&limit=8 (q ≤ 200 chars)
* GET /api/wiki/search?q=fixed+point&limit=10 (q ≤ 300 chars)
* GET /api/wiki/suggest?q=Brou&limit=8 (q ≤ 200 chars)
* GET /api/wiki/summary?title=Octopus[&cached=1]
* GET /api/wiki/article?title=Octopus[&full=1]
* GET /api/wiki/section?title=Octopus&id=3
* GET /api/wiki/senses?title=Set the articles a disambiguation page lists
*
* summary &cached=1 answers from the server's cache only, never waiting on Wikipedia (for model
@@ -22,9 +19,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";
import { HttpError, abortOnClose, sendJson as send } from "./util";
import type { CallOpts, Result, Uncached, WikiClient } from "./wiki";
const MAX_TITLES = 200;
const MAX_TITLE = 255;
const MAX_BODY = 64 * 1024;
const bad = (message: string) => new HttpError(400, message);
@@ -50,55 +45,22 @@ function int(url: URL, name: string, fallback: number, lo: number, hi: number):
return n;
}
async function readTitles(req: IncomingMessage, url: URL): Promise<string[]> {
let titles: unknown;
if (req.method === "POST") {
let size = 0;
const chunks: Buffer[] = [];
for await (const c of req) {
size += (c as Buffer).length;
if (size > MAX_BODY) throw bad("body too large");
chunks.push(c as Buffer);
}
try {
titles = (JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}") as { titles?: unknown }).titles;
} catch {
throw bad("body is not JSON");
}
} else {
titles = text(url, "titles", MAX_TITLES * (MAX_TITLE + 1)).split("|");
}
if (!Array.isArray(titles) || !titles.every((t) => typeof t === "string")) throw bad("titles must be a list of strings");
if (titles.length > MAX_TITLES) throw bad(`at most ${MAX_TITLES} titles`);
if (titles.some((t) => t.length > MAX_TITLE)) throw bad(`a title is longer than ${MAX_TITLE} characters`);
return titles;
}
/** Route /api/wiki/*. Returns false for any other path. */
export function wikiRoutes(client: () => WikiClient) {
return async function handle(req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
if (!url.pathname.startsWith("/api/wiki/")) return false;
const route = url.pathname.slice("/api/wiki/".length);
const allowed = route === "lookup" ? ["GET", "POST"] : ["GET"];
if (!allowed.includes(req.method ?? "GET")) {
send(res, 405, { ok: false, message: `use ${allowed.join(" or ")}` }, { allow: allowed.join(", ") });
if ((req.method ?? "GET") !== "GET") {
send(res, 405, { ok: false, message: "use GET" }, { allow: "GET" });
return true;
}
try {
const w = client();
const o: CallOpts = { priority: url.searchParams.get("bulk") === "1" ? "bulk" : "interactive", signal: abortOnClose(res) };
switch (route) {
case "lookup": {
const results = await w.lookup(await readTitles(req, url), o);
send(res, 200, { ok: true, results });
return true;
}
case "suggest":
reply(res, await w.suggest(text(url, "q", 200), int(url, "limit", 8, 1, 20), o), "suggestions");
return true;
case "search":
reply(res, await w.search(text(url, "q", 300), int(url, "limit", 10, 1, 50), o), "results");
return true;
case "summary": {
const title = text(url, "title", MAX_TITLE);
reply(res, url.searchParams.get("cached") === "1" ? await w.summary(title, { ...o, cacheOnly: true }) : await w.summary(title, o), "summary");
@@ -107,9 +69,6 @@ export function wikiRoutes(client: () => WikiClient) {
case "article":
reply(res, await w.article(text(url, "title", MAX_TITLE), { ...o, sections: url.searchParams.get("full") === "1" }), "article");
return true;
case "section":
reply(res, await w.section(text(url, "title", MAX_TITLE), int(url, "id", 0, 0, 10_000), o), "section");
return true;
case "senses":
reply(res, await w.senses(text(url, "title", MAX_TITLE), o), "senses");
return true;