@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
193 lines • 7.77 kB
JavaScript
import { randomUUID } from 'node:crypto';
import { asBuffer, toBytes } from './contents.js';
import { publishMedia } from './diagnostics.js';
import { ImageProcessorMissingError, VariantNotFoundError } from './errors.js';
import { sanitizeFileName } from './file_name.js';
/**
* A file attached to a model as a column value (adonis-attachment style). Pure value
* object — it carries disk + path + variant metadata and serializes to JSON. URL
* resolution and deletion go through {@link AttachmentManager} (which holds the disks).
*/
export class Attachment {
name;
disk;
path;
size;
mimeType;
variants;
meta;
constructor(data) {
this.name = data.name;
this.disk = data.disk;
this.path = data.path;
this.size = data.size;
this.mimeType = data.mimeType;
this.variants = data.variants;
this.meta = data.meta;
}
toJSON() {
return {
name: this.name,
disk: this.disk,
path: this.path,
size: this.size,
mimeType: this.mimeType,
variants: this.variants,
meta: this.meta,
};
}
/** Rebuild from a stored column value; returns null for null/undefined. */
static fromJSON(json) {
return json ? new Attachment(json) : null;
}
}
/**
* Creates and resolves {@link Attachment}s — the adonis-attachment-style API.
* `createFromFile` uploads the bytes (and any variants) and returns a value object
* you assign to a model column.
*/
export class AttachmentManager {
storage;
imageProcessor;
keyPrefix;
newId;
emitDiagnostics;
constructor(options) {
this.storage = options.storage;
this.imageProcessor = options.imageProcessor;
this.keyPrefix = options.keyPrefix ?? 'attachments';
this.newId = options.idGenerator ?? (() => randomUUID());
this.emitDiagnostics = options.emitDiagnostics ?? true;
}
async createFromFile(input, options = {}) {
const disk = options.disk ?? this.storage.defaultDisk;
const prefix = options.keyPrefix ?? this.keyPrefix;
const id = this.newId();
const dir = `${prefix}/${id}`;
// input.fileName is client-supplied (an upload's original name) and goes through
// sanitizeFileName before it is interpolated into the storage key — otherwise
// "../../etc/passwd" or an absolute path would escape the `${prefix}/${id}` prefix. See
// MediaLibrary#layoutPath for the sibling call site this mirrors.
const path = `${dir}/${sanitizeFileName(input.fileName)}`;
const target = this.storage.disk(disk);
const presets = options.variants ?? [];
// Stream large uploads straight through (no in-memory buffer) when we can: a Readable with a
// known size, no variants to generate off the buffered bytes, and a disk that supports it.
const canStream = !Buffer.isBuffer(input.contents) &&
input.size !== undefined &&
presets.length === 0 &&
typeof target.putStream === 'function';
if (canStream) {
// See MediaLibrary.attach: `input.size` gates this path, so it must reach the disk —
// S3's putStream cannot write without it.
await target.putStream?.(path, input.contents, {
contentType: input.mimeType,
contentLength: input.size,
});
}
else {
const bytes = await toBytes(input.contents);
await target.put(path, bytes, { contentType: input.mimeType });
}
const variants = {};
let size;
try {
size = input.size ?? (await target.getMetaData(path)).contentLength;
if (presets.length > 0) {
if (!this.imageProcessor)
throw new ImageProcessorMissingError();
const original = asBuffer(await target.getBytes(path));
for (const preset of presets) {
const result = await this.imageProcessor.convert(original, preset);
const variantPath = `${dir}/variants/${preset.name}.${result.format}`;
await target.put(variantPath, result.data, { contentType: result.contentType });
variants[preset.name] = {
disk,
path: variantPath,
size: result.data.byteLength,
mimeType: result.contentType,
};
}
}
}
catch (error) {
// Compensation: the original (and any variants already written) leaked when the metadata read
// or a conversion failed — best-effort remove them before rethrowing.
await this.#safeDelete(disk, path);
for (const variant of Object.values(variants)) {
await this.#safeDelete(variant.disk, variant.path);
}
throw error;
}
const attachment = new Attachment({
name: options.name ?? input.fileName,
disk,
path,
size,
mimeType: input.mimeType,
variants,
meta: options.meta ?? {},
});
if (this.emitDiagnostics) {
publishMedia('attachment.create', {
disk,
path,
size,
mimeType: attachment.mimeType,
name: attachment.name,
variants: Object.keys(variants),
});
}
return attachment;
}
/** Public URL for the attachment, or a named variant. */
async url(attachment, variant) {
const target = this.resolve(attachment, variant);
return this.storage.disk(target.disk).getUrl(target.path);
}
/**
* Signed, expiring URL (presign-capable disks). Everything in `options` except `variant` is a
* response header baked into the URL, applying to whoever follows the link rather than to this
* call: `contentDisposition` is what forces a download with a chosen file name.
*/
async signedUrl(attachment, expiresIn, options = {}) {
const { variant, ...responseOptions } = options;
const target = this.resolve(attachment, variant);
return this.storage.disk(target.disk).getSignedUrl(target.path, {
expiresIn,
...responseOptions,
});
}
/** Remove the attachment and all its variants from storage. */
async delete(attachment) {
await this.storage.disk(attachment.disk).delete(attachment.path);
for (const variant of Object.values(attachment.variants)) {
await this.storage.disk(variant.disk).delete(variant.path);
}
if (this.emitDiagnostics) {
publishMedia('attachment.delete', {
disk: attachment.disk,
path: attachment.path,
variants: Object.keys(attachment.variants),
});
}
}
resolve(attachment, variant) {
if (!variant)
return { disk: attachment.disk, path: attachment.path };
const v = attachment.variants[variant];
if (!v)
throw new VariantNotFoundError(variant);
return { disk: v.disk, path: v.path };
}
/** Best-effort disk cleanup for the orphan-compensation path; never masks the original error. */
async #safeDelete(disk, path) {
try {
await this.storage.disk(disk).delete(path);
}
catch {
// swallow: this is compensation for a failed create; the original error is what matters
}
}
}
//# sourceMappingURL=attachment.js.map