UNPKG

@adonis-agora/media

Version:

Media-library for AdonisJS — owner collections (MIME whitelist, single-file replace, ordering), image conversions (eager/lazy), pluggable content transformers (HLS video via mediabunny, metadata probe, image blur-up placeholder), and column attachments, a

197 lines • 10.8 kB
import type { MediaIdentityResolver } from './access.js'; import { type ResolvedMediaTenancy } from './agora/tenancy.js'; import { AttachmentManager } from './attachment.js'; import type { DeliveryMode, OnDemandImageConfig } from './delivery.js'; import type { DeliverySigningConfig } from './delivery_signing.js'; import { DirectUploadManager } from './direct_upload.js'; import type { ImageProcessor } from './image_processor.js'; import { MediaAccess } from './media_access.js'; import type { MediaCollectionConfig, MediaCollectionRegistry } from './media_collection.js'; import type { AttachExistingInput } from './media_library.js'; import { MediaLibrary } from './media_library.js'; import type { MediaRecord } from './media_record.js'; import type { MediaStore } from './media_store.js'; import type { UploadSessionStore } from './resumable_upload.js'; import { ResumableUploadManager } from './resumable_upload.js'; import { StorageManager } from './storage_manager.js'; import { MediaFake, type MediaFakeOptions } from './testing/media_fake.js'; import type { DiskResolver, MultipartPart } from './types.js'; import { type AbortDirectUploadInput, type CompleteDirectUploadInput, type DirectUploadCreated, type InitiateDirectUploadInput, type ProxyUploadInput, UploadManager } from './upload_manager.js'; import type { UploadMode } from './upload_mode.js'; export interface MediaManagerOptions { /** Default disk name (resolved by `resolve`). */ defaultDisk: string; /** Resolves a disk by name — `(name) => drive.use(name)` in production. */ resolve: DiskResolver; store: MediaStore; imageProcessor?: ImageProcessor; collections?: readonly MediaCollectionConfig[]; /** Who the current user is, for `media.access` (`access.identity`). Default: `ctx.auth.user`. */ accessIdentity?: MediaIdentityResolver; attachmentKeyPrefix?: string; emitDiagnostics?: boolean; /** Default upload mode for direct-S3 uploads (`auto`/`proxy`/`direct`). Default `auto`. */ uploadMode?: UploadMode; /** Default multipart part size in bytes (direct mode). Default 8 MiB. */ uploadPartSize?: number; /** Presigned part-URL TTL in seconds (direct mode). Default 3600. */ uploadPresignTtlSeconds?: number; /** * Session store for resumable (TUS) uploads. When provided, `media.resumable` exposes a * {@link ResumableUploadManager}; when omitted, accessing `media.resumable` throws a helpful error. */ uploadSessions?: UploadSessionStore; /** Prefix for temporary resumable chunk parts on the target disk. Default `.uploads`. */ resumableTmpPrefix?: string; /** Resumable session lifetime in seconds (TUS `expiration`). Omit for never-expiring sessions. */ resumableSessionTtlSeconds?: number; /** * Session store for session-backed direct uploads. When provided, `media.direct` exposes a * {@link DirectUploadManager}; when omitted, accessing `media.direct` throws a helpful error. * May be the very same store instance (or the same Lucid tables) as `uploadSessions`. */ directUploadSessions?: UploadSessionStore; /** Default part size for session-backed direct uploads. Default 20 MiB. */ directPartSize?: number; /** Presigned part-URL TTL in seconds for session-backed direct uploads. Default 3600. */ directPresignTtlSeconds?: number; /** Direct session lifetime in seconds. Omit for never-expiring sessions. */ directSessionTtlSeconds?: number; /** Default read strategy (`auto`/`public`/`signed`/`proxy`) for `library.deliver`. Default `auto`. */ deliveryMode?: DeliveryMode; /** Signed-URL lifetime in seconds when delivery resolves to `signed`. Default 300. */ deliverySignedTtlSeconds?: number; /** On-demand resizing for `library.deliver(id, { width })` (`delivery.images`). */ deliveryImages?: OnDemandImageConfig; /** Signed delivery URLs (`delivery.signing`). */ deliverySigning?: DeliverySigningConfig; /** Route of the delivery handler, with `:id` (`delivery.path`). */ deliveryPath?: string; /** Route of the stream handler, with `:id` and `:conversion` (`delivery.streamPath`). */ deliveryStreamPath?: string; /** Organizations as tenants, resolved (`tenancy` in `config/media.ts`). Default: off. */ tenancy?: ResolvedMediaTenancy; } /** * The singleton bound into the AdonisJS container as `MediaManager`. Composes the two layers over a * shared {@link StorageManager}: {@link MediaLibrary} (owner collections + conversions) and * {@link AttachmentManager} (column attachments). * * ```ts * const media = await app.container.make(MediaManager) * await media.library.attach({ ownerType: 'Post', ownerId: '1', collection: 'gallery', ... }) * const att = await media.attachments.createFromFile({ fileName, mimeType, contents }) * ``` */ export declare class MediaManager { #private; constructor(options: MediaManagerOptions); /** Storage façade the layers resolve disks through. */ get storage(): StorageManager; /** Owner collections + conversions. While {@link fake} is active, the recording in-memory twin. */ get library(): MediaLibrary; /** Authorization for media: the delivery route, authorized `image()`, `authorize()`/`can()`. */ get access(): MediaAccess; /** Column attachments. */ get attachments(): AttachmentManager; /** * The configured persistence SPI. Exposed for management/console reads (e.g. the cross-owner * {@link MediaStore.list}); day-to-day writes go through {@link MediaManager.library}. */ get store(): MediaStore; /** Organizations as tenants, as resolved from `config/media.ts` and `config/context.ts`. */ get tenancy(): ResolvedMediaTenancy; /** Direct-S3 upload coordinator (proxy + direct multipart modes). */ get uploads(): UploadManager; /** * Swap the whole manager onto in-memory doubles — the `drive.fake()` / `mail.fake()` of this * package. Because the swap happens INSIDE the manager, code that already holds it (the * `@adonis-agora/media/services/main` singleton, captured once at boot) sees the fake too. * * The twin runs the real {@link MediaLibrary} with this manager's collections and delivery * settings over an `InMemoryMediaStore`, in-memory disks for every disk name and a * `FakeImageProcessor`, so attach/list/deliver/signedUrl/delete keep their real semantics. Every * `media.library` call is recorded on the returned {@link MediaFake}, which can also stub a method. * * Calling it again replaces the previous fake with a fresh one. Undo with {@link restore}. * * ```ts * const fake = media.fake() * // ... exercise the app ... * fake.assertCalled('delete', (id) => id === record.id) * media.restore() * ``` */ fake(options?: MediaFakeOptions): MediaFake; /** Undo {@link fake}: the real store, disks and library are back. A no-op when not faked. */ restore(): void; /** * The resumable (TUS) upload coordinator. Throws {@link ResumableUploadsNotConfiguredError} unless * a session store was configured via `uploads.resumable` in `config/media.ts`. */ get resumable(): ResumableUploadManager; /** * Finish a resumable (TUS) upload and register the assembled object as a media record, in one * step and without ever reading the uploaded bytes back: `resumable.complete()` returns the final * `{ key, disk, size }`, which {@link MediaLibrary.attachExisting} adopts as-is. * * This lives here because the two layers meet only at the manager — {@link ResumableUploadManager} * knows nothing of the library. It is opt-in: {@link resumable}'s `complete()` stays the raw * primitive for uploads that should NOT become library assets. * * ```ts * await media.completeUploadToLibrary(sessionId, { * ownerType: 'Post', ownerId: post.id, collection: 'gallery', * fileName: 'scan.pdf', mimeType: 'application/pdf', * }) * ``` */ completeUploadToLibrary(sessionId: string, input: Omit<AttachExistingInput, 'key' | 'disk' | 'size'>): Promise<MediaRecord>; /** * The session-backed direct upload coordinator. Throws {@link DirectUploadsNotConfiguredError} * unless a session store was configured via `uploads.direct` in `config/media.ts`. */ get direct(): DirectUploadManager; /** Whether session-backed direct uploads are configured (a session store is present). */ get hasDirect(): boolean; /** * Finish a session-backed direct upload and register the assembled object as a media record, in * one step — the direct-mode twin of {@link completeUploadToLibrary}, meeting the two layers at * the manager the same way. `attachExisting` adopts the object zero-copy and re-validates the * collection's whitelist against the REAL bytes (a short head read), so a client that lied about * `contentType` at initiate is caught here, exactly like every other upload path. * * ```ts * await media.completeDirectUploadToLibrary(sessionId, { * ownerType: 'Lesson', ownerId: lesson.id, collection: 'video', * fileName: 'original.mp4', mimeType: 'video/mp4', * }, partsFromClient) * ``` */ completeDirectUploadToLibrary(sessionId: string, input: Omit<AttachExistingInput, 'key' | 'disk' | 'size'>, parts?: MultipartPart[]): Promise<MediaRecord>; /** * The registered collection configs — the single source of truth for `acceptsMimeTypes`. Exposed * so the upload edge (`TusUploadHandler`) can enforce the very same whitelist the library will * enforce at attach time, without the app restating it. */ get collections(): MediaCollectionRegistry; /** Whether resumable (TUS) uploads are configured (a session store is present). */ get hasResumable(): boolean; /** Resolve a raw disk by name (escape hatch to the underlying Drive disk). */ disk(name?: string): import("./types.js").Disk; /** Begin a direct-S3 multipart upload — returns presigned part URLs for the client. */ initiateDirectUpload(input: InitiateDirectUploadInput): Promise<DirectUploadCreated>; /** Assemble the client-uploaded parts into the final object. */ completeDirectUpload(input: CompleteDirectUploadInput): Promise<{ key: string; disk: string; }>; /** Abort an in-flight direct-S3 multipart upload. */ abortDirectUpload(input: AbortDirectUploadInput): Promise<void>; /** Proxy upload: stream bytes through the app to the disk (works on any disk). */ proxyUpload(input: ProxyUploadInput): Promise<{ key: string; disk: string; }>; } //# sourceMappingURL=media_manager.d.ts.map