type StorageErrorLike = { message: string status?: number statusCode?: string } /** * Resolve the HTTP status code from a storage-js `StorageError`, falling back when the error * carries no valid 4xx/5xx status (for example `StorageUnknownError` on network failures). */ export function getStorageErrorStatus(error: StorageErrorLike, fallbackStatus = 400): number { if ( typeof error.status === 'number' && Number.isInteger(error.status) && error.status >= 400 && error.status <= 599 ) { return error.status } const parsedStatusCode = error.statusCode ? Number(error.statusCode) : NaN if (Number.isInteger(parsedStatusCode) && parsedStatusCode >= 400 && parsedStatusCode <= 599) { return parsedStatusCode } return fallbackStatus } /** * Error response for a failed storage-js call, forwarding the upstream HTTP status when present. */ export function storageErrorResponse(error: StorageErrorLike, fallbackStatus = 400): Response { return Response.json( { error: { message: error.message } }, { status: getStorageErrorStatus(error, fallbackStatus) } ) } /** * Parse `SUPABASE_PUBLIC_URL` for rewriting internal storage URLs into client-reachable ones. * Returns `null` when the env var is missing or not a valid URL. */ export function getStoragePublicOrigin(): URL | null { const raw = process.env.SUPABASE_PUBLIC_URL if (!raw) return null try { return new URL(raw) } catch { return null } } export function missingStoragePublicUrlResponse(): Response { return Response.json( { error: { message: 'SUPABASE_PUBLIC_URL is not configured' } }, { status: 500 } ) } export function remapStoragePublicUrl(url: string, publicOrigin: URL): string { const remapped = new URL(url) remapped.protocol = publicOrigin.protocol remapped.host = publicOrigin.host remapped.port = publicOrigin.port return remapped.href }