opensi·si

Ƭ AccessToken: string

API Reference

Classes

  • HubApiError
  • InvalidApiResponseFormatError
  • JsonStreamParseError
  • SafetensorParseError
  • __internal_XetBlob

Interfaces

  • AuthInfo
  • CachedFileInfo
  • CachedRepoInfo
  • CachedRevisionInfo
  • CommitCopyFile
  • CommitData
  • CommitDeletedEntry
  • CommitEditFile
  • CommitEditFileParams
  • CommitFile
  • CommitInfo
  • CommitOutput
  • CopyDestination
  • CopyFilesEntry
  • CopyProgressEvent
  • CopySource
  • Credentials
  • DatasetEntry
  • FileDownloadInfoOutput
  • HFCacheInfo
  • JobVolume
  • LfsPathInfo
  • ListFileEntry
  • MlxQuantizationConfig
  • ModelConfig
  • ModelDerivedFields
  • ModelEntry
  • OAuthResult
  • ParallelDownloadOptions
  • PathInfo
  • QuantizationConfig
  • RangeEditCacheEntry
  • RepoId
  • SafetensorsIndexJson
  • SafetensorsShardFileInfo
  • SecurityFileStatus
  • SpaceEntry
  • SpaceResourceConfig
  • SpaceResourceRequirement
  • SpaceRuntime
  • TensorInfo
  • UserInfo
  • WhoAmIApp
  • WhoAmIOrg
  • WhoAmIUser
  • XetFileInfo
  • XetReadToken

Type Aliases

AccessToken

Ƭ AccessToken: string

Actually hf_${string}, but for convenience, using the string type

Defined in[[accesstoken.defined-in]]

packages/hub/src/types/public.ts:28


AccessTokenRole

Ƭ AccessTokenRole: "admin" | "write" | "contributor" | "read"

Defined in[[accesstokenrole.defined-in]]

packages/hub/src/types/public.ts:98


AuthType

Ƭ AuthType: "access_token" | "app_token" | "app_token_as_user"

Defined in[[authtype.defined-in]]

packages/hub/src/types/public.ts:100


CommitOperation

Ƭ CommitOperation: CommitDeletedEntry | CommitFile | CommitEditFile | CommitCopyFile

Defined in[[commitoperation.defined-in]]

packages/hub/src/lib/commit.ts:123


CommitParams

Ƭ CommitParams: { abortSignal?: AbortSignal ; branch?: string ; description?: string ; fetch?: typeof __type ; hubUrl?: string ; isPullRequest?: boolean ; maxFolderDepth?: number ; operations: CommitOperation[] ; parentCommit?: string ; rangeEditCache?: RangeEditCache ; repo: RepoDesignation ; title: string ; useWebWorkers?: boolean | { minSize?: number ; poolSize?: number } ; useXet?: boolean } & Partial<CredentialsParams>

Defined in[[commitparams.defined-in]]

packages/hub/src/lib/commit.ts:130


CommitProgressEvent

Ƭ CommitProgressEvent: { event: "phase" ; phase: "preuploading" | "uploadingLargeFiles" | "committing" } | { event: "fileProgress" ; path: string ; progress: number ; state: "hashing" | "uploading" | "error" }

Defined in[[commitprogressevent.defined-in]]

packages/hub/src/lib/commit.ts:200


ContentSource

Ƭ ContentSource: Blob | URL

Defined in[[contentsource.defined-in]]

packages/hub/src/lib/commit.ts:44


Dtype

Ƭ Dtype: "F64" | "F32" | "C64" | "F16" | "F8_E4M3" | "F8_E4M3FNUZ" | "F8_E5M2" | "F8_E5M2FNUZ" | "F8_E8M0" | "E8M0" | "F6_E3M2" | "F6_E2M3" | "F4" | "FP4" | "BF16" | "I64" | "U64" | "I32" | "U32" | "I16" | "I8" | "U16" | "U8" | "UE8" | "BOOL"

