import { randomUUID } from 'node:crypto' import { mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' const KEY_PATTERN = /^[0-9a-f-]{36}\.[a-z]{3,4}$/ /** Stores uploaded files on local disk under random names. */ export class FileStorage { readonly dir: string constructor(dir: string) { this.dir = dir } async save(data: Uint8Array, extension: string): Promise { await mkdir(this.dir, { recursive: true }) const key = `${randomUUID()}.${extension}` await writeFile(this.path(key), data, { flag: 'wx' }) return key } read(key: string): Promise { return readFile(this.path(key)) } async remove(key: string): Promise { await rm(this.path(key), { force: true }) } private path(key: string) { if (!KEY_PATTERN.test(key)) throw new Error(`Invalid storage key: ${key}`) return join(this.dir, key) } }