- listFiles() keeps the last trees it fetched by repo@SHA (a commit's files never change; capped at 50,000 files): adding a model right after the lookup no longer downloads the whole tree again. Callers get copies. - addModel() fetches the author's avatar in parallel with the file list. - The Hub check resolves revisions with resolveRevision(): /revision/<rev> with expand=sha, as huggingface_hub's model_info(expand=...) does, instead of the full model info (file list, card data, the Spaces using the model). Falls back to the full request if an answer comes without a SHA. - The Model card tab renders inside <Suspense>: the page no longer waits for the README to arrive from the Hub (up to the 20 s timeout when it's slow). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
291 lines
9.8 KiB
TypeScript
291 lines
9.8 KiB
TypeScript
// Minimal Hugging Face Hub API client (metadata only; downloads go through the `hf` CLI).
|
|
// Server-side only: it reads HF_TOKEN from the environment. Never import from client components.
|
|
|
|
import { coreEnv } from "@/lib/env";
|
|
import { parseRepoMetadata, type RepoMetadata } from "./metadata";
|
|
|
|
const HUB = "https://huggingface.co";
|
|
const TIMEOUT_MS = 20_000;
|
|
const USER_AGENT = "kaname-model-manager";
|
|
|
|
export const REPO_ID_RE = /^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/;
|
|
export const SHA_RE = /^[0-9a-f]{40}$/;
|
|
|
|
export type HubErrorCode =
|
|
| "invalid_repo_id"
|
|
| "invalid_token"
|
|
| "repo_not_found" // or private without access
|
|
| "revision_not_found"
|
|
| "gated_no_token"
|
|
| "gated_no_access"
|
|
| "rate_limited"
|
|
| "network"
|
|
| "unknown";
|
|
|
|
export class HubError extends Error {
|
|
constructor(
|
|
public code: HubErrorCode,
|
|
message: string,
|
|
public status?: number,
|
|
) {
|
|
super(message);
|
|
this.name = "HubError";
|
|
}
|
|
}
|
|
|
|
export type HubFile = {
|
|
path: string;
|
|
size: number;
|
|
/** Git blob SHA-1. */
|
|
blobOid: string;
|
|
/** SHA-256 of the content, for LFS/Xet files. */
|
|
lfsSha256: string | null;
|
|
xetHash: string | null;
|
|
};
|
|
|
|
export type RepoInfo = {
|
|
repoId: string;
|
|
sha: string;
|
|
gated: false | "auto" | "manual";
|
|
private: boolean;
|
|
lastModified: string | null;
|
|
metadata: RepoMetadata;
|
|
};
|
|
|
|
function headers(): HeadersInit {
|
|
const h: Record<string, string> = { "User-Agent": USER_AGENT };
|
|
const token = coreEnv().HF_TOKEN;
|
|
if (token) h.Authorization = `Bearer ${token}`;
|
|
return h;
|
|
}
|
|
|
|
async function hubFetch(url: string, init: RequestInit = {}): Promise<Response> {
|
|
try {
|
|
return await fetch(url, {
|
|
...init,
|
|
headers: { ...headers(), ...init.headers },
|
|
cache: "no-store",
|
|
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
});
|
|
} catch (err) {
|
|
const reason = err instanceof Error ? err.message : String(err);
|
|
throw new HubError("network", `Could not reach huggingface.co (${reason}).`);
|
|
}
|
|
}
|
|
|
|
/** Is the configured token valid? Only called after a 401, to tell a bad token from a missing repo. */
|
|
async function tokenIsValid(): Promise<boolean> {
|
|
const res = await hubFetch(`${HUB}/api/whoami-v2`);
|
|
return res.ok;
|
|
}
|
|
|
|
async function toHubError(res: Response, repoId: string, revision?: string): Promise<HubError> {
|
|
const code = res.headers.get("x-error-code");
|
|
const hasToken = Boolean(coreEnv().HF_TOKEN);
|
|
|
|
if (code === "RevisionNotFound") {
|
|
return new HubError("revision_not_found", `Revision "${revision}" not found in ${repoId}.`, res.status);
|
|
}
|
|
if (code === "GatedRepo") {
|
|
return hasToken
|
|
? new HubError(
|
|
"gated_no_access",
|
|
`${repoId} is gated and this token's account has not been granted access. Request access at ${HUB}/${repoId}.`,
|
|
res.status,
|
|
)
|
|
: new HubError(
|
|
"gated_no_token",
|
|
`${repoId} is gated. Set HF_TOKEN for an account that has accepted the terms at ${HUB}/${repoId}.`,
|
|
res.status,
|
|
);
|
|
}
|
|
if (res.status === 429) {
|
|
return new HubError("rate_limited", "Hugging Face rate limit hit. Try again in a minute.", res.status);
|
|
}
|
|
// The Hub answers 401 (without an error code) for missing repos when unauthenticated,
|
|
// and 401 for any request when the token is invalid.
|
|
if (res.status === 401 || res.status === 404 || code === "RepoNotFound") {
|
|
if (res.status === 401 && hasToken && !(await tokenIsValid())) {
|
|
return new HubError("invalid_token", "HF_TOKEN is invalid or expired.", res.status);
|
|
}
|
|
return new HubError(
|
|
"repo_not_found",
|
|
hasToken
|
|
? `Repository ${repoId} not found, or this token has no access to it.`
|
|
: `Repository ${repoId} not found. If it is private, set HF_TOKEN.`,
|
|
res.status,
|
|
);
|
|
}
|
|
const msg = res.headers.get("x-error-message") ?? res.statusText;
|
|
return new HubError("unknown", `Hugging Face API error ${res.status}: ${msg}`, res.status);
|
|
}
|
|
|
|
function assertRepoId(repoId: string) {
|
|
if (!REPO_ID_RE.test(repoId) || repoId.split("/").some((p) => p === "." || p === "..")) {
|
|
throw new HubError("invalid_repo_id", `"${repoId}" is not a valid repo ID (expected "org/name").`);
|
|
}
|
|
}
|
|
|
|
const enc = (s: string) => encodeURIComponent(s);
|
|
const repoPath = (repoId: string) => repoId.split("/").map(enc).join("/");
|
|
|
|
/** Resolve a branch, tag or commit to its full commit SHA, plus basic repo info. */
|
|
export async function getRepoInfo(repoId: string, revision: string): Promise<RepoInfo> {
|
|
assertRepoId(repoId);
|
|
const res = await hubFetch(`${HUB}/api/models/${repoPath(repoId)}/revision/${enc(revision)}`);
|
|
if (!res.ok) throw await toHubError(res, repoId, revision);
|
|
const j = (await res.json()) as {
|
|
id: string;
|
|
sha: string;
|
|
gated?: false | "auto" | "manual";
|
|
private?: boolean;
|
|
lastModified?: string;
|
|
} & Parameters<typeof parseRepoMetadata>[0];
|
|
return {
|
|
repoId: j.id ?? repoId,
|
|
sha: j.sha,
|
|
gated: j.gated ?? false,
|
|
private: j.private ?? false,
|
|
lastModified: j.lastModified ?? null,
|
|
metadata: parseRepoMetadata(j),
|
|
};
|
|
}
|
|
|
|
type TreeEntry = {
|
|
type: "file" | "directory";
|
|
path: string;
|
|
size: number;
|
|
oid: string;
|
|
lfs?: { oid: string; size: number };
|
|
xetHash?: string;
|
|
};
|
|
|
|
/**
|
|
* The commit a revision points to. Asks the Hub for just the SHA (`expand=sha`, as huggingface_hub's
|
|
* model_info does): the full model info can be large (file list, card data, the Spaces using it).
|
|
* Falls back to the full info if an answer comes without a SHA.
|
|
*/
|
|
export async function resolveRevision(repoId: string, revision: string): Promise<string> {
|
|
assertRepoId(repoId);
|
|
const res = await hubFetch(`${HUB}/api/models/${repoPath(repoId)}/revision/${enc(revision)}?expand=sha`);
|
|
if (res.ok) {
|
|
const j = (await res.json().catch(() => null)) as { sha?: unknown } | null;
|
|
if (typeof j?.sha === "string" && SHA_RE.test(j.sha)) return j.sha;
|
|
} else if (res.status !== 400) {
|
|
throw await toHubError(res, repoId, revision);
|
|
}
|
|
return (await getRepoInfo(repoId, revision)).sha;
|
|
}
|
|
|
|
// A commit's file list never changes, so the last few are kept: adding a model right after looking
|
|
// it up doesn't download its tree again. Capped by the number of files held.
|
|
const treeCache = new Map<string, HubFile[]>();
|
|
const TREE_CACHE_MAX_FILES = 50_000;
|
|
let treeCacheFiles = 0;
|
|
|
|
function rememberTree(key: string, files: HubFile[]) {
|
|
if (files.length > TREE_CACHE_MAX_FILES) return;
|
|
treeCache.set(key, files);
|
|
treeCacheFiles += files.length;
|
|
for (const [k, v] of treeCache) {
|
|
if (treeCacheFiles <= TREE_CACHE_MAX_FILES) break;
|
|
treeCache.delete(k);
|
|
treeCacheFiles -= v.length;
|
|
}
|
|
}
|
|
|
|
/** All files (recursive) at a commit, sorted by path. Follows the Link header for pagination. */
|
|
export async function listFiles(repoId: string, sha: string): Promise<HubFile[]> {
|
|
assertRepoId(repoId);
|
|
const key = `${repoId}@${sha}`;
|
|
const cached = treeCache.get(key);
|
|
if (cached) {
|
|
treeCache.delete(key); // most recently used last
|
|
treeCache.set(key, cached);
|
|
return [...cached];
|
|
}
|
|
const files: HubFile[] = [];
|
|
let url: string | null =
|
|
`${HUB}/api/models/${repoPath(repoId)}/tree/${enc(sha)}?recursive=true&expand=false&limit=1000`;
|
|
while (url) {
|
|
const res = await hubFetch(url);
|
|
if (!res.ok) throw await toHubError(res, repoId, sha);
|
|
for (const e of (await res.json()) as TreeEntry[]) {
|
|
if (e.type !== "file") continue;
|
|
files.push({
|
|
path: e.path,
|
|
size: e.size,
|
|
blobOid: e.oid,
|
|
lfsSha256: e.lfs?.oid ?? null,
|
|
xetHash: e.xetHash ?? null,
|
|
});
|
|
}
|
|
url = nextLink(res.headers.get("link"));
|
|
}
|
|
files.sort((a, b) => a.path.localeCompare(b.path));
|
|
if (SHA_RE.test(sha)) rememberTree(key, files);
|
|
return [...files];
|
|
}
|
|
|
|
function nextLink(link: string | null): string | null {
|
|
if (!link) return null;
|
|
for (const part of link.split(",")) {
|
|
const m = part.match(/<([^>]+)>\s*;\s*rel="?next"?/);
|
|
if (m) return m[1];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** Avatar URL of a Hub org or user, or null. Best effort: errors are swallowed. */
|
|
export async function getAuthorAvatar(name: string): Promise<string | null> {
|
|
for (const path of [`organizations/${enc(name)}/avatar`, `users/${enc(name)}/overview`]) {
|
|
try {
|
|
const res = await hubFetch(`${HUB}/api/${path}`);
|
|
if (!res.ok) continue;
|
|
const j = (await res.json()) as { avatarUrl?: string };
|
|
if (j.avatarUrl?.startsWith("https://")) return j.avatarUrl;
|
|
} catch {
|
|
// ignore, try next
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* For gated repos the file list is public, but downloads need accepted terms.
|
|
* Probe one file with a HEAD request (no body is downloaded) to find out early.
|
|
*/
|
|
export async function checkFileAccess(repoId: string, sha: string, path: string): Promise<void> {
|
|
const url = `${HUB}/${repoPath(repoId)}/resolve/${enc(sha)}/${path.split("/").map(enc).join("/")}`;
|
|
const res = await hubFetch(url, { method: "HEAD", redirect: "manual" });
|
|
if (res.ok || (res.status >= 300 && res.status < 400)) return;
|
|
throw await toHubError(res, repoId, sha);
|
|
}
|
|
|
|
const cardCache = new Map<string, string | null>();
|
|
const CARD_CACHE_MAX = 100;
|
|
const CARD_MAX_BYTES = 512 * 1024;
|
|
|
|
/**
|
|
* The repo's README.md at a commit, without YAML front matter. Null if there is none.
|
|
* Cached in memory: a commit's content never changes.
|
|
*/
|
|
export async function fetchModelCard(repoId: string, sha: string): Promise<string | null> {
|
|
assertRepoId(repoId);
|
|
const key = `${repoId}@${sha}`;
|
|
if (cardCache.has(key)) return cardCache.get(key)!;
|
|
|
|
const res = await hubFetch(`${HUB}/${repoPath(repoId)}/raw/${enc(sha)}/README.md`);
|
|
if (res.status === 404) {
|
|
cardCache.set(key, null);
|
|
return null;
|
|
}
|
|
if (!res.ok) throw await toHubError(res, repoId, sha);
|
|
let text = (await res.text()).slice(0, CARD_MAX_BYTES);
|
|
text = text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "").trim();
|
|
|
|
if (cardCache.size >= CARD_CACHE_MAX) cardCache.delete(cardCache.keys().next().value!);
|
|
cardCache.set(key, text || null);
|
|
return text || null;
|
|
}
|