import "server-only"; import { and, eq } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { models } from "@/lib/db/schema"; import { checkFileAccess, getRepoInfo, type HubFile, listFiles, type RepoInfo } from "./client"; export type LookupResult = { repoId: string; revision: string; sha: string; gated: RepoInfo["gated"]; lastModified: string | null; files: HubFile[]; /** Set when this repo is already in the library. */ existingModelId: string | null; }; /** * Accept "org/name", or a pasted Hub URL like https://huggingface.co/org/name/tree/main. * Returns the repo id and, if the URL contained one, the revision. */ export function normalizeRepoInput(input: string): { repoId: string; revision?: string } { let s = input.trim(); const url = s.match(/^https?:\/\/(?:www\.)?huggingface\.co\/(.+)$/i); if (url) s = url[1]; s = s.replace(/[?#].*$/, "").replace(/\/+$/, ""); const parts = s.split("/"); const repoId = parts.slice(0, 2).join("/"); const revision = parts[2] === "tree" || parts[2] === "blob" ? parts[3] : undefined; return { repoId, revision }; } /** Repo metadata + file list at the resolved commit, with an early access check for gated repos. */ export async function lookupRepo(repoId: string, revision: string): Promise { const info = await getRepoInfo(repoId, revision); const files = await listFiles(info.repoId, info.sha); if (info.gated && files.length > 0) { const smallest = files.reduce((a, b) => (b.size < a.size ? b : a)); await checkFileAccess(info.repoId, info.sha, smallest.path); } const existing = await db().query.models.findFirst({ columns: { id: true }, where: and(eq(models.repoType, "model"), eq(models.repoId, info.repoId)), }); return { repoId: info.repoId, revision, sha: info.sha, gated: info.gated, lastModified: info.lastModified, files, existingModelId: existing?.id ?? null, }; }