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
+23 -189

No files matched your search

+1 -1
View File
@@ -512,7 +512,7 @@ Node ids are the library's, so one batch of ops can work anywhere in it.
| `GET /api/l/<id>/nodes/<node>/tree[/<branch>]` | one node and everything under it, with their conflicts | | `GET /api/l/<id>/nodes/<node>/tree[/<branch>]` | one node and everything under it, with their conflicts |
| `GET /api/l/<id>/nodes/<node>/export[/<branch>]` | the same in the text format; header `x-skipped` counts what was left out | | `GET /api/l/<id>/nodes/<node>/export[/<branch>]` | the same in the text format; header `x-skipped` counts what was left out |
| `POST /api/l/<id>/nodes/<node>/import?name=file.md` | body: the file (2 MB at most), read in as the node's last child on main; 422 with `problems` if it does not parse | | `POST /api/l/<id>/nodes/<node>/import?name=file.md` | body: the file (2 MB at most), read in as the node's last child on main; 422 with `problems` if it does not parse |
| `GET /api/wiki/…` | Wikipedia through the server's cache: `summary`, `article` (`&full=1` for every section), `section`, `senses`, `suggest`, `search`, `lookup` (server/wikiRoutes.ts) | | `GET /api/wiki/…` | Wikipedia through the server's cache: `summary`, `article` (`&full=1` for every section), `senses`, `suggest` (server/wikiRoutes.ts) |
| `POST /api/l/<id>/links/scan` `{ node, review? }` | scan a node and record what is found as pending; with `review`, the model reviewer judges what is new, and the approved links are handed back to be made | | `POST /api/l/<id>/links/scan` `{ node, review? }` | scan a node and record what is found as pending; with `review`, the model reviewer judges what is new, and the approved links are handed back to be made |
| `GET /api/l/<id>/links/pending?node=<node>&subtree=1&tier=auto\|suggest&all=1&claim=1` | pending suggestions with the context a reviewer needs; `all` with every determination; `claim` hands out the approved links no page has made | | `GET /api/l/<id>/links/pending?node=<node>&subtree=1&tier=auto\|suggest&all=1&claim=1` | pending suggestions with the context a reviewer needs; `all` with every determination; `claim` hands out the approved links no page has made |
| `POST /api/l/<id>/links/accept` / `reject` `{ ids, author? }` | link them in one commit, or record them as declined | | `POST /api/l/<id>/links/accept` / `reject` `{ ids, author? }` | link them in one commit, or record them as declined |
+6 -7
View File
@@ -73,7 +73,6 @@ user, so neither is used.
| Batch title check | `GET /w/api.php?action=query&format=json&formatversion=2&redirects=1&prop=pageprops\|description&ppprop=disambiguation&titles=A\|B\|…` | "limited to 50 titles per query, or 500 for those with the `apihighlimits` right" ([API:Query](https://www.mediawiki.org/wiki/API:Query)). The answer has `normalized`, `redirects` (with `tofragment`), and `pages` with `missing`/`invalid`. A disambiguation page carries `pageprops.disambiguation`. The short description is in `description`. Pages are not returned in request order, so inputs are mapped back through normalized → redirects. | | Batch title check | `GET /w/api.php?action=query&format=json&formatversion=2&redirects=1&prop=pageprops\|description&ppprop=disambiguation&titles=A\|B\|…` | "limited to 50 titles per query, or 500 for those with the `apihighlimits` right" ([API:Query](https://www.mediawiki.org/wiki/API:Query)). The answer has `normalized`, `redirects` (with `tofragment`), and `pages` with `missing`/`invalid`. A disambiguation page carries `pageprops.disambiguation`. The short description is in `description`. Pages are not returned in request order, so inputs are mapped back through normalized → redirects. |
| Senses of a disambiguation page | same, with `generator=links&gplnamespace=0&gpllimit=max` on the one title | One request gives every linked article with its description. "Set" returned 73. | | Senses of a disambiguation page | same, with `generator=links&gplnamespace=0&gpllimit=max` on the one title | One request gives every linked article with its description. "Set" returned 73. |
| Title autocomplete | `GET /w/rest.php/v1/search/title?q=…&limit=…` | Documented for this: "a typeahead search that automatically suggests relevant pages by title" ([REST reference](https://www.mediawiki.org/wiki/API:REST_API/Reference)). Returns title, description and thumbnail, limit 1–100. `action=opensearch` returns empty descriptions on Wikimedia wikis ([API:Opensearch](https://www.mediawiki.org/wiki/API:Opensearch)). `list=prefixsearch` gives titles only. The completion index is "updated once a day" ([Help:CirrusSearch](https://www.mediawiki.org/wiki/Help:CirrusSearch)). | | Title autocomplete | `GET /w/rest.php/v1/search/title?q=…&limit=…` | Documented for this: "a typeahead search that automatically suggests relevant pages by title" ([REST reference](https://www.mediawiki.org/wiki/API:REST_API/Reference)). Returns title, description and thumbnail, limit 1–100. `action=opensearch` returns empty descriptions on Wikimedia wikis ([API:Opensearch](https://www.mediawiki.org/wiki/API:Opensearch)). `list=prefixsearch` gives titles only. The completion index is "updated once a day" ([Help:CirrusSearch](https://www.mediawiki.org/wiki/Help:CirrusSearch)). |
| Full-text search | `GET /w/rest.php/v1/search/page?q=…&limit=…` | Excerpt with `<span class="searchmatch">`, plus description and thumbnail, in one call. `q` takes CirrusSearch syntax: `morelike:Title` (pipe for several), `intitle:`, quotes. There is no parameter for passing context, and no text can be sent other than the query. `list=search` is equivalent (`srlimit` ≤ 500). |
| Preview | `GET /api/rest_v1/page/summary/{title}?redirect=true` | Extract, description, thumbnail, `revision`, `type: "disambiguation"`. Edge-cached (`s-maxage=1209600`), so it is cheap for Wikimedia. rest_v1 is RESTBase, which is being retired: there is no date for `page/summary` ([RESTBase/deprecation](https://www.mediawiki.org/wiki/RESTBase/deprecation)). The client falls back to `prop=extracts\|pageimages\|description\|info` if it disappears. | | Preview | `GET /api/rest_v1/page/summary/{title}?redirect=true` | Extract, description, thumbnail, `revision`, `type: "disambiguation"`. Edge-cached (`s-maxage=1209600`), so it is cheap for Wikimedia. rest_v1 is RESTBase, which is being retired: there is no date for `page/summary` ([RESTBase/deprecation](https://www.mediawiki.org/wiki/RESTBase/deprecation)). The client falls back to `prop=extracts\|pageimages\|description\|info` if it disappears. |
| Article by section | `GET /w/api.php?action=parse&page=…&redirects=1&prop=text\|tocdata\|revid\|displaytitle\|properties&disableeditsection=1&disablelimitreport=1&disabletoc=1` | One request for the whole page (Octopus: 480 KB raw, 69 KB after sanitising), split on the server at `div.mw-heading` boundaries and cached for 7 days. A section then costs nothing. `prop=sections` now warns "deprecated … use prop=tocdata". With `section=N`, both come back empty, so the section list cannot be had alongside one section's text. REST `/page/{title}/html` (Parsoid, with `<section>` wrappers) also works; the splitter flattens either. | | Article by section | `GET /w/api.php?action=parse&page=…&redirects=1&prop=text\|tocdata\|revid\|displaytitle\|properties&disableeditsection=1&disablelimitreport=1&disabletoc=1` | One request for the whole page (Octopus: 480 KB raw, 69 KB after sanitising), split on the server at `div.mw-heading` boundaries and cached for 7 days. A section then costs nothing. `prop=sections` now warns "deprecated … use prop=tocdata". With `section=N`, both come back empty, so the section list cannot be had alongside one section's text. REST `/page/{title}/html` (Parsoid, with `<section>` wrappers) also works; the splitter flattens either. |
@@ -108,7 +107,7 @@ When text is shown in the app it must carry:
- **Licence notice**: name the licence and link to it - **Licence notice**: name the licence and link to it
(https://creativecommons.org/licenses/by-sa/4.0/). (https://creativecommons.org/licenses/by-sa/4.0/).
- **Modifications**: one "must indicate in a reasonable fashion that the original work has been - **Modifications**: one "must indicate in a reasonable fashion that the original work has been
modified". We remove references, boxes and images, so `article()` and `section()` return modified". We remove references, boxes and images, so `article()` returns
`attribution.modified` and an `attribution.text` that says so. `attribution.modified` and an `attribution.text` that says so.
- **Share-alike** applies to modified article text that is redistributed. If a node quotes or adapts - **Share-alike** applies to modified article text that is redistributed. If a node quotes or adapts
article text and that text is exported or shared, that part is CC BY-SA. Linking to an article text and that text is exported or shared, that part is CC BY-SA. Linking to an
@@ -215,15 +214,15 @@ considered and set aside:
## 7. Caches ## 7. Caches
`<EX_DATA>/wiki-cache/<lang>/titles.json` (found 30 d, missing 3 d), `small.json` (summaries 14 d, `<EX_DATA>/wiki-cache/<lang>/titles.json` (found 30 d, missing 3 d), `small.json` (summaries 14 d,
senses 14 d, suggest and search 1 d), `articles/` (7 d). Vectors, per library: `<EX_DATA>/libraries/<id>/vectors/<name>.json` senses 14 d, suggest 1 d), `articles/` (7 d). Vectors, per library: `<EX_DATA>/libraries/<id>/vectors/<name>.json`
and `.f32`. An expired entry is still served, marked `stale`, when the network is down. The and `.f32`. An expired entry is still served, marked `stale`, when the network is down. The
variables that configure all this are in the README. variables that configure all this are in the README.
Notes on articles (src/core/article.ts) rely on this cache and add nothing to it: an article is Notes on articles (src/core/article.ts) rely on this cache and add nothing to it: an article is
re-read through `article?full=1`, whose answer always carries `revisionId` (and `pageId`), as re-read through `article?full=1`, whose answer always carries `revisionId` and `pageId` (a
every `section` answer does (a `summary` may not). A note records the revision it was made `summary` may not). A note records the revision it was made against; when the cached copy expires
against; when the cached copy expires (7 d) and Wikipedia has a newer revision, the note is found (7 d) and Wikipedia has a newer revision, the note is found again in it, or shown as detached with
again in it, or shown as detached with a link to the old revision. The browser keeps articles in a link to the old revision. The browser keeps articles in
memory for the page's life only, never in IndexedDB. memory for the page's life only, never in IndexedDB.
## 8. Link discovery as built ## 8. Link discovery as built
+4 -68
View File
@@ -6,12 +6,11 @@
* short description, missing. 50 titles per request (the API's limit). * short description, missing. 50 titles per request (the API's limit).
* senses(title) the articles a disambiguation page lists, with their descriptions. * senses(title) the articles a disambiguation page lists, with their descriptions.
* suggest(prefix) title autocomplete (REST search/title). * 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). * summary(title) extract, description, thumbnail, canonical URL, revision (REST page/summary).
* { cacheOnly: true } answers from the cache alone, never the network. * { 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 * article(title) lead plus the section list. The whole page is fetched once (action=parse),
* is fetched once (action=parse), split at its headings, sanitised (images * split at its headings, sanitised (images dropped), cached.
* dropped), cached. { sections: true } returns every section's html too. * { sections: true } returns every section's html too.
* *
* Every request goes through one serial queue with a minimum spacing, priority for interactive * 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 * 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 { existsSync, readFileSync } from "node:fs";
import { join } from "node:path"; import { join } from "node:path";
import { dataDir, writeAtomic as write } from "./util"; import { dataDir, writeAtomic as write } from "./util";
import { snippet, splitArticle } from "./wikiHtml"; import { splitArticle } from "./wikiHtml";
// ---- results ---- // ---- results ----
@@ -101,17 +100,6 @@ export interface TitleSuggestion {
thumbnail: string | null; thumbnail: string | null;
url: string; 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 { export interface Attribution {
title: string; title: string;
url: string; url: string;
@@ -162,12 +150,6 @@ export interface Article {
export interface FullArticle extends Article { export interface FullArticle extends Article {
sections: (SectionInfo & { html: string })[]; sections: (SectionInfo & { html: string })[];
} }
export interface Section extends SectionInfo {
title: string;
revisionId: number;
html: string;
attribution: Attribution;
}
// ---- configuration ---- // ---- configuration ----
@@ -182,7 +164,6 @@ const TTL = {
summary: 14 * DAY, summary: 14 * DAY,
article: 7 * DAY, article: 7 * DAY,
suggest: 1 * DAY, suggest: 1 * DAY,
search: 1 * DAY,
}; };
/** Spacing with a recognised contact in the User-Agent: 1 request/s, well under 200/min. */ /** Spacing with a recognised contact in the User-Agent: 1 request/s, well under 200/min. */
const SPACING_IDENTIFIED_MS = 1000; 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 -- // -- summary --
/** /**
@@ -911,20 +861,6 @@ export class WikiClient {
return unavailable("bad-response", String(e)); 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."; 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(); 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 { function headingOf(n: Node): El | null {
if (!isEl(n)) return null; if (!isEl(n)) return null;
if (/^h[2-6]$/.test(n.tagName)) return n; if (/^h[2-6]$/.test(n.tagName)) return n;
+1 -20
View File
@@ -224,7 +224,7 @@ const FIXTURES: Record<string, Fixture> = {
], ],
}, },
Eukaryote: { Eukaryote: {
id: 1_200_120, id: 1_200_122,
description: "Domain of life whose cells have nuclei", description: "Domain of life whose cells have nuclei",
lead: [ 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.`, `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) }); 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) { function wait(ms: number, signal?: AbortSignal | null) {
return new Promise<void>((done, fail) => { return new Promise<void>((done, fail) => {
const timer = setTimeout(done, ms); const timer = setTimeout(done, ms);
@@ -777,7 +759,6 @@ export function makeMockWikiFetch(slowMs = SLOW_MS, bulkMs = 0): typeof fetch {
const p = url.searchParams; const p = url.searchParams;
if (url.pathname.startsWith("/api/rest_v1/page/summary/")) return summary(url); 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/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") === "parse") return parse(url);
if (url.pathname === "/w/api.php" && p.get("action") === "query") return query(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); return json({ error: { code: "badrequest", info: `The mock does not answer ${url.pathname}` } }, 400);
+2 -43
View File
@@ -1,12 +1,9 @@
/** /**
* HTTP routes over server/wiki.ts: * 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/suggest?q=Brou&limit=8 (q ≤ 200 chars)
* GET /api/wiki/search?q=fixed+point&limit=10 (q ≤ 300 chars)
* GET /api/wiki/summary?title=Octopus[&cached=1] * GET /api/wiki/summary?title=Octopus[&cached=1]
* GET /api/wiki/article?title=Octopus[&full=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 * 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 * 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 { HttpError, abortOnClose, sendJson as send } from "./util";
import type { CallOpts, Result, Uncached, WikiClient } from "./wiki"; import type { CallOpts, Result, Uncached, WikiClient } from "./wiki";
const MAX_TITLES = 200;
const MAX_TITLE = 255; const MAX_TITLE = 255;
const MAX_BODY = 64 * 1024;
const bad = (message: string) => new HttpError(400, message); 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; 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. */ /** Route /api/wiki/*. Returns false for any other path. */
export function wikiRoutes(client: () => WikiClient) { export function wikiRoutes(client: () => WikiClient) {
return async function handle(req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> { return async function handle(req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
if (!url.pathname.startsWith("/api/wiki/")) return false; if (!url.pathname.startsWith("/api/wiki/")) return false;
const route = url.pathname.slice("/api/wiki/".length); const route = url.pathname.slice("/api/wiki/".length);
const allowed = route === "lookup" ? ["GET", "POST"] : ["GET"]; if ((req.method ?? "GET") !== "GET") {
if (!allowed.includes(req.method ?? "GET")) { send(res, 405, { ok: false, message: "use GET" }, { allow: "GET" });
send(res, 405, { ok: false, message: `use ${allowed.join(" or ")}` }, { allow: allowed.join(", ") });
return true; return true;
} }
try { try {
const w = client(); const w = client();
const o: CallOpts = { priority: url.searchParams.get("bulk") === "1" ? "bulk" : "interactive", signal: abortOnClose(res) }; const o: CallOpts = { priority: url.searchParams.get("bulk") === "1" ? "bulk" : "interactive", signal: abortOnClose(res) };
switch (route) { switch (route) {
case "lookup": {
const results = await w.lookup(await readTitles(req, url), o);
send(res, 200, { ok: true, results });
return true;
}
case "suggest": case "suggest":
reply(res, await w.suggest(text(url, "q", 200), int(url, "limit", 8, 1, 20), o), "suggestions"); reply(res, await w.suggest(text(url, "q", 200), int(url, "limit", 8, 1, 20), o), "suggestions");
return true; 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": { case "summary": {
const title = text(url, "title", MAX_TITLE); 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"); 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": case "article":
reply(res, await w.article(text(url, "title", MAX_TITLE), { ...o, sections: url.searchParams.get("full") === "1" }), "article"); reply(res, await w.article(text(url, "title", MAX_TITLE), { ...o, sections: url.searchParams.get("full") === "1" }), "article");
return true; 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": case "senses":
reply(res, await w.senses(text(url, "title", MAX_TITLE), o), "senses"); reply(res, await w.senses(text(url, "title", MAX_TITLE), o), "senses");
return true; return true;
+4 -11
View File
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { WikiClient, batches, parseRetryAfter, prepareTitle, userAgent, validContact } from "../server/wiki"; import { WikiClient, batches, parseRetryAfter, prepareTitle, userAgent, validContact } from "../server/wiki";
import { sanitizeWikiHtml, snippet, splitArticle } from "../server/wikiHtml"; import { sanitizeWikiHtml, splitArticle } from "../server/wikiHtml";
// A tiny fake Wikipedia: pages, redirects, disambiguation pages. // A tiny fake Wikipedia: pages, redirects, disambiguation pages.
const PAGES: Record<string, { id: number; description?: string; disambiguation?: boolean }> = { const PAGES: Record<string, { id: number; description?: string; disambiguation?: boolean }> = {
@@ -324,13 +324,6 @@ describe("sanitiser", () => {
expect(sanitizeWikiHtml(html, o)).toBe("<p>t</p>"); expect(sanitizeWikiHtml(html, o)).toBe("<p>t</p>");
}); });
it("marks search matches and escapes the rest", () => {
expect(snippet(`a <span class="searchmatch">fixed</span> point &lt;b&gt;`)).toEqual({
text: "a fixed point <b>",
html: "a <mark>fixed</mark> point &lt;b&gt;",
});
});
it("splits an article at its headings into a section tree", () => { it("splits an article at its headings into a section tree", () => {
const page = const page =
`<div class="mw-content-ltr mw-parser-output"><p>Lead.</p>` + `<div class="mw-content-ltr mw-parser-output"><p>Lead.</p>` +
@@ -348,7 +341,7 @@ describe("sanitiser", () => {
}); });
}); });
describe("article and section", () => { describe("article", () => {
const page = const page =
`<div class="mw-parser-output"><p>Lead <a href="/wiki/Octopus">octopus</a>.</p>` + `<div class="mw-parser-output"><p>Lead <a href="/wiki/Octopus">octopus</a>.</p>` +
`<div class="mw-heading mw-heading2"><h2 id="A">A</h2></div><p>Alpha<script>x</script></p>` + `<div class="mw-heading mw-heading2"><h2 id="A">A</h2></div><p>Alpha<script>x</script></p>` +
@@ -379,8 +372,8 @@ describe("article and section", () => {
]); ]);
expect(a.ok && a.value.attribution.text).toContain("CC BY-SA 4.0"); expect(a.ok && a.value.attribution.text).toContain("CC BY-SA 4.0");
expect(a.ok && a.value.attribution.revisionUrl).toBe("https://en.wikipedia.org/w/index.php?title=Thing&oldid=777"); expect(a.ok && a.value.attribution.revisionUrl).toBe("https://en.wikipedia.org/w/index.php?title=Thing&oldid=777");
const s = await w.section("thing", 1); const full = await w.article("thing", { sections: true });
expect(s.ok && s.value.html).toBe("<p>Alpha</p>"); expect(full.ok && full.value.sections[0].html).toBe("<p>Alpha</p>");
expect(calls.length).toBe(1); expect(calls.length).toBe(1);
expect(calls[0].url.searchParams.get("prop")).toBe("text|tocdata|revid|displaytitle|properties"); expect(calls[0].url.searchParams.get("prop")).toBe("text|tocdata|revid|displaytitle|properties");
}); });
+1 -4
View File
@@ -61,7 +61,7 @@ describe("mock Wikipedia", () => {
expect((await w.lookup(["No such page"]))[0]).toMatchObject({ status: "missing" }); expect((await w.lookup(["No such page"]))[0]).toMatchObject({ status: "missing" });
}); });
it("suggests case-insensitively by title or word prefix, and searches with marked excerpts", async () => { it("suggests case-insensitively by title or word prefix", async () => {
const w = client(); const w = client();
const s = await w.suggest("LAMB"); const s = await w.suggest("LAMB");
expect(s.ok && s.value.map((x) => x.title)).toEqual(["Lambda calculus"]); expect(s.ok && s.value.map((x) => x.title)).toEqual(["Lambda calculus"]);
@@ -70,9 +70,6 @@ describe("mock Wikipedia", () => {
const merc = await w.suggest("mercury"); const merc = await w.suggest("mercury");
expect(merc.ok && merc.value[0].title).toBe("Mercury"); expect(merc.ok && merc.value[0].title).toBe("Mercury");
expect(merc.ok && merc.value.map((x) => x.title)).toContain("Freddie Mercury"); expect(merc.ok && merc.value.map((x) => x.title)).toContain("Freddie Mercury");
const q = await w.search("nervous system");
expect(q.ok && q.value.map((x) => x.title)).toEqual(["Octopus", "Cephalopod"]);
expect(q.ok && q.value[0].snippetHtml).toMatch(/<mark>nervous<\/mark> <mark>system<\/mark>/);
}); });
it("misbehaves on purpose for the offline and rate-limited titles, without poisoning later calls", async () => { it("misbehaves on purpose for the offline and rate-limited titles, without poisoning later calls", async () => {
+4 -13
View File
@@ -58,27 +58,18 @@ describe("/api/wiki", () => {
it("validates input", async () => { it("validates input", async () => {
expect((await fetch(`${base}/api/wiki/suggest`)).status).toBe(400); expect((await fetch(`${base}/api/wiki/suggest`)).status).toBe(400);
expect((await fetch(`${base}/api/wiki/suggest?q=a&limit=999`)).status).toBe(400); expect((await fetch(`${base}/api/wiki/suggest?q=a&limit=999`)).status).toBe(400);
expect((await fetch(`${base}/api/wiki/search?q=${"x".repeat(301)}`)).status).toBe(400); expect((await fetch(`${base}/api/wiki/suggest?q=${"x".repeat(201)}`)).status).toBe(400);
const many = Array.from({ length: 201 }, (_, i) => `t${i}`); expect((await fetch(`${base}/api/wiki/summary?title=${"x".repeat(256)}`)).status).toBe(400);
expect((await fetch(`${base}/api/wiki/lookup`, { method: "POST", body: JSON.stringify({ titles: many }) })).status).toBe(400);
expect((await fetch(`${base}/api/wiki/lookup`, { method: "POST", body: "{nope" })).status).toBe(400);
expect((await fetch(`${base}/api/wiki/summary`, { method: "POST" })).status).toBe(405); expect((await fetch(`${base}/api/wiki/summary`, { method: "POST" })).status).toBe(405);
expect((await fetch(`${base}/api/wiki/nothing`)).status).toBe(404); expect((await fetch(`${base}/api/wiki/nothing`)).status).toBe(404);
}); });
it("answers lookups by GET and POST", async () => {
const g = await (await fetch(`${base}/api/wiki/lookup?titles=Foo|Bar`)).json();
expect(g.results.map((r: { status: string }) => r.status)).toEqual(["missing", "missing"]);
const p = await (await fetch(`${base}/api/wiki/lookup`, { method: "POST", body: JSON.stringify({ titles: ["Baz"] }) })).json();
expect(p).toMatchObject({ ok: true, results: [{ input: "Baz", status: "missing" }] });
});
it("serves suggestions, 404 for missing pages, 503 when offline", async () => { it("serves suggestions, 404 for missing pages, 503 when offline", async () => {
const s = await (await fetch(`${base}/api/wiki/suggest?q=Brou`)).json(); const s = await (await fetch(`${base}/api/wiki/suggest?q=Brou`)).json();
expect(s).toMatchObject({ ok: true, suggestions: [{ title: "Brouwer fixed-point theorem" }] }); expect(s).toMatchObject({ ok: true, suggestions: [{ title: "Brouwer fixed-point theorem" }] });
expect((await fetch(`${base}/api/wiki/summary?title=Nothing%20here`)).status).toBe(404); expect((await fetch(`${base}/api/wiki/summary?title=Nothing%20here`)).status).toBe(404);
online = false; online = false;
const r = await fetch(`${base}/api/wiki/search?q=fixed`); const r = await fetch(`${base}/api/wiki/suggest?q=fixed`);
expect(r.status).toBe(503); expect(r.status).toBe(503);
expect(await r.json()).toMatchObject({ ok: false, reason: "offline" }); expect(await r.json()).toMatchObject({ ok: false, reason: "offline" });
online = true; online = true;
@@ -136,7 +127,7 @@ describe("/api/wiki over the mock provider", () => {
}); });
it("answers every route with 503 off when turned off, and leaves other paths alone", async () => { it("answers every route with 503 off when turned off, and leaves other paths alone", async () => {
for (const path of ["/api/wiki/summary?title=Octopus", "/api/wiki/lookup", "/api/wiki/anything"]) { for (const path of ["/api/wiki/summary?title=Octopus", "/api/wiki/suggest?q=Oct", "/api/wiki/anything"]) {
expect(await get(off.base, path)).toEqual({ expect(await get(off.base, path)).toEqual({
status: 503, status: 503,
body: { ok: false, reason: "off", message: "Wikipedia is turned off on this server (EX_WIKI=off)." }, body: { ok: false, reason: "off", message: "Wikipedia is turned off on this server (EX_WIKI=off)." },