Open source CapCut alternative.
TypeScript
import path from "node:path";
import { LadderStoreNotConfiguredError } from "./ladderStore";
import { MediaNotConfiguredError } from "./mediaCdn";
import { R2NotConfiguredError } from "./r2";
import { errorBody, UserError } from "@/cut/lib/userError";
export const err = (failure: string | UserError, status: number) =>
Response.json(errorBody(failure, ""), { status });
/** A refusal raised deep inside a helper — a quota wall met halfway through a
* copy — carrying the exact response the route should answer with, so the
* wall reads the same wherever it is hit. `caught` unwraps it. */
export class HttpResponseError extends Error {
constructor(public readonly response: Response) {
super(`HTTP ${response.status}`);
}
}
export const caught = (e: unknown, fallback: string | UserError, status = 500) => {
if (e instanceof HttpResponseError) return e.response;
if (e instanceof R2NotConfiguredError) return err(e.message, 500);
// The real reason belongs in the server's logs, not in a response an
// anonymous share viewer reads: it names the environment variable to set.
// 5xx also keeps the client's retry — a 4xx reads as "stop asking".
if (e instanceof MediaNotConfiguredError) {
console.error(e.message);
return err(new UserError("cloud_media_unavailable", "Cloud media is unavailable."), 500);
}
if (e instanceof LadderStoreNotConfiguredError) {
console.error(e.message);
return err(new UserError("streaming_unavailable", "Streaming is unavailable."), 500);
}
return Response.json(errorBody(e, fallback), { status });
};
export const redirect = (url: string, headers: Record<string, string> = {}) =>
new Response(null, { status: 302, headers: { Location: url, ...headers } });
/** `?download=1` on a media URL asks for the bytes as an attachment — the
* engine's flag, read the same way here. */
export const wantsDownload = (req: Request) => new URL(req.url).searchParams.has("download");
/** Sanitize an upload name the way the engine's saveMedia does. */
export function safeFileName(original: string): string {
const base = storableFileName(original);
if (!base) throw new Error("Invalid file name.");
return base;
}
/** The sanitized name, or null for one no object can be stored under — an
* empty name, which a block asset carries, or a dotfile. Batch reads skip
* these so one fileless asset leaves the rest of the batch signed. */
export function storableFileName(original: string): string | null {
const base = path
.basename(original)
.replace(/[^\w.\-() ]+/g, "_")
.slice(-80);
return base && !base.startsWith(".") ? base : null;
}
/** A URL path segment decoded and checked: no separators, no dotfiles. */
export function decodeFileParam(raw: string): string {
const name = decodeURIComponent(raw);
if (!name || name.includes("/") || name.includes("\\") || name.startsWith(".")) {
throw new Error("Invalid file name.");
}
return name;
}
/** First variant of `base` (stem, stem-1, stem-2, …) not in `taken` — the
* engine's uniqueName against a known name set instead of the filesystem. */
export function dedupeName(base: string, taken: ReadonlySet<string>): string {
const ext = path.extname(base);
const stem = base.slice(0, base.length - ext.length) || "media";
let name = base;
for (let n = 1; taken.has(name); n++) name = `${stem}-${n}${ext}`;
return name;
}
/** The library folder inspiration items land in, derived from the user id so
* every writer — the complete route, the URL-import worker — upserts the same
* row instead of racing to create one. An ordinary folder otherwise. */
export const inspirationFolderId = (userId: string) => `inspiration-${userId}`;