${cap}
`); } else if (lc.has("gallerybox")) out.push(fig(li, find(li, (e) => classes(e).has("gallerytext"))?.childNodes ?? [])); } return out.filter(Boolean).join("\n"); } if ([...cls].some((c) => THUMB_CLASSES.has(c))) { // Several pictures side by side (Template:Multiple image): one figure each, the shared caption after them. const singles: El[] = []; const collect = (n: El) => n.childNodes.forEach((c) => isEl(c) && (classes(c).has("tsingle") ? singles.push(c) : collect(c))); collect(el); const capOf = (n: El) => find(n, (e) => classes(e).has("thumbcaption") || e.tagName === "figcaption", (e) => classes(e).has("tsingle")); if (!singles.length) return fig(el, capOf(el)?.childNodes ?? []); const out = singles.map((t) => fig(t, capOf(t)?.childNodes ?? [])); const shared = capOf(el); const cap = shared ? tidy(render(shared.childNodes, captionPolicy(policy))) : ""; if (!emptyHtml(cap)) out.push(`${cap}
`); return out.filter(Boolean).join("\n"); } // Any other picture (inline in a sentence, in a table cell): not kept. A figure may not sit inside a paragraph. return tag === "img" || tag === "picture" ? "" : null; }, }; return policy; } /** A policy that keeps no pictures: for captions. */ const captionPolicy = (p: HtmlPolicy): HtmlPolicy => ({ ...p, image: (_e, t) => (t === "img" || t === "picture" || t === "figure" ? "" : null) }); const squash = (s: string) => s.replace(/\s+/g, " ").trim(); /** An address on upload.wikimedia.org (protocol-relative or http made https), or null. */ function uploadUrl(raw: string | undefined): string | null { const s = raw?.trim(); if (!s) return null; try { const u = new URL(s.startsWith("//") ? `https:${s}` : s); if ((u.protocol !== "https:" && u.protocol !== "http:") || u.hostname !== UPLOAD_HOST || u.username || u.password || u.port) return null; u.protocol = "https:"; return u.href.length <= 2000 ? u.href : null; } catch { return null; } } const px = (v: string | undefined) => (v && /^\d{1,5}$/.test(v.trim()) ? Number(v.trim()) : null); /** * Which rendition of a Wikipedia picture to show, or null for an icon. The largest of src and its * srcset up to 2x (a 250 px thumbnail's 500 px one): never a size the page does not list, which * Wikimedia may not have made, and never the original unless the page shows it at its own size. */ function wikiRendition(img: El): { src: string; width?: number; height?: number } | null { const w = px(attr(img, "width")); const h = px(attr(img, "height")); if ((w !== null && w < ICON_MAX_PX) || (h !== null && h < ICON_MAX_PX)) return null; const cands: { url: string; x: number }[] = []; const src = uploadUrl(attr(img, "src")); if (src) cands.push({ url: src, x: 1 }); for (const c of (attr(img, "srcset") ?? "").split(/,\s+/)) { const [u, d = "1x"] = c.trim().split(/\s+/); const m = /^(\d+(?:\.\d+)?)x$/.exec(d); const url = uploadUrl(u); if (url && m && Number(m[1]) <= 2) cands.push({ url, x: Number(m[1]) }); } const pick = cands.sort((a, b) => b.x - a.x)[0]; if (!pick) return null; return { src: pick.url, ...(w && h ? { width: Math.round(w * pick.x), height: Math.round(h * pick.x) } : {}) }; } /** The File page a picture or video links to, on the article's own wiki: its author and licence are there. */ function filePage(container: El, lang: string): string | null { const page = (href: string | undefined) => { const m = href && /^(?:\/wiki\/|\.\/|https:\/\/[a-z][a-z0-9-]{1,15}\.wikipedia\.org\/wiki\/)([^?#\s"<>:/]+:[^?#\s"<>]+)(?:[?#].*)?$/.exec(href.trim()); return m ? `https://${lang}.wikipedia.org/wiki/${m[1]}` : null; }; const a = find(container, (e) => e.tagName === "a" && (classes(e).has("mw-file-description") || classes(e).has("image"))); const fromLink = a && page(attr(a, "href")); if (fromLink) return fromLink; // A video names its file on itself instead. const v = find(container, (e) => e.tagName === "video"); if (!v) return null; const title = attr(v, "data-mwtitle")?.trim(); return page(attr(v, "resource")) ?? (title && !/[\s#<>[\]|{}?]/.test(title.replace(/ /g, "_")) ? `https://${lang}.wikipedia.org/wiki/File:${encodeURIComponent(title.replace(/ /g, "_"))}` : null); } /** * One picture or video of a Wikipedia article as a figure: the first under `container` (not in its * caption), its caption rendered (links kept, pictures not), its File page as `data-full`. "" when * there is none worth keeping (an icon, an image from elsewhere, no File page, a sound). */ function wikiFigure(container: El, caption: Node[], policy: HtmlPolicy, lang: string, media: string[]): string { const inCaption = (e: El) => caption.includes(e) || e.childNodes.some((c) => caption.includes(c)); const el = find(container, (e) => e.tagName === "img" || e.tagName === "video", inCaption); const file = filePage(container, lang); if (!el || !file) return ""; const iconic = (e: El) => [...classes(e)].some((c) => ICON_CLASSES.has(c)); for (let p: El | null = el; p; p = p === container ? null : (p.parentNode as El | null)) if (iconic(p)) return ""; const cap = tidy(render(caption, captionPolicy(policy))); const keep = (u: string) => (media.includes(u) || media.push(u), WIKI_MEDIA_ROUTE + encodeURIComponent(u)); if (el.tagName === "video") { const v = wikiVideo(el); if (!v) return ""; return videoFacade({ video: v.src, width: v.width, height: v.height, file }, v.poster ? keep(v.poster) : null, emptyHtml(cap) ? "" : cap); } const r = wikiRendition(el); if (!r) return ""; const alt = squash(attr(el, "alt") ?? ""); const attrs: [string, string][] = [["src", keep(r.src)], ["alt", alt]]; if (r.width && r.height) attrs.push(["width", String(r.width)], ["height", String(r.height)]); attrs.push(["loading", "lazy"], ["decoding", "async"], ["data-full", file]); const text = !emptyHtml(cap) ? cap : alt ? escapeText(alt) : ""; return `${inner}
`; } } if (ALLOWED.has(tag)) { const attrs: [string, string][] = []; if (tag === "td" || tag === "th") { for (const k of ["colspan", "rowspan"]) if (/^\d{1,3}$/.test(attr(n, k) ?? "")) attrs.push([k, attr(n, k)!]); } if (tag === "ol" && /^-?\d{1,6}$/.test(attr(n, "start") ?? "")) attrs.push(["start", attr(n, "start")!]); if (VOID.has(tag)) return open(tag, attrs); const inner = render(n.childNodes, p); if (emptyHtml(inner) && tag !== "td" && tag !== "th") return ""; return open(tag, attrs) + inner + `${tag}>`; } // Anything else (span, div, section, cite…): keep the contents, drop the element. return render(n.childNodes, p); } /** Sanitise a fragment of Wikipedia HTML to the allowlist above. Output is safe to inject. */ export function sanitizeWikiHtml(html: string, lang: string): string { return tidy(render(parseFragment(html).childNodes, wikiPolicy(lang))); } export function tidy(html: string) { return html.replace(/\n{3,}/g, "\n\n").trim(); } function headingOf(n: Node): El | null { if (!isEl(n)) return null; if (/^h[2-6]$/.test(n.tagName)) return n; if (n.tagName === "div" && classes(n).has("mw-heading")) { return (n.childNodes.find((c) => isEl(c) && /^h[2-6]$/.test(c.tagName)) as El | undefined) ?? null; } return null; } /** Split a parsed page at its top-level headings and sanitise each part; `media` is every image address the parts show. */ export function splitArticle(html: string, lang: string): { lead: string; sections: (SectionInfo & { html: string })[]; media: string[] } { const frag = parseFragment(html); // The parser wraps everything in