import type { Readable } from 'node:stream';
import { type ResolvedMediaTenancy } from './agora/tenancy.js';
import { type DeliveryMode, type DeliveryResult, type OnDemandImageConfig } from './delivery.js';
import { type DeliverySigningConfig } from './delivery_signing.js';
import { type FocalPoint, type ImageProcessor } from './image_processor.js';
import { deliverRecord, findUnscoped, imageOfRecord, streamOfRecord } from './internal_symbols.js';
import { type MediaCollectionConfig, MediaCollectionRegistry } from './media_collection.js';
import type { MediaRecord } from './media_record.js';
import type { MediaListPage, MediaOwnerPageOptions, MediaStore } from './media_store.js';
import { type ResponsiveImage, type ResponsiveImageOptions } from './responsive_image.js';
import type { StorageManager } from './storage_manager.js';
import { type MediaStream } from './streaming.js';
import type { SignedUrlOptions } from './types.js';
export interface MediaLibraryOptions {
    storage: StorageManager;
    store: MediaStore;
    collections?: readonly MediaCollectionConfig[];
    /** Engine for image conversions. Required only if collections define conversions. */
    imageProcessor?: ImageProcessor;
    /** Emit `agora:media:*` diagnostics events (default true). */
    emitDiagnostics?: boolean;
    /** Injectable for deterministic tests. Defaults to `randomUUID`. */
    idGenerator?: () => string;
    /** Injectable for deterministic tests. Defaults to `() => new Date()`. */
    clock?: () => Date;
    /** Default read strategy for {@link MediaLibrary.deliver} (`delivery.mode`). Default `auto`. */
    deliveryMode?: DeliveryMode;
    /** Signed-URL lifetime when delivery resolves to `signed`. Default 300s. */
    deliverySignedTtlSeconds?: number;
    /** On-demand resizing for `deliver(id, { width })` (`delivery.images`). */
    deliveryImages?: OnDemandImageConfig;
    /** Signed delivery URLs (`delivery.signing`). */
    deliverySigning?: DeliverySigningConfig;
    /** Route the app mounts `MediaDeliveryHandler` on, with `:id` (`delivery.path`). Default `/media/:id`. */
    deliveryPath?: string;
    /**
     * Route the app mounts `media.access.streamRoute()` on, with `:id` and `:conversion`, WITHOUT
     * the trailing file part (`delivery.streamPath`). Default `/media/:id/stream/:conversion`.
     */
    deliveryStreamPath?: string;
    /**
     * Organizations as tenants (`tenancy` in `config/media.ts`, resolved against `config/context.ts`).
     * Off by default: nothing is stamped, filtered or prefixed.
     */
    tenancy?: ResolvedMediaTenancy;
}
/** What serving one file of a streaming package yields: a manifest's text, or the usual delivery. */
export type StreamFileResult = {
    kind: 'manifest';
    content: string;
    contentType: string;
    fileName: string;
} | DeliveryResult;
export interface AttachInput {
    ownerType: string;
    /** Owner primary key; a numeric Lucid id is accepted and coerced to a string internally. */
    ownerId: string | number;
    collection: string;
    /**
     * Deterministic id segment for the storage key, replacing the generated UUID. Use for
     * idempotent overwrites (e.g. a durable step that re-renders the same file): a fixed id
     * yields a fixed key that the disk overwrites on retry, instead of orphaning the prior
     * object under a fresh UUID.
     */
    id?: string;
    fileName: string;
    mimeType: string;
    contents: Buffer | Readable;
    /** Known byte size; when omitted it is read back from the disk after writing. */
    size?: number;
    name?: string;
    customProperties?: Record<string, unknown>;
    /** Disk override (else collection disk, else storage default). */
    disk?: string;
    /**
     * The tenant the file belongs to, with tenancy on (`null`: none). Default: the active tenant of
     * the request or job.
     */
    tenantId?: string | null;
}
/**
 * Input for {@link MediaLibrary.attachExisting} — the same descriptors as {@link AttachInput}, but
 * pointing at an object that ALREADY lives on the disk (`key`) instead of carrying its `contents`.
 */
