Open source CapCut alternative.
TypeScript
fix(site): fold non-JSON Cut engine replies into readable errors
David Lea9167de77cce
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 8b9d46fc..f498099c 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -1,6 +1,6 @@"use client";-import { apiFetch } from "./api";+import { apiFetch, apiJson } from "./api";import { useGenerate } from "./generate";import { enrichAsset, ensurePeaks } from "./media";import { getClipSpans, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";@@ -210,7 +210,7 @@ export async function runAiTool(},}),});- const body = (await res.json()) as MediaAsset & { error?: string };+ const body = await apiJson<MediaAsset>(res);if (!res.ok) throw new ToolError(body.error ?? "Could not render the freeze frame.");const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName) };const cur = useEditor.getState();diff --git a/site/src/cut/lib/api.ts b/site/src/cut/lib/api.tsindex dd272095..4726095a 100644--- a/site/src/cut/lib/api.ts+++ b/site/src/cut/lib/api.ts@@ -74,3 +74,23 @@ export async function apiFetch(path: string, init?: RequestInit) {const base = await engineReady();return fetch(`${base}${path}`, init);}++/** JSON body of an engine reply. A reply that never reached a handler is plain+ * text — a 404/405 from an engine build older than the route, a 403 refusal —+ * so a non-JSON body folds into an `error` message instead of throwing a+ * SyntaxError at the caller's parse. The 404/405 case is the hosted page+ * driving an out-of-date engine: the page updates on deploy, the engine only+ * when the user updates the Donkey app. */+export async function apiJson<T>(res: Response): Promise<T & { error?: string }> {+ const text = await res.text();+ try {+ return JSON.parse(text) as T & { error?: string };+ } catch {+ const stale = res.status === 404 || res.status === 405;+ return {+ error: stale+ ? "The Donkey app on this Mac doesn't support this yet — update Donkey and try again."+ : text.trim() || `The engine replied ${res.status}.`,+ } as T & { error?: string };+ }+}diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 5232d5b9..7a7cd200 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -1,6 +1,6 @@"use client";-import { apiFetch, apiUrl } from "./api";+import { apiFetch, apiJson, apiUrl } from "./api";import { clipSpeed, getClipSpans, projectDuration } from "./store";import { captionStyle, cueOverlay, cueWordWindows } from "./subtitles";import { renderOverlayPng } from "./textRender";@@ -287,14 +287,13 @@ export async function pollExport(if (isCanceled()) throw new Error("Export canceled.");await new Promise((r) => setTimeout(r, 400));const st = await apiFetch(`/api/cut/export/${jobId}`);- const status = (await st.json()) as {- status: string;- progress: number;- error?: string;+ const status = await apiJson<{+ status?: string;+ progress?: number;outName?: string;- };- if (status.status === "error") throw new Error(status.error ?? "Export failed.");- onProgress("Rendering", status.progress);+ }>(st);+ if (!st.ok || status.status === "error") throw new Error(status.error ?? "Export failed.");+ onProgress("Rendering", status.progress ?? 0);if (status.status === "done") return status.outName ?? "export.mp4";}}@@ -323,7 +322,7 @@ export function startExport(const form = await buildExportForm(projectId, doc, settings, "export");onProgress("Starting encoder", 0);const res = await apiFetch("/api/cut/export", { method: "POST", body: form });- const body = (await res.json()) as { id?: string; error?: string };+ const body = await apiJson<{ id?: string }>(res);if (!res.ok || !body.id) throw new Error(body.error ?? "Export failed to start.");jobId = body.id;diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsindex 778134c4..06fdf48a 100644--- a/site/src/cut/lib/generate.ts+++ b/site/src/cut/lib/generate.ts@@ -2,7 +2,7 @@import { useEffect } from "react";import { create } from "zustand";-import { apiFetch } from "./api";+import { apiFetch, apiJson } from "./api";import type { AssetRef } from "./assetRef";import { enrichAsset, importFileToProject } from "./media";import { refsToInlineImages } from "./refMedia";@@ -251,7 +251,7 @@ export const useGenerate = create<GenerateState>((set, get) => {method: "POST",body: form,});- const body = (await baked.json()) as MediaAsset & { error?: string };+ const body = await apiJson<MediaAsset>(baked);if (!baked.ok || !body.fileName) {throw new Error(body.error ?? "Could not add the image to the project.");}diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 27b2e113..15553d7c 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -1,6 +1,6 @@"use client";-import { apiFetch, apiUrl } from "./api";+import { apiFetch, apiJson, apiUrl } from "./api";import { enrichAsset } from "./media";import { useEditor } from "./store";import type { LibraryTemplate, MediaAsset, TemplateMedia, TemplateSaveInput } from "./types";@@ -53,7 +53,7 @@ export async function importUrlToLibrary(url: string): Promise<LibraryAsset> {headers: { "Content-Type": "application/json" },body: JSON.stringify({ url }),});- const body = (await res.json()) as LibraryAsset & { error?: string };+ const body = await apiJson<LibraryAsset>(res);if (!res.ok) throw new Error(body.error ?? "Could not import that URL.");return body;}@@ -64,7 +64,7 @@ export async function createLibraryFolder(name: string): Promise<LibraryFolder>headers: { "Content-Type": "application/json" },body: JSON.stringify({ name }),});- const body = (await res.json()) as LibraryFolder & { error?: string };+ const body = await apiJson<LibraryFolder>(res);if (!res.ok) throw new Error(body.error ?? "Could not create folder.");return body;}@@ -96,7 +96,7 @@ export async function uploadToLibrary(file: File): Promise<LibraryAsset> {const form = new FormData();form.append("file", file, file.name);const res = await apiFetch("/api/cut/library", { method: "POST", body: form });- const body = (await res.json()) as LibraryAsset & { error?: string };+ const body = await apiJson<LibraryAsset>(res);if (!res.ok) throw new Error(body.error ?? "Upload failed.");return body;}@@ -117,7 +117,7 @@ export async function importLibraryAsset(headers: { "Content-Type": "application/json" },body: JSON.stringify({ assetId: lib.id, projectId }),});- const body = (await res.json()) as { fileName?: string; error?: string };+ const body = await apiJson<{ fileName?: string }>(res);if (!res.ok || !body.fileName) throw new Error(body.error ?? "Could not add from library.");const asset: MediaAsset = {@@ -159,7 +159,7 @@ export async function saveTemplate(headers: { "Content-Type": "application/json" },body: JSON.stringify({ projectId, ...input }),});- const body = (await res.json()) as LibraryTemplate & { error?: string };+ const body = await apiJson<LibraryTemplate>(res);if (!res.ok) throw new Error(body.error ?? "Could not save the template.");return body;}@@ -180,7 +180,7 @@ export async function addTemplateToProject(headers: { "Content-Type": "application/json" },body: JSON.stringify({ projectId }),});- const body = (await res.json()) as { media?: TemplateMedia[]; error?: string };+ const body = await apiJson<{ media?: TemplateMedia[] }>(res);if (!res.ok || !body.media) throw new Error(body.error ?? "Could not add the template.");const s = useEditor.getState();@@ -210,7 +210,7 @@ export async function saveAssetToLibrary(projectId: string, asset: MediaAsset) {headers: { "Content-Type": "application/json" },body: JSON.stringify({ projectId, fileName: asset.fileName, name: asset.name }),});- const body = (await res.json()) as LibraryAsset & { error?: string };+ const body = await apiJson<LibraryAsset>(res);if (!res.ok) throw new Error(body.error ?? "Could not save to library.");return body;}diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex 6a1deb4b..8f5ec850 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -1,6 +1,6 @@"use client";-import { apiFetch } from "./api";+import { apiFetch, apiJson } from "./api";import { useEditor } from "./store";import type { AudioClip, MediaAsset, ProjectSummary, StoredAsset, VideoClip } from "./types";import { mediaUrl } from "./types";@@ -31,7 +31,8 @@ export async function createProjectFromFile(headers: { "Content-Type": "application/json" },body: JSON.stringify({ name, folderId }),});- const project = (await res.json()) as ProjectSummary;+ const project = await apiJson<ProjectSummary>(res);+ if (!res.ok || !project.id) throw new Error(project.error ?? "Could not create the project.");const asset = await importFileToProject(project.id, file);// Media the engine rejects leaves an empty project rather than a dangling id.@@ -96,7 +97,7 @@ export async function importFileToProject(method: "POST",body: form,});- const body = (await res.json()) as { fileName?: string; error?: string };+ const body = await apiJson<{ fileName?: string }>(res);if (!res.ok || !body.fileName) throw new Error(body.error ?? "Upload failed.");const url = mediaUrl(projectId, body.fileName);diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex ec0fb231..19d2f5a7 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -21,7 +21,7 @@ import type {TransitionStyle,VideoClip,} from "./types";-import { apiFetch } from "./api";+import { apiFetch, apiJson } from "./api";import { emptySubtitles, isCrossStyle, mediaUrl, SPEED_MAX, SPEED_MIN, TRANSITION_MAX } from "./types";import { readTextStyle } from "./textStyle";import { loadUiState, saveUiState } from "./uiState";@@ -1168,7 +1168,7 @@ export const useEditor = create<EditorState>((set, get) => {headers: { "Content-Type": "application/json" },body: JSON.stringify(spec),});- const body = (await res.json()) as { id?: string; error?: string };+ const body = await apiJson<{ id?: string }>(res);if (!res.ok || !body.id) throw new Error(body.error ?? "Transcription failed to start.");for (;;) {await new Promise((r) => setTimeout(r, 600));@@ -1228,10 +1228,9 @@ export const useEditor = create<EditorState>((set, get) => {headers: { "Content-Type": "application/json" },body: JSON.stringify({ frames, duration, locale: s.subtitles.locale ?? "en-US" }),});- const body = (await res.json()) as {+ const body = await apiJson<{cues?: { start: number; end: number; text: string }[];- error?: string;- };+ }>(res);if (!res.ok || !Array.isArray(body.cues)) {throw new Error(body.error ?? "Captioning failed.");}@@ -1281,7 +1280,7 @@ export const useEditor = create<EditorState>((set, get) => {cues: cues.map((c) => ({ start: c.start, end: c.end, text: c.text })),}),});- const body = (await res.json()) as { texts?: string[]; error?: string };+ const body = await apiJson<{ texts?: string[] }>(res);if (get().projectId !== projectId) return;push();if (res.ok && Array.isArray(body.texts) && body.texts.length === cues.length) {