import type { AdminStorageProvider, AdminStorageUploadInput } from '@admin/actions/storage/types' import { getClient } from '@admin/actions/r2/get-client' import { getConfig } from '@admin/actions/r2/get-config' import { buildStorageObjectKey } from '@admin/actions/storage/object-key' import { PutObjectCommand } from '@aws-sdk/client-s3' export const r2StorageProvider: AdminStorageProvider = { id: 'r2', isConfigured() { const config = getConfig() return Boolean( config.accountId && config.accessKeyId && config.secretAccessKey && config.bucketName && config.publicUrl ) }, async saveFile(input: AdminStorageUploadInput) { const config = getConfig() if (!this.isConfigured()) { throw new Error('Cloudflare R2 is not fully configured.') } const key = buildStorageObjectKey(input.filename, input.prefix) await getClient().send( new PutObjectCommand({ Bucket: config.bucketName, Key: key, Body: input.buffer, ContentType: input.contentType, ContentLength: input.contentLength }) ) return { key, url: `${config.publicUrl.replace(/\/$/, '')}/${key}` } } }