export interface AttachExistingInput {
    ownerType: string;
    /** Owner primary key; a numeric Lucid id is accepted and coerced to a string internally. */
    ownerId: string | number;
    collection: string;
    /**
     * Object key that already exists on the disk (e.g. what `resumable.complete()` returned). Its
     * bytes are never read or rewritten — the record simply points at it.
     */
    key: string;
    /** Disk holding {@link key} (else collection disk, else storage default). */
    disk?: string;
    fileName: string;
    mimeType: string;
    /** Known byte size; when omitted it is read from the disk's metadata (a HEAD, not a download). */
    size?: number;
    /** Deterministic id segment, as in {@link AttachInput.id}. Defaults to a generated UUID. */
    id?: string;
    name?: string;
    customProperties?: Record<string, unknown>;
    /**
     * Server-side move the object into the library's canonical layout
     * (`ownerType/ownerId/collection/id/fileName`) instead of registering it where it landed.
     * Default `false` — registering in place is free, while a move costs a backend copy.
     *
     * Requires a disk implementing the {@link ExtendedDisk} surface (its native, server-side
     * `move`); the bytes are NEVER streamed through the app to emulate one. Throws
     * {@link UploadNotSupportedError} on a disk without it.
     */
    moveIntoLayout?: boolean;
    /**
     * The tenant the file belongs to, with tenancy on (`null`: none). Default: the active tenant of
     * the request or job.
     */
    tenantId?: string | null;
}
/** Options for {@link MediaLibrary.deliver}. */
export interface DeliverOptions {
    /** Deliver this named conversion instead of the original (generated lazily if absent). */
    conversion?: string | undefined;
    /** Override the configured `delivery.mode` for this call. */
    mode?: DeliveryMode | undefined;
    /** Override the configured signed-URL lifetime, when the resolved mode is `signed`. */
    signedTtlSeconds?: number | undefined;
    /**
     * Deliver the image resized to this width (see {@link MediaLibrary.resized}). Wins over
     * `conversion`. Strings (a query-string value) are parsed and validated.
     */
    width?: number | string | undefined;
    /** Quality of the resized image; defaults to the first of `delivery.images.qualities`. */
    quality?: number | string | undefined;
    /** The request's `Accept` header, to negotiate the resized image's format. */
    accept?: string | undefined;
    /**
     * The request was authorized by a valid delivery signature (`MediaDeliveryHandler` sets this):
     * any `width`/`quality` is served, not just the `delivery.images` whitelist — the app chose it.
     */
    trusted?: boolean | undefined;
}
/** Options for {@link MediaLibrary.signedUrl}: the disk's response headers, plus a conversion to sign instead of the original. */
export interface MediaSignedUrlOptions extends Omit<SignedUrlOptions, 'expiresIn'> {
    /** Sign this named conversion instead of the original (generated lazily if absent). */
    conversion?: string;
}
/**
 * An owning entity bound to the library, so collection operations don't repeat
 * `ownerType`/`ownerId`. Obtained from {@link MediaLibrary.for}.
 */
