@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
453 lines • 22 kB
JavaScript
export class MimeNotAllowedError extends Error {
collection;
mimeType;
accepted;
code = 'E_MEDIA_MIME_NOT_ALLOWED';
constructor(collection, mimeType, accepted) {
super(`MIME type "${mimeType}" is not allowed in collection "${collection}". Allowed: ${accepted.join(', ')}.`);
this.collection = collection;
this.mimeType = mimeType;
this.accepted = accepted;
this.name = 'MimeNotAllowedError';
}
}
/**
* The bytes are not what the caller said they were. Raised when a collection declares
* `acceptsMimeTypes` and the file's magic-byte signature identifies a type that either the
* collection does not accept or that contradicts the declared `mimeType` — the case
* {@link MimeNotAllowedError} cannot catch, because the declared type is written by the app (often
* hardcoded) rather than proven by the content.
*/
export class ContentTypeMismatchError extends Error {
collection;
declaredMimeType;
detectedMimeType;
code = 'E_MEDIA_CONTENT_TYPE_MISMATCH';
constructor(collection, declaredMimeType, detectedMimeType, accepted) {
super(`File contents are actually "${detectedMimeType}" (detected from the file signature), not the declared "${declaredMimeType}". Collection "${collection}" accepts [${accepted.join(', ')}].`);
this.collection = collection;
this.declaredMimeType = declaredMimeType;
this.detectedMimeType = detectedMimeType;
this.name = 'ContentTypeMismatchError';
}
}
/**
* The content carries no recognisable signature, under a collection whose `acceptsMimeTypes` are
* ALL signature-detectable. Distinct from {@link ContentTypeMismatchError}, which reports bytes that
* were positively identified as some other type: here nothing was identified at all, and that is
* itself the proof — if every accepted type is one the signature table can recognise, content it
* cannot recognise is none of them.
*
* A collection that accepts even one signature-less type (`image/svg+xml`, `text/csv`,
* `text/plain`, office formats…) is NOT closed, and unrecognised content there stays accepted.
*/
export class ContentSignatureUnrecognizedError extends Error {
collection;
declaredMimeType;
accepted;
code = 'E_MEDIA_CONTENT_SIGNATURE_UNRECOGNIZED';
constructor(collection, declaredMimeType, accepted) {
super(`File contents carry no recognisable signature${declaredMimeType ? ` for the declared "${declaredMimeType}"` : ''}. Collection "${collection}" accepts only signature-detectable types [${accepted.join(', ')}], so content that matches none of their signatures cannot be any of them.`);
this.collection = collection;
this.declaredMimeType = declaredMimeType;
this.accepted = accepted;
this.name = 'ContentSignatureUnrecognizedError';
}
}
/**
* A media disk was resolved before `@adonisjs/drive` finished booting, so its disk manager does not
* exist yet. Drive's service module assigns the manager inside `app.booted(...)`; reading it any
* earlier yields `undefined`. The media provider resolves it lazily, at first real disk use, so in
* practice this only fires when media is called from outside a booted application.
*/
export class DriveNotReadyError extends Error {
code = 'E_MEDIA_DRIVE_NOT_READY';
constructor(disk) {
super(`Cannot resolve disk "${disk}": the \`@adonisjs/drive\` disk manager is not available yet because the application has not finished booting. Resolve media disks after boot (e.g. inside a request or a \`booted\` hook), or declare the disk in \`disks\` in config/media.ts so it does not go through Drive at all.`);
this.name = 'DriveNotReadyError';
}
}
/**
* A disk that is not in `disks` (config/media.ts) was asked for, and the app does not register
* `@adonisjs/drive` at all, so there is nowhere else to find it.
*/
export class DriveNotConfiguredError extends Error {
code = 'E_MEDIA_DRIVE_NOT_CONFIGURED';
constructor(disk) {
super(`Cannot resolve disk "${disk}": this app does not register \`@adonisjs/drive\`, and "${disk}" is not in \`disks\` in config/media.ts. Declare the disk there (e.g. \`disks.s3({ ... })\`), or install and configure \`@adonisjs/drive\`.`);
this.name = 'DriveNotConfiguredError';
}
}
export class MediaNotFoundError extends Error {
code = 'E_MEDIA_RECORD_NOT_FOUND';
constructor(id) {
super(`Media record not found: ${id}`);
this.name = 'MediaNotFoundError';
}
}
export class MediaObjectMissingError extends Error {
code = 'E_MEDIA_OBJECT_MISSING';
constructor(disk, key) {
super(`No object at key "${key}" on disk "${disk}". \`attachExisting\` registers an object that is already stored — upload it first (e.g. finish the resumable session), or use \`attach\` to write the bytes.`);
this.name = 'MediaObjectMissingError';
}
}
export class ConversionNotDefinedError extends Error {
code = 'E_MEDIA_CONVERSION_NOT_DEFINED';
constructor(collection, conversion) {
super(`Conversion "${conversion}" is not defined for collection "${collection}"`);
this.name = 'ConversionNotDefinedError';
}
}
/**
* A conversion was requested by a name that names neither an image preset nor a transformer of the
* record's collection — the transformer counterpart of {@link ConversionNotDefinedError}, raised by
* `MediaLibrary.transform`.
*/
export class TransformerNotDefinedError extends Error {
code = 'E_MEDIA_TRANSFORMER_NOT_DEFINED';
constructor(collection, transformer) {
super(`Transformer "${transformer}" is not defined for collection "${collection}"`);
this.name = 'TransformerNotDefinedError';
}
}
/**
* A transformer-produced conversion was read (`url` / `deliver` / HLS delivery) before it was
* generated. Deliberately NOT generated lazily on read like image conversions: a transform is
* assumed heavy (a video remux takes minutes), and a read path is the wrong place to pay that.
* Generate it explicitly — `media.library.transform(id, name)` from a job — then read again.
*/
export class TransformNotReadyError extends Error {
mediaId;
transformer;
code = 'E_MEDIA_TRANSFORM_NOT_READY';
constructor(mediaId, transformer) {
super(`Conversion "${transformer}" of media "${mediaId}" has not been generated yet. Transformer conversions are never generated inside a read path — run \`media.library.transform('${mediaId}', '${transformer}')\` (idempotent; call it from a job) and retry.`);
this.mediaId = mediaId;
this.transformer = transformer;
this.name = 'TransformNotReadyError';
}
}
/**
* Two derivatives of one collection claim the same name. Presets and transformers persist into the
* same `record.conversions` map, so the namespace is shared; raised at registry construction (boot),
* not on first attach.
*/
export class TransformerConflictError extends Error {
code = 'E_MEDIA_TRANSFORMER_CONFLICT';
constructor(collection, name) {
super(`Collection "${collection}" defines more than one conversion or transformer named "${name}". Preset and transformer names share the \`record.conversions\` namespace, so each name may appear once per collection.`);
this.name = 'TransformerConflictError';
}
}
/**
* A transformer needs a runtime capability the host doesn't provide — an optional peer that isn't
* installed (`mediabunny`), or an API the runtime lacks (WebCodecs in Node). Thrown by the built-in
* transformers and available for custom ones, so "this environment can't do that" always surfaces
* as one clear, typed error instead of a deep import/undefined crash.
*/
export class TransformerRuntimeMissingError extends Error {
transformer;
requirement;
code = 'E_MEDIA_TRANSFORMER_RUNTIME_MISSING';
constructor(transformer, requirement, hint) {
super(`Transformer "${transformer}" requires ${requirement}, which is not available in this runtime.${hint ? ` ${hint}` : ''}`);
this.transformer = transformer;
this.requirement = requirement;
this.name = 'TransformerRuntimeMissingError';
}
}
/**
* A transformer violated the output contract: wrote outside its prefix (`..`/absolute path),
* declared an `entry` it never wrote, or wrote artifacts without declaring an entry. These are
* programming errors in the transformer, surfaced with the transformer's name so the broken one is
* obvious.
*/
export class TransformerOutputError extends Error {
code = 'E_MEDIA_TRANSFORMER_OUTPUT_INVALID';
constructor(transformer, reason) {
super(`Transformer "${transformer}" produced an invalid output: ${reason}`);
this.name = 'TransformerOutputError';
}
}
/**
* A metadata-only conversion (a probe, a blurhash) was asked for its file — `url`, `signedUrl` or
* `deliver` — but it has no artifact; only `record.conversions[name].meta` exists. Read the record
* instead of a URL.
*/
export class ConversionArtifactMissingError extends Error {
code = 'E_MEDIA_CONVERSION_ARTIFACT_MISSING';
constructor(mediaId, conversion) {
super(`Conversion "${conversion}" of media "${mediaId}" is metadata-only — it has no artifact to deliver. Its result lives on \`record.conversions['${conversion}'].meta\`.`);
this.name = 'ConversionArtifactMissingError';
}
}
/**
* The HLS transformer could not stream-copy the source: a track's codec cannot be carried by the
* segment format (MPEG-TS wants h264/aac), and no re-encode path exists in this runtime. Definitive
* for the file — retrying cannot fix it; re-encode the source, or provide a WebCodecs
* implementation (see `transformers.video({ webcodecs })`).
*/
export class HlsSourceUnsupportedError extends Error {
code = 'E_MEDIA_HLS_SOURCE_UNSUPPORTED';
/**
* @param hint what the caller can do about it; defaults to the mediabunny/WebCodecs advice.
*/
constructor(details, hint = 'Without an encoder (WebCodecs) the tracks can only be stream-copied, so an incompatible codec is definitive — re-encode the source to h264/aac, or configure `transformers.video({ webcodecs })` with a WebCodecs implementation to enable the re-encode fallback.') {
super(`HLS remux is impossible for this source: ${details}. ${hint}`);
this.name = 'HlsSourceUnsupportedError';
}
}
/**
* An `ffmpeg` / `ffprobe` run (the `engines.ffmpeg()` / `engines.ffprobe()` engines) exited
* non-zero or produced something unusable. Carries the exit code and the tail of stderr, which is
* where ffmpeg explains itself (an unsupported codec for a stream copy, a corrupt input).
*/
export class FfmpegFailedError extends Error {
binary;
exitCode;
stderr;
code = 'E_MEDIA_FFMPEG_FAILED';
constructor(binary, exitCode, stderr) {
super(`${binary} failed${exitCode === null ? '' : ` (exit code ${exitCode})`}: ${stderr.trim().split('\n').slice(-5).join('\n')}`);
this.binary = binary;
this.exitCode = exitCode;
this.stderr = stderr;
this.name = 'FfmpegFailedError';
}
}
export class ImageProcessorMissingError extends Error {
code = 'E_MEDIA_IMAGE_PROCESSOR_MISSING';
constructor() {
super('No ImageProcessor was configured; conversions are unavailable');
this.name = 'ImageProcessorMissingError';
}
}
export class VariantNotFoundError extends Error {
code = 'E_MEDIA_VARIANT_NOT_FOUND';
constructor(variant) {
super(`Attachment has no variant "${variant}"`);
this.name = 'VariantNotFoundError';
}
}
export class UploadNotSupportedError extends Error {
code = 'E_MEDIA_UPLOAD_NOT_SUPPORTED';
constructor(disk, operation = 'direct multipart upload') {
super(`Disk "${disk}" does not support ${operation}. Use a multipart-capable disk (e.g. \`disks.s3()\`) or the \`proxy\` upload mode.`);
this.name = 'UploadNotSupportedError';
}
}
export class UploadSessionNotFoundError extends Error {
code = 'E_MEDIA_UPLOAD_SESSION_NOT_FOUND';
constructor(id) {
super(`Upload session not found: ${id}`);
this.name = 'UploadSessionNotFoundError';
}
}
export class UploadOffsetConflictError extends Error {
expected;
received;
code = 'E_MEDIA_UPLOAD_OFFSET_CONFLICT';
constructor(expected, received) {
super(`Upload offset conflict: expected ${expected}, received ${received}`);
this.expected = expected;
this.received = received;
this.name = 'UploadOffsetConflictError';
}
}
export class UploadSessionExpiredError extends Error {
code = 'E_MEDIA_UPLOAD_SESSION_EXPIRED';
constructor(id) {
super(`Upload session has expired: ${id}`);
this.name = 'UploadSessionExpiredError';
}
}
/**
* A part size the S3 multipart API cannot honour: below the 5 MiB minimum (every part but the last
* must reach it, or `CompleteMultipartUpload` fails with `EntityTooSmall` AFTER the client uploaded
* everything), or small enough that the file would need more than the 10,000 parts S3 allows.
* Raised at `initiate`, where it costs nothing — the alternative is discovering it at complete,
* when the whole file has already crossed the wire.
*/
export class UploadPartSizeError extends Error {
code = 'E_MEDIA_UPLOAD_PART_SIZE';
constructor(detail) {
super(`Invalid multipart part size: ${detail}`);
this.name = 'UploadPartSizeError';
}
}
/** A confirmed part number outside `1..totalParts` for the session — a client slicing with the wrong part size. */
export class UploadPartOutOfRangeError extends Error {
partNumber;
totalParts;
code = 'E_MEDIA_UPLOAD_PART_OUT_OF_RANGE';
constructor(partNumber, totalParts) {
super(`Part number ${partNumber} is outside this upload's range (1..${totalParts}). The client must slice the file with the partSize the session was created with.`);
this.partNumber = partNumber;
this.totalParts = totalParts;
this.name = 'UploadPartOutOfRangeError';
}
}
/**
* `complete()` was asked to assemble an upload whose parts are not all accounted for (neither
* confirmed to the session nor supplied in the call). Failing fast here names the EXACT missing
* part numbers; letting S3 discover it returns an opaque `InvalidPart` after a round-trip.
*/
export class UploadPartsIncompleteError extends Error {
sessionId;
missingParts;
code = 'E_MEDIA_UPLOAD_PARTS_INCOMPLETE';
constructor(sessionId, missingParts) {
super(`Cannot complete upload session ${sessionId}: no ETag for part(s) ${missingParts.join(', ')}. Upload and confirm them (or pass them to complete()) first — status() lists what is pending.`);
this.sessionId = sessionId;
this.missingParts = missingParts;
this.name = 'UploadPartsIncompleteError';
}
}
/**
* A client-supplied upload file name is unsafe to interpolate into a storage key: it contains a
* path separator (so, after normalizing `\` to `/`, more than one segment), resolves to `.`/`..`,
* is empty, or carries a control character. Raised by {@link sanitizeFileName} before the name ever
* reaches a storage key — `MediaLibrary`'s `attach`/`attachExisting`, the default `keyFor` of
* `DirectUploadHandler` and `TusUploadHandler`, and `AttachmentManager#createFromFile` — so a
* traversal attempt (`../../etc/passwd`) or an absolute path never gets the chance to escape the
* upload's directory. Mirrors
* {@link TransformerOutputError}'s stance on hostile-shaped paths: reject outright, never silently
* normalize into place.
*/
export class UnsafeFileNameError extends Error {
fileName;
code = 'E_MEDIA_UNSAFE_FILE_NAME';
constructor(fileName) {
super(`File name "${fileName}" is not a valid upload file name: it must be a single path segment ` +
'(no "/" or "\\"), not "." or "..", not empty, and free of control characters.');
this.fileName = fileName;
this.name = 'UnsafeFileNameError';
}
}
export class DirectUploadsNotConfiguredError extends Error {
code = 'E_MEDIA_DIRECT_NOT_CONFIGURED';
constructor() {
super("Session-backed direct uploads are not configured. Set `uploads.direct` in config/media.ts (e.g. `direct: { store: 'lucid', stores: { lucid: uploadSessions.lucid() } }`) to enable the direct upload session store.");
this.name = 'DirectUploadsNotConfiguredError';
}
}
export class ResumableUploadsNotConfiguredError extends Error {
code = 'E_MEDIA_RESUMABLE_NOT_CONFIGURED';
constructor() {
super("Resumable (TUS) uploads are not configured. Set `uploads.resumable` in config/media.ts (e.g. `resumable: { store: 'lucid', stores: { lucid: uploadSessions.lucid() } }`) to enable the resumable upload session store.");
this.name = 'ResumableUploadsNotConfiguredError';
}
}
export class StoreNotConfiguredError extends Error {
code = 'E_MEDIA_STORE_NOT_CONFIGURED';
constructor(name) {
super(`Media config selects store "${name}" but no matching factory exists in \`stores\`. Add \`stores.${name}\` to config/media.ts (e.g. \`stores: { ${name}: stores.lucid() }\`), or omit \`store\` to use the in-memory store.`);
this.name = 'StoreNotConfiguredError';
}
}
export class UploadSessionStoreNotConfiguredError extends Error {
code = 'E_MEDIA_UPLOAD_SESSION_STORE_NOT_CONFIGURED';
constructor(name) {
super(`Media config selects resumable session store "${name}" but no matching factory exists in \`uploads.resumable.stores\`. Add \`uploads.resumable.stores.${name}\` to config/media.ts (e.g. \`stores: { ${name}: uploadSessions.lucid() }\`), or omit \`store\` to use the in-memory session store.`);
this.name = 'UploadSessionStoreNotConfiguredError';
}
}
/**
* A resize was requested at a width or quality outside `delivery.images` — the whitelist that stops
* a client from filling the storage with one cached variant per arbitrary size. Map it to a 400.
*/
export class ImageSizeNotAllowedError extends Error {
field;
value;
allowed;
code = 'E_MEDIA_IMAGE_SIZE_NOT_ALLOWED';
constructor(field, value, allowed) {
super(`Image ${field} ${JSON.stringify(value)} is not allowed. Allowed: ${allowed.join(', ')} (delivery.images.${field === 'width' ? 'widths' : 'qualities'}).`);
this.field = field;
this.value = value;
this.allowed = allowed;
this.name = 'ImageSizeNotAllowedError';
}
}
/** A resize (`?w=`) was requested for a record that is not a raster image. Map it to a 400. */
export class NotAnImageError extends Error {
mediaId;
mimeType;
code = 'E_MEDIA_NOT_AN_IMAGE';
constructor(mediaId, mimeType) {
super(`Media "${mediaId}" is "${mimeType}", not an image that can be resized.`);
this.mediaId = mediaId;
this.mimeType = mimeType;
this.name = 'NotAnImageError';
}
}
/**
* A delivery request failed signature checking (`delivery.signing`): it carries no signature while
* one is required (`missing`), the signature does not match the request (`invalid` — any
* parameter changed, or a URL signed with another key), or it expired (`expired`). Map it to a 403.
*/
export class DeliverySignatureError extends Error {
reason;
code = 'E_MEDIA_DELIVERY_SIGNATURE';
constructor(reason) {
super(reason === 'missing'
? 'This media URL must be signed (delivery.signing.required).'
: reason === 'expired'
? 'This media URL has expired.'
: 'This media URL has an invalid signature.');
this.reason = reason;
this.name = 'DeliverySignatureError';
}
}
/**
* A media read or write was refused by its authorization rule (`media.access`, the delivery route,
* a collection's `access`). `status` is the HTTP answer: `401` when the request is anonymous,
* `403` when the signed-in user is not allowed.
*/
export class MediaAccessDeniedError extends Error {
action;
collection;
mediaId;
anonymous;
code = 'E_MEDIA_ACCESS_DENIED';
status;
constructor(action, collection, mediaId, anonymous) {
super(anonymous
? `Sign in to ${action} media in collection "${collection}".`
: `Not allowed to ${action} media in collection "${collection}".`);
this.action = action;
this.collection = collection;
this.mediaId = mediaId;
this.anonymous = anonymous;
this.name = 'MediaAccessDeniedError';
this.status = anonymous ? 401 : 403;
}
}
/**
* A tenant's call to the media control plane failed. `status` is what the tenant answers when the
* error reaches its delivery route: `503` when the control plane did not answer (down, timed out,
* its URL did not resolve), else the control plane's own status. `code` is the control plane's
* error code when it sent one (`E_MEDIA_MIME_NOT_ALLOWED`, …), so a caller can tell a refused file
* from an outage exactly as it would in a standalone app.
*/
export class MediaControlPlaneError extends Error {
status;
code;
constructor(message, status, code) {
super(message);
this.status = status;
this.name = 'MediaControlPlaneError';
this.code =
code ?? (status === 503 ? 'E_MEDIA_CONTROL_PLANE_UNAVAILABLE' : 'E_MEDIA_CONTROL_PLANE');
}
}
/** A `media.library` method that does not exist on a tenant: its files live on the control plane. */
export class MediaTenantUnsupportedError extends Error {
code = 'E_MEDIA_TENANT_UNSUPPORTED';
constructor(operation) {
super(`${operation} is not available on a media tenant: the files live on the control plane, which runs it (or does not offer it to tenants).`);
this.name = 'MediaTenantUnsupportedError';
}
}
//# sourceMappingURL=errors.js.map