yatta/storage
Local and S3 disks, uploads, signed URLs, streaming.
49 exported symbols and 184 members, read from src/types/storage.ts.
Construct
createStorage
functionFactory function creating and registering a configured instance.
createStorage(config?: StorageConfig): StorageManager- config
- Single disk or multi-disk configuration options.
Returns Configured instance.
import { createStorage } from "./storage"; export const storage = createStorage({ default: "local", disks: { local: { driver: "local", baseDir: "./uploads" }, },});escapeHtml
functionEscapes HTML control characters to prevent XSS in the embedded explorer UI.
escapeHtml(str: string): string- str
- Unsafe input string.
Returns HTML-safe escaped string.
guessContentType
functionInfers an appropriate MIME type from a filename extension.
guessContentType(filename: string): string- filename
- File name or key.
Returns Inferred MIME type, or `"application/octet-stream"` as fallback.
matchMime
functionEvaluates whether a MIME type matches a pattern (supports exact and wildcards like `image/*` or `*`).
matchMime(type: string, pattern: string): boolean- type
- Actual MIME type (e.g. `"image/png"`).
- pattern
- Filter pattern (e.g. `"image/*"`, `"*\/*"`).
Returns `true` if matched; otherwise `false`.
parseDuration
functionParses a human-readable duration string into **seconds**.
parseDuration(val?: HumanTime): number- val
- Duration string (e.g. `"30s"`, `"15m"`, `"1h"`, `"7d"`) or numeric seconds.
Returns Duration in seconds (defaults to 3600 if undefined or invalid).
parseDuration("1h"); // 3600parseDuration("30m"); // 1800parseDuration(120); // 120parseSize
functionParses a human-readable size string into raw **bytes**.
parseSize(val?: HumanSize): number- val
- Human size string (e.g. `"10MB"`, `"500KB"`, `"2GB"`) or numeric bytes.
Returns Number of bytes (defaults to 104,857,600 / 100MB if undefined).
parseSize("1KB"); // 1024parseSize("5MB"); // 5242880parseSize("1GB"); // 1073741824resolveSigningSecret
functionResolves the HMAC signing secret from config, environment variables, or generates
resolveSigningSecret(configuredSecret?: string): string- configuredSecret
- Optional explicit secret provided in disk configuration.
Returns 32+ character signing secret.
safeConstantTimeEqual
functionCompares two strings in constant time to prevent side-channel timing attacks on signatures.
safeConstantTimeEqual(a: string, b: string): boolean- a
- First string.
- b
- Second string.
Returns `true` if strings are identical; otherwise `false`.
sanitizeKey
functionSanitizes a storage key, preventing directory traversal attacks (`../`),
sanitizeKey(key: string): string- key
- Raw key input.
Returns Clean posix path.
verifyMagicBytes
functionDeep magic byte inspection across common file formats (JPEG, PNG, GIF, WEBP, PDF, ZIP, MP4, WebM, MP3, OGG).
verifyMagicBytes(buffer: Uint8Array, declaredMime: string): boolean- buffer
- Byte slice from the file header.
- declaredMime
- Declared MIME type to verify against.
Returns `true` if valid or non-verifiable format; `false` on signature mismatch.
FileAlreadyExistsError
classThrown when an upload target already exists and overwrite policy is set to `"error"`.
class FileAlreadyExistsError extends StorageErrorFileNotFoundError
classThrown when attempting to access, read, or manipulate a non-existent file key.
class FileNotFoundError extends StorageErrorFileRef
classFluent reference targeting a specific file key on a .
class FileRef23 members
writewrite(data: UploadInput, options?: UploadOptions): Promise<FileMetadata>Writes data to this file key.
- data
- Upload payload (Buffer, File, Stream, Object, etc.).
- options
- Upload options (MIME, size cap, overwrite policy).
putput(data: UploadInput, options?: UploadOptions): Promise<FileMetadata>Alias for .
readread(): Promise<StorageFile>Downloads and returns a instance for reading and streaming.
getget(): Promise<StorageFile>Alias for .
headhead(): Promise<FileMetadata>Retrieves file metadata without downloading the body.
statstat(): Promise<FileMetadata>Alias for .
existsexists(): Promise<boolean>Checks whether this file exists on disk.
ensureExistsensureExists(): Promise<this>Asserts that the file exists, throwing if missing.
Returns `this` for chaining.
ensureNotExistsensureNotExists(): Promise<this>Asserts that the file does not exist, throwing if present.
Returns `this` for chaining.
texttext(): Promise<string>Reads and decodes file contents as a UTF-8 text string.
jsonjson<T = unknown>(): Promise<T>Reads, decodes, and parses file contents as JSON.
bufferbuffer(): Promise<Buffer>Reads file contents into a Node.js / Bun `Buffer`.
arrayBufferarrayBuffer(): Promise<ArrayBuffer>Reads file contents into an `ArrayBuffer`.
streamstream(): Promise<ReadableStream<Uint8Array>>Opens a readable byte stream (`ReadableStream<Uint8Array>`) for this file.
blobblob(): Promise<Blob>Reads and returns file contents wrapped in a `Blob`.
deletedelete(): Promise<void>Deletes this file from storage.
copyTocopyTo(destinationKey: string): Promise<FileMetadata>Copies this file to a new destination key.
- destinationKey
- Destination storage key.
moveTomoveTo(destinationKey: string): Promise<FileMetadata>Moves / renames this file to a new destination key.
- destinationKey
- Destination storage key.
urlurl(): stringReturns the publicly accessible URL for this file.
expiresInexpiresIn(time: HumanTime): SignBuilderInitializes a configured with an expiration duration.
- time
- Expiration duration (e.g. `"1h"`, `"15m"`, or seconds).
signsign(expiresIn?: HumanTime, method?: "GET" | "PUT"): Promise<string>Directly generates a time-limited signed URL for this file.
- expiresIn
- Expiration duration (defaults to `"1h"`).
- method
- Allowed HTTP method (`"GET"` or `"PUT"`).
serveserve(request?: Request | null, options?: ServeOptions): Promise<Response>Streams this file as an HTTP Response supporting RFC 9110 Range headers and conditional 304s.
- request
- Incoming HTTP `Request` or null.
- options
- Delivery options (cache control, headers, disposition).
downloaddownload(options?: { filename?: string; }): Promise<Response>Delivers this file as a downloadable attachment (`Content-Disposition: attachment`).
- options
- Download options including optional custom download filename.
FolderRef
classVirtual directory handle scoping all operations under a given path prefix.
class FolderRef6 members
prefixpropertyprefix: stringNormalized directory prefix without trailing slash.
filefile(name: string): FileRefReturns a scoped within this folder.
- name
- File name or relative subpath.
putput(name: string): PutBuilderReturns a for writing a file scoped within this folder.
- name
- File name or relative subpath.
folderfolder(subfolder: string): FolderRefReturns a nested subfolder .
- subfolder
- Child folder name.
listlist(options?: Omit<ListOptions, "prefix">): Promise<FileMetadata[]>Lists all files residing under this folder prefix.
deletedelete(): Promise<void>Deletes all files residing under this folder prefix (up to 10,000 files).
LocalStorageDriver
classStorage driver operating directly on the local filesystem using Bun primitives (`Bun.file`, `Bun.write`).
class LocalStorageDriver implements IStorageDriver16 members
baseDirpropertybaseDir: stringResolved root directory path.
secretpropertysecret: stringpublicBaseUrlpropertypublicBaseUrl: stringresolvePathresolvePath(key: string): stringuploadupload(key: string, data: UploadInput, options?: UploadOptions): Promise<FileMetadata>downloaddownload(key: string): Promise<StorageFile>headhead(key: string): Promise<FileMetadata>deletedelete(key: string): Promise<void>deleteManydeleteMany(keys: string[]): Promise<void>copycopy(sourceKey: string, destKey: string): Promise<FileMetadata>movemove(sourceKey: string, destKey: string): Promise<FileMetadata>existsexists(key: string): Promise<boolean>listlist(options?: ListOptions): Promise<FileMetadata[]>signedUrlsignedUrl(key: string, options?: SignedUrlOptions): Promise<string>verifySignedUrlverifySignedUrl(key: string, exp: number, sig: string, method?: ): booleanVerifies an HMAC signature and expiration timestamp for a local file request.
- key
- Target file key.
- exp
- Expiration epoch timestamp (in seconds).
- sig
- HMAC-SHA256 signature token.
- method
- Expected HTTP method (`"GET"` or `"PUT"`).
Returns `true` if signature matches and is not expired; otherwise `false`.
publicUrlpublicUrl(key: string): string
PreconditionFailedError
classThrown when an HTTP conditional precondition (`If-Match` or `If-None-Match`) fails.
class PreconditionFailedError extends StorageErrorPutBuilder
classFluent builder for complex file upload configurations, content-addressed hashing,
class PutBuilder15 members
fromfrom(data: UploadInput): thisSupplies the payload data to be stored.
- data
- Upload data (File, Buffer, Stream, Object, etc.).
withContentTypewithContentType(type: string): thisDeclares an explicit MIME Content-Type.
withMetadatawithMetadata(meta: Record<string, string>): thisAttaches custom user metadata key-values.
asPublicasPublic(): thisMarks the upload as publicly readable (`acl: "public-read"`).
asPrivateasPrivate(): thisMarks the upload as private (`acl: "private"`).
maxSizemaxSize(limit: HumanSize): thisSets a maximum allowed byte size threshold.
verifyMagicverifyMagic(): thisEnables binary header magic byte validation against the declared MIME type.
ifExistsifExists(policy: OverwritePolicy): thisConfigures overwrite handling (`"replace"`, `"error"`, or `"skip"`).
overwriteoverwrite(allowed?: ): thisControls whether an existing file can be overwritten.
- allowed
- If `true`, replaces existing file; if `false`, throws error on collision.
noOverwritenoOverwrite(): thisDisallows overwriting an existing file (throws on collision).
ifMatchifMatch(etag: string): thisSets an `If-Match` ETag precondition for atomic updates.
ifNoneMatchifNoneMatch(pattern?: ): thisSets an `If-None-Match` precondition (use `"*"` to ensure the file does not already exist).
uniqueunique(): thisGenerates a collision-free filename by appending a timestamp and random hex suffix.
hashNamehashName(): thisEnables content-addressed storage: names the file using its SHA-256 hash in a sharded folder (`sha256/xx/yy/<hash>.ext`).
savesave(): Promise<FileMetadata>Executes the upload and returns file metadata.
S3StorageDriver
classStorage driver connecting directly to AWS S3, Cloudflare R2, or MinIO via `Bun.S3Client`.
class S3StorageDriver implements IStorageDriver14 members
clientpropertyclient: S3Clientbucketpropertybucket: stringcustomPublicUrlpropertycustomPublicUrl?: stringuploadupload(key: string, data: UploadInput, options?: UploadOptions): Promise<FileMetadata>downloaddownload(key: string): Promise<StorageFile>headhead(key: string): Promise<FileMetadata>deletedelete(key: string): Promise<void>deleteManydeleteMany(keys: string[]): Promise<void>copycopy(sourceKey: string, destKey: string): Promise<FileMetadata>movemove(sourceKey: string, destKey: string): Promise<FileMetadata>existsexists(key: string): Promise<boolean>listlist(options?: ListOptions): Promise<FileMetadata[]>signedUrlsignedUrl(key: string, options?: SignedUrlOptions): Promise<string>publicUrlpublicUrl(key: string): string
SignBuilder
classFluent builder for generating signed URLs.
class SignBuilder5 members
expiresInexpiresIn(time: HumanTime): thisSets the validity period of the signed URL.
- time
- Duration string (e.g. `"15m"`, `"2h"`, `"7d"`) or raw seconds.
forUploadforUpload(contentType?: string): thisConfigures the signed URL for uploading files via HTTP PUT.
- contentType
- Expected MIME type of the uploaded file.
forDownloadforDownload(): thisConfigures the signed URL for downloading files via HTTP GET (default).
getget(): Promise<string>Generates and returns the cryptographic signed URL.
signedsigned(): Promise<string>Alias for .
StorageDisk
classPrimary storage disk instance managing file storage, validation, security, and streaming.
class StorageDisk17 members
filefile(key: string): FileRefReturns a fluent targeting a specific file key.
putput(key: string): PutBuilderReturns a to upload and configure a file.
signsign(key: string): SignBuilderReturns a to generate a signed URL for a key.
folderfolder(prefix: string): FolderRefReturns a scoping operations to a virtual directory prefix.
uploadupload(key: string, data: UploadInput, options?: UploadOptions): Promise<FileMetadata>Uploads and stores a file, applying MIME checking, size limits, magic-byte inspection,
Processing Pipeline: 1. MIME resolution and pattern validation. 2. Size limit checks and proactive stream capping. 3. Non-destructive binary magic-byte verification (rewinds stream on completion). 4. Overwrite policy and HTTP precondition evaluation (`If-Match`, `If-None-Match`).
- key
- Target storage key.
- data
- Payload data.
- options
- Upload options.
Returns Metadata for the stored file.
downloaddownload(key: string): Promise<StorageFile>Downloads a file and returns a instance for reading or streaming.
- key
- Target storage key.
headhead(key: string): Promise<FileMetadata>Retrieves file metadata without downloading the body content.
- key
- Target storage key.
statstat(key: string): Promise<FileMetadata>Alias for .
deletedelete(key: string): Promise<void>Deletes a file by key.
deleteManydeleteMany(keys: string[]): Promise<void>Deletes multiple files concurrently.
copycopy(source: string, destination: string): Promise<FileMetadata>Copies a file to a new destination key.
movemove(source: string, destination: string): Promise<FileMetadata>Moves / renames a file to a new destination key.
existsexists(key: string): Promise<boolean>Checks whether a file exists.
listlist(options?: ListOptions): Promise<FileMetadata[]>Lists files matching optional prefix constraints.
searchsearch(options: SearchOptions): Promise<FileMetadata[]>Searches for files by prefix, MIME type, and size range.
signedUrlsignedUrl(key: string, options?: SignedUrlOptions): Promise<string>Generates a time-limited cryptographic signed URL for temporary file access.
publicUrlpublicUrl(key: string): stringReturns the public HTTP URL for the given key.
StorageError
classBase error class thrown by Yatta Storage operations.
class StorageError extends ErrorStorageFile
classHigh-performance file handle providing reading, parsing, and RFC 9110 compliant HTTP delivery.
class StorageFile8 members
streamstream(): ReadableStream<Uint8Array>Returns a fresh `ReadableStream<Uint8Array>` of the file contents.
arrayBufferarrayBuffer(): Promise<ArrayBuffer>Reads and resolves the entire file as an `ArrayBuffer`.
bufferbuffer(): Promise<Buffer>Reads and resolves the entire file as a Node.js / Bun `Buffer`.
texttext(): Promise<string>Reads and decodes the entire file as a UTF-8 text string.
jsonjson<T = unknown>(): Promise<T>Reads, decodes, and parses the file contents as JSON.
blobblob(): Promise<Blob>Reads and wraps the file contents as a WHATWG `Blob` with the correct MIME type.
serveserve(requestOrRange?: Request | string | null, options?: ServeOptions): ResponseGenerates a fully compliant WHATWG HTTP `Response` implementing RFC 9110 HTTP streaming.
Handles: - `200 OK`: Standard full-body delivery. - `206 Partial Content`: Byte-range requests (`Range: bytes=start-end`, suffix ranges). - `304 Not Modified`: Conditional checks (`If-None-Match`, `If-Modified-Since`). - `416 Range Not Satisfiable`: Out-of-bounds byte ranges. - `HEAD`: Validates metadata and headers without streaming body content.
- requestOrRange
- Incoming `Request` object, raw `Range` header string, or `null`.
- options
- Delivery options (cache control, content disposition, download name).
Returns Configured WHATWG `Response`.
toResponsetoResponse(requestOrRange?: Request | string | null, init?: ResponseInit): ResponseConvenience alias for `.serve(requestOrRange, { headers: init.headers })`.
- requestOrRange
- Incoming `Request` or range header.
- init
- Standard `ResponseInit` headers.
Returns Configured WHATWG `Response`.
StorageManager
classMulti-disk manager coordinating local filesystems, S3/R2 cloud storage,
class StorageManager13 members
diskspropertydisks:defaultDiskNamepropertydefaultDiskName:authorizerpropertyauthorizer?: StorageAuthorizercreateDiskcreateDisk(cfg: DriverConfig, security?: StorageSecurityConfig, fallbackSecret?: string): StorageDiskdiskdisk<D extends RegisteredDisks = RegisteredDisks>(name?: D): StorageDiskSelects a configured storage disk by name.
- name
- Name of the target disk. Defaults to the configured default disk.
Returns The corresponding .
defaultDiskgetterdefaultDisk: StorageDiskReturns the primary default storage disk.
filefile(key: string): FileRefReturns a targeting a key on the default disk.
putput(key: string): PutBuilderReturns a for writing a file on the default disk.
signsign(key: string): SignBuilderReturns a for generating a signed URL on the default disk.
folderfolder(prefix: string): FolderRefReturns a scoping operations to a virtual directory on the default disk.
searchsearch(options: SearchOptions): Promise<FileMetadata[]>Searches for files matching criteria on the default disk.
renderUIrenderUI(options?: { title?: string; mountPath?: string; }): ResponseRenders the embedded zero-dependency Storage Explorer web dashboard.
- options
- Optional page title and mount path.
Returns Complete HTML `Response`.
handleRequesthandleRequest(req: Request, prefix?: ): Promise<Response>High-Performance Unified Request Router.
Routes handled: - `GET <prefix>/`: Renders the Storage Explorer UI. - `GET <prefix>/api/files`: Lists files on the default disk. - `POST <prefix>/api/upload`: Handles multipart form file uploads. - `DELETE <prefix>/api/files?path=<key>`: Deletes a file. - `GET <prefix>/api/signed?path=<key>`: Generates a temporary signed URL. - `GET <prefix>/files/signed`: Serves files verified against cryptographic signed URLs. - `GET <prefix>/files/<key>`: Direct HTTP streaming delivery with byte-range support.
- req
- Incoming HTTP `Request`.
- prefix
- URL prefix mount path (defaults to `"/storage"`).
Returns Generated WHATWG `Response`.
StorageSecurityError
classThrown when a path traversal attempt, null byte injection, or unauthorized access is detected.
class StorageSecurityError extends StorageErrorTypes
BaseDriverConfig
interfaceCommon configuration shared across all storage drivers.
interface BaseDriverConfig1 member
publicUrlpropertypublicUrl?: stringPublic base URL prefix used to generate public access URLs (e.g. `"/storage/files"`).
FileMetadata
interfaceStandard file metadata contract returned by storage operations.
interface FileMetadata7 members
pathpropertypath: stringRelative storage key (e.g. `"avatars/user.png"`).
sizepropertysize: numberTotal file size in bytes.
contentTypepropertycontentType: stringResolved or declared MIME type (e.g. `"image/png"`).
lastModifiedpropertylastModified: DateTimestamp when the file was last modified.
etagpropertyetag?: stringHTTP entity tag for caching and concurrency control.
urlpropertyurl: stringPublicly resolvable URL to access the file.
metadatapropertymetadata?: Record<string, string>Optional custom user-defined metadata key-value pairs.
IStorageDriver
interfaceCommon driver interface implemented by all storage backends (Local Disk, S3, R2, MinIO).
interface IStorageDriver11 members
uploadupload(key: string, data: UploadInput, options?: UploadOptions): Promise<FileMetadata>Uploads and stores a file.
downloaddownload(key: string): Promise<StorageFile>Downloads and returns a file handle.
headhead(key: string): Promise<FileMetadata>Retrieves file metadata without downloading the body.
deletedelete(key: string): Promise<void>Deletes a single file by key.
deleteManydeleteMany(keys: string[]): Promise<void>Deletes multiple files concurrently.
copycopy(sourceKey: string, destKey: string): Promise<FileMetadata>Copies a file from source key to destination key.
movemove(sourceKey: string, destKey: string): Promise<FileMetadata>Moves a file from source key to destination key.
existsexists(key: string): Promise<boolean>Checks if a file exists.
listlist(options?: ListOptions): Promise<FileMetadata[]>Lists files matching optional prefix constraints.
signedUrlsignedUrl(key: string, options?: SignedUrlOptions): Promise<string>Generates a time-limited signed URL for temporary access.
publicUrlpublicUrl(key: string): stringGenerates the public HTTP URL for the file key.
ListOptions
interfaceOptions for directory and prefix listings.
interface ListOptions3 members
prefixpropertyprefix?: stringFilter results to keys starting with this prefix.
limitpropertylimit?: numberMaximum number of files to return (defaults to 1000).
cursorpropertycursor?: stringPagination continuation token.
LocalDriverConfig
interfaceConfiguration options for the local filesystem storage driver.
interface LocalDriverConfig3 members
driverpropertydriver: "local"Storage driver discriminant.
baseDirpropertybaseDir: stringRoot directory on the local filesystem where files will be stored.
secretpropertysecret?: stringSecret key used to sign and verify HMAC URLs for this disk.
MultiDiskStorageConfig
interfaceMulti-disk storage configuration contract.
interface MultiDiskStorageConfig5 members
defaultpropertydefault?: stringName of the default disk used when none is specified.
diskspropertydisks: Record<string, DriverConfig>Named map of configured storage disks.
securitypropertysecurity?: StorageSecurityConfigGlobal security policy applied across all disks.
secretpropertysecret?: stringFallback cryptographic secret for URL signing.
authorizepropertyauthorize?: StorageAuthorizerGlobal authorization guard for request handling.
S3DriverConfig
interfaceConfiguration options for the S3 / Cloudflare R2 / MinIO storage driver.
interface S3DriverConfig7 members
driverpropertydriver: "s3"Storage driver discriminant.
bucketpropertybucket: stringTarget S3 bucket name.
accessKeyIdpropertyaccessKeyId?: stringAWS or S3 access key ID.
secretAccessKeypropertysecretAccessKey?: stringAWS or S3 secret access key.
endpointpropertyendpoint?: stringCustom endpoint URL for MinIO, Cloudflare R2, or Wasabi (e.g. `https://<account>.r2.cloudflarestorage.com`).
regionpropertyregion?: stringAWS region (defaults to `"us-east-1"`).
sessionTokenpropertysessionToken?: stringOptional AWS STS session token.
SearchOptions
interfaceFilter criteria for disk search operations.
interface SearchOptions5 members
prefixpropertyprefix?: stringSearch within this prefix / directory path.
typepropertytype?: stringMIME type pattern filter (e.g. `"image/*"`, `"video/mp4"`).
minSizepropertyminSize?: HumanSizeMinimum file size threshold (e.g. `"1MB"`).
maxSizepropertymaxSize?: HumanSizeMaximum file size threshold (e.g. `"50MB"`).
limitpropertylimit?: numberMaximum result count limit (defaults to 1000).
ServeOptions
interfaceOptions for rendering HTTP streaming responses via `.serve()`.
interface ServeOptions4 members
cacheControlpropertycacheControl?: stringHTTP `Cache-Control` header directive (e.g. `"public, max-age=31536000, immutable"`).
dispositionpropertydisposition?: "inline" | "attachment"HTTP `Content-Disposition` delivery mode (`"inline"` or `"attachment"`).
downloadNamepropertydownloadName?: stringCustom filename supplied for downloads. Defaults to the key's base filename.
headerspropertyheaders?: HeadersInitAdditional custom response headers to merge.
SignedUrlOptions
interfaceOptions for generating temporary cryptographic signed URLs.
interface SignedUrlOptions3 members
expiresInpropertyexpiresIn?: HumanTimeLifetime of the URL before expiring. Defaults to `"1h"`.
methodpropertymethod?: "GET" | "PUT"HTTP method permitted by this signed URL (`"GET"` or `"PUT"`). Defaults to `"GET"`.
contentTypepropertycontentType?: stringRequired Content-Type for PUT upload signatures.
StorageAuthContext
interfaceContext payload passed to callbacks for access control checks.
interface StorageAuthContext4 members
requestpropertyrequest: RequestIncoming HTTP request triggering the action.
actionpropertyaction: StorageActionAction being attempted.
keypropertykey?: stringTarget file key or path, if applicable.
diskpropertydisk?: stringTarget disk identifier.
StorageRegister
interfaceAugment this interface in application code for strict autocomplete across named disks:
interface StorageRegisterdeclare module "./storage" { interface StorageRegister { disks: "local" | "s3" | "backups" | "uploads"; }}StorageSecurityConfig
interfaceGlobal disk security and validation constraints.
interface StorageSecurityConfig5 members
maxUploadSizepropertymaxUploadSize?: HumanSizeGlobal maximum upload size cap.
allowedTypespropertyallowedTypes?: string[]Whitelisted MIME types or patterns allowed for upload.
verifyMimepropertyverifyMime?: booleanGlobally enforce magic-byte signature validation on uploads.
rejectUnknownMimepropertyrejectUnknownMime?: booleanAutomatically reject generic `"application/octet-stream"` uploads.
signedUrlspropertysignedUrls?: booleanRestrict file access strictly to signed URLs.
UploadOptions
interfaceOptions for configuring upload operations.
interface UploadOptions9 members
contentTypepropertycontentType?: stringExplicit MIME type override. Defaults to auto-detection from file extension or content.
metadatapropertymetadata?: Record<string, string>Arbitrary string metadata key-values attached to the file.
maxSizepropertymaxSize?: HumanSizeUpper bound size limit (e.g. `"10MB"`, `5242880`). Breaching throws a 413 error.
allowedTypespropertyallowedTypes?: string[]List of permitted MIME types or wildcards (e.g. `["image/*", "application/pdf"]`).
aclpropertyacl?: "public-read" | "private"S3 Access Control List setting.
verifyMagicBytespropertyverifyMagicBytes?: booleanPerform non-destructive binary header inspection to verify MIME authenticity.
ifExistspropertyifExists?: OverwritePolicyAction taken if destination key exists: `"replace"`, `"error"`, or `"skip"`.
ifMatchpropertyifMatch?: stringPerform conditional write only if destination ETag matches this value.
ifNoneMatchpropertyifNoneMatch?: stringPerform conditional write only if destination does not match (e.g. `"*"` to forbid overwrite).
DriverConfig
typeUnion of driver configuration types.
type DriverConfig = LocalDriverConfig | S3DriverConfigHumanSize
typeHuman-readable byte size string or raw size in bytes.
Supported units: - `"B"`: Bytes - `"KB"`: Kilobytes (1024 B) - `"MB"`: Megabytes (1024 KB) - `"GB"`: Gigabytes (1024 MB) - `"TB"`: Terabytes (1024 GB)
type HumanSize = `${number}${"B" | "KB" | "MB" | "GB" | "TB"}` | numberHumanTime
typeHuman-readable duration string or raw duration in **seconds**.
Supported units: - `"s"`: Seconds - `"m"`: Minutes - `"h"`: Hours - `"d"`: Days - `"w"`: Weeks
type HumanTime = `${number}${"s" | "m" | "h" | "d" | "w"}` | numberOverwritePolicy
typeStrategy applied when writing to a key that already exists:
type OverwritePolicy = "replace" | "error" | "skip"Prettify
typeHelper type to flatten complex intersected types for cleaner IDE hover tooltips.
type Prettify<T> = { [K in keyof T]: T[K]; } & {}RegisteredDisks
typeResolves the union of configured disk names from , or falls back to generic `string`.
type RegisteredDisks = StorageRegister extends { disks: infer D extends string; } ? D : stringStorageAction
typeGranular storage operations checked during authorization hooks.
type StorageAction = "read" | "write" | "delete" | "list" | "sign"StorageAuthorizer
typeAuthorization guard function returning `true` to allow or `false` to deny storage actions.
type StorageAuthorizer = (ctx: StorageAuthContext) => Promise<boolean> | booleanStorageConfig
typeCombined configuration accepted by `createStorage`.
type StorageConfig = DriverConfig | (MultiDiskStorageConfig & { driver?: never; })StorageProxy
typeAmbient proxy type combining and methods.
type StorageProxy = StorageManager & StorageDiskUploadInput
typePermitted input types for upload operations.
type UploadInput = File | Blob | Uint8Array | ArrayBuffer | Buffer | ReadableStream<Uint8Array> | string | Record<string, unknown> | unknown[]AuthConfig or JobPayload — declaring your schema once is enough for the rest to follow. See Typed keys.