import { readFile } from 'node:fs/promises'; import { basename } from 'node:path'; import { safeErrorBody } from '../http-error-safety.js'; type FetchLike = typeof fetch; /** * Upload a local media file to GoBananas R2 and return its durable, public, direct-HTTPS URL * (no redirects) — the host the Magnific REST API can fetch. Verified live 2026-06-16: * uguu/catbox URLs make Magnific's video endpoints error, whereas a `*.r2.dev` URL is fetched * cleanly. Requires GO_BANANAS_API_KEY; base overridable via GO_BANANAS_API_URL. */ export async function uploadToGoBananasR2( localPath: string, opts: { env?: NodeJS.ProcessEnv; fetchImpl?: FetchLike } = {}, ): Promise { const env = opts.env ?? process.env; const fetchImpl = opts.fetchImpl ?? fetch; const key = (env.GO_BANANAS_API_KEY ?? '').trim(); if (!key) throw new Error('GoBananas R2 upload requires GO_BANANAS_API_KEY.'); const base = (env.GO_BANANAS_API_URL ?? 'https://gobananasai.com/api').trim(); const bytes = await readFile(localPath); const form = new FormData(); form.append('file', new Blob([new Uint8Array(bytes)]), basename(localPath)); const res = await fetchImpl(`${base}/media/upload`, { method: 'POST', headers: { 'X-API-Key': key }, body: form, }); if (!res.ok) { throw new Error(`GoBananas R2 upload failed (HTTP ${res.status}): ${safeErrorBody(await res.text().catch(() => ''))}`); } const json = (await res.json()) as { url?: unknown; public_url?: unknown; media_url?: unknown }; const url = (json.url ?? json.public_url ?? json.media_url) as string | undefined; if (!url) throw new Error('GoBananas R2 upload returned no url.'); return url; }