Open source CapCut alternative.
TypeScript
feat(site): a library item follows the folder it is filed into [rebuild]
David Le10c94f131c5e
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex c6a09f31..3a47979f 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -50,9 +50,9 @@ Cloud projects follow the account: the same project opens in any browser on anyEvery client call goes through a backend seam (`site/src/cut/lib/backend/`): the local driver is the engine transport unchanged, the cloud driver rewrites the same paths to `/api/cut-cloud/*` with the session cookie, and the browser driver answers storage routes in the page from origin-private storage, falling through to the cloud twin for AI. Residency is per project and fixed when the project is created, so creating one is where the user chooses. One picker makes that choice, standing beside New project in the sidebar: it names a shelf — Local or Cloud — and everything the browser creates lands there, new projects and anything added to the library alike. Local is this Mac's engine when the app has connected and this browser's own storage otherwise, so a machine without the app still has a real local shelf. The choice sticks on that browser until they change it, and every other New project button follows it. Inside a folder the folder decides, since a project files only into a folder beside it. The home lists every shelf as one listing — the Mac's from its stored listing when the app is closed — each project badged with where it lives, and opening one binds the editor to that project's backend. Capability flags on the driver hide what a backend can't do, so components never feature-detect.-The library is the exception, because it is the user's one shelf across places: every residency keeps a library, and the Library lists them at once as one listing, newest first, with a badge saying which shelf each item is on. So a cloud project can pull a clip off this Mac, and a browser project can pull one out of the cloud. A shelf that lives in the page holds its media in the same origin-private storage its projects use, and a link imported onto it rides the cloud worker — a page can't fetch a video off a YouTube link — with the bytes coming back down and the staged cloud copy dropped after. The Mac's shelf takes that same route as a second try: sites refuse fetches on the strength of the tool making them, so a link the engine's own tools can't bring back is fetched by the worker and lands here anyway. Each shelf is remembered on its own, so the Library tab keeps listing the Mac's items with the app closed, read-only, and clicking one raises the same banner an unreachable local project does. The editor's library picker asks only for what it can reach, since an item it cannot copy into the project has no business in a picker. Each item's own shelf answers for it: previews, renames, and deletes go to the backend it came from, and folders belong to one shelf, so items file only into folders beside them. Adding to a project is the one crossing: on the project's own shelf the server copies the file without the bytes leaving it, and off it the browser carries them down and back up.+The library is the exception, because it is the user's one shelf across places: every residency keeps a library, and the Library lists them at once as one listing, newest first, with a badge saying which shelf each item is on. So a cloud project can pull a clip off this Mac, and a browser project can pull one out of the cloud. A shelf that lives in the page holds its media in the same origin-private storage its projects use, and a link imported onto it rides the cloud worker — a page can't fetch a video off a YouTube link — with the bytes coming back down and the staged cloud copy dropped after. The Mac's shelf takes that same route as a second try: sites refuse fetches on the strength of the tool making them, so a link the engine's own tools can't bring back is fetched by the worker and lands here anyway. Each shelf is remembered on its own, so the Library tab keeps listing the Mac's items with the app closed, read-only, and clicking one raises the same banner an unreachable local project does. The editor's library picker asks only for what it can reach, since an item it cannot copy into the project has no business in a picker. Each item's own shelf answers for it: previews, renames, and deletes go to the backend it came from, and folders belong to one shelf, so items file only into folders beside them. Adding to a project is the one crossing: on the project's own shelf the server copies the file without the bytes leaving it, and off it the browser carries them down and back up. Filing an item into a folder on another shelf crosses the same way — the bytes come down and go back up, a file with its cover and a template with its own media, and the copy left behind comes off.-Some of what the Library holds is lent. Most items are copied when they are used — a clip's bytes become the project's own — but a font is pointed at: every title set in it names it, and the file stays on the shelf where every project can reach it. Lent items follow three rules. They are identified by their bytes, so the same file on two shelves is one entry in the menu and one id in a document. A new one lands on the shelf every surface can read, whenever it is small and the account has room. And a project moving to the cloud takes what it points at with it, so a title keeps its typeface when it starts rendering there — since the id is the bytes, not a word of the document changes. Fonts are the first of these; a .ttf, .otf, .woff or .woff2 dropped on the Library is filed in folders, deleted, and counted against storage like anything else, and every project offers it for titles and captions. A font download arrives as a zip, so the zip is droppable: the faces come out of it and the licence text stays behind, and a family of eighteen weights becomes a single entry. The file is checked by installing it through the renderer's font seam before any bytes move, so what lands is what a preview and an export can draw with, and the family name comes off the font's own metadata rather than the file name. A new account starts with an empty Fonts folder to say the shelf takes them; it is an ordinary folder and can be deleted. A render job reaches the cloud shelf alone, which is what those rules are for. A font filed into a folder belongs to that folder's shelf like anything else, and a full account keeps its font on the shelf it was working from: it draws in the tab, is marked in the font menu as living on this device, and falls back to the base face in a render job. A title set in a font that is later deleted falls back too, so nothing in a document has to be rewritten.+Some of what the Library holds is lent. Most items are copied when they are used — a clip's bytes become the project's own — but a font is pointed at: every title set in it names it, and the file stays on the shelf where every project can reach it. Lent items follow three rules. They are identified by their bytes, so the same file on two shelves is one entry in the menu and one id in a document. A new one lands on the shelf every surface can read, whenever it is small and the account has room. And a project moving to the cloud takes what it points at with it, so a title keeps its typeface when it starts rendering there — since the id is the bytes, not a word of the document changes. Fonts are the first of these; a .ttf, .otf, .woff or .woff2 dropped on the Library is filed in folders, deleted, and counted against storage like anything else, and every project offers it for titles and captions. A font download arrives as a zip, so the zip is droppable: the faces come out of it and the licence text stays behind, and a family of eighteen weights becomes a single entry. The file is checked by installing it through the renderer's font seam before any bytes move, so what lands is what a preview and an export can draw with, and the family name comes off the font's own metadata. That same moment draws the specimen the shelf keeps as the file's cover, so a font card shows the alphabet in its own face whether or not the page looking at it has that face installed. A new account starts with an empty Fonts folder to say the shelf takes them; it is an ordinary folder and can be deleted. A render job reaches the cloud shelf alone, which is what those rules are for. A font filed into a folder belongs to that folder's shelf like anything else, and a full account keeps its font on the shelf it was working from: it draws in the tab, is marked in the font menu as living on this device, and falls back to the base face in a render job. A title set in a font that is later deleted falls back too, so nothing in a document has to be rewritten.Cloud projects store their doc in Postgres (versioned; a stale autosave 409s and the editor reloads the newer copy) and media in R2: uploads go direct from the browser on presigned URLs (the hosted functions never see the bytes), playback streams on signed range URLs, and a flat per-user quota is enforced at presign time. That quota is visible rather than implicit: a free account editing a cloud project sees what it has used in the editor's top bar, and a presign rejected for space opens an upgrade offer wherever it happened instead of a bare error. The same slot carries the countdown when a subscription is set to cancel, and clicking it opens the billing portal.diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex 64439296..3e0ee6ed 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -76,12 +76,14 @@ import {libraryMediaUrl,libraryPosterUrl,carryAssetTo,+ carryTemplateTo,moveLibraryItem,renameLibraryFolder,renameTemplate,uploadToLibrary,type ImportStage,type LibraryAsset,+ type LibraryTemplateItem,type LibraryData,} from "@/cut/lib/library";import { normalizeLink } from "@/cut/lib/link";@@ -579,6 +581,24 @@ export function LibraryView() {!!a && a.residency !== target && live(a.residency),): [];+ const carriedTemplates =+ target && live(target)+ ? ids+ .map((id) => templates.find((t) => t.id === id))+ .filter(+ (t): t is LibraryTemplateItem =>+ !!t && t.residency !== target && live(t.residency),+ )+ : [];+ if (carriedTemplates.length > 0) {+ setSelected(new Set());+ await Promise.all(+ carriedTemplates.map((t) =>+ carryTemplateTo(t, target!, folderId).catch(() => {}),+ ),+ );+ void reload();+ }if (carried.length > 0) {setSelected(new Set());await Promise.all(diff --git a/site/src/cut/components/Lightbox.tsx b/site/src/cut/components/Lightbox.tsxindex d35e52a6..2f0839b4 100644--- a/site/src/cut/components/Lightbox.tsx+++ b/site/src/cut/components/Lightbox.tsx@@ -264,7 +264,7 @@ function FontBody({ item }: { item: LightboxItem }) {<divclassName={cn("overflow-hidden rounded-2xl bg-white text-black shadow-2xl",- item.poster ? "" : "px-10 py-12"+ item.poster ? "" : "px-10 py-12",)}><FontSpecimendiff --git a/site/src/cut/lib/backend/browser/library.ts b/site/src/cut/lib/backend/browser/library.tsindex efc435ea..f2610ee7 100644--- a/site/src/cut/lib/backend/browser/library.ts+++ b/site/src/cut/lib/backend/browser/library.ts@@ -31,7 +31,12 @@ const projectMediaApiPath = (id: string, fileName: string) =>`/api/cut/projects/${id}/media/${encodeURIComponent(fileName)}`;/** Where a URL-imported asset came from, kept as notes on the asset. */-type LibrarySource = { url: string; title?: string; uploader?: string; uploadDate?: string };+type LibrarySource = {+ url: string;+ title?: string;+ uploader?: string;+ uploadDate?: string;+};type StoredAsset = {id: string;@@ -58,10 +63,18 @@ type LibraryIndex = {templates: LibraryTemplate[];};-const EMPTY: LibraryIndex = { version: 1, assets: [], folders: [], templates: [] };+const EMPTY: LibraryIndex = {+ version: 1,+ assets: [],+ folders: [],+ templates: [],+};async function readIndex(): Promise<LibraryIndex> {- const idx = await store.readJson<LibraryIndex>(await store.libraryDir(), INDEX_FILE);+ const idx = await store.readJson<LibraryIndex>(+ await store.libraryDir(),+ INDEX_FILE,+ );if (!idx) return EMPTY;return {version: 1,@@ -111,7 +124,8 @@ function parseField<T>(value: FormDataEntryValue | null): T | null {async function register(fileName: string, file?: File | null): Promise<void> {const path = libraryMediaApiPath(fileName);if (registeredUrl(path)) return;- const bytes = file ?? (await store.readFileAt(await store.libraryMediaDir(), fileName));+ const bytes =+ file ?? (await store.readFileAt(await store.libraryMediaDir(), fileName));if (bytes) registerBlobFile(path, bytes);}@@ -137,9 +151,14 @@ async function list(): Promise<Response> {async function addAsset(fileName: string,name: string,- meta: { type?: AssetType; duration?: number; width?: number; height?: number } | null,+ meta: {+ type?: AssetType;+ duration?: number;+ width?: number;+ height?: number;+ } | null,source?: LibrarySource | null,- posterFile?: string+ posterFile?: string,): Promise<StoredAsset> {const type = meta?.type ?? typeOf(fileName);if (!type) throw new Error("Unsupported file type.");@@ -149,7 +168,9 @@ async function addAsset(name,type,duration: meta?.duration ?? 0,- ...(meta?.width && meta?.height ? { width: meta.width, height: meta.height } : {}),+ ...(meta?.width && meta?.height+ ? { width: meta.width, height: meta.height }+ : {}),addedAt: Date.now(),folderId: null,...(source ? { source } : {}),@@ -172,7 +193,10 @@ async function upload(req: Request): Promise<Response> {const file = form.get("file");if (!(file instanceof File)) return err("No file in upload.", 400);const nameField = form.get("name");- const name = typeof nameField === "string" && nameField.trim() ? nameField.trim() : file.name;+ const name =+ typeof nameField === "string" && nameField.trim()+ ? nameField.trim()+ : file.name;const meta = parseField<{type?: AssetType;duration?: number;@@ -180,7 +204,8 @@ async function upload(req: Request): Promise<Response> {height?: number;}>(form.get("meta"));const source = parseField<LibrarySource>(form.get("source"));- if (!(meta?.type ?? typeOf(file.name))) return err("Unsupported file type.", 400);+ if (!(meta?.type ?? typeOf(file.name)))+ return err("Unsupported file type.", 400);const fileName = await store.saveLibraryMedia(file, file.name);await register(fileName, file);// An import carries the source's cover alongside the media; it is stored@@ -189,7 +214,10 @@ async function upload(req: Request): Promise<Response> {let posterFile: string | undefined;if (posterField instanceof File) {const ext = posterField.name.match(/\.[a-z0-9]+$/i)?.[0] ?? ".jpg";- posterFile = await store.saveLibraryMedia(posterField, `${fileName}.poster${ext}`);+ posterFile = await store.saveLibraryMedia(+ posterField,+ `${fileName}.poster${ext}`,+ );await register(posterFile, posterField);}return json(await addAsset(fileName, name, meta, source, posterFile));@@ -198,7 +226,10 @@ async function upload(req: Request): Promise<Response> {}}-async function serveMedia(fileName: string, download: boolean): Promise<Response> {+async function serveMedia(+ fileName: string,+ download: boolean,+): Promise<Response> {const file = await store.readFileAt(await store.libraryMediaDir(), fileName);if (!file) return err("Media file not found.", 404);await register(fileName, file);@@ -227,9 +258,14 @@ async function removeAsset(id: string): Promise<Response> {async function move(req: Request): Promise<Response> {try {- const { id, folderId } = (await req.json()) as { id: string; folderId: string | null };+ const { id, folderId } = (await req.json()) as {+ id: string;+ folderId: string | null;+ };await mutateIndex((idx) => {- const item = idx.assets.find((a) => a.id === id) ?? idx.templates.find((t) => t.id === id);+ const item =+ idx.assets.find((a) => a.id === id) ??+ idx.templates.find((t) => t.id === id);if (!item) throw new Error("Library item not found.");if (folderId && !idx.folders.some((f) => f.id === folderId)) {throw new Error("Folder not found.");@@ -272,7 +308,7 @@ async function renameFolder(req: Request, id: string): Promise<Response> {if (!folder) throw new Error("Folder not found.");folder.name = trimmed.slice(0, 80);return folder;- })+ }),);} catch (e) {return caught(e, "Could not rename folder.");@@ -294,7 +330,10 @@ async function deleteFolder(id: string): Promise<Response> {}/** Copy a library file into a project's media folder. */-async function copyIntoProject(projectId: string, fileName: string): Promise<string> {+async function copyIntoProject(+ projectId: string,+ fileName: string,+): Promise<string> {const file = await store.readFileAt(await store.libraryMediaDir(), fileName);if (!file) throw new Error("Library file not found.");const stored = await store.saveMedia(projectId, file, fileName);@@ -303,8 +342,14 @@ async function copyIntoProject(projectId: string, fileName: string): Promise<str}/** Copy a project's media file onto the shelf. */-async function copyFromProject(projectId: string, fileName: string): Promise<string> {- const file = await store.readFileAt(await store.mediaDir(projectId), fileName);+async function copyFromProject(+ projectId: string,+ fileName: string,+): Promise<string> {+ const file = await store.readFileAt(+ await store.mediaDir(projectId),+ fileName,+ );if (!file) throw new Error("Media file not found in project.");const stored = await store.saveLibraryMedia(file, fileName);await register(stored, file);@@ -313,10 +358,14 @@ async function copyFromProject(projectId: string, fileName: string): Promise<strasync function addToProject(req: Request): Promise<Response> {try {- const { assetId, projectId } = (await req.json()) as { assetId: string; projectId: string };+ const { assetId, projectId } = (await req.json()) as {+ assetId: string;+ projectId: string;+ };const asset = (await readIndex()).assets.find((a) => a.id === assetId);if (!asset) return err("Library asset not found.", 404);- if (!(await store.readDoc(projectId))) return err("Project not found.", 404);+ if (!(await store.readDoc(projectId)))+ return err("Project not found.", 404);return json({ fileName: await copyIntoProject(projectId, asset.fileName) });} catch (e) {return caught(e, "Could not add from library.");@@ -345,7 +394,7 @@ async function saveFromProject(req: Request): Promise<Response> {duration: known?.duration,width: known?.width,height: known?.height,- })+ }),);} catch (e) {return caught(e, "Could not save to library.");@@ -366,14 +415,20 @@ type TemplateInput = {async function saveTemplate(req: Request): Promise<Response> {try {- const { projectId, ...input } = (await req.json()) as { projectId: string } & TemplateInput;- if (!(await store.readDoc(projectId))) return err("Project not found.", 404);+ const { projectId, ...input } = (await req.json()) as {+ projectId: string;+ } & TemplateInput;+ if (!(await store.readDoc(projectId)))+ return err("Project not found.", 404);if (!input.media?.length && !input.texts?.length && !input.cues?.length) {return err("Nothing to save.", 500);}const media: TemplateMedia[] = [];for (const m of input.media ?? []) {- media.push({ ...m, fileName: await copyFromProject(projectId, m.fileName) });+ media.push({+ ...m,+ fileName: await copyFromProject(projectId, m.fileName),+ });}const template: LibraryTemplate = {id: crypto.randomUUID().slice(0, 8),@@ -395,15 +450,67 @@ async function saveTemplate(req: Request): Promise<Response> {}}-async function materializeTemplate(req: Request, id: string): Promise<Response> {+/** Take in a template carried off another shelf: its doc, and its media as+ * files in the doc's order — `layers` and `audio` point at `media` by index, so+ * only the file names change. */+async function importTemplate(req: Request): Promise<Response> {+ try {+ const form = await req.formData();+ const input = parseField<TemplateInput & { folderId?: string | null }>(+ form.get("doc"),+ );+ if (!input) return err("No template in the request.", 400);+ const files = form+ .getAll("file")+ .filter((f): f is File => f instanceof File);+ const media: TemplateMedia[] = [];+ for (const [i, m] of (input.media ?? []).entries()) {+ const file = files[i];+ if (!file) return err("Template media missing.", 400);+ const fileName = await store.saveLibraryMedia(+ file,+ m.fileName || file.name,+ );+ await register(fileName, file);+ media.push({ ...m, fileName });+ }+ const template: LibraryTemplate = {+ id: crypto.randomUUID().slice(0, 8),+ name: (input.name || "Template").trim().slice(0, 80),+ addedAt: Date.now(),+ duration: input.duration,+ media,+ layers: input.layers ?? [],+ audio: input.audio ?? [],+ texts: input.texts ?? [],+ cues: input.cues ?? [],+ folderId: input.folderId ?? null,+ };+ await mutateIndex((idx) => {+ idx.templates.push(template);+ });+ return json(template);+ } catch (e) {+ return caught(e, "Could not add the template.");+ }+}++async function materializeTemplate(+ req: Request,+ id: string,+): Promise<Response> {try {const { projectId } = (await req.json()) as { projectId: string };- if (!(await store.readDoc(projectId))) return err("Project not found.", 404);+ if (!(await store.readDoc(projectId)))+ return err("Project not found.", 404);const template = (await readIndex()).templates.find((t) => t.id === id);if (!template) return err("Template not found.", 404);const media: TemplateMedia[] = [];for (const m of template.media) {- media.push({ ...m, fileName: await copyIntoProject(projectId, m.fileName) });+ media.push({+ ...m,+ fileName: await copyIntoProject(projectId, m.fileName),+ });}return json({ template, media });} catch (e) {@@ -428,11 +535,16 @@ async function addToTemplate(req: Request, id: string): Promise<Response> {if (!t) throw new Error("Template not found.");const mi = t.media.length;t.media = [...t.media, { ...media, fileName: stored }];- if (audio) t.audio = [...t.audio, { ...audio, media: mi, start: t.duration }];- else if (layer) t.layers = [...t.layers, { ...layer, media: mi, start: t.duration }];+ if (audio)+ t.audio = [...t.audio, { ...audio, media: mi, start: t.duration }];+ else if (layer)+ t.layers = [+ ...t.layers,+ { ...layer, media: mi, start: t.duration },+ ];t.duration += extend;return t;- })+ }),);} catch (e) {await store.deleteLibraryMedia(stored);@@ -454,7 +566,7 @@ async function renameTemplate(req: Request, id: string): Promise<Response> {if (!template) throw new Error("Template not found.");template.name = trimmed.slice(0, 80);return template;- })+ }),);} catch (e) {return caught(e, "Could not rename the template.");@@ -488,7 +600,7 @@ export async function dispatchLibraryRoute(rest: string[],method: string,req: () => Request,- download: boolean+ download: boolean,): Promise<Response | null> {// /libraryif (rest.length === 0) {@@ -505,15 +617,20 @@ export async function dispatchLibraryRoute(if (rest[0] === "folders") {if (rest.length === 1 && method === "POST") return createFolder(req());- if (rest.length === 2 && method === "PUT") return renameFolder(req(), rest[1]);+ if (rest.length === 2 && method === "PUT")+ return renameFolder(req(), rest[1]);if (rest.length === 2 && method === "DELETE") return deleteFolder(rest[1]);return err("Not found.", 404);}if (rest[0] === "templates") {if (rest.length === 1 && method === "POST") return saveTemplate(req());- if (rest.length === 2 && method === "PUT") return renameTemplate(req(), rest[1]);- if (rest.length === 2 && method === "DELETE") return deleteTemplate(rest[1]);+ if (rest.length === 2 && rest[1] === "import" && method === "POST")+ return importTemplate(req());+ if (rest.length === 2 && method === "PUT")+ return renameTemplate(req(), rest[1]);+ if (rest.length === 2 && method === "DELETE")+ return deleteTemplate(rest[1]);if (rest.length === 3 && method === "POST") {if (rest[2] === "use") return materializeTemplate(req(), rest[1]);if (rest[2] === "add") return addToTemplate(req(), rest[1]);diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 1c8a7fd9..71070581 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -28,7 +28,12 @@ import {} from "./residency";import { useEditor } from "./store";import { playheadAt } from "./playhead";-import type { LibraryTemplate, MediaAsset, TemplateMedia, TemplateSaveInput } from "./types";+import type {+ LibraryTemplate,+ MediaAsset,+ TemplateMedia,+ TemplateSaveInput,+} from "./types";import { IMAGE_CLIP_SECONDS, mediaUrl } from "./types";export interface LibrarySource {@@ -76,15 +81,20 @@ export interface LibraryData {}export const libraryMediaUrl = (fileName: string, residency: Residency) =>- backendFor(residency).url(`/api/cut/library/media/${encodeURIComponent(fileName)}`);+ backendFor(residency).url(+ `/api/cut/library/media/${encodeURIComponent(fileName)}`,+ );/** The asset's cover image, when the import brought one back. */-export const libraryPosterUrl = (a: Pick<LibraryAsset, "posterFile" | "residency">) =>- a.posterFile ? libraryMediaUrl(a.posterFile, a.residency) : undefined;+export const libraryPosterUrl = (+ a: Pick<LibraryAsset, "posterFile" | "residency">,+) => (a.posterFile ? libraryMediaUrl(a.posterFile, a.residency) : undefined);/** Save a library file to the user's Downloads folder, off the shelf it sits* on. */-export function downloadLibraryAsset(a: Pick<LibraryAsset, "fileName" | "residency">) {+export function downloadLibraryAsset(+ a: Pick<LibraryAsset, "fileName" | "residency">,+) {downloadFromUrl(libraryMediaUrl(a.fileName, a.residency), a.fileName);}@@ -105,7 +115,9 @@ async function fetchLibraryFrom(r: Residency): Promise<LibraryData> {/** One shelf as this browser last saw it, for a residency it can't ask right* now. Those files are still on that Mac; only the way to reach them is gone. */-async function rememberedLibraryFrom(r: Residency): Promise<LibraryData | null> {+async function rememberedLibraryFrom(+ r: Residency,+): Promise<LibraryData | null> {const hit = await readSnapshot<LibraryData>(libraryShelfKey(r));return hit?.value ?? null;}@@ -121,13 +133,17 @@ async function rememberedLibraryFrom(r: Residency): Promise<LibraryData | null>* is entitled to see them; the editor's library picker doesn't, because an* item it can't copy into the project has no business in a picker.*/-export async function fetchLibrary(opts?: { remembered?: boolean }): Promise<LibraryData> {+export async function fetchLibrary(opts?: {+ remembered?: boolean;+}): Promise<LibraryData> {const live = availableResidencies();const rs = opts?.remembered ? listedResidencies() : live;const parts = await Promise.all(rs.map((r) =>- live.includes(r) ? fetchLibraryFrom(r).catch(() => null) : rememberedLibraryFrom(r)- )+ live.includes(r)+ ? fetchLibraryFrom(r).catch(() => null)+ : rememberedLibraryFrom(r),+ ),);const got = parts.filter((p): p is LibraryData => p !== null);if (got.length === 0) throw new Error("Could not load the library.");@@ -135,7 +151,9 @@ export async function fetchLibrary(opts?: { remembered?: boolean }): Promise<Lib[...items].sort((a, b) => b.addedAt - a.addedAt);return {assets: byNewest(got.flatMap((p) => p.assets)),- folders: got.flatMap((p) => p.folders).sort((a, b) => a.createdAt - b.createdAt),+ folders: got+ .flatMap((p) => p.folders)+ .sort((a, b) => a.createdAt - b.createdAt),templates: byNewest(got.flatMap((p) => p.templates)),};}@@ -149,7 +167,9 @@ export type ImportStage = "queued" | "downloading" | "saving";* the short-form feeds are vertical, everything else is filmed wide. The tile* takes the real shape the moment the media lands. */export function estimatedShape(url: string): { width: number; height: number } {- return SHORT_FORM_URL.test(url) ? { width: 9, height: 16 } : { width: 16, height: 9 };+ return SHORT_FORM_URL.test(url)+ ? { width: 9, height: 16 }+ : { width: 16, height: 9 };}const SHORT_FORM_URL =@@ -158,10 +178,11 @@ const SHORT_FORM_URL =export async function importUrlToLibrary(url: string,residency: Residency = activeResidency(),- onStage?: (stage: ImportStage) => void+ onStage?: (stage: ImportStage) => void,): Promise<LibraryAsset[]> {url = normalizeLink(url);- if (residency === "browser") return importUrlThroughCloud(url, "browser", onStage);+ if (residency === "browser")+ return importUrlThroughCloud(url, "browser", onStage);onStage?.("downloading");const backend = backendFor(residency);const res = await backend.fetch("/api/cut/library/import-url", {@@ -173,20 +194,26 @@ export async function importUrlToLibrary(// worker does the fetch, so that side waits on the job.if (backend.kind === "cloud") {const started = await apiJson<{ jobId?: string }>(res);- if (!res.ok || !started.jobId) throw new Error(started.error ?? "Could not import that URL.");+ if (!res.ok || !started.jobId)+ throw new Error(started.error ?? "Could not import that URL.");const done = await pollCloudJob<{ assets?: LibraryAsset[] }>(started.jobId,backend,"Could not import that URL.",- { onState: (state) => onStage?.(state === "queued" ? "queued" : "downloading") }+ {+ onState: (state) =>+ onStage?.(state === "queued" ? "queued" : "downloading"),+ },);// The library holds media, so a source that turned out to be only words// fails here — the same line the engine's library import draws.- if (!done.assets?.length) throw new Error("That link has no media to import.");+ if (!done.assets?.length)+ throw new Error("That link has no media to import.");return done.assets.map((a) => ({ ...a, residency }));}const body = await apiJson<LibraryAsset[]>(res);- if (res.ok) return (Array.isArray(body) ? body : []).map((a) => ({ ...a, residency }));+ if (res.ok)+ return (Array.isArray(body) ? body : []).map((a) => ({ ...a, residency }));// The engine fetches with the tools it ships, and a site can refuse the// build it happens to carry — TikTok reads the requests it impersonates with// and answers with nothing usable. The cloud worker fetches with a different@@ -215,7 +242,7 @@ export async function importUrlToLibrary(async function importUrlThroughCloud(url: string,target: Residency,- onStage?: (stage: ImportStage) => void+ onStage?: (stage: ImportStage) => void,): Promise<LibraryAsset[]> {onStage?.("downloading");const res = await cloudBackend.fetch("/api/cut/library/import-url", {@@ -224,22 +251,27 @@ async function importUrlThroughCloud(body: JSON.stringify({ url }),});const started = await apiJson<{ jobId?: string }>(res);- if (!res.ok || !started.jobId) throw new Error(started.error ?? "Could not import that URL.");+ if (!res.ok || !started.jobId)+ throw new Error(started.error ?? "Could not import that URL.");const done = await pollCloudJob<{ assets?: LibraryAsset[] }>(started.jobId,cloudBackend,"Could not import that URL.",- { onState: (state) => onStage?.(state === "queued" ? "queued" : "downloading") }+ {+ onState: (state) =>+ onStage?.(state === "queued" ? "queued" : "downloading"),+ },);// The library holds media, so a source that turned out to be only words// fails here — the same line the engine's library import draws.- if (!done.assets?.length) throw new Error("That link has no media to import.");+ if (!done.assets?.length)+ throw new Error("That link has no media to import.");const landed: LibraryAsset[] = [];onStage?.("saving");try {for (const staged of done.assets) {const bytes = await cloudBackend.fetch(- `/api/cut/library/media/${encodeURIComponent(staged.fileName)}`+ `/api/cut/library/media/${encodeURIComponent(staged.fileName)}`,);if (!bytes.ok) throw new Error("Could not import that URL.");const form = new FormData();@@ -247,9 +279,10 @@ async function importUrlThroughCloud(form.append("name", staged.name);if (staged.posterFile) {const poster = await cloudBackend.fetch(- `/api/cut/library/media/${encodeURIComponent(staged.posterFile)}`+ `/api/cut/library/media/${encodeURIComponent(staged.posterFile)}`,);- if (poster.ok) form.append("poster", await poster.blob(), staged.posterFile);+ if (poster.ok)+ form.append("poster", await poster.blob(), staged.posterFile);}form.append("meta",@@ -258,7 +291,7 @@ async function importUrlThroughCloud(duration: staged.duration,width: staged.width,height: staged.height,- })+ }),);if (staged.source) form.append("source", JSON.stringify(staged.source));const saved = await backendFor(target).fetch("/api/cut/library", {@@ -266,13 +299,15 @@ async function importUrlThroughCloud(body: form,});const body = await apiJson<LibraryAsset>(saved);- if (!saved.ok) throw new Error(body.error ?? "Could not import that URL.");+ if (!saved.ok)+ throw new Error(body.error ?? "Could not import that URL.");landed.push({ ...body, residency: target });}} catch (e) {// A part-written import is worse than none: the user reads an error and is// left holding half a link.- for (const a of landed) await deleteFromLibrary(target, a.id).catch(() => {});+ for (const a of landed)+ await deleteFromLibrary(target, a.id).catch(() => {});throw e;} finally {for (const staged of done.assets) {@@ -286,7 +321,7 @@ async function importUrlThroughCloud(export async function createLibraryFolder(name: string,- residency: Residency = activeResidency()+ residency: Residency = activeResidency(),): Promise<LibraryFolder> {const res = await backendFor(residency).fetch("/api/cut/library/folders", {method: "POST",@@ -301,20 +336,29 @@ export async function createLibraryFolder(export async function renameLibraryFolder(residency: Residency,id: string,- name: string+ name: string,): Promise<void> {- const res = await backendFor(residency).fetch(`/api/cut/library/folders/${id}`, {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name }),- });+ const res = await backendFor(residency).fetch(+ `/api/cut/library/folders/${id}`,+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name }),+ },+ );if (!res.ok) throw new Error("Could not rename folder.");}-export async function deleteLibraryFolder(residency: Residency, id: string): Promise<void> {- const res = await backendFor(residency).fetch(`/api/cut/library/folders/${id}`, {- method: "DELETE",- });+export async function deleteLibraryFolder(+ residency: Residency,+ id: string,+): Promise<void> {+ const res = await backendFor(residency).fetch(+ `/api/cut/library/folders/${id}`,+ {+ method: "DELETE",+ },+ );if (!res.ok) throw new Error("Could not delete folder.");}@@ -324,7 +368,7 @@ export async function deleteLibraryFolder(residency: Residency, id: string): Proexport async function moveLibraryItem(residency: Residency,id: string,- folderId: string | null+ folderId: string | null,): Promise<void> {const res = await backendFor(residency).fetch("/api/cut/library/move", {method: "POST",@@ -345,24 +389,30 @@ export async function moveLibraryItem(export async function carryAssetTo(asset: LibraryAsset,to: Residency,- folderId: string | null+ folderId: string | null,): Promise<LibraryAsset> {const res = await backendFor(asset.residency).fetch(- `/api/cut/library/media/${encodeURIComponent(asset.fileName)}`+ `/api/cut/library/media/${encodeURIComponent(asset.fileName)}`,);if (!res.ok) throw new Error("Could not read that file off its shelf.");const from = libraryPosterUrl(asset);const cover = from? await backendFor(asset.residency)- .fetch(`/api/cut/library/media/${encodeURIComponent(asset.posterFile!)}`)+ .fetch(+ `/api/cut/library/media/${encodeURIComponent(asset.posterFile!)}`,+ ).then((r) => (r.ok ? r.blob() : null)).catch(() => null): null;- const landed = await uploadToLibrary(new File([await res.blob()], asset.fileName), to, {- name: asset.name,- ...(asset.source ? { source: asset.source } : {}),- ...(cover ? { poster: cover } : {}),- });+ const landed = await uploadToLibrary(+ new File([await res.blob()], asset.fileName),+ to,+ {+ name: asset.name,+ ...(asset.source ? { source: asset.source } : {}),+ ...(cover ? { poster: cover } : {}),+ },+ );if (folderId) await moveLibraryItem(to, landed.id, folderId).catch(() => {});await deleteFromLibrary(asset.residency, asset.id).catch(() => {});return { ...landed, folderId };@@ -375,9 +425,13 @@ export async function carryAssetTo(* family name the font calls itself — the shelf's label and the font menu's —* and a specimen drawn in the face it just installed, which becomes the file's* cover, so a card never has to have the font installed to show it. */-async function checkFont(file: File): Promise<{ label: string; poster: Blob | null }> {+async function checkFont(+ file: File,+): Promise<{ label: string; poster: Blob | null }> {if (file.size > MAX_FONT_BYTES) {- throw new Error(`Fonts are limited to ${Math.round(MAX_FONT_BYTES / 1024 ** 2)}MB.`);+ throw new Error(+ `Fonts are limited to ${Math.round(MAX_FONT_BYTES / 1024 ** 2)}MB.`,+ );}const bytes = await file.arrayBuffer();const family = `lf-check-${file.size}`;@@ -398,7 +452,7 @@ export async function uploadToLibrary(/** What the shelf should call it and where it came from, when the file is* arriving from somewhere that already knows — a carry from another shelf,* say. Left out, the file names itself and keeps whatever cover it makes. */- keep: { name?: string; source?: LibrarySource; poster?: Blob } = {}+ keep: { name?: string; source?: LibrarySource; poster?: Blob } = {},): Promise<LibraryAsset> {const backend = backendFor(residency);// A font has no streams to measure; it is checked by installing it instead,@@ -413,19 +467,32 @@ export async function uploadToLibrary(// cloud can't cheaply probe an R2 object the way the engine probes disk.// A file this browser can't decode would land as a zero-length asset it// also couldn't preview, so reject it before any bytes go up.- const meta = fontLabel ? fontMeta : await probeFileMeta(file).catch(() => null);- if (!meta || (meta.type !== "image" && meta.type !== "font" && !(meta.duration > 0))) {+ const meta = fontLabel+ ? fontMeta+ : await probeFileMeta(file).catch(() => null);+ if (+ !meta ||+ (meta.type !== "image" && meta.type !== "font" && !(meta.duration > 0))+ ) {throw new Error(- "This file can't be read in this browser, so it can't go in the cloud library. Import it in the Mac app instead."+ "This file can't be read in this browser, so it can't go in the cloud library. Import it in the Mac app instead.",);}- const key = await presignedUpload("/api/cut/library/presign", file, file.name, backend);+ const key = await presignedUpload(+ "/api/cut/library/presign",+ file,+ file.name,+ backend,+ );// The cover rides up as an object of its own; `complete` marks it and// records it against the asset.const posterKey = poster- ? await presignedUpload("/api/cut/library/presign", poster, posterName, backend).catch(- () => null- )+ ? await presignedUpload(+ "/api/cut/library/presign",+ poster,+ posterName,+ backend,+ ).catch(() => null): null;const res = await backend.fetch("/api/cut/library/complete", {method: "POST",@@ -454,20 +521,32 @@ export async function uploadToLibrary(// The shelf is this page's storage, with no ffprobe behind it: the file is// measured here, and one this browser can't read is refused rather than// shelved as an asset nothing can play.- const meta = fontLabel ? fontMeta : await probeFileMeta(file).catch(() => null);- if (!meta || (meta.type !== "image" && meta.type !== "font" && !(meta.duration > 0))) {- throw new Error("This file can't be read in this browser, so it can't go in the library.");+ const meta = fontLabel+ ? fontMeta+ : await probeFileMeta(file).catch(() => null);+ if (+ !meta ||+ (meta.type !== "image" && meta.type !== "font" && !(meta.duration > 0))+ ) {+ throw new Error(+ "This file can't be read in this browser, so it can't go in the library.",+ );}form.append("meta", JSON.stringify(meta));}- const res = await backend.fetch("/api/cut/library", { method: "POST", body: form });+ const res = await backend.fetch("/api/cut/library", {+ method: "POST",+ body: form,+ });const body = await apiJson<LibraryAsset>(res);if (!res.ok) throw new Error(body.error ?? "Upload failed.");return { ...body, residency };}export async function deleteFromLibrary(residency: Residency, id: string) {- const res = await backendFor(residency).fetch(`/api/cut/library/${id}`, { method: "DELETE" });+ const res = await backendFor(residency).fetch(`/api/cut/library/${id}`, {+ method: "DELETE",+ });if (!res.ok) throw new Error("Could not delete.");}@@ -482,7 +561,7 @@ async function copyLibraryFileToProject(residency: Residency,fileName: string,assetId?: string,- opts?: { onProgress?: (fraction: number) => void; signal?: AbortSignal }+ opts?: { onProgress?: (fraction: number) => void; signal?: AbortSignal },): Promise<string> {const target = getBackend();if (assetId && residency === target.kind) {@@ -493,15 +572,22 @@ async function copyLibraryFileToProject(signal: opts?.signal,});const body = await apiJson<{ fileName?: string }>(res);- if (!res.ok || !body.fileName) throw new Error(body.error ?? "Could not add from library.");+ if (!res.ok || !body.fileName)+ throw new Error(body.error ?? "Could not add from library.");return body.fileName;}const bytes = await backendFor(residency).fetch(`/api/cut/library/media/${encodeURIComponent(fileName)}`,- { signal: opts?.signal }+ { signal: opts?.signal },);if (!bytes.ok) throw new Error("Could not read that library file.");- return uploadProjectMediaTo(target, projectId, await bytes.blob(), fileName, opts);+ return uploadProjectMediaTo(+ target,+ projectId,+ await bytes.blob(),+ fileName,+ opts,+ );}/** Register a library asset in the open project's media, without placing it on@@ -511,9 +597,10 @@ async function copyLibraryFileToProject(* across residencies). */export async function importLibraryAsset(projectId: string,- lib: LibraryAsset+ lib: LibraryAsset,): Promise<MediaAsset> {- if (lib.type === "font") throw new Error("Fonts are used from the font menu, not the timeline.");+ if (lib.type === "font")+ throw new Error("Fonts are used from the font menu, not the timeline.");return importRemote(projectId,{@@ -525,7 +612,14 @@ export async function importLibraryAsset(width: lib.width,height: lib.height,},- (opts) => copyLibraryFileToProject(projectId, lib.residency, lib.fileName, lib.id, opts)+ (opts) =>+ copyLibraryFileToProject(+ projectId,+ lib.residency,+ lib.fileName,+ lib.id,+ opts,+ ),);}@@ -533,7 +627,7 @@ export async function importLibraryAsset(* the playhead. */export async function addLibraryAssetToProject(projectId: string,- lib: LibraryAsset+ lib: LibraryAsset,): Promise<MediaAsset> {const asset = await importLibraryAsset(projectId, lib);useEditor.getState().addAssetAtPlayhead(asset.id);@@ -544,7 +638,7 @@ export async function addLibraryAssetToProject(* the project's own shelf: the server copies the media straight across. */export async function saveTemplate(projectId: string,- input: TemplateSaveInput+ input: TemplateSaveInput,): Promise<LibraryTemplateItem> {const residency = activeResidency();const res = await backendFor(residency).fetch("/api/cut/library/templates", {@@ -557,6 +651,68 @@ export async function saveTemplate(return { ...body, residency };}+/**+ * Carry a template to another shelf, filed where it lands.+ *+ * A template's media live privately in the library, so the carry takes them+ * with it: the files come down here and go up on the target shelf — presigned+ * objects in the cloud, a multipart post anywhere else — and the doc arrives in+ * the same order, since `layers` and `audio` point at `media` by index. The+ * template left behind comes off.+ */+export async function carryTemplateTo(+ t: LibraryTemplateItem,+ to: Residency,+ folderId: string | null,+): Promise<void> {+ const source = backendFor(t.residency);+ const files: File[] = [];+ for (const m of t.media) {+ const res = await source.fetch(+ `/api/cut/library/media/${encodeURIComponent(m.fileName)}`,+ );+ if (!res.ok)+ throw new Error("Could not read that template's media off its shelf.");+ files.push(new File([await res.blob()], m.fileName));+ }+ const input = {+ name: t.name,+ folderId,+ duration: t.duration,+ media: t.media,+ layers: t.layers,+ audio: t.audio,+ texts: t.texts,+ cues: t.cues,+ };+ const backend = backendFor(to);+ let res: Response;+ if (to === "cloud") {+ const keys: string[] = [];+ for (const f of files) {+ keys.push(+ await presignedUpload("/api/cut/library/presign", f, f.name, backend),+ );+ }+ res = await backend.fetch("/api/cut/library/templates/import", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...input, keys }),+ });+ } else {+ const form = new FormData();+ form.append("doc", JSON.stringify(input));+ for (const f of files) form.append("file", f, f.name);+ res = await backend.fetch("/api/cut/library/templates/import", {+ method: "POST",+ body: form,+ });+ }+ const body = await apiJson<LibraryTemplate>(res);+ if (!res.ok) throw new Error(body.error ?? "Could not add the template.");+ await deleteTemplate(t.residency, t.id);+}+/** Append a project asset to a library template as one more part at its end:* the server copies the file into the library and returns the updated* template. Same-shelf only — the copy happens server-side, where neither@@ -564,13 +720,13 @@ export async function saveTemplate(export async function addAssetToLibraryTemplate(projectId: string,template: LibraryTemplateItem,- asset: MediaAsset+ asset: MediaAsset,): Promise<LibraryTemplateItem> {if (template.residency !== getBackend().kind) {throw new Error(template.residency === "cloud"? "That template is in the cloud; this project isn't."- : "That template is on this Mac; this project isn't."+ : "That template is on this Mac; this project isn't.",);}const len = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;@@ -578,23 +734,26 @@ export async function addAssetToLibraryTemplate(asset.type === "audio"? { audio: { in: 0, out: len, volume: 1 } }: { layer: { in: 0, out: len, muted: false, track: 1, asClip: true } };- const res = await getBackend().fetch(`/api/cut/library/templates/${template.id}/add`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- projectId,- media: {- fileName: asset.fileName,- name: asset.name,- type: asset.type,- duration: asset.duration,- width: asset.width,- height: asset.height,- },- extend: len,- ...part,- }),- });+ const res = await getBackend().fetch(+ `/api/cut/library/templates/${template.id}/add`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ projectId,+ media: {+ fileName: asset.fileName,+ name: asset.name,+ type: asset.type,+ duration: asset.duration,+ width: asset.width,+ height: asset.height,+ },+ extend: len,+ ...part,+ }),+ },+ );const body = await apiJson<LibraryTemplate>(res);if (!res.ok) throw new Error(body.error ?? "Could not add to the template.");return { ...body, residency: template.residency };@@ -603,20 +762,29 @@ export async function addAssetToLibraryTemplate(export async function renameTemplate(residency: Residency,id: string,- name: string+ name: string,): Promise<void> {- const res = await backendFor(residency).fetch(`/api/cut/library/templates/${id}`, {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name }),- });+ const res = await backendFor(residency).fetch(+ `/api/cut/library/templates/${id}`,+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name }),+ },+ );if (!res.ok) throw new Error("Could not rename the template.");}-export async function deleteTemplate(residency: Residency, id: string): Promise<void> {- const res = await backendFor(residency).fetch(`/api/cut/library/templates/${id}`, {- method: "DELETE",- });+export async function deleteTemplate(+ residency: Residency,+ id: string,+): Promise<void> {+ const res = await backendFor(residency).fetch(+ `/api/cut/library/templates/${id}`,+ {+ method: "DELETE",+ },+ );if (!res.ok) throw new Error("Could not delete the template.");}@@ -625,21 +793,29 @@ export async function deleteTemplate(residency: Residency, id: string): Promise<* whole copy server-side; off it each file rides through the browser. */async function copyTemplateMediaToProject(projectId: string,- template: LibraryTemplateItem+ template: LibraryTemplateItem,): Promise<TemplateMedia[]> {if (template.residency === getBackend().kind) {- const res = await getBackend().fetch(`/api/cut/library/templates/${template.id}/use`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ projectId }),- });+ const res = await getBackend().fetch(+ `/api/cut/library/templates/${template.id}/use`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ projectId }),+ },+ );const body = await apiJson<{ media?: TemplateMedia[] }>(res);- if (!res.ok || !body.media) throw new Error(body.error ?? "Could not add the template.");+ if (!res.ok || !body.media)+ throw new Error(body.error ?? "Could not add the template.");return body.media;}const out: TemplateMedia[] = [];for (const m of template.media) {- const fileName = await copyLibraryFileToProject(projectId, template.residency, m.fileName);+ const fileName = await copyLibraryFileToProject(+ projectId,+ template.residency,+ m.fileName,+ );out.push({ ...m, fileName });}return out;@@ -650,7 +826,7 @@ async function copyTemplateMediaToProject(export async function addTemplateToProject(projectId: string,template: LibraryTemplateItem,- at?: number+ at?: number,): Promise<void> {const media = await copyTemplateMediaToProject(projectId, template);@@ -681,7 +857,7 @@ export async function addTemplateToProject(* Nothing is placed on the timeline. */export async function importTemplateToProject(projectId: string,- template: LibraryTemplateItem+ template: LibraryTemplateItem,): Promise<void> {const media = await copyTemplateMediaToProject(projectId, template);useEditor.getState().addTemplate({@@ -701,7 +877,7 @@ export async function importTemplateToProject(export function addProjectTemplateToTimeline(projectId: string,template: LibraryTemplate,- at?: number+ at?: number,) {const s = useEditor.getState();const assetIds = template.media.map((m) => {@@ -728,13 +904,17 @@ export function addProjectTemplateToTimeline(* project's own shelf, where the server can copy the bytes itself. */export async function saveAssetToLibrary(projectId: string,- asset: MediaAsset+ asset: MediaAsset,): Promise<LibraryAsset> {const residency = activeResidency();const res = await backendFor(residency).fetch("/api/cut/library/save", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ projectId, fileName: asset.fileName, name: asset.name }),+ body: JSON.stringify({+ projectId,+ fileName: asset.fileName,+ name: asset.name,+ }),});const body = await apiJson<LibraryAsset>(res);if (!res.ok) throw new Error(body.error ?? "Could not save to library.");diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.tsindex 4058e52d..dd3916f3 100644--- a/site/src/cut/server/cloud/library.ts+++ b/site/src/cut/server/cloud/library.ts@@ -18,7 +18,15 @@ import { mediaObjectUrl } from "./mediaCdn";import { getProject, takenMediaNames } from "./projects";import { copy, del, head, libraryKey, presignPut, projectMediaKey } from "./r2";import { addUsage, quotaCheck } from "./usage";-import { caught, decodeFileParam, dedupeName, err, redirect, safeFileName, typeOf } from "./util";+import {+ caught,+ decodeFileParam,+ dedupeName,+ err,+ redirect,+ safeFileName,+ typeOf,+} from "./util";/** Descriptive fields the engine derives with ffprobe; the cloud stores them on* the row, supplied by the client (which probed in the browser) or copied from@@ -64,7 +72,7 @@ async function takenLibraryNames(userId: string): Promise<Set<string>> {function assetView(row: { id: string; folderId: string | null; meta: unknown; createdAt: Date },- obj: { fileName: string }+ obj: { fileName: string },): LibraryAsset {const meta = (row.meta ?? {}) as AssetMeta;return {@@ -81,7 +89,12 @@ function assetView(};}-function templateView(row: { id: string; name: string; doc: unknown; createdAt: Date }): LibraryTemplate {+function templateView(row: {+ id: string;+ name: string;+ doc: unknown;+ createdAt: Date;+}): LibraryTemplate {const doc = row.doc as unknown as TemplateDoc;return {id: row.id,@@ -105,9 +118,19 @@ async function findTemplate(userId: string, id: string) {/** A project media object row, complete, by fileName — the copy source for* save/saveTemplate/addToTemplate. */-async function projectMediaObject(userId: string, projectId: string, fileName: string) {+async function projectMediaObject(+ userId: string,+ projectId: string,+ fileName: string,+) {return prisma.cutMediaObject.findFirst({- where: { userId, projectId, kind: "media", fileName, uploadState: "complete" },+ where: {+ userId,+ projectId,+ kind: "media",+ fileName,+ uploadState: "complete",+ },});}@@ -122,7 +145,7 @@ async function libraryMediaObject(userId: string, fileName: string) {async function copyIntoLibrary(userId: string,src: MediaObjectRow,- taken: Set<string>+ taken: Set<string>,): Promise<string> {const dest = dedupeName(safeFileName(src.fileName), taken);taken.add(dest);@@ -150,9 +173,11 @@ async function copyIntoLibrary(* route and the storage-reclamation sweep (gc.ts). */export async function deleteLibraryAssetCascade(userId: string,- id: string+ id: string,): Promise<number | null> {- const asset = await prisma.cutLibraryAsset.findFirst({ where: { id, userId } });+ const asset = await prisma.cutLibraryAsset.findFirst({+ where: { id, userId },+ });if (!asset) return null;const obj = await prisma.cutMediaObject.findFirst({where: { id: asset.mediaObjectId, userId },@@ -171,7 +196,8 @@ export async function deleteLibraryAssetCascade(.reduce((n, o) => n + Number(o.bytes), 0);await prisma.$transaction(async (tx) => {await tx.cutLibraryAsset.delete({ where: { id } });- for (const o of objects) await tx.cutMediaObject.delete({ where: { id: o.id } });+ for (const o of objects)+ await tx.cutMediaObject.delete({ where: { id: o.id } });if (freed > 0) await addUsage(tx, userId, -freed);});if (objects.length > 0) await del(objects.map((o) => o.r2Key));@@ -184,7 +210,7 @@ async function copyIntoProject(userId: string,projectId: string,libFileName: string,- taken: Set<string>+ taken: Set<string>,): Promise<string> {const src = await libraryMediaObject(userId, libFileName);if (!src) throw new Error("Library asset not found.");@@ -216,7 +242,8 @@ async function deleteLibraryObject(userId: string, fileName: string) {if (!row) return;await prisma.$transaction(async (tx) => {await tx.cutMediaObject.delete({ where: { id: row.id } });- if (row.uploadState === "complete") await addUsage(tx, userId, -Number(row.bytes));+ if (row.uploadState === "complete")+ await addUsage(tx, userId, -Number(row.bytes));});await del([row.r2Key]);}@@ -224,9 +251,18 @@ async function deleteLibraryObject(userId: string, fileName: string) {export const libraryCloud = {async list(userId: string) {const [assetRows, folderRows, templateRows] = await Promise.all([- prisma.cutLibraryAsset.findMany({ where: { userId }, orderBy: { createdAt: "desc" } }),- prisma.cutFolder.findMany({ where: { userId, scope: "library" }, orderBy: { createdAt: "asc" } }),- prisma.cutTemplate.findMany({ where: { userId }, orderBy: { createdAt: "desc" } }),+ prisma.cutLibraryAsset.findMany({+ where: { userId },+ orderBy: { createdAt: "desc" },+ }),+ prisma.cutFolder.findMany({+ where: { userId, scope: "library" },+ orderBy: { createdAt: "asc" },+ }),+ prisma.cutTemplate.findMany({+ where: { userId },+ orderBy: { createdAt: "desc" },+ }),]);const objs = await prisma.cutMediaObject.findMany({where: { id: { in: assetRows.map((r) => r.mediaObjectId) } },@@ -251,16 +287,26 @@ export const libraryCloud = {/** Mint a presigned PUT for a direct-to-library upload. */async presign(userId: string, req: Request) {try {- const body = (await req.json()) as { fileName?: string; mime?: string; bytes?: number };+ const body = (await req.json()) as {+ fileName?: string;+ mime?: string;+ bytes?: number;+ };if (!body.fileName || typeof body.bytes !== "number" || body.bytes <= 0) {return err("fileName and bytes are required.", 400);}if (!typeOf(body.fileName)) return err("Unsupported file type.", 400);const over = await quotaCheck(userId, body.bytes);if (over) return over;- const fileName = dedupeName(safeFileName(body.fileName), await takenLibraryNames(userId));+ const fileName = dedupeName(+ safeFileName(body.fileName),+ await takenLibraryNames(userId),+ );const key = libraryKey(userId, fileName);- const url = await presignPut(key, body.mime ?? "application/octet-stream");+ const url = await presignPut(+ key,+ body.mime ?? "application/octet-stream",+ );await prisma.cutMediaObject.create({data: {userId,@@ -287,18 +333,28 @@ export const libraryCloud = {meta?: AssetMeta;};if (!key) return err("key is required.", 400);- const obj = await prisma.cutMediaObject.findFirst({ where: { userId, r2Key: key } });+ const obj = await prisma.cutMediaObject.findFirst({+ where: { userId, r2Key: key },+ });if (!obj) return err("Unknown upload.", 404);const info = obj.uploadState === "complete" ? null : await head(key);- if (obj.uploadState !== "complete" && !info) return err("The upload never arrived.", 400);+ if (obj.uploadState !== "complete" && !info)+ return err("The upload never arrived.", 400);// A cover that came up alongside the file: its own object, finished the// same way, named on the asset so the delete cascade takes it too.const posterObj = posterKey- ? await prisma.cutMediaObject.findFirst({ where: { userId, r2Key: posterKey } })+ ? await prisma.cutMediaObject.findFirst({+ where: { userId, r2Key: posterKey },+ }): null;const posterInfo =- posterObj && posterObj.uploadState !== "complete" ? await head(posterKey!) : null;- const posterFile = posterInfo || posterObj?.uploadState === "complete" ? posterObj!.fileName : undefined;+ posterObj && posterObj.uploadState !== "complete"+ ? await head(posterKey!)+ : null;+ const posterFile =+ posterInfo || posterObj?.uploadState === "complete"+ ? posterObj!.fileName+ : undefined;const row = await prisma.$transaction(async (tx) => {if (posterObj && posterInfo) {await tx.cutMediaObject.update({@@ -330,9 +386,11 @@ export const libraryCloud = {name: meta?.name ?? obj.fileName,type: meta?.type ?? typeOf(obj.fileName) ?? "video",duration: meta?.duration ?? 0,- ...(meta?.width ? { width: meta.width, height: meta.height } : {}),+ ...(meta?.width+ ? { width: meta.width, height: meta.height }+ : {}),...(meta?.source ? { source: meta.source } : {}),- ...(posterFile ?? meta?.posterFile+ ...((posterFile ?? meta?.posterFile)? { posterFile: posterFile ?? meta?.posterFile }: {}),} as unknown as Prisma.InputJsonValue,@@ -348,17 +406,25 @@ export const libraryCloud = {/** Copy a library asset into a project's media space. */async use(userId: string, req: Request) {try {- const { assetId, projectId } = (await req.json()) as { assetId: string; projectId: string };- const asset = await prisma.cutLibraryAsset.findFirst({ where: { id: assetId, userId } });+ const { assetId, projectId } = (await req.json()) as {+ assetId: string;+ projectId: string;+ };+ const asset = await prisma.cutLibraryAsset.findFirst({+ where: { id: assetId, userId },+ });if (!asset) throw new Error("Library asset not found.");- const obj = await prisma.cutMediaObject.findUnique({ where: { id: asset.mediaObjectId } });+ const obj = await prisma.cutMediaObject.findUnique({+ where: { id: asset.mediaObjectId },+ });if (!obj) throw new Error("Library asset not found.");- if (!(await getProject(userId, projectId))) throw new Error("Project not found.");+ if (!(await getProject(userId, projectId)))+ throw new Error("Project not found.");const fileName = await copyIntoProject(userId,projectId,obj.fileName,- await takenMediaNames(userId, projectId)+ await takenMediaNames(userId, projectId),);return Response.json({ fileName });} catch (e) {@@ -377,10 +443,14 @@ export const libraryCloud = {const src = await projectMediaObject(userId, projectId, fileName);if (!src) throw new Error("Media file not found in project.");const project = await getProject(userId, projectId);- const docAsset = (project?.doc as { assets?: StoredAsset[] } | undefined)?.assets?.find(- (a) => a.fileName === fileName+ const docAsset = (+ project?.doc as { assets?: StoredAsset[] } | undefined+ )?.assets?.find((a) => a.fileName === fileName);+ const dest = await copyIntoLibrary(+ userId,+ src,+ await takenLibraryNames(userId),);- const dest = await copyIntoLibrary(userId, src, await takenLibraryNames(userId));const obj = await libraryMediaObject(userId, dest);if (!obj) throw new Error("Could not save to library.");const row = await prisma.cutLibraryAsset.create({@@ -391,7 +461,9 @@ export const libraryCloud = {name: name || fileName,type: docAsset?.type ?? typeOf(dest) ?? "video",duration: docAsset?.duration ?? 0,- ...(docAsset?.width ? { width: docAsset.width, height: docAsset.height } : {}),+ ...(docAsset?.width+ ? { width: docAsset.width, height: docAsset.height }+ : {}),} as unknown as Prisma.InputJsonValue,},});@@ -404,16 +476,24 @@ export const libraryCloud = {/** Move an item — asset or template — into a folder (or `null` to ungroup). */async move(userId: string, req: Request) {try {- const { id, folderId } = (await req.json()) as { id: string; folderId: string | null };+ const { id, folderId } = (await req.json()) as {+ id: string;+ folderId: string | null;+ };if (folderId) {const folder = await prisma.cutFolder.findFirst({where: { id: folderId, userId, scope: "library" },});if (!folder) throw new Error("Folder not found.");}- const asset = await prisma.cutLibraryAsset.findFirst({ where: { id, userId } });+ const asset = await prisma.cutLibraryAsset.findFirst({+ where: { id, userId },+ });if (asset) {- await prisma.cutLibraryAsset.update({ where: { id }, data: { folderId: folderId ?? null } });+ await prisma.cutLibraryAsset.update({+ where: { id },+ data: { folderId: folderId ?? null },+ });return Response.json({ ok: true });}const template = await findTemplate(userId, id);@@ -445,8 +525,8 @@ export const libraryCloud = {return redirect(mediaObjectUrl(libraryKey(userId, fileName),- download ? { downloadName: fileName } : undefined- )+ download ? { downloadName: fileName } : undefined,+ ),);} catch (e) {return caught(e, "Bad request.", 400);@@ -463,7 +543,11 @@ export const libraryCloud = {const row = await prisma.cutFolder.create({data: { userId, name: trimmed.slice(0, 80), scope: "library" },});- return Response.json({ id: row.id, name: row.name, createdAt: row.createdAt.getTime() });+ return Response.json({+ id: row.id,+ name: row.name,+ createdAt: row.createdAt.getTime(),+ });} catch (e) {return caught(e, "Could not create folder.");}@@ -474,7 +558,9 @@ export const libraryCloud = {const { name } = (await req.json()) as { name?: string };const trimmed = (name ?? "").trim();if (!trimmed) throw new Error("Folder name required.");- const row = await prisma.cutFolder.findFirst({ where: { id, userId, scope: "library" } });+ const row = await prisma.cutFolder.findFirst({+ where: { id, userId, scope: "library" },+ });if (!row) throw new Error("Folder not found.");const updated = await prisma.cutFolder.update({where: { id },@@ -493,7 +579,9 @@ export const libraryCloud = {async deleteFolder(userId: string, id: string) {try {await prisma.$transaction(async (tx) => {- await tx.cutFolder.deleteMany({ where: { id, userId, scope: "library" } });+ await tx.cutFolder.deleteMany({+ where: { id, userId, scope: "library" },+ });// Items in the folder fall back to ungrouped rather than vanishing.await tx.cutLibraryAsset.updateMany({where: { userId, folderId: id },@@ -522,8 +610,11 @@ export const libraryCloud = {* copied into the library privately, then the edit is stored. */async saveTemplate(userId: string, req: Request) {try {- const { projectId, ...input } = (await req.json()) as { projectId: string } & TemplateInput;- if (!(await getProject(userId, projectId))) throw new Error("Project not found.");+ const { projectId, ...input } = (await req.json()) as {+ projectId: string;+ } & TemplateInput;+ if (!(await getProject(userId, projectId)))+ throw new Error("Project not found.");if (!input.media?.length && !input.texts?.length && !input.cues?.length) {throw new Error("Nothing to save.");}@@ -533,7 +624,14 @@ export const libraryCloud = {const src = await projectMediaObject(userId, projectId, m.fileName);if (!src) throw new Error("Media file not found in project.");const dest = await copyIntoLibrary(userId, src, taken);- media.push({ fileName: dest, name: m.name, type: m.type, duration: m.duration, width: m.width, height: m.height });+ media.push({+ fileName: dest,+ name: m.name,+ type: m.type,+ duration: m.duration,+ width: m.width,+ height: m.height,+ });}const doc: TemplateDoc = {folderId: null,@@ -545,7 +643,11 @@ export const libraryCloud = {cues: input.cues ?? [],};const row = await prisma.cutTemplate.create({- data: { userId, name: (input.name || "Template").trim().slice(0, 80), doc: asJson(doc) },+ data: {+ userId,+ name: (input.name || "Template").trim().slice(0, 80),+ doc: asJson(doc),+ },});return Response.json(templateView(row));} catch (e) {@@ -553,19 +655,84 @@ export const libraryCloud = {}},+ /** Take in a template carried off another shelf: its media are presigned+ * objects already in R2, named here in the doc's own order. */+ async importTemplate(userId: string, req: Request) {+ try {+ const { keys, ...input } = (await req.json()) as TemplateInput & {+ keys?: string[];+ folderId?: string | null;+ };+ if (!input.media?.length && !input.texts?.length && !input.cues?.length) {+ throw new Error("Nothing to add.");+ }+ const media: TemplateMedia[] = [];+ for (const [i, m] of (input.media ?? []).entries()) {+ const key = keys?.[i];+ const obj = key+ ? await prisma.cutMediaObject.findFirst({+ where: { userId, r2Key: key },+ })+ : null;+ if (!obj) throw new Error("Template media missing.");+ if (obj.uploadState !== "complete") {+ const info = await head(key!);+ if (!info) throw new Error("The upload never arrived.");+ await prisma.$transaction(async (tx) => {+ await tx.cutMediaObject.update({+ where: { id: obj.id },+ data: {+ uploadState: "complete",+ bytes: BigInt(info.bytes),+ ...(info.mime ? { mime: info.mime } : {}),+ },+ });+ await addUsage(tx, userId, info.bytes);+ });+ }+ media.push({ ...m, fileName: obj.fileName });+ }+ const doc: TemplateDoc = {+ folderId: input.folderId ?? null,+ duration: input.duration,+ media,+ layers: input.layers ?? [],+ audio: input.audio ?? [],+ texts: input.texts ?? [],+ cues: input.cues ?? [],+ };+ const row = await prisma.cutTemplate.create({+ data: {+ userId,+ name: (input.name || "Template").trim().slice(0, 80),+ doc: asJson(doc),+ },+ });+ return Response.json(templateView(row));+ } catch (e) {+ return caught(e, "Could not add the template.");+ }+ },+/** Materialize a template into a project: copy its media in and hand back the* project file names (in template media order) plus the stored edit. */async useTemplate(userId: string, id: string, req: Request) {try {const { projectId } = (await req.json()) as { projectId: string };- if (!(await getProject(userId, projectId))) throw new Error("Project not found.");+ if (!(await getProject(userId, projectId)))+ throw new Error("Project not found.");const row = await findTemplate(userId, id);if (!row) throw new Error("Template not found.");const template = templateView(row);const taken = await takenMediaNames(userId, projectId);const media: TemplateMedia[] = [];for (const m of template.media) {- const dest = await copyIntoProject(userId, projectId, m.fileName, taken);+ const dest = await copyIntoProject(+ userId,+ projectId,+ m.fileName,+ taken,+ );media.push({ ...m, fileName: dest });}return Response.json({ template, media });@@ -586,24 +753,41 @@ export const libraryCloud = {};const row = await findTemplate(userId, id);if (!row) throw new Error("Template not found.");- const src = await projectMediaObject(userId, projectId, input.media.fileName);+ const src = await projectMediaObject(+ userId,+ projectId,+ input.media.fileName,+ );if (!src) throw new Error("Media file not found in project.");- const dest = await copyIntoLibrary(userId, src, await takenLibraryNames(userId));- const doc = (row.doc as unknown as TemplateDoc);+ const dest = await copyIntoLibrary(+ userId,+ src,+ await takenLibraryNames(userId),+ );+ const doc = row.doc as unknown as TemplateDoc;const mi = (doc.media ?? []).length;const next: TemplateDoc = {...doc,media: [...(doc.media ?? []), { ...input.media, fileName: dest }],audio: input.audio- ? [...(doc.audio ?? []), { ...input.audio, media: mi, start: doc.duration }]- : doc.audio ?? [],+ ? [+ ...(doc.audio ?? []),+ { ...input.audio, media: mi, start: doc.duration },+ ]+ : (doc.audio ?? []),layers:!input.audio && input.layer- ? [...(doc.layers ?? []), { ...input.layer, media: mi, start: doc.duration }]- : doc.layers ?? [],+ ? [+ ...(doc.layers ?? []),+ { ...input.layer, media: mi, start: doc.duration },+ ]+ : (doc.layers ?? []),duration: doc.duration + input.extend,};- const updated = await prisma.cutTemplate.update({ where: { id }, data: { doc: asJson(next) } });+ const updated = await prisma.cutTemplate.update({+ where: { id },+ data: { doc: asJson(next) },+ });return Response.json(templateView(updated));} catch (e) {return caught(e, "Could not add to the template.");@@ -634,7 +818,8 @@ export const libraryCloud = {await prisma.cutTemplate.delete({ where: { id } });// The media copies are private to this template, so removing them is safe.const doc = row.doc as unknown as TemplateDoc;- for (const m of doc.media ?? []) await deleteLibraryObject(userId, m.fileName);+ for (const m of doc.media ?? [])+ await deleteLibraryObject(userId, m.fileName);}return Response.json({ ok: true });} catch (e) {@@ -652,5 +837,7 @@ export const fontsFolderId = (userId: string) => `fonts-${userId}`;export async function seedFontsFolder(userId: string): Promise<void> {const id = fontsFolderId(userId);if (await prisma.cutFolder.findUnique({ where: { id } })) return;- await prisma.cutFolder.create({ data: { id, userId, name: "Fonts", scope: "library" } });+ await prisma.cutFolder.create({+ data: { id, userId, name: "Fonts", scope: "library" },+ });}diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex 7d5cb3e6..f0a6df38 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -69,6 +69,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "POST", path: "/api/cut-cloud/library/save", handler: (r, u) => libraryCloud.save(u, r) },{ method: "POST", path: "/api/cut-cloud/library/move", handler: (r, u) => libraryCloud.move(u, r) },{ method: "POST", path: "/api/cut-cloud/library/templates", handler: (r, u) => libraryCloud.saveTemplate(u, r) },+ { method: "POST", path: "/api/cut-cloud/library/templates/import", handler: (r, u) => libraryCloud.importTemplate(u, r) },{ method: "POST", path: "/api/cut-cloud/library/templates/:id/use", handler: (r, u, p) => libraryCloud.useTemplate(u, p.id, r) },{ method: "POST", path: "/api/cut-cloud/library/templates/:id/add", handler: (r, u, p) => libraryCloud.addToTemplate(u, p.id, r) },{ method: "PUT", path: "/api/cut-cloud/library/templates/:id", handler: (r, u, p) => libraryCloud.renameTemplate(u, p.id, r) },diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.tsindex 52c7fb8d..1b14dc93 100644--- a/site/src/cut/server/http/library.ts+++ b/site/src/cut/server/http/library.ts@@ -5,6 +5,7 @@ import {createFolder,deleteFolder,deleteTemplate,+ importTemplate,libMediaPath,listFolders,listLibrary,@@ -22,7 +23,8 @@ import {import { serveFileRange, wantsDownload } from "../serveFile";import { importFromUrl } from "../urlImport";-const err = (message: string, status: number) => Response.json({ error: message }, { status });+const err = (message: string, status: number) =>+ Response.json({ error: message }, { status });const caught = (e: unknown, fallback: string) =>err(e instanceof Error ? e.message : fallback, 500);@@ -40,13 +42,34 @@ export const libraryApi = {/** Save a timeline selection as a by-reference template. */async saveTemplate(req: Request) {try {- const { projectId, ...input } = (await req.json()) as { projectId: string } & TemplateInput;+ const { projectId, ...input } = (await req.json()) as {+ projectId: string;+ } & TemplateInput;return Response.json(await saveTemplate(projectId, input));} catch (e) {return caught(e, "Could not save the template.");}},+ /** Take in a template carried off another shelf: its doc as `doc`, its media+ * as `file` parts in the doc's order. */+ async importTemplate(req: Request) {+ try {+ const form = await req.formData();+ const doc = JSON.parse(+ String(form.get("doc") ?? "{}"),+ ) as TemplateInput & {+ folderId?: string | null;+ };+ const files = form+ .getAll("file")+ .filter((f): f is File => f instanceof File);+ return Response.json(await importTemplate(doc, files));+ } catch (e) {+ return caught(e, "Could not add the template.");+ }+ },+/** Materialize a template into a project (copies its media in). */async useTemplate(req: Request, { id }: { id: string }) {try {@@ -60,9 +83,9 @@ export const libraryApi = {/** Append a project media file to a template as one more part. */async addToTemplate(req: Request, { id }: { id: string }) {try {- const { projectId, ...input } = (await req.json()) as { projectId: string } & Parameters<- typeof addMediaToTemplate- >[2];+ const { projectId, ...input } = (await req.json()) as {+ projectId: string;+ } & Parameters<typeof addMediaToTemplate>[2];return Response.json(await addMediaToTemplate(id, projectId, input));} catch (e) {return caught(e, "Could not add to the template.");@@ -162,8 +185,8 @@ export const libraryApi = {file,typeof name === "string" ? name : undefined,source,- poster instanceof File ? poster : undefined- )+ poster instanceof File ? poster : undefined,+ ),);} catch (e) {return caught(e, "Upload failed.");@@ -201,7 +224,9 @@ export const libraryApi = {fileName: string;name?: string;};- return Response.json(await addFromProject(projectId, fileName, name ?? fileName));+ return Response.json(+ await addFromProject(projectId, fileName, name ?? fileName),+ );} catch (e) {return caught(e, "Could not save to library.");}@@ -217,6 +242,10 @@ export const libraryApi = {} catch {return new Response("Bad request.", { status: 400 });}- return serveFileRange(p, req, wantsDownload(req) ? { downloadName: name } : {});+ return serveFileRange(+ p,+ req,+ wantsDownload(req) ? { downloadName: name } : {},+ );},};diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex 32b1edf5..785b5d4b 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -60,6 +60,7 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "POST", path: "/api/cut/library/import-url", handler: (req) => libraryApi.importUrl(req) },{ method: "POST", path: "/api/cut/library/move", handler: (req) => libraryApi.move(req) },{ method: "POST", path: "/api/cut/library/templates", handler: (req) => libraryApi.saveTemplate(req) },+ { method: "POST", path: "/api/cut/library/templates/import", handler: (req) => libraryApi.importTemplate(req) },{ method: "POST", path: "/api/cut/library/templates/:id/use", handler: (req, p) => libraryApi.useTemplate(req, { id: p.id }) },{ method: "POST", path: "/api/cut/library/templates/:id/add", handler: (req, p) => libraryApi.addToTemplate(req, { id: p.id }) },{ method: "PUT", path: "/api/cut/library/templates/:id", handler: (req, p) => libraryApi.renameTemplate(req, { id: p.id }) },diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex 1a7e9bac..e03b13e4 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -121,7 +121,9 @@ async function readIndex(): Promise<LibraryIndex> {console.error(`Corrupt library index ${indexPath()}:`, err);}try {- const idx = JSON.parse(await readFile(`${indexPath()}.bak`, "utf8")) as LibraryIndex;+ const idx = JSON.parse(+ await readFile(`${indexPath()}.bak`, "utf8"),+ ) as LibraryIndex;await writeIndex(idx);return idx;} catch (err) {@@ -141,7 +143,9 @@ async function writeIndex(idx: LibraryIndex) {// one asset, and write the whole file back — clobbering each other's changes.// Each mutation reads the freshly-written state, applies its change, and writes.let indexLock: Promise<unknown> = Promise.resolve();-async function mutateIndex<T>(fn: (idx: LibraryIndex) => T | Promise<T>): Promise<T> {+async function mutateIndex<T>(+ fn: (idx: LibraryIndex) => T | Promise<T>,+): Promise<T> {const run = indexLock.then(async () => {const idx = await readIndex();const result = await fn(idx);@@ -150,7 +154,7 @@ async function mutateIndex<T>(fn: (idx: LibraryIndex) => T | Promise<T>): Promis});indexLock = run.then(() => undefined,- () => undefined+ () => undefined,);return run;}@@ -185,15 +189,24 @@ function ffprobe(args: string[]): Promise<string> {async function probe(filePath: string) {const duration = parseFloat(- await ffprobe(["-show_entries", "format=duration", "-of", "csv=p=0", filePath])+ await ffprobe([+ "-show_entries",+ "format=duration",+ "-of",+ "csv=p=0",+ filePath,+ ]),);let width: number | undefined;let height: number | undefined;if (VIDEO_RE.test(filePath) || IMAGE_RE.test(filePath)) {const dims = await ffprobe([- "-select_streams", "v:0",- "-show_entries", "stream=width,height",- "-of", "csv=p=0",+ "-select_streams",+ "v:0",+ "-show_entries",+ "stream=width,height",+ "-of",+ "csv=p=0",filePath,]).catch(() => "");const [w, h] = dims.split(",").map(Number);@@ -207,7 +220,10 @@ async function probe(filePath: string) {}async function freeName(original: string) {- const base = path.basename(original).replace(/[^\w.\-() ]+/g, "_").slice(-80);+ const base = path+ .basename(original)+ .replace(/[^\w.\-() ]+/g, "_")+ .slice(-80);return uniqueName(base, libMediaPath);}@@ -223,7 +239,7 @@ export async function register(fileName: string,name: string,source?: LibrarySource,- posterFile?: string+ posterFile?: string,): Promise<LibraryAsset> {const type = typeOf(fileName);if (!type) throw new Error("Unsupported file type.");@@ -252,19 +268,25 @@ export async function addUpload(file: File,name?: string,source?: LibrarySource,- poster?: File+ poster?: File,): Promise<LibraryAsset> {if (!typeOf(file.name)) throw new Error("Unsupported file type.");await mkdir(libMedia(), { recursive: true });const fileName = await freeName(file.name);- await writeFile(libMediaPath(fileName), Buffer.from(await file.arrayBuffer()));+ await writeFile(+ libMediaPath(fileName),+ Buffer.from(await file.arrayBuffer()),+ );// An import that came down from elsewhere brings the source's cover with it;// it is stored like any other library file, named after the media it belongs// to, and taken down with it.let posterFile: string | undefined;if (poster) {posterFile = `${fileName}.poster${path.extname(poster.name) || ".jpg"}`;- await writeFile(libMediaPath(posterFile), Buffer.from(await poster.arrayBuffer()));+ await writeFile(+ libMediaPath(posterFile),+ Buffer.from(await poster.arrayBuffer()),+ );}return register(fileName, name?.trim() || file.name, source, posterFile);}@@ -273,7 +295,7 @@ export async function addUpload(export async function addFromProject(projectId: string,fileName: string,- name: string+ name: string,): Promise<LibraryAsset> {const src = projectMediaPath(projectId, fileName);if (!(await exists(src))) throw new Error("Media file not found in project.");@@ -289,7 +311,7 @@ export async function addDownloaded(srcPath: string,name: string,source?: LibrarySource,- posterPath?: string+ posterPath?: string,): Promise<LibraryAsset> {if (!typeOf(srcPath)) throw new Error("Unsupported file type.");await mkdir(libMedia(), { recursive: true });@@ -307,7 +329,10 @@ export async function addDownloaded(/** Copy a library asset into a project's media folder. Returns the file name* inside the project. */-export async function useInProject(assetId: string, projectId: string): Promise<string> {+export async function useInProject(+ assetId: string,+ projectId: string,+): Promise<string> {const idx = await readIndex();const asset = idx.assets.find((a) => a.id === assetId);if (!asset) throw new Error("Library asset not found.");@@ -355,7 +380,10 @@ export async function createFolder(name: string): Promise<LibraryFolder> {return folder;}-export async function renameFolder(id: string, name: string): Promise<LibraryFolder> {+export async function renameFolder(+ id: string,+ name: string,+): Promise<LibraryFolder> {const trimmed = name.trim();if (!trimmed) throw new Error("Folder name required.");return mutateIndex((idx) => {@@ -371,7 +399,8 @@ export async function deleteFolder(id: string) {idx.folders = (idx.folders ?? []).filter((f) => f.id !== id);// Items in the folder fall back to ungrouped rather than vanishing.for (const a of idx.assets) if (a.folderId === id) a.folderId = null;- for (const t of idx.templates ?? []) if (t.folderId === id) t.folderId = null;+ for (const t of idx.templates ?? [])+ if (t.folderId === id) t.folderId = null;});}@@ -379,7 +408,8 @@ export async function deleteFolder(id: string) {export async function moveItem(id: string, folderId: string | null) {await mutateIndex((idx) => {const item =- idx.assets.find((a) => a.id === id) ?? (idx.templates ?? []).find((t) => t.id === id);+ idx.assets.find((a) => a.id === id) ??+ (idx.templates ?? []).find((t) => t.id === id);if (!item) throw new Error("Library item not found.");if (folderId && !(idx.folders ?? []).some((f) => f.id === folderId)) {throw new Error("Folder not found.");@@ -395,7 +425,14 @@ export async function moveItem(id: string, folderId: string | null) {export interface TemplateInput {name: string;duration: number;- media: { fileName: string; name: string; type: "video" | "audio" | "image"; duration: number; width?: number; height?: number }[];+ media: {+ fileName: string;+ name: string;+ type: "video" | "audio" | "image";+ duration: number;+ width?: number;+ height?: number;+ }[];layers: TemplateLayer[];audio: TemplateAudio[];texts: unknown[];@@ -409,7 +446,51 @@ export async function listTemplates(): Promise<LibraryTemplate[]> {/** Save a selection as a template: copy each source into the library privately* and store the edit that references it. */-export async function saveTemplate(projectId: string, input: TemplateInput): Promise<LibraryTemplate> {+/**+ * Land a template that came off another shelf.+ *+ * A template's media live privately in the library, so carrying one here means+ * taking its files as they arrive and keeping the doc's own order: `layers` and+ * `audio` point at `media` by index, and only the file names change.+ */+export async function importTemplate(+ input: TemplateInput & { folderId?: string | null },+ files: File[],+): Promise<LibraryTemplate> {+ if (!input.media?.length && !input.texts?.length && !input.cues?.length) {+ throw new Error("Nothing to add.");+ }+ await mkdir(libMedia(), { recursive: true });+ const media: TemplateMedia[] = [];+ for (const [i, m] of (input.media ?? []).entries()) {+ const file = files[i];+ if (!file) throw new Error("Template media missing.");+ const dest = await freeName(m.fileName || file.name);+ await writeFile(libMediaPath(dest), Buffer.from(await file.arrayBuffer()));+ media.push({ ...m, fileName: dest });+ }+ const template: LibraryTemplate = {+ id: crypto.randomUUID().slice(0, 8),+ name: (input.name || "Template").trim().slice(0, 80),+ addedAt: Date.now(),+ duration: input.duration,+ media,+ layers: input.layers ?? [],+ audio: input.audio ?? [],+ texts: input.texts ?? [],+ cues: input.cues ?? [],+ folderId: input.folderId ?? null,+ };+ await mutateIndex((idx) => {+ idx.templates = [...(idx.templates ?? []), template];+ });+ return template;+}++export async function saveTemplate(+ projectId: string,+ input: TemplateInput,+): Promise<LibraryTemplate> {if (!(await readProject(projectId))) throw new Error("Project not found.");if (!input.media?.length && !input.texts?.length && !input.cues?.length) {throw new Error("Nothing to save.");@@ -418,10 +499,18 @@ export async function saveTemplate(projectId: string, input: TemplateInput): Proconst media: TemplateMedia[] = [];for (const m of input.media) {const src = projectMediaPath(projectId, m.fileName);- if (!(await exists(src))) throw new Error("Media file not found in project.");+ if (!(await exists(src)))+ throw new Error("Media file not found in project.");const dest = await freeName(m.fileName);await copyFile(src, libMediaPath(dest));- media.push({ fileName: dest, name: m.name, type: m.type, duration: m.duration, width: m.width, height: m.height });+ media.push({+ fileName: dest,+ name: m.name,+ type: m.type,+ duration: m.duration,+ width: m.width,+ height: m.height,+ });}const template: LibraryTemplate = {id: crypto.randomUUID().slice(0, 8),@@ -449,7 +538,9 @@ export async function useTemplate(templateId: string, projectId: string) {if (!template) throw new Error("Template not found.");const media: TemplateMedia[] = [];for (const m of template.media) {- const dest = await uniqueName(m.fileName, (n) => projectMediaPath(projectId, n));+ const dest = await uniqueName(m.fileName, (n) =>+ projectMediaPath(projectId, n),+ );await copyFile(libMediaPath(m.fileName), projectMediaPath(projectId, dest));media.push({ ...m, fileName: dest });}@@ -468,7 +559,7 @@ export async function addMediaToTemplate(layer?: Omit<TemplateLayer, "media" | "start">;audio?: Omit<TemplateAudio, "media" | "start">;extend: number;- }+ },): Promise<LibraryTemplate> {const src = projectMediaPath(projectId, input.media.fileName);if (!(await exists(src))) throw new Error("Media file not found in project.");@@ -481,8 +572,16 @@ export async function addMediaToTemplate(if (!t) throw new Error("Template not found.");const mi = t.media.length;t.media = [...t.media, { ...input.media, fileName: dest }];- if (input.audio) t.audio = [...t.audio, { ...input.audio, media: mi, start: t.duration }];- else if (input.layer) t.layers = [...t.layers, { ...input.layer, media: mi, start: t.duration }];+ if (input.audio)+ t.audio = [+ ...t.audio,+ { ...input.audio, media: mi, start: t.duration },+ ];+ else if (input.layer)+ t.layers = [+ ...t.layers,+ { ...input.layer, media: mi, start: t.duration },+ ];t.duration += input.extend;return t;});@@ -492,7 +591,10 @@ export async function addMediaToTemplate(}}-export async function renameTemplate(id: string, name: string): Promise<LibraryTemplate> {+export async function renameTemplate(+ id: string,+ name: string,+): Promise<LibraryTemplate> {const trimmed = name.trim();if (!trimmed) throw new Error("Template name required.");return mutateIndex((idx) => {@@ -510,5 +612,6 @@ export async function deleteTemplate(id: string) {return t;});// The media copies are private to this template, so removing them is safe.- for (const m of template?.media ?? []) await rm(libMediaPath(m.fileName), { force: true });+ for (const m of template?.media ?? [])+ await rm(libMediaPath(m.fileName), { force: true });}