Defined in[[dtype.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:291


JsonStreamEvent

Ƭ JsonStreamEvent: { type: "startObject" } | { type: "endObject" } | { type: "startArray" } | { type: "endArray" } | { key: string ; type: "key" } | { type: "value" ; value: string | number | boolean | null }

Minimal, dependency-free, incremental (SAX-style) JSON parser.

JSON.parse requires the whole document in memory twice (the source string + the resulting object tree), which makes it unusable for documents that are large but whose interesting content is tiny — e.g. a model.safetensors.index.json of a big MoE, where the 60 MB weight_map only exists to tell us the ~100 distinct shard filenames.

This parser instead emits a flat event stream as bytes arrive, so the consumer can keep only what it cares about and let everything else be garbage collected. Memory usage is bounded by the size of the largest individual token (string / number), not by the size of the document.

The implementation is a resumable state machine: any token may be split across chunk boundaries (including multi-byte UTF-8 sequences and \uXXXX escapes).

Strictness: the accepted grammar is RFC 8259 (same as JSON.parse), minus a few checks that would cost a lot for little benefit here — notably number shapes are validated by Number() rather than by the state machine, so a handful of inputs JSON.parse rejects are accepted. Everything JSON.parse accepts is accepted, with identical values.

Example

for await (const event of streamJson(blob.stream())) {
  if (event.type === "key") { ... }
}

Defined in[[jsonstreamevent.defined-in]]

packages/hub/src/utils/streamJson.ts:27


ModelAdditionalField

Ƭ ModelAdditionalField: Exclude\ | keyof ModelDerivedFields

Defined in[[modeladditionalfield.defined-in]]

packages/hub/src/lib/list-models.ts:50


PipelineType

Ƭ PipelineType: keyof typeof PIPELINE_DATA

Defined in[[pipelinetype.defined-in]]

packages/tasks/dist/commonjs/pipelines.d.ts:380


RangeEditCache

Ƭ RangeEditCache: Map<string, RangeEditCacheEntry>

In-memory state of a file previously written through the range-edit path, keyed by its xet hash. Lets a subsequent append (or edit of the file's last term) skip the reconstruction and file-chunk-hashes API calls entirely: the partial merkle state and verification hashes are already known.

Pass the same RangeEditCache instance to successive commit calls that append to the same file to avoid calling the CAS metadata APIs on every append.

Defined in[[rangeeditcache.defined-in]]

packages/hub/src/utils/rangeEdit.ts:16


RepoDesignation

Ƭ RepoDesignation: RepoId | RepoFullName

Defined in[[repodesignation.defined-in]]

packages/hub/src/types/public.ts:17


RepoFullName

Ƭ RepoFullName: string | `spaces/\{string}\` \| \`datasets/{string}` | `buckets/\{string}\` \| \`kernels/{string}`

Defined in[[repofullname.defined-in]]

packages/hub/src/types/public.ts:10


RepoType

Ƭ RepoType: "space" | "dataset" | "model" | "bucket" | "kernel"

Defined in[[repotype.defined-in]]

packages/hub/src/types/public.ts:3


ResolveModelAdditionalFields

Ƭ ResolveModelAdditionalFields<T>: Pick<ApiModelInfo, T & keyof ApiModelInfo> & Pick<ModelDerivedFields, T & keyof ModelDerivedFields>

Type parameters[[resolvemodeladditionalfields.type-parameters]]

Name Type
T extends ModelAdditionalField

Defined in[[resolvemodeladditionalfields.defined-in]]

packages/hub/src/lib/list-models.ts:54


SafetensorsFileHeader

Ƭ SafetensorsFileHeader: Record<TensorName, TensorInfo> & { __metadata__?: { total_parameters?: string | number } & Record<string, string> }

Defined in[[safetensorsfileheader.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:324


SafetensorsParseFromRepo

Ƭ SafetensorsParseFromRepo: { filepaths: string[] ; header: SafetensorsFileHeader ; parameterCount?: Partial<Record<Dtype, number>> ; parameterTotal?: number ; sharded: false } | { filepaths: string[] ; headers: SafetensorsShardedHeaders ; index: SafetensorsIndexJson ; parameterCount?: Partial<Record<Dtype, number>> ; parameterTotal?: number ; sharded: true }

Defined in[[safetensorsparsefromrepo.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:348


SafetensorsShardedHeaders

Ƭ SafetensorsShardedHeaders: Record<FileName, SafetensorsFileHeader>

Defined in[[safetensorsshardedheaders.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:346


SpaceHardwareFlavor

Ƭ SpaceHardwareFlavor: "cpu-basic" | "cpu-upgrade" | "cpu-performance" | "cpu-xl" | "sprx8" | "zero-a10g" | "inf2x6" | "t4-small" | "t4-medium" | "l4x1" | "l4x4" | "l40sx1" | "l40sx4" | "l40sx8" | "a10g-small" | "a10g-large" | "a10g-largex2" | "a10g-largex4" | "a100-large" | "a100x4" | "a100x8" | "h200" | "h200x2" | "h200x4" | "h200x8" | "rtx-pro-6000" | "rtx-pro-6000x2" | "rtx-pro-6000x4" | "rtx-pro-6000x8"

Defined in[[spacehardwareflavor.defined-in]]

packages/hub/src/types/public.ts:53


SpaceSdk

Ƭ SpaceSdk: "streamlit" | "gradio" | "docker" | "static"

Defined in[[spacesdk.defined-in]]

packages/hub/src/types/public.ts:84


SpaceStage

Ƭ SpaceStage: "NO_APP_FILE" | "CONFIG_ERROR" | "BUILDING" | "BUILD_ERROR" | "RUNNING" | "RUNNING_BUILDING" | "RUNTIME_ERROR" | "DELETING" | "PAUSED" | "SLEEPING"

Defined in[[spacestage.defined-in]]

packages/hub/src/types/public.ts:86


TensorName

Ƭ TensorName: string

Defined in[[tensorname.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:290


WhoAmI

Ƭ WhoAmI: WhoAmIApp | WhoAmIOrg | WhoAmIUser

Defined in[[whoami.defined-in]]

packages/hub/src/lib/who-am-i.ts:51

Variables

DATASET_EXPANDABLE_KEYS

• Const DATASET_EXPANDABLE_KEYS: readonly ["author", "cardData", "citation", "createdAt", "disabled", "description", "downloads", "downloadsAllTime", "gated", "gitalyUid", "lastModified", "likes", "paperswithcode_id", "private", "sha", "tags"]

Defined in[[datasetexpandablekeys.defined-in]]

packages/hub/src/lib/list-datasets.ts:17


DATASET_EXPAND_KEYS

• Const DATASET_EXPAND_KEYS: readonly ["private", "downloads", "gated", "likes", "lastModified"]

Defined in[[datasetexpandkeys.defined-in]]

packages/hub/src/lib/list-datasets.ts:9


DEFAULT_REVISION

• Const DEFAULT_REVISION: "main"

Defined in[[defaultrevision.defined-in]]

packages/hub/src/lib/snapshot-download.ts:13


DIFFUSERS_SAFETENSORS_FILE

• Const DIFFUSERS_SAFETENSORS_FILE: "diffusion_pytorch_model.safetensors"

Defined in[[diffuserssafetensorsfile.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:21


DIFFUSERS_SAFETENSORS_INDEX_FILE

• Const DIFFUSERS_SAFETENSORS_INDEX_FILE: "diffusion_pytorch_model.safetensors.index.json"

Defined in[[diffuserssafetensorsindexfile.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:22


DIFFUSERS_WEIGHTS_SUBFOLDERS

• Const DIFFUSERS_WEIGHTS_SUBFOLDERS: readonly ["transformer", "unet"]

Defined in[[diffusersweightssubfolders.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:23


HUB_URL

• Const HUB_URL: ""

Base URL of the Hugging Face Hub.

Defined in[[huburl.defined-in]]

packages/hub/src/consts.ts:4


MODEL_DERIVED_FIELD_TO_API_KEY

• Const MODEL_DERIVED_FIELD_TO_API_KEY: Record\

Defined in[[modelderivedfieldtoapikey.defined-in]]

packages/hub/src/lib/list-models.ts:46


MODEL_EXPANDABLE_KEYS

• Const MODEL_EXPANDABLE_KEYS: readonly ["author", "cardData", "config", "createdAt", "disabled", "downloads", "downloadsAllTime", "gated", "gitalyUid", "inferenceProviderMapping", "lastModified", "library_name", "likes", "model-index", "pipeline_tag", "private", "safetensors", "sha", "spaces", "tags", "transformersInfo"]

Defined in[[modelexpandablekeys.defined-in]]

packages/hub/src/lib/list-models.ts:18


MODEL_EXPAND_KEYS

• Const MODEL_EXPAND_KEYS: readonly ["pipeline_tag", "private", "gated", "downloads", "likes", "lastModified"]

Defined in[[modelexpandkeys.defined-in]]

packages/hub/src/lib/list-models.ts:9


REGEX_COMMIT_HASH

• Const REGEX_COMMIT_HASH: RegExp

Defined in[[regexcommithash.defined-in]]

packages/hub/src/lib/download-file-to-cache-dir.ts:16


REPO_ID_SEPARATOR

• Const REPO_ID_SEPARATOR: string = "--"

Defined in[[repoidseparator.defined-in]]

packages/hub/src/lib/cache-management.ts:25


RE_SAFETENSORS_FILE

• Const RE_SAFETENSORS_FILE: RegExp

Defined in[[resafetensorsfile.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:26


RE_SAFETENSORS_INDEX_FILE

• Const RE_SAFETENSORS_INDEX_FILE: RegExp

Defined in[[resafetensorsindexfile.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:27


RE_SAFETENSORS_SHARD_FILE

• Const RE_SAFETENSORS_SHARD_FILE: RegExp

Defined in[[resafetensorsshardfile.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:28


SAFETENSORS_FILE

• Const SAFETENSORS_FILE: "model.safetensors"

Defined in[[safetensorsfile.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:17


SAFETENSORS_INDEX_FILE

• Const SAFETENSORS_INDEX_FILE: "model.safetensors.index.json"

Defined in[[safetensorsindexfile.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:18


SPACE_EXPANDABLE_KEYS

• Const SPACE_EXPANDABLE_KEYS: readonly ["author", "cardData", "datasets", "disabled", "gitalyUid", "lastModified", "createdAt", "likes", "private", "runtime", "sdk", "sha", "subdomain", "tags", "models"]

Defined in[[spaceexpandablekeys.defined-in]]

packages/hub/src/lib/list-spaces.ts:15


SPACE_EXPAND_KEYS

• Const SPACE_EXPAND_KEYS: readonly ["sdk", "likes", "private", "lastModified"]

Defined in[[spaceexpandkeys.defined-in]]

packages/hub/src/lib/list-spaces.ts:9

Functions

__internal_sha256

▸ __internal_sha256(buffer, opts?): AsyncGenerator<number, string>

Parameters[[internalsha256.parameters]]

Name Type
buffer Blob
opts? Object
opts.abortSignal? AbortSignal
opts.useWebWorker? boolean | { minSize?: number ; poolSize?: number }

Returns[[internalsha256.returns]]

AsyncGenerator<number, string>

hex-encoded sha

Yields

progress (0-1)

Defined in[[internalsha256.defined-in]]

packages/hub/src/utils/sha256.ts:72


assertSafeShardFilename

▸ assertSafeShardFilename(filename): void

weight_map filenames come from a repo file, so they're attacker-controlled: they must stay relative paths inside the index's own directory.

A literal includes("..") check isn't enough, because the URL the filename ends up in is parsed by the WHATWG URL parser after the check, and that parser percent-decodes dot segments: %2e%2e (or .%2e, %2E%2E, …) is a .. segment for it, so it escapes the repo — and with a credential attached, the request lands authorized on another repo's resolve URL.

So decode before validating (repeatedly, to catch %252e%252e), and reject anything that isn't a plain relative path.

Parameters[[assertsafeshardfilename.parameters]]

Name Type
filename string

Returns[[assertsafeshardfilename.returns]]

void

Defined in[[assertsafeshardfilename.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:511


cancelJob

▸ cancelJob(params): Promise<ApiJob>

Cancel a job.

Parameters[[canceljob.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; jobId: string ; namespace: string } & CredentialsParams

Returns[[canceljob.returns]]

Promise<ApiJob>

Defined in[[canceljob.defined-in]]

packages/hub/src/lib/jobs/cancel-job.ts:10


checkRepoAccess

▸ checkRepoAccess(params): Promise<void>

Check if we have read access to a repository.

Throw a HubApiError error if we don't have access. HubApiError.statusCode will be 401, 403 or 404.

Parameters[[checkrepoaccess.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; repo: RepoDesignation } & Partial<CredentialsParams>

Returns[[checkrepoaccess.returns]]

Promise<void>

Defined in[[checkrepoaccess.defined-in]]

packages/hub/src/lib/check-repo-access.ts:13


commit

▸ commit(params): Promise<CommitOutput | undefined>

Parameters[[commit.parameters]]

Name Type
params CommitParams

Returns[[commit.returns]]

Promise<CommitOutput | undefined>

undefined for bucket uploads, CommitOutput otherwise

Defined in[[commit.defined-in]]

packages/hub/src/lib/commit.ts:1031


commitIter

▸ commitIter(params): AsyncGenerator<CommitProgressEvent, CommitOutput | undefined>

Internal function for now, used by commit.

Can be exposed later to offer fine-tuned progress info

CommitOutput is not present for bucket commits

Parameters[[commititer.parameters]]

Name Type
params CommitParams

Returns[[commititer.returns]]

AsyncGenerator<CommitProgressEvent, CommitOutput | undefined>

Defined in[[commititer.defined-in]]

packages/hub/src/lib/commit.ts:219


commitIterBucket

▸ commitIterBucket(params): AsyncGenerator<CommitProgressEvent>

Parameters[[commititerbucket.parameters]]

Name Type
params CommitParams

Returns[[commititerbucket.returns]]

AsyncGenerator<CommitProgressEvent>

Defined in[[commititerbucket.defined-in]]

packages/hub/src/lib/commit.ts:775


computeNumOfParamsByDtypeSingleFile

▸ computeNumOfParamsByDtypeSingleFile(header, quantConfig?, expertDtype?): Partial<Record<Dtype, number>>

Sums parameters per dtype for one file's header, applying the quantization packing factors and skipping bookkeeping tensors.

Parameters[[computenumofparamsbydtypesinglefile.parameters]]

Name Type
header SafetensorsFileHeader
quantConfig? QuantizationConfig
expertDtype? string

Returns[[computenumofparamsbydtypesinglefile.returns]]

Partial<Record<Dtype, number>>

Defined in[[computenumofparamsbydtypesinglefile.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:1379


copyFile

▸ copyFile(params): Promise<undefined>

Copy a single file from a source repo/bucket to the destination bucket.

The copy is server-side (no data transfer) when the source file is xet-backed. For small non-xet repo files (e.g. config.json) the file is downloaded and re-uploaded to the destination bucket in the same commit.

LFS pointer files that have not been migrated to xet are rejected up front (they would otherwise require downloading the full LFS blob).

Parameters[[copyfile.parameters]]

Name Type
params { destination: CopyDestination ; source: CopySource } & SharedParams

Returns[[copyfile.returns]]

Promise<undefined>

Example

await copyFile({
  source: {
    repo: { type: "model", name: "username/my-model" },
    path: "model.safetensors",
  },
  destination: {
    repo: { type: "bucket", name: "username/my-bucket" },
    path: "models/my-model/model.safetensors",
  },
  accessToken: "hf_...",
});

Defined in[[copyfile.defined-in]]

packages/hub/src/lib/copy-files.ts:111


copyFileIter

▸ copyFileIter(params): AsyncGenerator<CopyProgressEvent, undefined>

Async-iterator variant of copyFile that yields CopyProgressEvents while downloading non-xet source files (xet-backed files are copied server-side and do not emit events). See copyFile for the semantics.

Parameters[[copyfileiter.parameters]]

Name Type
params { destination: CopyDestination ; source: CopySource } & SharedParams

Returns[[copyfileiter.returns]]

AsyncGenerator<CopyProgressEvent, undefined>

Example

for await (const event of copyFileIter({ source, destination, accessToken })) {
  console.log(`downloaded ${event.path} (${event.downloaded}/${event.total})`);
}

Defined in[[copyfileiter.defined-in]]

packages/hub/src/lib/copy-files.ts:144


copyFiles

▸ copyFiles(params): Promise<undefined>

Copy multiple files (potentially from different source repos/buckets) to the destination bucket in a single commit.

For xet-backed source files, the copy is performed server-side with no data transfer. For non-xet source files (typically small git-stored repo files), the file is downloaded and re-uploaded as part of the same commit.

LFS pointer files that have not been migrated to xet are rejected up front.

Parameters[[copyfiles.parameters]]

Name Type
params { destination: BucketDesignation ; files: CopyFilesEntry[] } & SharedParams

Returns[[copyfiles.returns]]

Promise<undefined>

Example

await copyFiles({
  destination: { type: "bucket", name: "username/my-bucket" },
  files: [
    {
      source: {
        repo: { type: "bucket", name: "username/other-bucket" },
        path: "data.bin",
      },
      destinationPath: "data.bin",
    },
    {
      source: {
        repo: { type: "model", name: "username/my-model" },
        path: "model.safetensors",
      },
      destinationPath: "models/my-model/model.safetensors",
    },
  ],
  accessToken: "hf_...",
});

Defined in[[copyfiles.defined-in]]

packages/hub/src/lib/copy-files.ts:199


copyFilesIter

▸ copyFilesIter(params): AsyncGenerator<CopyProgressEvent, undefined>

Async-iterator variant of copyFiles that yields CopyProgressEvents while downloading non-xet source files (xet-backed files are copied server-side and do not emit events). See copyFiles for the semantics.

Parameters[[copyfilesiter.parameters]]

Name Type
params { destination: BucketDesignation ; files: CopyFilesEntry[] } & SharedParams

Returns[[copyfilesiter.returns]]

AsyncGenerator<CopyProgressEvent, undefined>

Defined in[[copyfilesiter.defined-in]]

packages/hub/src/lib/copy-files.ts:219


copyFolder

▸ copyFolder(params): Promise<undefined>

Copy a folder (recursively) from a source repo/bucket to the destination bucket in a single commit.

Per-file paths are resolved relative to CopySource.path; the source folder itself is not preserved in the destination unless CopyDestination.path keeps it.

Parameters[[copyfolder.parameters]]

Name Type
params { destination: Omit<CopyDestination, "path"> & { path?: string } ; source: Omit<CopySource, "path"> & { path?: string } } & SharedParams

Returns[[copyfolder.returns]]

Promise<undefined>

Example

// Copy an entire dataset under "datasets/my-dataset/" in the bucket
await copyFolder({
  source: { repo: { type: "dataset", name: "username/my-dataset" } },
  destination: {
    repo: { type: "bucket", name: "username/my-bucket" },
    path: "datasets/my-dataset/",
  },
  accessToken: "hf_...",
});

// Copy a subfolder
await copyFolder({
  source: {
    repo: { type: "bucket", name: "username/src-bucket" },
    path: "models/",
  },
  destination: {
    repo: { type: "bucket", name: "username/dst-bucket" },
    path: "backup/",
  },
  accessToken: "hf_...",
});

Defined in[[copyfolder.defined-in]]

packages/hub/src/lib/copy-files.ts:277


copyFolderIter

▸ copyFolderIter(params): AsyncGenerator<CopyProgressEvent, undefined>

Async-iterator variant of copyFolder that yields CopyProgressEvents while downloading non-xet source files (xet-backed files are copied server-side and do not emit events). See copyFolder for the semantics.

Parameters[[copyfolderiter.parameters]]

Name Type
params { destination: Omit<CopyDestination, "path"> & { path?: string } ; source: Omit<CopySource, "path"> & { path?: string } } & SharedParams

Returns[[copyfolderiter.returns]]

AsyncGenerator<CopyProgressEvent, undefined>

Defined in[[copyfolderiter.defined-in]]

packages/hub/src/lib/copy-files.ts:297


countCommits

▸ countCommits(params): Promise<number>

Parameters[[countcommits.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; repo: RepoDesignation ; revision?: string } & Partial<CredentialsParams>

Returns[[countcommits.returns]]

Promise<number>

Defined in[[countcommits.defined-in]]

packages/hub/src/lib/count-commits.ts:7


createBranch

▸ createBranch(params): Promise<void>

Parameters[[createbranch.parameters]]

Name Type Description
params Object -
params.accessToken? string -
params.branch string The name of the branch to create
params.empty? boolean Use this to create an empty branch, with no commits.
params.fetch? (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> MDN Reference
params.hubUrl? string -
params.overwrite? boolean Use this to overwrite the branch if it already exists. If you only specify overwrite and no revision/empty, and the branch already exists, it will be a no-op.
params.repo RepoDesignation -
params.revision? string Revision to create the branch from. Defaults to the default branch. Use empty: true to create an empty branch.

Returns[[createbranch.returns]]

Promise<void>

Defined in[[createbranch.defined-in]]

packages/hub/src/lib/create-branch.ts:6


createCollection

▸ createCollection(params): Promise<{ slug: string }>

Parameters[[createcollection.parameters]]

Name Type
params { collection: ApiCreateCollectionPayload ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string } & Partial<CredentialsParams>

Returns[[createcollection.returns]]

Promise<{ slug: string }>

Defined in[[createcollection.defined-in]]

packages/hub/src/lib/create-collection.ts:7


createRepo

▸ createRepo(params): Promise<{ id: string ; repoUrl: string }>

Parameters[[createrepo.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; files?: { content: ArrayBuffer | Blob ; path: string }[] ; hardware?: SpaceHardwareFlavor | undefined ; hubUrl?: string ; license?: string ; private?: boolean ; repo: RepoDesignation ; resourceGroupId?: string ; sdk?: SpaceSdk | undefined ; visibility?: "public" | "private" | "protected" } & CredentialsParams

Returns[[createrepo.returns]]

Promise<{ id: string ; repoUrl: string }>

Defined in[[createrepo.defined-in]]

packages/hub/src/lib/create-repo.ts:9


createScheduledJob

▸ createScheduledJob(params): Promise<ApiScheduledJob>

Create a scheduled job.

Parameters[[createscheduledjob.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; namespace: string } & CreateScheduledJobOptions & CredentialsParams

Returns[[createscheduledjob.returns]]

Promise<ApiScheduledJob>

Defined in[[createscheduledjob.defined-in]]

packages/hub/src/lib/jobs/create-scheduled-job.ts:11


datasetInfo

▸ datasetInfo<T>(params): Promise<DatasetEntry & Pick<ApiDatasetInfo, T>>

Type parameters[[datasetinfo.type-parameters]]

Name Type
T extends "author" | "cardData" | "disabled" | "gitalyUid" | "createdAt" | "tags" | "paperswithcode_id" | "sha" | "citation" | "description" | "downloadsAllTime" = never

Parameters[[datasetinfo.parameters]]

Name Type
params { additionalFields?: T[] ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; name: string ; revision?: string } & Partial<CredentialsParams>

Returns[[datasetinfo.returns]]

Promise<DatasetEntry & Pick<ApiDatasetInfo, T>>

Defined in[[datasetinfo.defined-in]]

packages/hub/src/lib/dataset-info.ts:9


deleteBranch

▸ deleteBranch(params): Promise<void>

Parameters[[deletebranch.parameters]]

Name Type Description
params Object -
params.accessToken? string -
params.branch string The name of the branch to delete
params.fetch? (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> MDN Reference
params.hubUrl? string -
params.repo RepoDesignation -

Returns[[deletebranch.returns]]

Promise<void>

Defined in[[deletebranch.defined-in]]

packages/hub/src/lib/delete-branch.ts:6


deleteCollection

▸ deleteCollection(params): Promise<void>

Parameters[[deletecollection.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; slug: string } & Partial<CredentialsParams>

Returns[[deletecollection.returns]]

Promise<void>

Defined in[[deletecollection.defined-in]]

packages/hub/src/lib/delete-collection.ts:6


deleteFile

▸ deleteFile(params): Promise<CommitOutput | undefined>

Parameters[[deletefile.parameters]]

Name Type
params { branch?: string ; commitDescription?: string ; commitTitle?: string ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; isPullRequest?: boolean ; parentCommit?: string ; path: string ; repo: RepoDesignation } & CredentialsParams

Returns[[deletefile.returns]]

Promise<CommitOutput | undefined>

Defined in[[deletefile.defined-in]]

packages/hub/src/lib/delete-file.ts:5


deleteFiles

▸ deleteFiles(params): Promise<CommitOutput | undefined>

Parameters[[deletefiles.parameters]]

Name Type
params { branch?: string ; commitDescription?: string ; commitTitle?: string ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; isPullRequest?: boolean ; parentCommit?: string ; paths: string[] ; repo: RepoDesignation } & CredentialsParams

Returns[[deletefiles.returns]]

Promise<CommitOutput | undefined>

Defined in[[deletefiles.defined-in]]

packages/hub/src/lib/delete-files.ts:5


deleteRepo

▸ deleteRepo(params): Promise<void>

Parameters[[deleterepo.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; repo: RepoDesignation } & CredentialsParams

Returns[[deleterepo.returns]]

Promise<void>

Defined in[[deleterepo.defined-in]]

packages/hub/src/lib/delete-repo.ts:7


deleteScheduledJob

▸ deleteScheduledJob(params): Promise<void>

Delete a scheduled job.

Parameters[[deletescheduledjob.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; jobId: string ; namespace: string } & CredentialsParams

Returns[[deletescheduledjob.returns]]

Promise<void>

Defined in[[deletescheduledjob.defined-in]]

packages/hub/src/lib/jobs/delete-scheduled-job.ts:9


downloadFile

▸ downloadFile(params): Promise<Blob | null>

Parameters[[downloadfile.parameters]]

Name Type
params { downloadInfo?: FileDownloadInfoOutput ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; parallelDownloads?: boolean | ParallelDownloadOptions ; path: string ; raw?: boolean ; repo: RepoDesignation ; revision?: string ; xet?: boolean | { readToken: XetReadToken } } & Partial<CredentialsParams>

Returns[[downloadfile.returns]]

Promise<Blob | null>

null when the file doesn't exist

Defined in[[downloadfile.defined-in]]

packages/hub/src/lib/download-file.ts:13


downloadFileToCacheDir

▸ downloadFileToCacheDir(params): Promise<string>

Download a given file if it's not already present in the local cache.

Parameters[[downloadfiletocachedir.parameters]]

Name Type
params { cacheDir?: string ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; path: string ; raw?: boolean ; repo: RepoDesignation ; revision?: string } & Partial<CredentialsParams>

Returns[[downloadfiletocachedir.returns]]

Promise<string>

the symlink to the blob object

Defined in[[downloadfiletocachedir.defined-in]]

packages/hub/src/lib/download-file-to-cache-dir.ts:46


duplicateJob

▸ duplicateJob(params): Promise<ApiJob>

Duplicate a job (re-run with the same spec).

Parameters[[duplicatejob.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; jobId: string ; namespace: string } & CredentialsParams

Returns[[duplicatejob.returns]]

Promise<ApiJob>

Defined in[[duplicatejob.defined-in]]

packages/hub/src/lib/jobs/duplicate-job.ts:10


encodeShardFilename

▸ encodeShardFilename(filename): string

Defense in depth: the download URL is built by string interpolation, so encode each path segment of the (already validated) filename rather than trusting it to be URL-safe.

Parameters[[encodeshardfilename.parameters]]

Name Type
filename string

Returns[[encodeshardfilename.returns]]

string

Defined in[[encodeshardfilename.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:570


fileDownloadInfo

▸ fileDownloadInfo(params): Promise<FileDownloadInfoOutput | null>

Parameters[[filedownloadinfo.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; noContentDisposition?: boolean ; path: string ; raw?: boolean ; repo: RepoDesignation ; revision?: string } & Partial<CredentialsParams>

Returns[[filedownloadinfo.returns]]

Promise<FileDownloadInfoOutput | null>

null when the file doesn't exist

Defined in[[filedownloadinfo.defined-in]]

packages/hub/src/lib/file-download-info.ts:27


fileExists

▸ fileExists(params): Promise<boolean>

Parameters[[fileexists.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; path: string ; repo: RepoDesignation ; revision?: string } & Partial<CredentialsParams>

Returns[[fileexists.returns]]

Promise<boolean>

Defined in[[fileexists.defined-in]]

packages/hub/src/lib/file-exists.ts:7


getBlobStat

▸ getBlobStat(blobPath, blobStats): Promise<Stats>

Parameters[[getblobstat.parameters]]

Name Type
blobPath string
blobStats Map<string, Stats>

Returns[[getblobstat.returns]]

Promise<Stats>

Defined in[[getblobstat.defined-in]]

packages/hub/src/lib/cache-management.ts:254


getHFHubCachePath

▸ getHFHubCachePath(): string

Returns[[gethfhubcachepath.returns]]

string

Defined in[[gethfhubcachepath.defined-in]]

packages/hub/src/lib/cache-management.ts:19


getJob

▸ getJob(params): Promise<ApiJob>

Get a specific job by ID.

Parameters[[getjob.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; jobId: string ; namespace: string } & CredentialsParams

Returns[[getjob.returns]]

Promise<ApiJob>

Defined in[[getjob.defined-in]]

packages/hub/src/lib/jobs/get-job.ts:10


getQuantizationMultiplier

▸ getQuantizationMultiplier(tensorName, dtype, quantConfig?, expertDtype?, mlxQuantizedModules?): number

Gets the parameter multiplier for a quantized tensor based on quantization method.

May be fractional — see packingFactor.

Parameters[[getquantizationmultiplier.parameters]]

Name Type
tensorName string
dtype Dtype
quantConfig? QuantizationConfig
expertDtype? string
mlxQuantizedModules? ReadonlySet<string>

Returns[[getquantizationmultiplier.returns]]

number

Defined in[[getquantizationmultiplier.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:1259


getRepoFolderName

▸ getRepoFolderName(«destructured»): string

Parameters[[getrepofoldername.parameters]]

Name Type
«destructured» RepoId

Returns[[getrepofoldername.returns]]

string

Defined in[[getrepofoldername.defined-in]]

packages/hub/src/lib/cache-management.ts:27


getScheduledJob

▸ getScheduledJob(params): Promise<ApiScheduledJob>

Get a specific scheduled job by ID.

Parameters[[getscheduledjob.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; jobId: string ; namespace: string } & CredentialsParams

Returns[[getscheduledjob.returns]]

Promise<ApiScheduledJob>

Defined in[[getscheduledjob.defined-in]]

packages/hub/src/lib/jobs/get-scheduled-job.ts:10


globMatch

▸ globMatch(pattern, str): boolean

Glob match without RegExp: splits pattern on * and checks that each literal segment appears in order within str. Avoids RegExp entirely (no ReDoS risk, no SyntaxError from attacker-controlled patterns in config.json).

Parameters[[globmatch.parameters]]

Name Type
pattern string
str string

Returns[[globmatch.returns]]

boolean

Defined in[[globmatch.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:1153


isQuantizedTensor

▸ isQuantizedTensor(tensorName, quantConfig?, mlxQuantizedModules?): boolean

Determines if a tensor is quantized based on quantization config and tensor name.

Python's transformers uses plain substring matching for modules_to_not_convert, so bare names like "lm_head" must match "model.lm_head.weight". When the pattern contains a * we fall back to proper glob matching for flexibility.

Parameters[[isquantizedtensor.parameters]]

Name Type
tensorName string
quantConfig? QuantizationConfig
mlxQuantizedModules? ReadonlySet<string>

Returns[[isquantizedtensor.returns]]

boolean

Defined in[[isquantizedtensor.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:1189


listCollections

▸ listCollections(params?): AsyncGenerator<ApiCollectionInfo>

Parameters[[listcollections.parameters]]

Name Type
params? { search?: { owner?: string[] | undefined; item?: string[] | undefined; q?: string | undefined; } | undefined; sort?: "lastModified" | "trending" | "upvotes" | undefined; limit?: number | undefined; hubUrl?: string | undefined; fetch?: { ...; } | undefined; } & Partial<...>

Returns[[listcollections.returns]]

AsyncGenerator<ApiCollectionInfo>

Defined in[[listcollections.defined-in]]

packages/hub/src/lib/list-collections.ts:12


listCommits

▸ listCommits(params): AsyncGenerator<CommitData>

Parameters[[listcommits.parameters]]

Name Type
params { batchSize?: number ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; repo: RepoDesignation ; revision?: string } & Partial<CredentialsParams>

Returns[[listcommits.returns]]

AsyncGenerator<CommitData>

Defined in[[listcommits.defined-in]]

packages/hub/src/lib/list-commits.ts:17


listDatasets

▸ listDatasets<T>(params?): AsyncGenerator<DatasetEntry & Pick<ApiDatasetInfo, T>>

Type parameters[[listdatasets.type-parameters]]

Name Type
T extends "author" | "cardData" | "disabled" | "gitalyUid" | "createdAt" | "tags" | "paperswithcode_id" | "sha" | "citation" | "description" | "downloadsAllTime" = never

Parameters[[listdatasets.parameters]]

Name Type
params? { search?: { query?: string | undefined; owner?: string | undefined; tags?: string[] | undefined; } | undefined; hubUrl?: string | undefined; additionalFields?: T[] | undefined; limit?: number | undefined; sort?: "id" | ... 8 more ... | undefined; fetch?: { ...; } | undefined; } & Partial<...>

Returns[[listdatasets.returns]]

AsyncGenerator<DatasetEntry & Pick<ApiDatasetInfo, T>>

Defined in[[listdatasets.defined-in]]

packages/hub/src/lib/list-datasets.ts:47


listFiles

▸ listFiles(params): AsyncGenerator<ListFileEntry>

List files in a folder. To list ALL files in the directory, call it with params.recursive set to true.

Parameters[[listfiles.parameters]]

Name Type
params { expand?: boolean ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; path?: string ; recursive?: boolean ; repo: RepoDesignation ; revision?: string } & Partial<CredentialsParams>

Returns[[listfiles.returns]]

AsyncGenerator<ListFileEntry>

Defined in[[listfiles.defined-in]]

packages/hub/src/lib/list-files.ts:53


listJobHardware

▸ listJobHardware(params?): Promise<ApiJobHardware[]>

Get the list of available hardware for jobs. This endpoint is public and does not require authentication, but authentication is optional.

Parameters[[listjobhardware.parameters]]

Name Type
params? { hubUrl?: string | undefined; fetch?: { (input: URL | RequestInfo, init?: RequestInit | undefined): Promise; (input: string | ... 1 more ... | Request, init?: RequestInit | undefined): Promise<...>; } | undefined; } & Partial<...>

Returns[[listjobhardware.returns]]

Promise<ApiJobHardware[]>

Defined in[[listjobhardware.defined-in]]

packages/hub/src/lib/jobs/list-job-hardware.ts:11


listJobs

▸ listJobs(params): Promise<ApiJob[]>

List jobs for a namespace (user or organization).

Parameters[[listjobs.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; namespace: string } & CredentialsParams

Returns[[listjobs.returns]]

Promise<ApiJob[]>

Defined in[[listjobs.defined-in]]

packages/hub/src/lib/jobs/list-jobs.ts:10


listModels

▸ listModels<T>(params?): AsyncGenerator<ModelEntry & ResolveModelAdditionalFields<T>>

Type parameters[[listmodels.type-parameters]]

Name Type
T extends ModelAdditionalField = never

Parameters[[listmodels.parameters]]

Name Type
params? { search?: { query?: string | undefined; owner?: string | undefined; task?: "other" | "text-classification" | "token-classification" | "table-question-answering" | "question-answering" | ... 52 more ... | undefined; tags?: string[] | undefined; inferenceProviders?: string[] | undefined; apps?: string[] | undefined; ...

Returns[[listmodels.returns]]

AsyncGenerator<ModelEntry & ResolveModelAdditionalFields<T>>

Defined in[[listmodels.defined-in]]

packages/hub/src/lib/list-models.ts:68


listScheduledJobs

▸ listScheduledJobs(params): Promise<ApiScheduledJob[]>

List scheduled jobs for a namespace.

Parameters[[listscheduledjobs.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; namespace: string } & CredentialsParams

Returns[[listscheduledjobs.returns]]

Promise<ApiScheduledJob[]>

Defined in[[listscheduledjobs.defined-in]]

packages/hub/src/lib/jobs/list-scheduled-jobs.ts:10


listSpaces

▸ listSpaces<T>(params?): AsyncGenerator<SpaceEntry & Pick<ApiSpaceInfo, T>>

Type parameters[[listspaces.type-parameters]]

Name Type
T extends "models" | "datasets" | "author" | "cardData" | "disabled" | "gitalyUid" | "createdAt" | "tags" | "sha" | "subdomain" | "runtime" = never

Parameters[[listspaces.parameters]]

Name Type
params? { search?: { query?: string | undefined; owner?: string | undefined; tags?: string[] | undefined; } | undefined; hubUrl?: string | undefined; fetch?: { (input: URL | RequestInfo, init?: RequestInit | undefined): Promise<...>; (input: string | ... 1 more ... | Request, init?: RequestInit | undefined): Promise<...>; }...

Returns[[listspaces.returns]]

AsyncGenerator<SpaceEntry & Pick<ApiSpaceInfo, T>>

Defined in[[listspaces.defined-in]]

packages/hub/src/lib/list-spaces.ts:44


matchesCompressedTensorsTarget

▸ matchesCompressedTensorsTarget(target, moduleName): boolean

Matches a module name against a compressed-tensors target.

Targets are either exact module names, class names (e.g. "Linear", which we cannot resolve from tensor names and therefore ignore), or Python regexes prefixed with re:. To avoid evaluating attacker-controlled RegExp from config.json (ReDoS, SyntaxError — see globMatch), we translate the common regex subset (.* wildcard, ^/$ anchors, \. escapes) to globMatch and treat targets using any other regex syntax as non-matching.

Parameters[[matchescompressedtensorstarget.parameters]]

Name Type
target string
moduleName string

Returns[[matchescompressedtensorstarget.returns]]

boolean

Defined in[[matchescompressedtensorstarget.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:1231


modelInfo

▸ modelInfo<T>(params): Promise<ModelEntry & ResolveModelAdditionalFields<T>>

Type parameters[[modelinfo.type-parameters]]

Name Type
T extends ModelAdditionalField = never

Parameters[[modelinfo.parameters]]

Name Type
params { additionalFields?: T[] ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; name: string ; revision?: string } & Partial<CredentialsParams>

Returns[[modelinfo.returns]]

Promise<ModelEntry & ResolveModelAdditionalFields<T>>

Defined in[[modelinfo.defined-in]]

packages/hub/src/lib/model-info.ts:16


oauthHandleRedirect

▸ oauthHandleRedirect(opts?): Promise<OAuthResult>

To call after the OAuth provider redirects back to the app.

There is also a helper function oauthHandleRedirectIfPresent, which will call oauthHandleRedirect if the URL contains an oauth code in the query parameters and return false otherwise.

Parameters[[oauthhandleredirect.parameters]]

Name Type Description
opts? Object -
opts.codeVerifier? string codeVerifier generated by oauthLoginUrl Default ts localStorage.getItem("huggingface.co:oauth:code_verifier")
opts.hubUrl? string The URL of the hub. Defaults to HUB_URL.
opts.nonce? string nonce generated by oauthLoginUrl Default ts localStorage.getItem("huggingface.co:oauth:nonce")
opts.redirectedUrl? string The URL to analyze. Default ts window.location.href

Returns[[oauthhandleredirect.returns]]

Promise<OAuthResult>

Defined in[[oauthhandleredirect.defined-in]]

packages/hub/src/lib/oauth-handle-redirect.ts:123


oauthHandleRedirectIfPresent

▸ oauthHandleRedirectIfPresent(opts?): Promise<OAuthResult | false>

To call after the OAuth provider redirects back to the app.

It returns false if the URL does not contain an oauth code in the query parameters, otherwise it calls oauthHandleRedirect.

Depending on your app, you may want to call oauthHandleRedirect directly instead.

Parameters[[oauthhandleredirectifpresent.parameters]]

Name Type Description
opts? Object -
opts.codeVerifier? string codeVerifier generated by oauthLoginUrl Default ts localStorage.getItem("huggingface.co:oauth:code_verifier")
opts.hubUrl? string The URL of the hub. Defaults to HUB_URL.
opts.nonce? string nonce generated by oauthLoginUrl Default ts localStorage.getItem("huggingface.co:oauth:nonce")
opts.redirectedUrl? string The URL to analyze. Default ts window.location.href

Returns[[oauthhandleredirectifpresent.returns]]

Promise<OAuthResult | false>

Defined in[[oauthhandleredirectifpresent.defined-in]]

packages/hub/src/lib/oauth-handle-redirect.ts:293


oauthLoginUrl

▸ oauthLoginUrl(opts?): Promise<string>

Use "Sign in with Hub" to authenticate a user, and get oauth user info / access token.

Returns an url to redirect to. After the user is redirected back to your app, call oauthHandleRedirect to get the oauth user info / access token.

When called from inside a static Space with OAuth enabled, it will load the config from the space, otherwise you need to at least specify the client ID of your OAuth App.

Parameters[[oauthloginurl.parameters]]

Name Type Description
opts? Object -
opts.clientId? string OAuth client ID. For static Spaces, you can omit this and it will be loaded from the Space config, as long as hf_oauth: true is present in the README.md's metadata. For other Spaces, it is available to the backend in the OAUTH_CLIENT_ID environment variable, as long as hf_oauth: true is present in the README.md's metadata. You can also create a Developer Application at and use its client ID.
opts.hubUrl? string -
opts.localStorage? Object If provided, will be filled with the code verifier and nonce used for the OAuth flow, instead of using localStorage. When calling oauthHandleRedirectIfPresent or oauthHandleRedirect you will need to provide the same values.
opts.localStorage.codeVerifier? string -
opts.localStorage.nonce? string -
opts.redirectUrl? string Redirect URI, defaults to the current URL. For Spaces, any URL within the Space is allowed. For Developer Applications, you can add any URL you want to the list of allowed redirect URIs at
opts.scopes? string OAuth scope, a list of space-separated scopes. For static Spaces, you can omit this and it will be loaded from the Space config, as long as hf_oauth: true is present in the README.md's metadata. For other Spaces, it is available to the backend in the OAUTH_SCOPES environment variable, as long as hf_oauth: true is present in the README.md's metadata. Defaults to "openid profile". You can also create a Developer Application at and use its scopes. See for a list of available scopes.
opts.state? string State to pass to the OAuth provider, which will be returned in the call to oauthLogin after the redirect.

Returns[[oauthloginurl.returns]]

Promise<string>

Example

import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub";

const oauthResult = await oauthHandleRedirectIfPresent();

if (!oauthResult) {
  // If the user is not logged in, redirect to the login page
  window.location.href = await oauthLoginUrl();
}

// You can use oauthResult.accessToken, oauthResult.accessTokenExpiresAt and oauthResult.userInfo
console.log(oauthResult);

(Theoretically, this function could be used to authenticate a user for any OAuth provider supporting PKCE and OpenID Connect by changing hubUrl, but it is currently only tested with the Hugging Face Hub.)

Defined in[[oauthloginurl.defined-in]]

packages/hub/src/lib/oauth-login-url.ts:31


parseRepoType

▸ parseRepoType(type): RepoType

Parameters[[parserepotype.parameters]]

Name Type
type string

Returns[[parserepotype.returns]]

RepoType

Defined in[[parserepotype.defined-in]]

packages/hub/src/lib/cache-management.ts:264


parseSafetensorsMetadata

▸ parseSafetensorsMetadata(params): Promise<SetRequired<SafetensorsParseFromRepo, "parameterCount">>

Analyze model.safetensors.index.json or model.safetensors from a model hosted on Hugging Face using smart range requests to extract its metadata.

Parameters[[parsesafetensorsmetadata.parameters]]

Name Type
params { computeParametersCount: true ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; library?: string ; path?: string ; repo: RepoDesignation ; revision?: string ; useSafetensorsMetadataEndpoint?: boolean } & Partial<CredentialsParams>

Returns[[parsesafetensorsmetadata.returns]]

Promise<SetRequired<SafetensorsParseFromRepo, "parameterCount">>

Defined in[[parsesafetensorsmetadata.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:738

▸ parseSafetensorsMetadata(params): Promise<SafetensorsParseFromRepo>

Parameters[[parsesafetensorsmetadata.parameters]]

Name Type
params { computeParametersCount?: boolean ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; library?: string ; path?: string ; repo: RepoDesignation ; revision?: string ; useSafetensorsMetadataEndpoint?: boolean } & Partial<CredentialsParams>

Returns[[parsesafetensorsmetadata.returns]]

Promise<SafetensorsParseFromRepo>

Defined in[[parsesafetensorsmetadata.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:775


parseSafetensorsShardFilename

▸ parseSafetensorsShardFilename(filename): SafetensorsShardFileInfo | null

Parameters[[parsesafetensorsshardfilename.parameters]]

Name Type
filename string

Returns[[parsesafetensorsshardfilename.returns]]

SafetensorsShardFileInfo | null

Defined in[[parsesafetensorsshardfilename.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:36


parseTotalParameters

▸ parseTotalParameters(value, computedTotal?): number | undefined

Reads the total_parameters shortcut from the header/index metadata. It's self-reported and the Hub displays it verbatim, bypassing the header validation above — so cap it at the computed count when we have one (a no-op for well-formed files, where the two agree).

Parameters[[parsetotalparameters.parameters]]

Name Type
value undefined | string | number
computedTotal? number

Returns[[parsetotalparameters.returns]]

number | undefined

Defined in[[parsetotalparameters.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:699


pathsInfo

▸ pathsInfo(params): Promise<PathInfo & { lastCommit: CommitInfo ; securityFileStatus: SecurityFileStatus }[]>

Parameters[[pathsinfo.parameters]]

Name Type
params { expand: true ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; paths: string[] ; repo: RepoDesignation ; revision?: string } & Partial<CredentialsParams>

Returns[[pathsinfo.returns]]

Promise<PathInfo & { lastCommit: CommitInfo ; securityFileStatus: SecurityFileStatus }[]>

Defined in[[pathsinfo.defined-in]]

packages/hub/src/lib/paths-info.ts:51

▸ pathsInfo(params): Promise<PathInfo[]>

Parameters[[pathsinfo.parameters]]

Name Type
params { expand?: boolean ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; paths: string[] ; repo: RepoDesignation ; revision?: string } & Partial<CredentialsParams>

Returns[[pathsinfo.returns]]

Promise<PathInfo[]>

Defined in[[pathsinfo.defined-in]]

packages/hub/src/lib/paths-info.ts:64


relativeUnderFolder

▸ relativeUnderFolder(filePath, folderPath): string

Compute the path of filePath relative to folderPath. Used to map source paths under a folder being copied to destination paths under the new prefix.

Parameters[[relativeunderfolder.parameters]]

Name Type
filePath string
folderPath string

Returns[[relativeunderfolder.returns]]

string

Defined in[[relativeunderfolder.defined-in]]

packages/hub/src/lib/copy-files.ts:558


repoExists

▸ repoExists(params): Promise<boolean>

Parameters[[repoexists.parameters]]

Name Type Description
params Object -
params.accessToken? string -
params.fetch? (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
params.hubUrl? string -
params.repo RepoDesignation -
params.revision? string An optional Git revision id which can be a branch name, a tag, or a commit hash.

Returns[[repoexists.returns]]

Promise<boolean>

Defined in[[repoexists.defined-in]]

packages/hub/src/lib/repo-exists.ts:6


resumeScheduledJob

▸ resumeScheduledJob(params): Promise<void>

Resume a scheduled job.

Parameters[[resumescheduledjob.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; jobId: string ; namespace: string } & CredentialsParams

Returns[[resumescheduledjob.returns]]

Promise<void>

Defined in[[resumescheduledjob.defined-in]]

packages/hub/src/lib/jobs/resume-scheduled-job.ts:9


runJob

▸ runJob(params): Promise<ApiJob>

Run a new job.

Parameters[[runjob.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; namespace: string } & CreateJobOptions & CredentialsParams

Returns[[runjob.returns]]

Promise<ApiJob>

Defined in[[runjob.defined-in]]

packages/hub/src/lib/jobs/run-job.ts:12


runScheduledJob

▸ runScheduledJob(params): Promise<ApiJob | null>

Trigger a scheduled job to run immediately. Returns the job that was triggered, or null if another instance is already running.

Parameters[[runscheduledjob.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; jobId: string ; namespace: string } & CredentialsParams

Returns[[runscheduledjob.returns]]

Promise<ApiJob | null>

Defined in[[runscheduledjob.defined-in]]

packages/hub/src/lib/jobs/run-scheduled-job.ts:11


scanCacheDir

▸ scanCacheDir(cacheDir?): Promise<HFCacheInfo>

Parameters[[scancachedir.parameters]]

Name Type Default value
cacheDir undefined | string undefined

Returns[[scancachedir.returns]]

Promise<HFCacheInfo>

Defined in[[scancachedir.defined-in]]

packages/hub/src/lib/cache-management.ts:72


scanCachedRepo

▸ scanCachedRepo(repoPath): Promise<CachedRepoInfo>

Parameters[[scancachedrepo.parameters]]

Name Type
repoPath string

Returns[[scancachedrepo.returns]]

Promise<CachedRepoInfo>

Defined in[[scancachedrepo.defined-in]]

packages/hub/src/lib/cache-management.ts:118


scanRefsDir

▸ scanRefsDir(refsPath, refsByHash): Promise<void>

Parameters[[scanrefsdir.parameters]]

Name Type
refsPath string
refsByHash Map<string, string[]>

Returns[[scanrefsdir.returns]]

Promise<void>

Defined in[[scanrefsdir.defined-in]]

packages/hub/src/lib/cache-management.ts:210


scanSnapshotDir

▸ scanSnapshotDir(revisionPath, cachedFiles, blobStats): Promise<void>

Parameters[[scansnapshotdir.parameters]]

Name Type
revisionPath string
cachedFiles CachedFileInfo[]
blobStats Map<string, Stats>

Returns[[scansnapshotdir.returns]]

Promise<void>

Defined in[[scansnapshotdir.defined-in]]

packages/hub/src/lib/cache-management.ts:227


snapshotDownload

▸ snapshotDownload(params): Promise<string>

Downloads an entire repository at a given revision in the cache directory getHFHubCachePath. You can list all cached repositories using scanCachedRepo

Parameters[[snapshotdownload.parameters]]

Name Type
params { cacheDir?: string ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; repo: RepoDesignation ; revision?: string } & Partial<CredentialsParams>

Returns[[snapshotdownload.returns]]

Promise<string>

Remarks

It uses internally downloadFileToCacheDir.

Defined in[[snapshotdownload.defined-in]]

packages/hub/src/lib/snapshot-download.ts:20


spaceInfo

▸ spaceInfo<T>(params): Promise<SpaceEntry & Pick<ApiSpaceInfo, T>>

Type parameters[[spaceinfo.type-parameters]]

Name Type
T extends "models" | "datasets" | "author" | "cardData" | "disabled" | "gitalyUid" | "createdAt" | "tags" | "sha" | "subdomain" | "runtime" = never

Parameters[[spaceinfo.parameters]]

Name Type
params { additionalFields?: T[] ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; name: string ; revision?: string } & Partial<CredentialsParams>

Returns[[spaceinfo.returns]]

Promise<SpaceEntry & Pick<ApiSpaceInfo, T>>

Defined in[[spaceinfo.defined-in]]

packages/hub/src/lib/space-info.ts:10


streamJobEvents

▸ streamJobEvents(params): AsyncGenerator<string, void, unknown>

Stream job events using Server-Sent Events (SSE). Returns an async iterable of event chunks.

Parameters[[streamjobevents.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; jobId: string ; namespace: string } & CredentialsParams

Returns[[streamjobevents.returns]]

AsyncGenerator<string, void, unknown>

Defined in[[streamjobevents.defined-in]]

packages/hub/src/lib/jobs/stream-job-events.ts:10


streamJobLogs

▸ streamJobLogs(params): AsyncGenerator<{ message: string ; timestamp: Date }, void, unknown>

Stream job logs using Server-Sent Events (SSE). Returns an async iterable of log chunks.

Parameters[[streamjoblogs.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; jobId: string ; namespace: string } & CredentialsParams

Returns[[streamjoblogs.returns]]

AsyncGenerator<{ message: string ; timestamp: Date }, void, unknown>

Defined in[[streamjoblogs.defined-in]]

packages/hub/src/lib/jobs/stream-job-logs.ts:10


streamJobMetrics

▸ streamJobMetrics(params): AsyncGenerator<string, void, unknown>

Stream job metrics using Server-Sent Events (SSE). Returns an async iterable of metric chunks.

Parameters[[streamjobmetrics.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; jobId: string ; namespace: string } & CredentialsParams

Returns[[streamjobmetrics.returns]]

AsyncGenerator<string, void, unknown>

Defined in[[streamjobmetrics.defined-in]]

packages/hub/src/lib/jobs/stream-job-metrics.ts:10


streamJson

▸ streamJson(source, options?): AsyncGenerator<JsonStreamEvent, void, undefined>

Parameters[[streamjson.parameters]]

Name Type Description
source ReadableStream<Uint8Array<ArrayBufferLike>> | AsyncIterable<Uint8Array<ArrayBufferLike>, any, any> -
options? Object -
options.maxDepth? number Maximum object/array nesting depth. Default ts 1_000
options.maxTokenLength? number Maximum length, in characters, of a single string / number token. Default ts 16_000_000

Returns[[streamjson.returns]]

AsyncGenerator<JsonStreamEvent, void, undefined>

Defined in[[streamjson.defined-in]]

packages/hub/src/utils/streamJson.ts:123


suspendScheduledJob

▸ suspendScheduledJob(params): Promise<void>

Suspend (pause) a scheduled job.

Parameters[[suspendscheduledjob.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string ; jobId: string ; namespace: string } & CredentialsParams

Returns[[suspendscheduledjob.returns]]

Promise<void>

Defined in[[suspendscheduledjob.defined-in]]

packages/hub/src/lib/jobs/suspend-scheduled-job.ts:9


uploadFile

▸ uploadFile(params): Promise<CommitOutput | undefined>

Parameters[[uploadfile.parameters]]

Name Type
params { abortSignal?: AbortSignal ; branch?: string ; commitDescription?: string ; commitTitle?: string ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; file: URL | CommitEditFileParams | File | { content: ContentSource ; path: string } ; hubUrl?: string ; isPullRequest?: boolean ; parentCommit?: string ; rangeEditCache?: RangeEditCache ; repo: RepoDesignation ; useWebWorkers?: boolean | { minSize?: number ; poolSize?: number } ; useXet?: boolean } & Partial<CredentialsParams>

Returns[[uploadfile.returns]]

Promise<CommitOutput | undefined>

Defined in[[uploadfile.defined-in]]

packages/hub/src/lib/upload-file.ts:39


uploadFiles

▸ uploadFiles(params): Promise<CommitOutput | undefined>

Parameters[[uploadfiles.parameters]]

Name Type
params { abortSignal?: AbortSignal ; branch?: string ; commitDescription?: string ; commitTitle?: string ; fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; files: (URL | CommitEditFileParams | File | { content: ContentSource ; path: string })[] ; hubUrl?: string ; isPullRequest?: boolean ; maxFolderDepth?: number ; parentCommit?: string ; rangeEditCache?: RangeEditCache ; repo: RepoDesignation ; useWebWorkers?: boolean | { minSize?: number ; poolSize?: number } ; useXet?: boolean } & Partial<CredentialsParams>

Returns[[uploadfiles.returns]]

Promise<CommitOutput | undefined>

Defined in[[uploadfiles.defined-in]]

packages/hub/src/lib/upload-files.ts:6


uploadFilesWithProgress

▸ uploadFilesWithProgress(params): AsyncGenerator<CommitProgressEvent, CommitOutput | undefined>

Uploads with progress

Needs XMLHttpRequest to be available for progress events for uploads on models, datasets and spaces. Set useWebWorkers to true in order to have progress events for hashing for models, datasets and spaces.

Parameters[[uploadfileswithprogress.parameters]]

Name Type
params { abortSignal?: AbortSignal ; branch?: string ; commitDescription?: string ; commitTitle?: string ; files: (URL | CommitEditFileParams | File | { content: ContentSource ; path: string })[] ; hubUrl?: string ; isPullRequest?: boolean ; maxFolderDepth?: number ; parentCommit?: string ; rangeEditCache?: RangeEditCache ; repo: RepoDesignation ; useWebWorkers?: boolean | { minSize?: number ; poolSize?: number } ; useXet?: boolean } & Partial<CredentialsParams>

Returns[[uploadfileswithprogress.returns]]

AsyncGenerator<CommitProgressEvent, CommitOutput | undefined>

Defined in[[uploadfileswithprogress.defined-in]]

packages/hub/src/lib/upload-files-with-progress.ts:21


validateTensorEntry

▸ validateTensorEntry(path, tensorName, info, fileSizeBytes): void

Validates one tensor entry from a header: dims are finite integers under MAX_TENSOR_DIM, data_offsets are sane, and — when the file size is known — the declared byte span fits in the file. data_offsets is checked rather than shape * dtype size because the two may legitimately disagree (padding), so offsets are the only ground truth the format gives us.

Parameters[[validatetensorentry.parameters]]

Name Type
path string
tensorName string
info TensorInfo
fileSizeBytes undefined | number

Returns[[validatetensorentry.returns]]

void

Defined in[[validatetensorentry.defined-in]]

packages/hub/src/lib/parse-safetensors-metadata.ts:246


whoAmI

▸ whoAmI(params): Promise<WhoAmI & { auth: AuthInfo }>

Parameters[[whoami.parameters]]

Name Type
params { fetch?: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>(input: string | URL | Request, init?: RequestInit) => Promise<Response> ; hubUrl?: string } & CredentialsParams

Returns[[whoami.returns]]

Promise<WhoAmI & { auth: AuthInfo }>

Defined in[[whoami.defined-in]]

packages/hub/src/lib/who-am-i.ts:62

Source and license

Source: Huggingface.js documentation, adapted for this site. Licensing and attribution follow the terms of the upstream project.