import { digest } from "../normalize.ts"; import { type Adapter, type Candidate, matchesVersion, type Request, type Section, } from "../types.ts"; import { createNetwork, type NetworkOptions, ProviderError, parseJson, record, string, } from "./network.ts"; type Options = NetworkOptions & { apiKey?: string | (() => string | undefined); }; const libraryId = /^\/[a-z0-9_.-]+\/[a-z0-9_.-]+$/i; function origin(value: unknown): string | null { try { const url = new URL(string(value)); if ( url.protocol !== "https:" || url.username || url.password || url.hostname === "localhost" || !url.hostname.includes(".") || /^[\d.]+$/.test(url.hostname) || url.hostname.includes(":") ) return null; url.search = ""; return url.href; } catch { return null; } } function servedVersion( data: Record, requested: string | undefined, urls: string[], ): string | null { if (!requested) return null; const envelope = record(data["version"]); if (Object.keys(envelope).length) { const served = string(envelope["served"]); if (envelope["status"] === "verified" && matchesVersion(requested, served)) return served; throw new ProviderError("version"); } // A requested ID is not evidence: Context7 can silently serve its current docs. const versions = urls.map((url) => { const parsed = new URL(url); const parts = parsed.pathname.split("/"); const version = parsed.hostname === "github.com" && (parts[3] === "blob" || parts[3] === "tree") ? parts[4] : null; return version && /^v?\d+(?:\.\d+)*(?:[-+][\w.-]+)?$/.test(version) && matchesVersion(requested, version) ? version : null; }); if ( versions.length && versions.every((version) => version !== null) && new Set(versions).size === 1 ) return versions[0] ?? null; throw new ProviderError("version"); } function content(data: Record): { sections: Section[]; urls: string[]; } { const output: { heading: string; body: string; url: string; rank: number }[] = []; for (const item of Array.isArray(data["codeSnippets"]) ? data["codeSnippets"].slice(0, 100) : []) { const snippet = record(item); const url = origin(snippet["codeId"]); if (!url) continue; const examples = ( Array.isArray(snippet["codeList"]) ? snippet["codeList"].slice(0, 20) : [] ).map((item) => { const example = record(item); const code = string(example["code"]); let fenceLength = 3; for (const match of code.matchAll(/`+/g)) fenceLength = Math.max(fenceLength, match[0].length + 1); const fence = "`".repeat(fenceLength); const language = string(example["language"]).replace( /[^a-z0-9_+-]/gi, "", ); return `${fence}${language}\n${code}\n${fence}`; }); output.push({ heading: string(snippet["codeTitle"]) || "Documentation", body: [string(snippet["codeDescription"]), ...examples].join("\n\n"), url, rank: typeof snippet["rank"] === "number" ? snippet["rank"] : output.length, }); } for (const item of Array.isArray(data["infoSnippets"]) ? data["infoSnippets"].slice(0, 100) : []) { const snippet = record(item); const url = origin(snippet["pageId"]); if (!url || !string(snippet["content"])) continue; output.push({ heading: string(snippet["breadcrumb"]) || "Documentation", body: string(snippet["content"]), url, rank: typeof snippet["rank"] === "number" ? snippet["rank"] : output.length, }); } output.sort((a, b) => a.rank - b.rank); if (!output.length) throw new ProviderError("invalid"); return { sections: output.map((item, index) => ({ locator: String(index), heading: item["heading"], body: `${item["body"]}\n\nSource: ${item["url"]}`, })), urls: output.map((item) => item["url"]), }; } export function context7Adapter(options: Options = {}): Adapter { const network = createNetwork("https://context7.com", options); const apiKey = () => { try { return typeof options.apiKey === "function" ? options.apiKey() : options.apiKey; } catch { throw new ProviderError("auth"); } }; async function load(c: Candidate, r: Request, validator?: string | null) { if (!libraryId.test(c.id) || c.scope !== "query:" + digest(r.query)) throw new ProviderError("invalid"); const url = new URL("https://context7.com/api/v2/context"); url.searchParams.set( "libraryId", c.id + (r.version ? "/" + r.version : ""), ); url.searchParams.set("query", r.query); url.searchParams.set("type", "json"); const secret = apiKey(); const response = await network(url.href, { maxBytes: 2 * 1024 * 1024, apiKey: secret, signal: r.signal, validator, }); if (response.unchanged) return "unchanged" as const; const data = record(parseJson(response.text, secret)); const converted = content(data); const version = servedVersion(data, r.version, converted.urls); return { candidate: { ...c, version }, sections: converted.sections, attribution: "Context7; original snippet sources cited in each section.", validator: response.validator, }; } return { id: "context7", rank: 4, formatVersion: 1, coverage: "query", async discover(r) { if ( r.target.length > 500 || !r.query || r.query.length > 500 || (r.version && !/^v?[a-z0-9_.+-]{1,100}$/i.test(r.version)) ) throw new ProviderError("invalid"); const url = new URL("https://context7.com/api/v2/libs/search"); url.searchParams.set("libraryName", r.target); url.searchParams.set("query", r.query); const secret = apiKey(); const data = record( parseJson( ( await network(url.href, { maxBytes: 2 * 1024 * 1024, apiKey: secret, signal: r.signal, }) ).text, secret, ), ); if (!Array.isArray(data["results"])) throw new ProviderError("invalid"); let results = data["results"] .map(record) .filter((item) => libraryId.test(string(item["id"]))); const exact = results.filter( (item) => string(item["id"]).toLowerCase() === r.target.toLowerCase() || string(item["title"]).toLowerCase() === r.target.toLowerCase(), ); if (exact.length) results = exact; const candidates: Candidate[] = []; for (const item of results.slice(0, 20)) { const c: Candidate = { id: string(item["id"]), target: r.target, version: null, origin: "https://context7.com" + string(item["id"]), title: string(item["title"]), source: "context7", scope: "query:" + digest(r.query), evidence: null, }; if (r.version) { try { const document = await load(c, r); if (document === "unchanged") throw new ProviderError("invalid"); c.version = document.candidate.version; c.evidence = "Context7 served version or version-pinned snippet origins"; } catch (error) { if (error instanceof ProviderError && error.code === "version") continue; throw error; } } candidates.push(c); } return candidates; }, async retrieve(c, r, validator) { const document = await load(c, r, validator); if (document !== "unchanged" && c.version !== document.candidate.version) throw new ProviderError("version"); return document; }, }; }