export interface OwnerMediaBinding {
    attach(input: Omit<AttachInput, 'ownerType' | 'ownerId'>): Promise<MediaRecord>;
    attachExisting(input: Omit<AttachExistingInput, 'ownerType' | 'ownerId'>): Promise<MediaRecord>;
    list(collection?: string): Promise<MediaRecord[]>;
}
export declare class MediaLibrary {
    #private;
    /**
     * The storage façade the library resolves disks through. Public (read-only) so delivery
     * composition — {@link HlsDeliveryHandler} serving individual package artifacts, custom handlers
     * doing the same — can reach the disk of a record it already holds without re-plumbing a
     * resolver. Writes still belong to the library's own methods.
     */
    readonly storage: StorageManager;
    private readonly store;
    /**
     * Registered collection configs. Public because `acceptsMimeTypes` must have exactly one source
     * of truth: the TUS handler enforces the same whitelist at upload time by reading it from here,
     * rather than the app restating the list next to its routes.
     */
    readonly collections: MediaCollectionRegistry;
    private readonly imageProcessor;
    private readonly emitDiagnostics;
    private readonly newId;
    private readonly now;
    private readonly deliveryMode;
    private readonly deliverySignedTtlSeconds;
    private readonly deliveryImages;
    private readonly deliverySigning;
    private readonly deliveryPath;
    private readonly deliveryStreamPath;
    constructor(options: MediaLibraryOptions);
    private emit;
    attach(input: AttachInput): Promise<MediaRecord>;
    /**
     * Register an object that ALREADY exists on the disk as a media record — zero-copy: its bytes are
     * never read back or rewritten, only its metadata is inspected. The bridge for uploads that land
     * on the disk on their own (`media.resumable` / TUS, direct-S3), where round-tripping the bytes
     * through {@link attach} would defeat the point of a resumable upload.
     *
     * Everything after storage behaves exactly as {@link attach}: collection resolution,
     * `acceptsMimeTypes`, atomic `single: true` replace, ordering, eager conversions and diagnostics.
     *
     * ```ts
     * const { key, disk, size } = await media.resumable.complete(sessionId)
     * await media.library.attachExisting({
     *   ownerType: 'Post', ownerId: post.id, collection: 'gallery',
     *   key, disk, size, fileName: 'scan.pdf', mimeType: 'application/pdf',
     * })
     * ```
     *
     * Unlike {@link attach}, a failure downstream of the object does NOT delete it: the caller wrote
     * those bytes and may retry with them, so only what this call created is rolled back.
     */
    attachExisting(input: AttachExistingInput): Promise<MediaRecord>;
    /** Generate (if absent) and persist a named conversion; returns the updated record. Lazy entry point. */
    ensureConversion(id: string, conversionName: string): Promise<MediaRecord>;
    /**
     * Set (or clear, with `null`) the part of the image every crop must keep — a face in an avatar,
     * the subject of a banner. Stored as `customProperties.focalPoint` (`{ x, y }`, fractions of the
     * displayed image), handed to the processor for every cropping preset (`fit: 'cover'` with both
     * sides), and returned by {@link image} so CSS crops (`object-fit: cover`) keep it too.
     *
     * The cropping conversions already generated are dropped — the eager ones regenerated at once,
     * the lazy ones on next access — since they were cut around the old point.
     *
     * ```ts
     * await media.library.setFocalPoint(user.avatarMediaId, { x: 0.42, y: 0.31 })
     * ```
     */
    setFocalPoint(id: string, point: FocalPoint | null): Promise<MediaRecord>;
    /**
     * Resize the image to one of `delivery.images.widths`, on demand — the server half of a
     * `next/image`-style loader (`?w=640&q=75`). Generated once and kept as the conversion
     * `@w640q75`, so later requests (and `delete()`) treat it like any other conversion. Never
     * enlarges: past the original's width it is the original's size, re-encoded.
     *
     * Returns the conversion to deliver, or `undefined` for an SVG (served as is: it scales by itself).
     * Throws {@link ImageSizeNotAllowedError} outside the whitelist and {@link NotAnImageError} for a
     * record that is not an image.
     */
    resized(id: string, request: {
        width: number | string;
        quality?: number | string | undefined;
        accept?: string | undefined;
        /** Signed by the app: any width/quality in range, not just the whitelist. */
        trusted?: boolean | undefined;
    }): Promise<{
        record: MediaRecord;
        conversion: string | undefined;
    }>;
    /**
     * Run a named {@link Transformer} of the record's collection and persist its output as
     * `record.conversions[name]`. **Idempotent**: an already-generated conversion returns the record
     * untouched, so a retried job skips straight through — the library assumes no queue system, it
     * only guarantees this call is safe to repeat.
     *
     * ```ts
     * // app job (the app owns the queue, retries and any locking):
     * await media.library.transform(payload.mediaId, 'video')
     * ```
     *
     * Deliberately explicit: unlike image presets, a transformer conversion is never generated
     * lazily inside `url()`/`deliver()` — reads on a missing one throw {@link TransformNotReadyError}
     * instead of stalling a request behind a remux. Transformers marked `eager: true` are the
     * exception and run inside attach (see {@link Transformer}).
     *
     * Two concurrent calls for the same media+name both run and the second save wins; the artifacts
     * are deterministic per key, so the result is identical — wasteful, not corrupting. Serialize
     * with your own lock if the double work matters.
     *
     * A mid-flight failure sweeps whatever artifacts were already written (best-effort) and
     * re-throws, so no conversion entry is ever persisted for a half-written package.
     */
    transform(id: string, transformerName: string): Promise<MediaRecord>;
    list(ownerType: string, ownerId: string | number, collection?: string): Promise<MediaRecord[]>;
    find(id: string): Promise<MediaRecord | null>;
    /**
     * One page of an owner's files across `collections`, newest first: what a "my files" screen
     * lists. Pass the previous page's `nextCursor` as `cursor`. With tenancy on, only the active
     * tenant's files.
     *
     * ```ts
     * const page = await media.library.page('User', user.id, { collections: ['avatar', 'documents'] })
     * ```
     */
    page(ownerType: string, ownerId: string | number, options?: MediaOwnerPageOptions): Promise<MediaListPage>;
    /** Change a file's display `name` (not its stored file name or path). Returns the record. */
    rename(id: string, name: string): Promise<MediaRecord>;
    /** {@link find} across every tenant: for a request a delivery signature already authorized. @internal */
    [findUnscoped](id: string): Promise<MediaRecord | null>;
    /**
     * Bind an owning entity so collection operations don't repeat its type/id:
     * `const m = media.library.for('Post', post.id); await m.attach({ collection, ... })`.
     */
    for(ownerType: string, ownerId: string | number): OwnerMediaBinding;
    delete(id: string): Promise<void>;
    /**
     * Public URL for a media record or one of its conversions. When a conversion is
     * requested and not yet generated, it is produced lazily (and cached) first.
     */
    url(id: string, conversion?: string): Promise<string>;
    /**
     * Everything an `<img>` needs to render a stored image like `next/image`: `srcSet` from the
     * collection's presets, the intrinsic `width`/`height` and the blur-up `placeholder` — as plain
     * JSON, for a page prop. Render it with `<MediaImage>` from `@adonis-agora/media-react`.
     *
     * ```ts
     * // config: presets at a few widths (eager, so they exist from the attach on) + the placeholder
     * { name: 'banner', conversions: [{ name: 'sm', width: 640, eager: true }, { name: 'lg', width: 1280, eager: true }],
     *   transformers: [transformers.placeholder()] }
     *
     * return inertia.render('courses/show', { banner: await media.library.image(course.bannerMediaId) })
     * ```
     *
     * The intrinsic size and the original-as-candidate come from the placeholder, so without
     * `transformers.placeholder()` the result has no `width`/`height` and only the presets in
     * `srcSet`. Like {@link url}, this answers "how", not "who": authorize the caller first.
     */
    image(id: string, options?: ResponsiveImageOptions): Promise<ResponsiveImage>;
    /** {@link image} for a record already fetched (by `media.access.image`). @internal */
    [imageOfRecord](fetched: MediaRecord, options?: ResponsiveImageOptions): Promise<ResponsiveImage>;
    /**
     * URL of the delivery route (`delivery.path`, default `/media/:id`) for a record — optionally a
     * conversion, or resized (`width`/`quality`). With `delivery.signing` configured it is signed and
     * expires, and `MediaDeliveryHandler` serves exactly what was signed (any width) and nothing else;
     * without it, a plain route URL (widths limited to `delivery.images`).
     *
     * ```ts
     * media.library.deliveryUrl(id)                 // /media/<id>?exp=…&sig=…
     * media.library.deliveryUrl(id, { width: 640 }) // /media/<id>?w=640&exp=…&sig=…
     * ```
     */
    deliveryUrl(id: string, options?: {
        conversion?: string;
        width?: number;
        quality?: number;
        /** Seconds; overrides `delivery.signing.expiresIn`. */
        expiresIn?: number;
    }): string;
    /**
     * What a player needs to stream a video: the URLs of every HLS/DASH manifest the record's
     * conversions provide (`transformers.video()`), HLS first, through the
     * stream route (`delivery.streamPath`, served by `media.access.streamRoute()`). Pass the result
     * to `useMediaStream` from `@adonis-agora/media-react` as is.
     *
     * With `delivery.signing`, the URLs are signed for the whole package: the route then serves the
     * manifest and every segment it leads to without asking the app again, until they expire. The
     * lifetime is `expiresIn`, else `delivery.signing.expiresIn` — but never shorter than the video
     * plus an hour, so a player does not lose access mid-video.
     *
     * Like {@link image}, this answers "how", not "who": authorize the caller first — or use
     * `media.access.stream(ctx, id)`, which does.
     *
     * Throws {@link TransformNotReadyError} when no streamable conversion exists yet.
     */
    stream(id: string, options?: {
        /** Which conversions to offer, in order. Default: every streamable one. */
        conversions?: readonly string[];
        /** Signed-URL lifetime in seconds (with `delivery.signing`). */
        expiresIn?: number;
    }): Promise<MediaStream>;
    /** {@link stream} for a record already fetched (by `media.access.stream`). @internal */
    [streamOfRecord](record: MediaRecord, options?: {
        conversions?: readonly string[];
        expiresIn?: number;
    }): MediaStream;
    /**
     * URL of one file of a streaming package on the stream route — signed for the whole package
     * with `delivery.signing`. {@link stream} builds the entry URLs with it.
     */
    streamUrl(record: MediaRecord, conversion: string, file: string, options?: {
        expiresIn?: number;
    }): string;
    /**
     * The `exp=…&sig=…` that authorizes every file of one streaming package (no `?`), or `''`
     * without `delivery.signing`. The signature covers the record and the conversion — not a file —
     * so it can ride along on every reference a manifest makes.
     */
    streamQuery(record: MediaRecord, conversion: string, expiresIn?: number): string;
    /**
     * Serve one file of a record's streaming package — the "how" of `media.access.streamRoute()`
     * (authorize first). `file` is checked against the package's persisted artifact list, so a
     * request can never reach outside it.
     *
     * - A **manifest** (`.m3u8`/`.mpd`) comes back as text. Its references are relative and resolve
     *   to the same route, so it is served as stored — plus `query` (a package signature) on every
     *   relative reference when given, which is how segment requests inherit the authorization.
     * - Anything else (segments, init sections) is delivered per `mode` (default `delivery.mode`):
     *   a redirect to the object (signed URLs stay short-lived — they are minted per segment
     *   request), or a stream through the app.
     */
    streamFile(record: MediaRecord, conversion: string, file: string, options?: {
        query?: string | undefined;
        mode?: DeliveryMode | undefined;
        signedTtlSeconds?: number | undefined;
    }): Promise<StreamFileResult>;
    /**
     * Check a delivery request against `delivery.signing`: `true` when it is signed and valid (serve
     * any size it names), `false` when signing is off or the request is unsigned and that is allowed.
     * Throws {@link DeliverySignatureError} for an invalid or expired signature, or a missing one when
     * `delivery.signing.required` (the default). `MediaDeliveryHandler` calls this for you.
     */
    checkDeliverySignature(request: {
        mediaId: string;
        conversion?: string | undefined;
        width?: number | string | undefined;
        quality?: number | string | undefined;
        expires?: number | string | undefined;
        signature?: string | undefined;
    }, options?: {
        /** Override `delivery.signing.required` for this check (a route that authorizes by itself). */
        required?: boolean;
    }): boolean;
    /**
     * Resolve how a media record should reach the client, per the configured `delivery.mode` — the
     * read-side counterpart to `uploads.mode`. Returns either a URL to redirect to (`public`/`signed`)
     * or a {@link Readable} to pipe (`proxy`), so an app on a private bucket with no
     * internet-reachable storage stops hand-rolling a streaming route.
     *
     * Like every other library method this answers "how", NOT "who": authorize the caller first. See
     * {@link MediaDeliveryHandler} for mounting this as a route.
     *
     * ```ts
     * const result = await media.library.deliver(id)
     * if (result.kind === 'redirect') return response.redirect(result.url)
     * response.header('content-type', result.mimeType)
     * return response.stream(result.stream)
     * ```
     */
    deliver(id: string, options?: DeliverOptions): Promise<DeliveryResult>;
    /** {@link deliver} for a record already fetched (by `media.access.serve`). @internal */
    [deliverRecord](record: MediaRecord, options?: DeliverOptions): Promise<DeliveryResult>;
    /**
     * Signed, expiring URL for a media record or one of its conversions.
     *
     * Everything in `options` except `conversion` is a response header the presigner bakes into
     * the URL, so it applies to whoever follows the link rather than to this call:
     * `contentDisposition` is what forces a download with a chosen file name.
     */
    signedUrl(id: string, expiresIn: string | number, options?: MediaSignedUrlOptions): Promise<string>;
}
//# sourceMappingURL=media_library.d.ts.map