// Minimal, unauthenticated client for the public Hugging Face Hub API. // The tree endpoint sends CORS headers, so this runs fine from a static Space. const HUB = "https://huggingface.co"; export type RepoType = "model" | "dataset"; export interface TreeEntry { type: "file" | "directory"; path: string; size: number; oid: string; lfs?: { oid: string; size: number }; /** Present when listed with `expand: true`. */ lastCommit?: { id: string; title: string; date: string }; } const prefix = (type: RepoType) => (type === "dataset" ? "datasets/" : ""); const encodePath = (path: string) => path.split("/").map(encodeURIComponent).join("/"); /** List a repo folder, following the API's `Link: rel="next"` pagination. */ export async function listTree( repo: string, opts: { type?: RepoType; revision?: string; path?: string; recursive?: boolean; expand?: boolean } = {}, ): Promise { const { type = "model", revision = "main", path = "", recursive = false, expand = false } = opts; const params = new URLSearchParams(); if (recursive) params.set("recursive", "true"); if (expand) params.set("expand", "true"); // No trailing slash for the repo root: the Hub redirects it without CORS headers. const sub = path ? `/${encodePath(path)}` : ""; const qs = params.size ? `?${params}` : ""; let url: string | null = `${HUB}/api/${type}s/${repo}/tree/${encodeURIComponent(revision)}${sub}${qs}`; const out: TreeEntry[] = []; while (url) { const res: Response = await fetch(url); if (!res.ok) throw new Error(`Hub API ${res.status} for ${repo}/${path}`); out.push(...((await res.json()) as TreeEntry[])); url = res.headers.get("Link")?.match(/<([^>]+)>;\s*rel="next"/)?.[1] ?? null; } return out; } export const hub = { repo: (repo: string, type: RepoType = "model") => `${HUB}/${prefix(type)}${repo}`, blob: (repo: string, path: string, revision = "main", type: RepoType = "model") => `${HUB}/${prefix(type)}${repo}/blob/${revision}/${encodePath(path)}`, resolve: (repo: string, path: string, revision = "main", type: RepoType = "model") => `${HUB}/${prefix(type)}${repo}/resolve/${revision}/${encodePath(path)}`, download: (repo: string, path: string, revision = "main") => `${hub.resolve(repo, path, revision)}?download=true`, };