import { isAcceptedUploadMimeType } from "./../mime"; // 50 MB export const DEFAULT_MAX_UPLOAD_SIZE = 50 * 1024 * 1024; export const DEFAULT_DEV_UPLOADS_BASE_URL = "https://uploads.local.invalid"; export type UploadFileToBucketResult = { objectKey: string; url: string; }; type PutOptions = { httpMetadata?: { contentType?: string; cacheControl?: string; contentDisposition?: string; }; customMetadata?: Record; }; export type BucketLike = { put: ( key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | Blob, options?: PutOptions, ) => Promise; }; export type UploadFileToBucketOptions = { file: File; bucket: BucketLike; publicBaseUrl: string; }; export function sanitizeUploadFilename(original: string): string { const dotIdx = original.lastIndexOf("."); const extension = dotIdx >= 0 ? original.slice(dotIdx).toLowerCase() : ""; const base = dotIdx >= 0 ? original.slice(0, dotIdx) : original; const sanitizedBase = base .normalize("NFD") .replace(/[\u0300-\u036f]/g, "") .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .replace(/^-+|-+$/g, "") .slice(0, 80); const fallbackBase = sanitizedBase.length > 0 ? sanitizedBase : "file"; return `${fallbackBase}${extension}`; } function encodeObjectKeyForUrl(objectKey: string): string { return objectKey .split("/") .map((segment) => encodeURIComponent(segment)) .join("/"); } function isProductionLikeEnv(): boolean { return process.env.FLIPPABLE_ENV === "production" || process.env.FLIPPABLE_ENV === "preview"; } function getValidatedPublicBaseUrl(publicBaseUrl: string): string { const trimmedPublicBaseUrl = publicBaseUrl.trim(); if (trimmedPublicBaseUrl.length === 0) { if (isProductionLikeEnv()) { throw new Error("Missing UP_UPLOADS_BASE_URL for file uploads"); } return DEFAULT_DEV_UPLOADS_BASE_URL; } let parsedBaseUrl: URL; try { parsedBaseUrl = new URL(trimmedPublicBaseUrl); } catch { if (isProductionLikeEnv()) { throw new Error(`Invalid UP_UPLOADS_BASE_URL: ${trimmedPublicBaseUrl}`); } return DEFAULT_DEV_UPLOADS_BASE_URL; } if (parsedBaseUrl.protocol !== "https:" && parsedBaseUrl.protocol !== "http:") { if (isProductionLikeEnv()) { throw new Error(`Invalid UP_UPLOADS_BASE_URL protocol: ${parsedBaseUrl.protocol}`); } return DEFAULT_DEV_UPLOADS_BASE_URL; } return parsedBaseUrl.toString(); } function buildUploadObjectKey({ filename }: { filename: string }): string { const timestamp = Date.now(); const randomSuffix = crypto.randomUUID().replace(/-/g, "").slice(0, 8); const parts = ["uploads"]; parts.push(`${timestamp}_${randomSuffix}_${filename}`); return parts.join("/"); } function assertFileIsAllowed({ file }: { file: File }): void { const maxBytes = DEFAULT_MAX_UPLOAD_SIZE; if (file.size > maxBytes) { throw new Error(`File "${file.name}" exceeds max upload size (${maxBytes} bytes)`); } if (!isAcceptedUploadMimeType(file.type)) { throw new Error(`Unsupported MIME type "${file.type || "unknown"}" for file "${file.name}"`); } } export async function uploadFileToBucket({ file, bucket, publicBaseUrl, }: UploadFileToBucketOptions): Promise { assertFileIsAllowed({ file }); const safeFilename = sanitizeUploadFilename(file.name || "file"); const objectKey = buildUploadObjectKey({ filename: safeFilename, }); if (process.env.FLIPPABLE_ENV !== "production" && process.env.FLIPPABLE_ENV !== "preview") { console.debug(`Uploading file "${file.name}" as "${objectKey}" with MIME type "${file.type}"`); } else { await bucket.put(objectKey, file.stream(), { httpMetadata: { contentType: file.type || "application/octet-stream", cacheControl: "public, max-age=31536000, immutable", contentDisposition: `inline; filename="${safeFilename.replace(/"/g, "")}"`, }, customMetadata: { originalFilename: file.name, uploadedAt: new Date().toISOString(), }, }); } const encodedKey = encodeObjectKeyForUrl(objectKey); const normalizedPublicBaseUrl = getValidatedPublicBaseUrl(publicBaseUrl); const url = new URL(encodedKey, normalizedPublicBaseUrl).toString(); return { objectKey, url, }; }