import { readdir, readFile, stat } from "node:fs/promises"; import path from "node:path"; import { SourceRegistry, type ShardSource, type SourceSpec } from "yt-dlp-transcript-mcp/research"; import { connectedArchives } from "yt-dlp-transcript-common/lib/remoteArchives"; import { fetchOnOrigin, readBounded, type FetchLike } from "yt-dlp-transcript-common/lib/remoteArchives-server"; import { REPO_ROOT, REPORTS_ROOT, SITES_DIR } from "../paths.mjs"; import { readCensus } from "./census.mjs"; import type { SourceOption } from "./types"; import { hidePrivateSites } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; // --------------------------------------------------------------------------- // THE SOURCE PICKER (plans/umtool-redesign.md, "Research, first-class" 1): // which corpus the ask bar reads. // // local the composed public dir on this machine, resolved as the MCP // server's default resolves it: TRANSCRIPT_LOCAL_DIR, else // EXPORT_PUBLIC_DIR, else /export/public // remote a published archive: every CONNECTED archive (settings.json // `remoteArchives`, plus TRANSCRIPT_SITE_URL's — the one resolver, // yt-dlp-transcript-common/lib/remoteArchives.ts), then every // transcripts/sites/*/site.json with a `siteUrl` not already // listed (a private site has none, and is not offered) // hub TRANSCRIPT_HUB_URL, else settings.json `homepageUrl` // // Only an OFFERED handle opens: a request naming any other directory or origin // is refused, so the routes can never be pointed at an arbitrary path. // // The live source for a handle is the MCP's own (SourceRegistry), cached per // handle on globalThis (one copy for every route bundle, as lib/projects.ts // learned in P2a). A local one is reopened when its corpus.json changes -- a // site build recomposes export/public -- and a remote or a hub after // REMOTE_TTL_MS, since the sources cache their channel lists for life. // --------------------------------------------------------------------------- const REMOTE_TTL_MS = 15 * 60_000; export function localDir(): string { const env = process.env.TRANSCRIPT_LOCAL_DIR?.trim() || process.env.EXPORT_PUBLIC_DIR?.trim(); return env ? path.resolve(/* turbopackIgnore: true */ env) : path.join(/* turbopackIgnore: true */ REPO_ROOT, "export", "public"); } function hubUrl(settings: { homepageUrl?: unknown } | null): string | null { const env = process.env.TRANSCRIPT_HUB_URL?.trim(); if (env) return env.replace(/\/+$/, ""); const h = settings?.homepageUrl; return typeof h === "string" && /^https?:\/\//.test(h.trim()) ? h.trim().replace(/\/+$/, "") : null; } async function readJson(file: string): Promise { try { return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")) as T; } catch { return null; } } /** Every corpus the ask bar may read, the default first: the local one, unless it has no build and an archive is offered. */ /** * The sources a PICKER draws (settings.privacy.hidePrivateSites): `list` * without a private site's published archive (isPrivateSite's rule, * `audience: "private"`). The one the page has chosen (`keep`) stays, as * "A private site", so the picker shows what is in use. Only a page that DRAWS * the list calls this — listSources() itself stays the full list, because it * is also openSource's allow-list and every reader's default: a case on a * private site's source must keep reading that source. */ export async function shownSources(list: SourceOption[], keep?: string | null): Promise { if (!hidePrivateSites()) return list; const ids = await readdir(/* turbopackIgnore: true */ SITES_DIR).catch(() => [] as string[]); const hidden = new Set(); for (const id of ids) { if (id.startsWith("_") || id.startsWith(".")) continue; const site = await readJson<{ siteUrl?: unknown; audience?: unknown }>(path.join(/* turbopackIgnore: true */ SITES_DIR, id, "site.json")); if (site?.audience !== "private") continue; const url = typeof site.siteUrl === "string" ? site.siteUrl.trim().replace(/\/+$/, "") : ""; if (url) hidden.add(`remote:${url}`); } if (!hidden.size) return list; return list.flatMap((s) => !hidden.has(s.handle) ? [s] : s.handle === keep ? [{ ...s, label: "A private site", detail: "" }] : [], ); } export async function listSources(): Promise { const dir = localDir(); const corpus = await readJson<{ site?: { title?: string } }>(path.join(/* turbopackIgnore: true */ dir, "corpus.json")); const out: SourceOption[] = [ { handle: `local:${dir}`, kind: "local", label: "Local corpus", detail: corpus?.site?.title ? `this machine · ${corpus.site.title} build` : "this machine", }, ]; const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json"); const settings = await readJson<{ homepageUrl?: unknown; remoteArchives?: unknown }>(settingsFile); const sites: SourceOption[] = []; for (const a of connectedArchives(settings?.remoteArchives)) { sites.push({ handle: `remote:${a.origin}`, kind: "remote", label: a.title, detail: `connected · ${a.origin.replace(/^https?:\/\//, "")}`, }); } const ids = await readdir(/* turbopackIgnore: true */ SITES_DIR).catch(() => [] as string[]); for (const id of ids.sort()) { if (id.startsWith("_") || id.startsWith(".")) continue; const site = await readJson<{ siteUrl?: unknown; siteTitle?: unknown }>(path.join(/* turbopackIgnore: true */ SITES_DIR, id, "site.json")); const url = typeof site?.siteUrl === "string" ? site.siteUrl.trim().replace(/\/+$/, "") : ""; if (!/^https?:\/\//.test(url)) continue; if (sites.some((x) => x.handle === `remote:${url}`)) continue; sites.push({ handle: `remote:${url}`, kind: "remote", label: typeof site?.siteTitle === "string" && site.siteTitle ? site.siteTitle : id, detail: `published · ${url.replace(/^https?:\/\//, "")}`, }); } // NO LOCAL CORPUS (no composed corpus.json on this machine — a fresh // clone) and an archive to read: the archives come first, so the default // source (`sources[0]` everywhere, and openSource with no handle) is the // first archive (demo epic D1 item 2). The local entry stays offered, last. if (!corpus && sites.length > 0) { out[0] = { ...out[0], detail: "this machine · no build" }; out.unshift(...sites); } else out.push(...sites); const hub = hubUrl(settings); if (hub) out.push({ handle: `hub:${hub}`, kind: "hub", label: "Hub", detail: `every listed site · ${hub.replace(/^https?:\/\//, "")}` }); return out; } function specOf(handle: string): SourceSpec { const m = /^(local|remote|hub):(.+)$/s.exec(handle); if (!m) throw new SourceError(`not a source: ${handle}`); if (m[1] === "local") return { kind: "local", dir: m[2] }; if (m[1] === "remote") return { kind: "remote", url: m[2] }; return { kind: "hub", url: m[2] }; } export class SourceError extends Error { constructor( message: string, readonly status = 400, ) { super(message); } } /** Transcripts vs captions per channel, counted by a search that read it whole. */ export type ChannelCensus = { total: number; transcript: number; captions: number; unknown: number; byYear: Record; }; export type Opened = { option: SourceOption; source: ShardSource; /** By channel key; only channels a full scan has counted. */ census: Map; /** The source's build (buildIdentity); null when it cannot be told, and then nothing is persisted. */ identity: string | null; /** A persisted census from another build: not used, and said so. */ censusStale: { identity: string; updatedAt: string } | null; }; const IDENTITY_TIMEOUT_MS = 10_000; /** * Which BUILD a source is, for the persisted census (census.mjs): a published * site's or a hub's corpus.json `generatedAt`; for the local dir that and the * file's mtime and size (a recomposed export/public changes both). Null when * it cannot be told -- then the census is counted but not kept. */ export async function buildIdentity(option: SourceOption, doFetch: FetchLike = fetch as unknown as FetchLike): Promise { if (option.kind === "local") { const file = path.join(/* turbopackIgnore: true */ option.handle.slice("local:".length), "corpus.json"); const st = await stat(/* turbopackIgnore: true */ file).catch(() => null); if (!st) return null; const corpus = await readJson<{ generatedAt?: unknown }>(file); return `${typeof corpus?.generatedAt === "string" ? corpus.generatedAt : "-"}|${st.mtimeMs}|${st.size}`; } const url = option.handle.replace(/^(remote|hub):/, "").replace(/#.*$/, ""); try { // An archive is untrusted input: read on its own origin (no redirect // elsewhere is followed) and never past the document bound. const at = `${url}/corpus.json`; const res = await fetchOnOrigin(doFetch, at, { signal: AbortSignal.timeout(IDENTITY_TIMEOUT_MS) }); if (!res.ok) return null; const j = JSON.parse(await readBounded(res, at)) as { generatedAt?: unknown }; return typeof j.generatedAt === "string" && j.generatedAt ? j.generatedAt : null; } catch { return null; } } type Entry = { opened: Opened; stamp: string; at: number }; const g = globalThis as { __umtoolResearchSources?: Map }; const cache = (g.__umtoolResearchSources ??= new Map()); async function stampOf(option: SourceOption): Promise { if (option.kind !== "local") return ""; const dir = option.handle.slice("local:".length); const st = await stat(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, "corpus.json")).catch(() => null); return st ? `${st.mtimeMs}:${st.size}` : "none"; } /** * The live source for an offered handle (the local one when none is named). * A handle that is not offered is a 400. */ export async function openSource(handle: string | null | undefined): Promise { const options = await listSources(); const want = handle?.trim() || options[0].handle; const option = options.find((o) => o.handle === want); if (!option) throw new SourceError(`not an offered source: ${want} — choose the local corpus, a published site or the hub`); const stamp = await stampOf(option); const hit = cache.get(option.handle); if (hit && hit.stamp === stamp && (option.kind === "local" || Date.now() - hit.at < REMOTE_TTL_MS)) { hit.opened.option = option; return hit.opened; } const registry = new SourceRegistry(specOf(option.handle)); let source: ShardSource; try { source = (await registry.resolve(undefined)).source; } catch (e) { throw new SourceError(`${option.label} cannot be read: ${(e as Error).message}`, 502); } // What a search counted for this source before, when it was this build. const identity = await buildIdentity(option); const census = new Map(); let censusStale: Opened["censusStale"] = null; if (identity) { const kept = await readCensus(REPORTS_ROOT, option.handle, identity); for (const [k, c] of Object.entries(kept.channels ?? {})) census.set(k, c as ChannelCensus); if (kept.stale) censusStale = kept.stale; } const opened: Opened = { option, source, census, identity, censusStale }; cache.set(option.handle, { opened, stamp, at: Date.now() }); return opened; }