🎥 Make videos programmatically with React
Elements: Add assets to `createElementPayload()` (#11415)
Igor Samokhovets5af44f462ef1
diff --git a/bun.lock b/bun.lockindex 5b61c89348..16e51720c1 100644--- a/bun.lock+++ b/bun.lock@@ -368,6 +368,7 @@"dependencies": {"@babel/parser": "7.24.1","@babel/types": "7.24.0",+ "@remotion/studio-protocol": "workspace:*","@remotion/studio-shared": "workspace:*","ast-types": "0.16.1","recast": "0.23.21",diff --git a/packages/browser-studio/e2e/browser-studio.test.ts b/packages/browser-studio/e2e/browser-studio.test.tsindex 112ad38a16..4f4f89e4a1 100644--- a/packages/browser-studio/e2e/browser-studio.test.ts+++ b/packages/browser-studio/e2e/browser-studio.test.ts@@ -8,6 +8,7 @@ import {} from '@playwright/test';import {createElementPayload,+ staticFileRef,StudioProtocolInternals,} from '@remotion/studio-protocol';import {strFromU8, unzipSync} from 'fflate';@@ -1225,30 +1226,47 @@ test('drops and imports an Element payload with the deployment Remotion version'}const dataTransfer = await canvas.evaluateHandle(() => new DataTransfer());- await dataTransfer.evaluate((transfer) => {- const payload = JSON.stringify({- type: 'remotion-element',- version: 1,- element: {- dependencies: [{name: '@remotion/shapes', version: null}],- dimensions: {width: 320, height: 180},- displayName: 'Browser Element',- durationInFrames: 60,- installationMode: 'wrapped',- slug: 'browser-element',- sourceCode: `import {Rect} from '@remotion/shapes';--export const BrowserElement = () => <Rect width={320} height={180} fill="red" />;+ await dataTransfer.evaluate(+ (transfer, initialProps) => {+ const payload = JSON.stringify({+ type: 'remotion-element',+ version: 2,+ element: {+ assets: [+ {+ path: 'browser-element/logo.svg',+ type: 'base64',+ data: btoa(+ '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><rect width="20" height="20" fill="blue" /></svg>',+ ),+ },+ ],+ dependencies: [{name: '@remotion/shapes', version: null}],+ dimensions: {width: 320, height: 180},+ displayName: 'Browser Element',+ durationInFrames: 60,+ installationMode: 'wrapped',+ initialProps,+ slug: 'browser-element',+ sourceCode: `import {Rect} from '@remotion/shapes';+import {Img} from 'remotion';++export const BrowserElement = ({logoSrc}: {logoSrc: string}) => <>+ <Rect width={320} height={180} fill="red" />+ <Img alt="Element asset" src={logoSrc} />+</>;`,- },- });- transfer.effectAllowed = 'copy';- transfer.setData(- 'application/vnd.remotion.drag+json;v=1;type=element;width=320;height=180;duration=60',- payload,- );- transfer.setData('text/plain', payload);- });+ },+ });+ transfer.effectAllowed = 'copy';+ transfer.setData(+ 'application/vnd.remotion.drag+json;v=1;type=element;width=320;height=180;duration=60',+ payload,+ );+ transfer.setData('text/plain', payload);+ },+ {logoSrc: staticFileRef('browser-element/logo.svg')},+ );const coordinates = {clientX: box.x + box.width / 2,clientY: box.y + box.height / 2,@@ -1296,8 +1314,12 @@ export const BrowserElement = () => <Rect width={320} height={180} fill="red" />}),).toMatchObject({- composition: expect.stringContaining('<BrowserElement />'),- element: expect.stringContaining('export const BrowserElement'),+ composition: expect.stringMatching(+ /logoSrc=\{staticFile\(["']browser-element\/logo\.svg["']\)\}/,+ ),+ element: expect.stringContaining(+ '<Img alt="Element asset" src={logoSrc} />',+ ),installedVersion: expect.any(String),});const versions = await page.evaluate(() => {@@ -1314,6 +1336,9 @@ export const BrowserElement = () => <Rect width={320} height={180} fill="red" />};});expect(versions.installed).toBe(versions.remotion);+ await expect(+ studio.getByRole('img', {name: 'Element asset'}),+ ).toHaveJSProperty('naturalWidth', 20);await expect(studio.getByText('Browser Element', {exact: true}),).toBeVisible();diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex e075470586..08be867870 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -62,11 +62,18 @@ import type {SequenceNodePath,SequencePropsSubscriptionKey,} from 'remotion';-import {createBrowserStudioProjectController} from './browser-studio-project-controller';+import {+ createBrowserStudioProjectController,+ getCanonicalPublicFiles,+} from './browser-studio-project-controller';import {makeBrowserStudioProjectArchive} from './download-project';-import {downloadRemoteAssetInBrowserStudio} from './download-remote-asset';+import {+ downloadRemoteAssetInBrowserStudio,+ fetchRemoteAssetBytesInBrowserStudio,+} from './download-remote-asset';+import {getBrowserStudioStoredPublicFile} from './opfs-public-files';import {saveSequencePropsInProject} from './save-sequence-props';-import type {VirtualProject} from './types';+import type {VirtualProject, VirtualProjectPublicFile} from './types';const {basicCaptionsElementSource,@@ -83,6 +90,7 @@ const {insertVideoLayers: insertVideoLayersCodemod,JsxElementIdentityMismatchError,JsxElementNotFoundAtLocationError,+pasteEffects: pasteEffectsCodemod,simpleDiff,} = CodemodsInternals;@@ -2174,6 +2182,9 @@ export const createBrowserStudioOperations = ({),insertElement: async (request) => {try {+ StudioProtocolInternals.assertElementAssets(request.element.assets);+ StudioProtocolInternals.assertElementAssetReferences(request.element);+ const {element} = request;const installationMode = request.element.installationMode ?? 'wrapped';const componentOwnsSequence =installationMode === 'component-owned-sequence';@@ -2235,7 +2246,7 @@ export const createBrowserStudioOperations = ({compositionFile: request.compositionFile,compositionId: request.compositionId,},- element: request.element,+ element,project,});if (@@ -2252,7 +2263,7 @@ export const createBrowserStudioOperations = ({conflict: {existingSource: plan.existingSource,filePath: plan.filePath,- incomingSource: request.element.sourceCode,+ incomingSource: element.sourceCode,},};}@@ -2267,11 +2278,79 @@ export const createBrowserStudioOperations = ({conflict: {existingSource: plan.existingSource,filePath: plan.filePath,- incomingSource: request.element.sourceCode,+ incomingSource: element.sourceCode,},};}+ const resolvedAssets =+ await StudioProtocolInternals.resolveElementAssets({+ assets: request.element.assets,+ downloadAsset: (options) =>+ fetchRemoteAssetBytesInBrowserStudio({+ ...options,+ acceptHeader: null,+ }),+ });+ const publicFiles = getCanonicalPublicFiles(originalProject);+ const newAssetFiles: Record<string, VirtualProjectPublicFile> =+ Object.create(null);+ for (const {path: assetPath, contents} of resolvedAssets) {+ const destination = assetPath.toLowerCase();+ const conflict = Object.keys(publicFiles).find((filePath) => {+ const existingPath = filePath.toLowerCase();+ return (+ (filePath !== assetPath && existingPath === destination) ||+ existingPath.startsWith(`${destination}/`) ||+ destination.startsWith(`${existingPath}/`)+ );+ });+ if (conflict !== undefined) {+ throw new Error(+ `Asset ${assetPath} conflicts with existing public file ${conflict}`,+ );+ }++ const existing = publicFiles[assetPath];+ if (existing === undefined) {+ newAssetFiles[assetPath] = contents;+ continue;+ }++ const storage = originalProject.publicFileStorage;+ if (+ typeof existing !== 'string' &&+ !(existing instanceof Uint8Array) &&+ storage === undefined+ ) {+ throw new Error(+ `Stored public file ${assetPath} has no project storage`,+ );+ }++ const existingBlob =+ typeof existing === 'string' || existing instanceof Uint8Array+ ? new Blob([+ typeof existing === 'string'+ ? existing+ : existing.slice().buffer,+ ])+ : await getBrowserStudioStoredPublicFile({+ file: existing,+ storage: storage!,+ });+ if (+ existingBlob.size !== contents.byteLength ||+ !new Uint8Array(await existingBlob.arrayBuffer()).every(+ (byte, index) => byte === contents[index],+ )+ ) {+ throw new Error(+ `Asset ${assetPath} already exists with different contents`,+ );+ }+ }+const installedDependencies = await resolveElementDependencies(request.element.dependencies,);@@ -2322,12 +2401,18 @@ export const createBrowserStudioOperations = ({...insertion.project,files: {...insertion.project.files,- [plan.elementFilePath]: request.element.sourceCode,+ [plan.elementFilePath]: element.sourceCode,},};const nextProject = addDependenciesToProject({dependencies: installedDependencies,- project: projectWithElement,+ project: {+ ...projectWithElement,+ publicFiles: {+ ...(projectWithElement.publicFiles ?? {}),+ ...newAssetFiles,+ },+ },});if (getProject() !== originalProject) {throw new Error(@@ -2367,6 +2452,8 @@ export const createBrowserStudioOperations = ({packageInstallation,prepareElementInstall: async (request) => {try {+ StudioProtocolInternals.assertElementAssets(request.element.assets);+ StudioProtocolInternals.assertElementAssetReferences(request.element);const plan = await getElementInstallPlanForProject({...request,project: getProject(),diff --git a/packages/browser-studio/src/browser-studio-project-controller.ts b/packages/browser-studio/src/browser-studio-project-controller.tsindex 404fa839a2..e8af78aaa6 100644--- a/packages/browser-studio/src/browser-studio-project-controller.ts+++ b/packages/browser-studio/src/browser-studio-project-controller.ts@@ -28,6 +28,7 @@ type ProjectNodePathMutationFiles = SequenceNodePathMutation['files'];type HistoryEntry = {before: VirtualProject;after: VirtualProject;+ publicFilePaths: string[];fileName: string;nodePathMutationFiles: ProjectNodePathMutationFiles | null;undoRedoNavigation: UndoRedoNavigation | null;@@ -67,8 +68,9 @@ const normalizePublicFilePath = (path: string) => {return withoutLeadingSlash;};-const getCanonicalPublicFiles = (project: VirtualProject) => {- const canonicalFiles: Record<string, VirtualProjectPublicFile> = {};+export const getCanonicalPublicFiles = (project: VirtualProject) => {+ const canonicalFiles: Record<string, VirtualProjectPublicFile> =+ Object.create(null);for (const [path, contents] of Object.entries(project.publicFiles ?? {})) {const canonicalPath = normalizePublicFilePath(path);@@ -265,7 +267,12 @@ export const createBrowserStudioPublicFileManager = ({: new Blob([typeof contents === 'string' ? contents : contents.slice().buffer,]);- const url = resolvedCreateObjectUrl(blob);+ // Unlike raster images, SVGs need a MIME type to render from a Blob URL.+ const url = resolvedCreateObjectUrl(+ name.toLowerCase().endsWith('.svg')+ ? blob.slice(0, blob.size, 'image/svg+xml')+ : blob,+ );objectUrls.set(name, {contents:typeof contents === 'string' || isStoredPublicFile(contents)@@ -528,13 +535,16 @@ export const createBrowserStudioProjectController = ({return nodePathMutation;};- const applyMutation = ({- fileName,- mutate,- nodePathMutationFiles,- timelineSelection,- undoRedoNavigation,- }: ProjectMutation) => {+ const applyProjectMutation = (+ {+ fileName,+ mutate,+ nodePathMutationFiles,+ timelineSelection,+ undoRedoNavigation,+ }: ProjectMutation,+ trackPublicFiles: boolean,+ ) => {const before = getProject();const after = mutate(before);@@ -546,6 +556,9 @@ export const createBrowserStudioProjectController = ({undoStack.push({before,after,+ publicFilePaths: trackPublicFiles+ ? getChangedPublicFilePaths(before, after)+ : [],fileName,nodePathMutationFiles,undoRedoNavigation,@@ -573,6 +586,29 @@ export const createBrowserStudioProjectController = ({return nodePathMutation;};+ const restoreProject = (+ snapshot: VirtualProject,+ publicFilePaths: string[],+ ) => {+ const current = getProject();+ const publicFiles = getCanonicalPublicFiles(current);+ const previousFiles = getCanonicalPublicFiles(snapshot);+ // Replay only explicit public-file edits, not stale whole-project snapshots.+ for (const filePath of publicFilePaths) {+ if (Object.hasOwn(previousFiles, filePath)) {+ publicFiles[filePath] = previousFiles[filePath];+ } else {+ delete publicFiles[filePath];+ }+ }++ return {+ ...snapshot,+ publicFiles,+ publicFileStorage: current.publicFileStorage,+ };+ };+const undo = (): Promise<UndoResponse> => {const entry = undoStack.pop();if (!entry) {@@ -591,7 +627,7 @@ export const createBrowserStudioProjectController = ({}));const nodePathMutation = commitProject({previousProject: getProject(),- nextProject: entry.before,+ nextProject: restoreProject(entry.before, entry.publicFilePaths),nodePathMutationFiles: files ?? null,timelineSelection: null,});@@ -611,7 +647,7 @@ export const createBrowserStudioProjectController = ({undoStack.push(entry);const nodePathMutation = commitProject({previousProject: getProject(),- nextProject: entry.after,+ nextProject: restoreProject(entry.after, entry.publicFilePaths),nodePathMutationFiles: entry.nodePathMutationFiles,timelineSelection: null,});@@ -623,7 +659,8 @@ export const createBrowserStudioProjectController = ({};return {- applyMutation,+ // Source mutations retain assets, just like source-file undo in desktop Studio.+ applyMutation: (mutation) => applyProjectMutation(mutation, false),deleteStaticFile: ({relativePath}) => {try {const canonicalPath = normalizePublicFilePath(relativePath);@@ -633,17 +670,20 @@ export const createBrowserStudioProjectController = ({return Promise.resolve({success: true, existed: false});}- applyMutation({- fileName: canonicalPath,- nodePathMutationFiles: null,- timelineSelection: null,- undoRedoNavigation: null,- mutate: (project) => {- const nextPublicFiles = getCanonicalPublicFiles(project);- delete nextPublicFiles[canonicalPath];- return {...project, publicFiles: nextPublicFiles};+ applyProjectMutation(+ {+ fileName: canonicalPath,+ nodePathMutationFiles: null,+ timelineSelection: null,+ undoRedoNavigation: null,+ mutate: (project) => {+ const nextPublicFiles = getCanonicalPublicFiles(project);+ delete nextPublicFiles[canonicalPath];+ return {...project, publicFiles: nextPublicFiles};+ },},- });+ true,+ );return Promise.resolve({success: true, existed: true});} catch (error) {return Promise.reject(error);@@ -691,18 +731,21 @@ export const createBrowserStudioProjectController = ({throw new Error(`${newRelativePath} already exists`);}- applyMutation({- fileName: oldPath,- nodePathMutationFiles: null,- timelineSelection: null,- undoRedoNavigation: null,- mutate: (project) => {- const nextPublicFiles = getCanonicalPublicFiles(project);- nextPublicFiles[newPath] = nextPublicFiles[oldPath];- delete nextPublicFiles[oldPath];- return {...project, publicFiles: nextPublicFiles};+ applyProjectMutation(+ {+ fileName: oldPath,+ nodePathMutationFiles: null,+ timelineSelection: null,+ undoRedoNavigation: null,+ mutate: (project) => {+ const nextPublicFiles = getCanonicalPublicFiles(project);+ nextPublicFiles[newPath] = nextPublicFiles[oldPath];+ delete nextPublicFiles[oldPath];+ return {...project, publicFiles: nextPublicFiles};+ },},- });+ true,+ );return Promise.resolve({success: true});} catch (error) {return Promise.reject(error);@@ -745,20 +788,23 @@ export const createBrowserStudioProjectController = ({: typeof contents === 'string'? contents: new Uint8Array(contents.slice(0));- applyMutation({- fileName: canonicalPath,- nodePathMutationFiles: null,- timelineSelection: null,- undoRedoNavigation: null,- mutate: (project) => ({- ...project,- publicFileStorage: storage ?? project.publicFileStorage,- publicFiles: {- ...getCanonicalPublicFiles(project),- [canonicalPath]: nextContents,- },- }),- });+ applyProjectMutation(+ {+ fileName: canonicalPath,+ nodePathMutationFiles: null,+ timelineSelection: null,+ undoRedoNavigation: null,+ mutate: (project) => ({+ ...project,+ publicFileStorage: storage ?? project.publicFileStorage,+ publicFiles: {+ ...getCanonicalPublicFiles(project),+ [canonicalPath]: nextContents,+ },+ }),+ },+ true,+ );if (storage) {queueGarbageCollection(storage);}diff --git a/packages/browser-studio/src/download-remote-asset.ts b/packages/browser-studio/src/download-remote-asset.tsindex d2efbce497..0bef7acdc0 100644--- a/packages/browser-studio/src/download-remote-asset.ts+++ b/packages/browser-studio/src/download-remote-asset.ts@@ -21,19 +21,15 @@ const getPublicFileSize = (contents: VirtualProjectPublicFile) => {: contents.sizeInBytes;};-export const downloadRemoteAssetInBrowserStudio = async ({- getProject,- request,- writeStaticFile,+export const fetchRemoteAssetBytesInBrowserStudio = async ({+ acceptHeader,+ maxSize,+ url,}: {- getProject: () => VirtualProject;- request: DownloadRemoteAssetRequest;- writeStaticFile: (request: {- contents: string | ArrayBuffer;- filePath: string;- }) => Promise<void>;-}): Promise<DownloadRemoteAssetResponse> => {- const url = new URL(request.url);+ acceptHeader: string | null;+ maxSize: number;+ url: URL;+}) => {if (url.protocol !== 'http:' && url.protocol !== 'https:') {throw new Error('Only HTTP(S) URLs can be imported');}@@ -43,16 +39,15 @@ export const downloadRemoteAssetInBrowserStudio = async ({}const abortController = new AbortController();- const timeout = setTimeout(() => {- abortController.abort();- }, remoteAssetDownloadTimeout);-- let contents: Uint8Array;+ const timeout = setTimeout(+ () => abortController.abort(),+ remoteAssetDownloadTimeout,+ );try {let response: Response;try {response = await fetch(url, {- headers: {accept: remoteAssetAcceptHeader},+ headers: acceptHeader === null ? undefined : {accept: acceptHeader},signal: abortController.signal,});} catch (error) {@@ -72,50 +67,45 @@ export const downloadRemoteAssetInBrowserStudio = async ({}const contentLength = response.headers.get('content-length');- if (contentLength !== null && Number(contentLength) > maxRemoteAssetSize) {+ if (contentLength !== null && Number(contentLength) > maxSize) {abortController.abort();throw new Error('Remote asset exceeds the 50MB size limit');}if (!response.body) {const buffer = await response.arrayBuffer();- if (buffer.byteLength > maxRemoteAssetSize) {+ if (buffer.byteLength > maxSize) {throw new Error('Remote asset exceeds the 50MB size limit');}- contents = new Uint8Array(buffer);- } else {- const reader = response.body.getReader();- const chunks: Uint8Array[] = [];- let size = 0;-- while (true) {- const {done, value} = await reader.read();- if (done) {- break;- }-- if (!value) {- continue;- }-- size += value.byteLength;- if (size > maxRemoteAssetSize) {- abortController.abort();- await reader.cancel();- throw new Error('Remote asset exceeds the 50MB size limit');- }-- chunks.push(value);- }+ return new Uint8Array(buffer);+ }- contents = new Uint8Array(size);- let offset = 0;- for (const chunk of chunks) {- contents.set(chunk, offset);- offset += chunk.byteLength;+ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let size = 0;+ while (true) {+ const {done, value} = await reader.read();+ if (done) break;+ if (!value) continue;+ size += value.byteLength;+ if (size > maxSize) {+ abortController.abort();+ await reader.cancel();+ throw new Error('Remote asset exceeds the 50MB size limit');}++ chunks.push(value);}++ const contents = new Uint8Array(size);+ let offset = 0;+ for (const chunk of chunks) {+ contents.set(chunk, offset);+ offset += chunk.byteLength;+ }++ return contents;} catch (error) {if (error instanceof Error && error.name === 'AbortError') {throw new Error('Timed out downloading remote asset');@@ -125,6 +115,26 @@ export const downloadRemoteAssetInBrowserStudio = async ({} finally {clearTimeout(timeout);}+};++export const downloadRemoteAssetInBrowserStudio = async ({+ getProject,+ request,+ writeStaticFile,+}: {+ getProject: () => VirtualProject;+ request: DownloadRemoteAssetRequest;+ writeStaticFile: (request: {+ contents: string | ArrayBuffer;+ filePath: string;+ }) => Promise<void>;+}): Promise<DownloadRemoteAssetResponse> => {+ const url = new URL(request.url);+ const contents = await fetchRemoteAssetBytesInBrowserStudio({+ acceptHeader: remoteAssetAcceptHeader,+ maxSize: maxRemoteAssetSize,+ url,+ });const fileType = detectFileType(contents);if (!isImageFileType(fileType)) {diff --git a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts b/packages/browser-studio/src/test/browser-studio-project-operations.test.tsindex d5b36761c3..0158a6e8cb 100644--- a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts@@ -1,5 +1,5 @@import {expect, test} from 'bun:test';-import type {ElementDragData} from '@remotion/studio-protocol';+import {staticFileRef, type ElementDragData} from '@remotion/studio-protocol';import type {EventSourceEvent} from '@remotion/studio-shared';import {createBrowserStudioOperations} from '../browser-studio-operations';import {@@ -508,6 +508,7 @@ test('imports an Element with pinned Remotion dependencies as one undoable mutat},});const element = {+ assets: [{path: 'elements/lower-third.bin', type: 'base64', data: 'AAEC'}],dependencies: [{name: '@remotion/shapes', version: null},{name: 'zod', version: '4.1.5'},@@ -515,12 +516,19 @@ test('imports an Element with pinned Remotion dependencies as one undoable mutatdimensions: {width: 640, height: 180},displayName: 'Lower Third',durationInFrames: 90,- initialProps: {label: 'Starter'},+ initialProps: {+ label: 'Starter',+ logoSrc: staticFileRef('elements/lower-third.bin'),+ },installationMode: 'wrapped' as const,slug: 'titles/lower-third',sourceCode: `import {Rect} from '@remotion/shapes';+import {Img} from 'remotion';-export const LowerThird = () => <Rect width={640} height={180} />;+export const LowerThird = ({logoSrc}: {logoSrc: string}) => <>+ <Rect width={640} height={180} />+ <Img name="Logo" src={logoSrc} />+</>;`,} satisfies ElementDragData['element'];const preflight = await operations.prepareElementInstall({@@ -570,6 +578,7 @@ export const LowerThird = () => <Rect width={640} height={180} />;undoRedoNavigation: null,newComposition: null,});+if (!inserted.success) {throw new Error(inserted.type === 'error' ? inserted.reason : 'Unexpected file conflict',@@ -577,8 +586,14 @@ export const LowerThird = () => <Rect width={640} height={180} />;}expect(resolvedDependencyNames).toEqual([['@remotion/shapes', 'zod']]);- expect(project.files['/project/src/lower-third.element.tsx']).toBe(- element.sourceCode,+ const installedElementSource =+ project.files['/project/src/lower-third.element.tsx'];+ expect(installedElementSource).toBe(element.sourceCode);+ expect(project.files['/project/src/Composition.tsx']).toMatch(+ /logoSrc=\{staticFile\(["']elements\/lower-third\.bin["']\)\}/,+ );+ expect(project.publicFiles?.['elements/lower-third.bin']).toEqual(+ new Uint8Array([0, 1, 2]),);expect(project.files['/project/src/Composition.tsx']).toContain('import { LowerThird } from "./lower-third.element";',@@ -610,7 +625,7 @@ export const LowerThird = () => <Rect width={640} height={180} />;);expect((await operations.redo()).success).toBe(true);expect(project.files['/project/src/lower-third.element.tsx']).toBe(- element.sourceCode,+ installedElementSource,);const installRequest = {@@ -628,8 +643,9 @@ export const LowerThird = () => <Rect width={640} height={180} />;expect(await operations.insertElement(installRequest)).toMatchObject({success: false,type: 'file-conflict',+ conflict: {incomingSource: installedElementSource},});- const customizedSource = `${element.sourceCode}\n// Customized\n`;+ const customizedSource = `${installedElementSource}\n// Customized\n`;project = {...project,files: {@@ -646,7 +662,7 @@ export const LowerThird = () => <Rect width={640} height={180} />;).success,).toBe(true);expect(project.files['/project/src/speaker-name.element.tsx']).toBe(- element.sourceCode,+ installedElementSource,);expect(project.files['/project/src/lower-third.element.tsx']).toBe(customizedSource,@@ -666,17 +682,154 @@ export const LowerThird = () => <Rect width={640} height={180} />;).success,).toBe(true);expect(project.files['/project/src/lower-third.element.tsx']).toBe(- element.sourceCode,+ installedElementSource,);expect((await operations.undo()).success).toBe(true);expect(project.files['/project/src/lower-third.element.tsx']).toBe(customizedSource,);expect(project.files['/project/src/speaker-name.element.tsx']).toBe(- element.sourceCode,+ installedElementSource,+ );+});++const makeElementAssetFixture = () => {+ let project = createBlankTemplateProject();+ const operations = createBrowserStudioOperations({+ dependencyVersions: {},+ getStaticFiles: null,+ getProject: () => project,+ initialElement: null,+ onProjectChange: (nextProject) => {+ project = nextProject;+ },+ resolveDependencies: null,+ });+ return {+ getProject: () => project,+ operations,+ install: (+ assets: ElementDragData['element']['assets'],+ installationName: string | null,+ ) =>+ operations.insertElement({+ installationName,+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ element: {+ assets,+ dependencies: [],+ dimensions: null,+ displayName: 'Asset Element',+ durationInFrames: 30,+ initialProps: null,+ installationMode: 'wrapped',+ slug: 'asset-element',+ sourceCode: 'export const AssetElement = () => <div />;',+ },+ expectedFileState: null,+ from: null,+ overwriteExisting: false,+ position: null,+ undoRedoNavigation: null,+ newComposition: null,+ }),+ };+};++test('retains installed assets across earlier history while allowing explicit asset undo and redo', async () => {+ const {getProject, install, operations} = makeElementAssetFixture();+ const originalSource = getProject().files['/project/src/Composition.tsx'];+ await operations.writeStaticFile({+ filePath: 'upload.txt',+ contents: 'Uploaded',+ });+ for (const [name, assetPath] of [+ ['first', 'first.bin'],+ ['second', '__proto__'],+ ]) {+ expect(+ (await install([{path: assetPath, type: 'base64', data: 'AAEC'}], name))+ .success,+ ).toBe(true);+ }++ const installedAssets = {+ 'first.bin': new Uint8Array([0, 1, 2]),+ ['__proto__']: new Uint8Array([0, 1, 2]),+ };+ for (let i = 0; i < 3; i++) {+ expect((await operations.undo()).success).toBe(true);+ }++ expect(getProject().files['/project/src/Composition.tsx']).toBe(+ originalSource,+ );+ expect(getProject().publicFiles).toEqual(installedAssets);+ for (let i = 0; i < 3; i++) {+ expect((await operations.redo()).success).toBe(true);+ }++ expect(getProject().publicFiles).toEqual({+ ...installedAssets,+ 'upload.txt': 'Uploaded',+ });+ expect(getProject().files['/project/src/Composition.tsx']).toContain(+ '<AssetElement2',+ );+ const events: EventSourceEvent[] = [];+ const unsubscribe = operations.subscribeToEvent((event) =>+ events.push(event),+ );+ await new Promise((resolve) => setTimeout(resolve, 0));+ unsubscribe();+ expect(+ events.findLast((event) => event.type === 'new-public-folder'),+ ).toMatchObject({+ files: expect.arrayContaining([+ expect.objectContaining({+ name: '__proto__',+ sizeInBytes: 3,+ src: '/__proto__',+ }),+ ]),+ });++ await operations.deleteStaticFile({relativePath: '__proto__'});+ expect(Object.hasOwn(getProject().publicFiles ?? {}, '__proto__')).toBe(+ false,+ );+ expect((await operations.undo()).success).toBe(true);+ expect(Object.entries(getProject().publicFiles ?? {})).toContainEqual([+ '__proto__',+ new Uint8Array([0, 1, 2]),+ ]);+ expect((await operations.redo()).success).toBe(true);+ expect(Object.hasOwn(getProject().publicFiles ?? {}, '__proto__')).toBe(+ false,);});+test.each([+ ['folder', 'folder/asset.bin'],+ ['folder/asset.bin', 'folder'],+ ['Asset.bin', 'asset.bin'],+])(+ 'rejects installation of %s conflicting with public path %s',+ async (existingPath, assetPath) => {+ const {getProject, install, operations} = makeElementAssetFixture();+ await operations.writeStaticFile({+ filePath: existingPath,+ contents: 'Existing',+ });+ const before = getProject();+ expect(+ await install([{path: assetPath, type: 'base64', data: 'AAEC'}], null),+ ).toMatchObject({success: false, type: 'error'});+ expect(getProject()).toBe(before);+ },+);+test('installs an Element into a new composition as one undoable mutation', async () => {const initialProject = createBlankTemplateProject();let project = initialProject;@@ -691,6 +844,7 @@ test('installs an Element into a new composition as one undoable mutation', asynresolveDependencies: null,});const element = {+ assets: [],dependencies: [],dimensions: {width: 640, height: 180},displayName: 'Browser Element',@@ -790,12 +944,20 @@ test('installs component-owned Element timing and initial props', async () => {resolveDependencies: null,});const element = {+ assets: [{path: 'captions/sound.bin', type: 'base64', data: 'AAEC'}],dependencies: [],dimensions: {width: 640, height: 180},displayName: 'Captions',durationInFrames: 90,initialProps: {- captions: [{text: 'Starter', startMs: 0, endMs: 1000}],+ captions: [+ {+ text: 'Starter',+ startMs: 0,+ endMs: 1000,+ sound: staticFileRef('captions/sound.bin'),+ },+ ],style: {color: 'red',position: 'relative',@@ -845,6 +1007,9 @@ test('installs component-owned Element timing and initial props', async () => {expect(composition).not.toContain('<Sequence');expect(composition).toContain('<Captions');expect(composition).toContain('captions={[');+ expect(project.publicFiles?.['captions/sound.bin']).toEqual(+ new Uint8Array([0, 1, 2]),+ );expect(composition).toContain('text: "Starter"');expect(composition).toContain('width={640}');expect(composition).toContain('durationInFrames={90}');@@ -901,6 +1066,7 @@ test('rejects contradictory component-owned Element initial props', async () =>compositionFile: '/project/src/Composition.tsx',compositionId: 'MyComp',element: {+ assets: [],dependencies: [],dimensions: {width: 640, height: 180},displayName: 'Captions',diff --git a/packages/codemods/package.json b/packages/codemods/package.jsonindex f9ffb8b303..91d305a4f0 100644--- a/packages/codemods/package.json+++ b/packages/codemods/package.json@@ -26,6 +26,7 @@"dependencies": {"@babel/parser": "7.24.1","@babel/types": "7.24.0",+ "@remotion/studio-protocol": "workspace:*","@remotion/studio-shared": "workspace:*","ast-types": "0.16.1","recast": "0.23.21",diff --git a/packages/codemods/src/insert-jsx-element.ts b/packages/codemods/src/insert-jsx-element.tsindex 40e2c3322e..c121c47f56 100644--- a/packages/codemods/src/insert-jsx-element.ts+++ b/packages/codemods/src/insert-jsx-element.ts@@ -15,6 +15,7 @@ import type {ObjectProperty,VariableDeclaration,} from '@babel/types';+import {StudioProtocolInternals} from '@remotion/studio-protocol';import {isUrl,type InsertJsxElementRequest,@@ -23,6 +24,7 @@ import {type SequenceNodePathRemapping,} from '@remotion/studio-shared';import type {namedTypes} from 'ast-types';+import type {ExpressionKind} from 'ast-types/lib/gen/kinds';import * as recast from 'recast';import type {SequenceNodePath} from 'remotion';import {NoReactInternals} from 'remotion/no-react';@@ -1001,10 +1003,48 @@ const createStaticFileSrcAttribute = ({);};+const createComponentPropValue = (+ value: unknown,+ getStaticFileLocalName: () => string,+): ExpressionKind => {+ const b = recast.types.builders;+ if (StudioProtocolInternals.isStaticFileRef(value)) {+ return b.callExpression(b.identifier(getStaticFileLocalName()), [+ b.stringLiteral(value.__remotion_element_asset),+ ]);+ }++ if (Array.isArray(value)) {+ return b.arrayExpression(+ value.map((item) =>+ createComponentPropValue(item, getStaticFileLocalName),+ ),+ );+ }++ if (value !== null && typeof value === 'object') {+ return b.objectExpression(+ Object.entries(value).map(([key, item]) => {+ const property = b.objectProperty(+ b.stringLiteral(key),+ createComponentPropValue(item, getStaticFileLocalName),+ );+ property.computed = key === '__proto__';+ return property;+ }),+ );+ }++ return parseValueExpression(value);+};+const createComponentProp = ({name,value,-}: ComponentProp): namedTypes.JSXAttribute => {+ getStaticFileLocalName,+}: ComponentProp & {+ getStaticFileLocalName: () => string;+}): namedTypes.JSXAttribute => {if (typeof value === 'string') {return createStringAttribute(name, value);}@@ -1012,7 +1052,7 @@ const createComponentProp = ({return recast.types.builders.jsxAttribute(recast.types.builders.jsxIdentifier(name),recast.types.builders.jsxExpressionContainer(- parseValueExpression(value) as never,+ createComponentPropValue(value, getStaticFileLocalName) as never,),) as unknown as namedTypes.JSXAttribute;};@@ -1052,12 +1092,14 @@ const createSolidElement = ({};const createComponentElement = ({+ getStaticFileLocalName,addPositionStyle,from,localName,props,position,}: {+ getStaticFileLocalName: () => string;addPositionStyle: boolean;from: number | null;localName: string;@@ -1073,7 +1115,7 @@ const createComponentElement = ({const styleExpression =styleProp === undefined? recast.types.builders.objectExpression([])- : parseValueExpression(styleProp.value);+ : createComponentPropValue(styleProp.value, getStaticFileLocalName);if (styleExpression.type !== 'ObjectExpression') {throw new Error('Component style must be an object to add a position');}@@ -1104,7 +1146,9 @@ const createComponentElement = ({recast.types.builders.jsxOpeningElement(recast.types.builders.jsxIdentifier(localName),[- ...propsWithoutStyle.map(createComponentProp),+ ...propsWithoutStyle.map((prop) =>+ createComponentProp({...prop, getStaticFileLocalName}),+ ),...(from === null ? [] : [createNumberAttribute('from', from)]),...(styleAttribute === null ? [] : [styleAttribute]),],@@ -1506,7 +1550,7 @@ const ensureOfficialNamedImport = ({getImportedName(specifier) === importedName,);if (existing) {- return existing.local.name;+ return existing.local?.name ?? importedName;}}@@ -2667,6 +2711,7 @@ const createInsertableJsxElement = ({});return createComponentElement({+ getStaticFileLocalName: () => ensureStaticFileImport(ast),addPositionStyle: addPositionStyleToComponent,from,localName: componentLocalName,diff --git a/packages/docs/docs/studio-protocol/component-library-integration.mdx b/packages/docs/docs/studio-protocol/component-library-integration.mdxindex 9ae83084d6..b12350be8d 100644--- a/packages/docs/docs/studio-protocol/component-library-integration.mdx+++ b/packages/docs/docs/studio-protocol/component-library-integration.mdx@@ -27,7 +27,15 @@ Show each component in a [`<Player>`](/docs/player). The preview lets users examImport the component normally for the preview. The website bundler then compiles the component.-Use the same dimensions and duration in the Player and the Element payload. For a `component-owned-sequence` Element with replaceable starter content, set [`initialProps`](/docs/studio-protocol/create-element-payload#initialprops) in the payload and pass the same object to the Player as `inputProps`.+Use the same dimensions and duration in the Player and the Element payload. For replaceable starter content in either installation mode, set [`initialProps`](/docs/studio-protocol/create-element-payload#initialprops) in the payload and pass the corresponding values to the Player as `inputProps`.++### Preview installed assets++Accept asset URLs as component props. Pass hosted URLs to the Player, and use [`staticFileRef()`](/docs/studio-protocol/static-file-ref) in the payload's `initialProps` for assets that should be installed. Declare each referenced path in [`assets`](/docs/studio-protocol/create-element-payload#assets).++Studio installs the assets and generates [`staticFile()`](/docs/staticfile) expressions on the component invocation. The Element source stays unchanged. This works in both installation modes.++Assets that should remain remote after installation can use URL strings directly in `initialProps`.## Reuse component code@@ -102,6 +110,7 @@ When Studio embeds the library through Browse Elements, use [`isInsideStudio()`]- [Element guidelines](/elements/contributing#element-guidelines)- [`<Player>`](/docs/player)- [`createElementPayload()`](/docs/studio-protocol/create-element-payload)+- [`staticFileRef()`](/docs/studio-protocol/static-file-ref)- [`setStudioDragData()`](/docs/studio-protocol/set-studio-drag-data)- [`installInStudio()`](/docs/studio-protocol/install-in-studio)- [`isInsideStudio()`](/docs/studio-protocol/is-inside-studio)diff --git a/packages/docs/docs/studio-protocol/create-element-payload.mdx b/packages/docs/docs/studio-protocol/create-element-payload.mdxindex a53078ee17..2d3b1e678e 100644--- a/packages/docs/docs/studio-protocol/create-element-payload.mdx+++ b/packages/docs/docs/studio-protocol/create-element-payload.mdx@@ -11,11 +11,13 @@ Creates a validated, versioned Element payload for [`buildOpenInRemotionNewUrl()## Example```ts twoslash title="element-payload.ts"-import {createElementPayload} from '@remotion/studio-protocol';+import {createElementPayload, staticFileRef} from '@remotion/studio-protocol';const elementSourceCode = `-export const MyElement = () => {- return <div>Hello world</div>;+import {Img} from 'remotion';++export const MyElement = ({logoSrc}: {logoSrc: string}) => {+ return <Img name="Logo" src={logoSrc} />;};`;@@ -29,6 +31,19 @@ const payload = createElementPayload({],dimensions: {width: 900, height: 260},durationInFrames: 90,+ initialProps: {logoSrc: staticFileRef('my-element/logo.png')},+ assets: [+ {+ path: 'my-element/logo.png',+ type: 'url',+ url: 'https://example.com/logo.png',+ },+ {+ path: 'my-element/data.json',+ type: 'base64',+ data: 'eyJvayI6dHJ1ZX0=',+ },+ ],});```@@ -58,6 +73,20 @@ For `@remotion/*` packages, set `version` to `null`. Studio installs the versionDo not declare `react`, `react-dom`, or `remotion`; every Remotion project already provides them.+### assets?<AvailableFrom v="4.0.528" />++Files to install in the project's public directory. The default is `[]`.++Set `path` to a forward-slash path relative to the public directory. Use [`staticFileRef()`](/docs/studio-protocol/static-file-ref) in `initialProps` to pass the installed asset to your component. Studio generates a [`staticFile()`](/docs/staticfile) expression on the component invocation and leaves the Element source unchanged. Paths cannot be absolute, contain traversal or platform-unsafe segments, or conflict with another declared asset path.++For a remote file, set `type` to `'url'` and provide an HTTP(S) `url` without credentials. For an embedded file, set `type` to `'base64'` and provide strictly encoded `data`. Browser Studio requires remote servers to allow cross-origin requests (CORS).++An installation can contain at most 100 assets and 50MB of downloaded or decoded data in total. The complete Element payload remains limited to 250,000 JSON characters, including embedded base64 data. Use remote URLs for larger files.++Studio fetches assets only after you confirm the installation. An existing file is reused when its bytes match. Different contents cause the installation to fail, even when you approve replacing an existing Element source file. Undo removes installed source changes but retains successfully installed assets; redo does not download them again.++Assets use Element payload version 2. Asset-free payloads continue to use version 1. A Studio that only supports version 1 asks you to upgrade instead of installing source without its assets.+### dimensionsThe preferred width and height, or `null` for an Element without fixed dimensions. Both values must be positive finite numbers.@@ -70,13 +99,13 @@ The preferred duration shown while dragging. It must be a positive integer.### initialProps?<AvailableFrom v="4.0.524" />-Use `initialProps` when a `component-owned-sequence` Element needs replaceable starter content. Studio writes each property onto the installed component. The default is `null`.+Props to write onto the installed component invocation, in both installation modes. The default is `null`. In `'wrapped'` mode, the component invocation is inside the generated Sequence.-Use JSON-compatible values and valid JSX attribute names. For `component-owned-sequence`, omit `from`, `durationInFrames`, and `name` because Studio supplies them. In this mode, `style` must be an object.+Use JSON-compatible values and valid JSX attribute names. Asset props can use [`staticFileRef()`](/docs/studio-protocol/static-file-ref), including inside nested objects and arrays. Studio turns these references into `staticFile()` expressions on the caller, not inside the Element source.-Pass the same props to the component preview. Element dimensions are not passed as component props, so include `width` and `height` when the component needs them.+For `component-owned-sequence`, omit `from`, `durationInFrames`, and `name` because Studio supplies them. In this mode, `style` must be an object.-In `'wrapped'` mode, Studio also passes `initialProps` to the component inside the generated Sequence. Most wrapped Elements do not need this because their editable values can stay on internal `Interactive` call sites in the copied source.+Pass the corresponding values to the component preview, using hosted URLs instead of asset references. Element dimensions are not passed as component props in `component-owned-sequence` mode, so include `width` and `height` when the component needs them.### installationMode?<AvailableFrom v="4.0.506" />@@ -90,7 +119,7 @@ See [Design it for composition](/elements/contributing#design-it-for-composition## Return value-A `StudioElementPayload` with payload version `1`. Pass the returned object unchanged to a transport API instead of serializing it manually.+A `StudioElementPayload`. Asset-free payloads use version `1`; payloads with assets use version `2`. Pass the returned object unchanged to a transport API instead of serializing it manually.Invalid input throws a `TypeError`.@@ -100,6 +129,7 @@ Invalid input throws a `TypeError`.## See also+- [`staticFileRef()`](/docs/studio-protocol/static-file-ref)- [`buildOpenInRemotionNewUrl()`](/docs/studio-protocol/build-open-in-remotion-new-url)- [`setStudioDragData()`](/docs/studio-protocol/set-studio-drag-data)- [`installInStudio()`](/docs/studio-protocol/install-in-studio)diff --git a/packages/docs/docs/studio-protocol/static-file-ref.mdx b/packages/docs/docs/studio-protocol/static-file-ref.mdxnew file mode 100644index 0000000000..b5caa7109c--- /dev/null+++ b/packages/docs/docs/studio-protocol/static-file-ref.mdx@@ -0,0 +1,80 @@+---+image: /generated/articles-docs-studio-protocol-static-file-ref.png+title: 'staticFileRef()'+crumb: '@remotion/studio-protocol'+---++# staticFileRef()<AvailableFrom v="4.0.528" />++Reference an Element asset in [`initialProps`](/docs/studio-protocol/create-element-payload#initialprops). When the Element is installed, Studio downloads the asset into the user's project's `public/` directory and generates a [`staticFile()`](/docs/staticfile) expression on the component invocation. The Element source is not rewritten.++## Example++Accept the asset URL as a component prop:++```tsx twoslash title="MyElement.tsx"+import {Img} from 'remotion';++export const MyElement = ({logoSrc}: {logoSrc: string}) => (+ <Img name="Logo" src={logoSrc} />+);+```++Declare the asset and reference it in the installation props:++```ts twoslash title="element-payload.ts"+import {createElementPayload, staticFileRef} from '@remotion/studio-protocol';++const sourceCode = `export const MyElement = ({logoSrc}: {logoSrc: string}) => <img src={logoSrc} />;`;+// ---cut---+const logo = {+ path: 'my-element/logo.png',+ type: 'url',+ url: 'https://cdn.example.com/logo.png',+} as const;++const payload = createElementPayload({+ displayName: 'My Element',+ slug: 'my-element',+ sourceCode,+ dependencies: [],+ dimensions: {width: 900, height: 260},+ durationInFrames: 90,+ assets: [logo],+ initialProps: {+ logoSrc: staticFileRef(logo.path),+ },+});+```++Studio saves the asset to `public/my-element/logo.png` and inserts:++```tsx title="Generated component invocation"+<MyElement logoSrc={staticFile('my-element/logo.png')} />+```++This works in both installation modes. In `'wrapped'` mode, Studio places this invocation inside a generated `<Sequence>`.++For the website preview, pass the hosted URL as the Player's `inputProps`, for example `inputProps={{logoSrc: logo.url}}`. Do not pass the reference object to the preview component: it is installation metadata, not a URL.++## Arguments++### path++A public-relative path that exactly matches an entry in the payload's [`assets`](/docs/studio-protocol/create-element-payload#assets). The path may come from a variable. Undeclared paths and malformed references are rejected before asset downloads.++## Return value++A JSON-serializable `StaticFileRef` object for use in `initialProps`. References may also appear inside nested objects and arrays. Pass the returned value unchanged; do not construct or depend on its internal representation.++For assets that should remain remote after installation, pass a URL string instead.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering={false} player={false} studio={false} hideServers />++## See also++- [`createElementPayload()`](/docs/studio-protocol/create-element-payload)+- [Integrating a component library with Studio](/docs/studio-protocol/component-library-integration)+- [`staticFile()`](/docs/staticfile)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex d194998964..c5c6f84399 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -830,6 +830,7 @@ const sidebars: SidebarsConfig = {items: ['studio-protocol/component-library-integration','studio-protocol/create-element-payload',+ 'studio-protocol/static-file-ref','studio-protocol/build-open-in-remotion-new-url','studio-protocol/set-studio-drag-data','studio-protocol/install-in-studio',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex d17693fbc8..aa309918f7 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -7643,6 +7643,15 @@ export const articles = [noAi: false,slug: 'studio-protocol/set-studio-drag-data',},+ {+ id: 'studio-protocol/static-file-ref',+ title: 'staticFileRef()',+ relativePath: 'docs/studio-protocol/static-file-ref.mdx',+ compId: 'articles-docs-studio-protocol-static-file-ref',+ crumb: '@remotion/studio-protocol',+ noAi: false,+ slug: 'studio-protocol/static-file-ref',+ },{id: 'studio/api',title: '@remotion/studio',diff --git a/packages/docs/static/generated/articles-docs-studio-protocol-static-file-ref.png b/packages/docs/static/generated/articles-docs-studio-protocol-static-file-ref.pngnew file mode 100644index 0000000000..a051ba5f87Binary files /dev/null and b/packages/docs/static/generated/articles-docs-studio-protocol-static-file-ref.png differdiff --git a/packages/example/e2e/studio-protocol.test.mts b/packages/example/e2e/studio-protocol.test.mtsindex e7e02ff551..efa78c22af 100644--- a/packages/example/e2e/studio-protocol.test.mts+++ b/packages/example/e2e/studio-protocol.test.mts@@ -53,6 +53,12 @@ test('installs an Element from a website into a clean Studio project', async ({const temporaryProject = fs.mkdtempSync(path.join(os.tmpdir(), 'remotion-studio-protocol-'),);+ const installedAsset = path.join(+ temporaryProject,+ 'public',+ 'protocol-element',+ 'data.bin',+ );fs.cpSync(path.join(packagesDirectory, 'template-blank'), temporaryProject, {recursive: true,});@@ -168,6 +174,11 @@ const CloseupPlaceholder = () => {path.join(packagesDirectory, 'studio-protocol', 'dist', 'esm', 'index.mjs'),'utf8',);+ const protocolElementSource = `export const ProtocolElement = ({assetSrc}: {assetSrc: string}) => (+ <div data-asset={assetSrc}>+ Installed through protocol+ </div>+);`;const senderServer = createServer((request, response) => {if (request.url === '/protocol.js') {response.writeHead(200, {'Content-Type': 'text/javascript'});@@ -183,15 +194,21 @@ const CloseupPlaceholder = () => {<p id="environment"></p><p id="status"></p><script type="module">- import {addElementLibraryToStudio, createElementPayload, installInStudio, isInsideStudio, setStudioDragData, StudioProtocolInternals} from '/protocol.js';+ import {addElementLibraryToStudio, createElementPayload, staticFileRef, installInStudio, isInsideStudio, setStudioDragData, StudioProtocolInternals} from '/protocol.js';document.querySelector('#environment').textContent = isInsideStudio() ? 'Inside Remotion Studio' : 'Outside Remotion Studio';const payload = createElementPayload({displayName: 'Protocol Element',slug: 'protocol-element',- sourceCode: 'export const ProtocolElement = () => <div>Installed through protocol</div>;',+ sourceCode: ${JSON.stringify(protocolElementSource)},dependencies: [],dimensions: {width: 640, height: 120},durationInFrames: 30,+ initialProps: {assetSrc: staticFileRef('protocol-element/data.bin')},+ assets: [{+ path: 'protocol-element/data.bin',+ type: 'base64',+ data: 'AAEC',+ }],});const dragHandle = document.createElement('div');dragHandle.id = 'drag-element';@@ -379,6 +396,14 @@ const CloseupPlaceholder = () => {name: 'Install Protocol Element',});await expect(dialog).toBeVisible();+ await dialog.getByRole('button', {name: 'Cancel'}).click();+ expect(fs.existsSync(installedAsset)).toBe(false);+ await browseElements.click();+ await expect(externalLibraryItem).toBeVisible();+ await externalLibraryItem.click();+ await expect(elementsIframe).toBeVisible();+ await installInStudio.click();+ await expect(dialog).toBeVisible();const currentDestination = dialog.getByRole('button', {name: 'Current composition',});@@ -440,17 +465,16 @@ const CloseupPlaceholder = () => {'protocol-element.element.tsx',);await waitForFile(elementFile);- expect(fs.readFileSync(elementFile, 'utf8')).toContain(- 'export const ProtocolElement',- );+ const installedElementSource = fs.readFileSync(elementFile, 'utf8');+ expect(installedElementSource).toBe(protocolElementSource);const compositionSource = fs.readFileSync(path.join(temporaryProject, 'src', 'Composition.tsx'),'utf8',);- expect(compositionSource).toContain('ProtocolElement');expect(compositionSource).toContain('protocol-element.element');+ expect(fs.readFileSync(installedAsset)).toEqual(Buffer.from([0, 1, 2]));expect(compositionSource).toMatch(- /<Sequence\b(?=[^>]*\bfrom=\{45\})(?=[^>]*\bdurationInFrames=\{30\})[^>]*>\s*<ProtocolElement\s*\/>\s*<\/Sequence>/,+ /<Sequence\b(?=[^>]*\bfrom=\{45\})(?=[^>]*\bdurationInFrames=\{30\})[^>]*>\s*<ProtocolElement\s+assetSrc=\{staticFile\(["']protocol-element\/data\.bin["']\)\}\s*\/>\s*<\/Sequence>/,);const suppliedSource = fs.readFileSync(elementFile, 'utf8');@@ -802,6 +826,7 @@ const CloseupPlaceholder = () => {expect(fs.readFileSync(path.join(closeupDirectory, 'Closeup.tsx'), 'utf8'),).not.toContain('id="ProtocolElementScene"');+ expect(fs.readFileSync(installedAsset)).toEqual(Buffer.from([0, 1, 2]));await studioPage.getByRole('button', {name: /^Redo/}).click();await expect(studioPage).toHaveURL(`${studioUrl}/ProtocolElementScene`, {@@ -819,6 +844,7 @@ const CloseupPlaceholder = () => {expect(fs.readFileSync(newCompositionElementFile, 'utf8')).toContain('export const ProtocolElement',);+ expect(fs.readFileSync(installedAsset)).toEqual(Buffer.from([0, 1, 2]));await studioPage.bringToFront();await studioPage.keyboard.press('Escape');diff --git a/packages/studio-protocol/src/drag-data.ts b/packages/studio-protocol/src/drag-data.tsindex ab934361ed..89eb56da8d 100644--- a/packages/studio-protocol/src/drag-data.ts+++ b/packages/studio-protocol/src/drag-data.ts@@ -66,9 +66,10 @@ export type MakeEffectDragDataInput = EffectDragData['effect'] & {export type MakeElementDragDataInput = Omit<ElementDragData['element'],- 'initialProps'+ 'assets' | 'initialProps'> & {readonly type: 'element';+ readonly assets?: ElementDragData['element']['assets'];readonly durationInFrames: number;readonly initialProps?: ElementDragData['element']['initialProps'];};@@ -234,6 +235,7 @@ export const makeDragData = ((case 'element':return construct(makeElementDragData({+ assets: input.assets ?? [],dependencies: input.dependencies,dimensions: input.dimensions,displayName: input.displayName,diff --git a/packages/studio-protocol/src/element-drag-data.ts b/packages/studio-protocol/src/element-drag-data.tsindex c81808a14e..36aa07fee6 100644--- a/packages/studio-protocol/src/element-drag-data.ts+++ b/packages/studio-protocol/src/element-drag-data.ts@@ -7,6 +7,25 @@ import {isValidPackageName} from './validation';export type ElementInstallationMode = 'wrapped' | 'component-owned-sequence';+const maxElementAssets = 100;+export const maxElementAssetBytes = 50 * 1024 * 1024;++export type ElementAsset =+ | {+ readonly path: string;+ readonly type: 'url';+ readonly url: string;+ }+ | {+ readonly path: string;+ readonly type: 'base64';+ readonly data: string;+ };++export type StaticFileRef = {+ readonly __remotion_element_asset: string;+};+export type ElementInitialPropValue =| string| number@@ -31,8 +50,9 @@ export type ElementDependency =export type ElementDragData = {type: 'remotion-element';- version: 1;+ version: 1 | 2;element: {+ assets: ElementAsset[];dependencies: ElementDependency[];durationInFrames?: number;initialProps: ElementInitialProps | null;@@ -157,44 +177,97 @@ export const isElementDependency = (): value is ElementDependency =>z.safeParse(elementDependencySchema, value).success;-export const makeElementDragData = ({- dependencies,- dimensions,- displayName,- durationInFrames,- initialProps,- slug,- sourceCode,- installationMode,-}: Omit<ElementDragData['element'], 'dependencies'> & {- dependencies: ElementDependency[];-}): ElementDragData => {- for (const dependency of dependencies) {- assertElementDependency(dependency);+const windowsReservedNames = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;+const strictBase64Regex =+ /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;++export const isValidElementAssetPath = (assetPath: string) =>+ assetPath.length > 0 &&+ assetPath.length <= 1024 &&+ !assetPath.startsWith('/') &&+ !assetPath.includes('\\') &&+ assetPath+ .split('/')+ .every(+ (segment) =>+ segment !== '' &&+ segment !== '.' &&+ segment !== '..' &&+ !/[<>:"|?*]/.test(segment) &&+ !Array.from(segment).some(+ (character) => character.charCodeAt(0) <= 31,+ ) &&+ !/[. ]$/.test(segment) &&+ !windowsReservedNames.test(segment),+ );++const isValidElementAssetUrl = (value: string) => {+ try {+ const url = new URL(value);+ return (+ (url.protocol === 'http:' || url.protocol === 'https:') &&+ url.username === '' &&+ url.password === ''+ );+ } catch {+ return false;}-- return {- type: 'remotion-element',- version: 1,- element: {- dependencies: Array.from(- new Map(- dependencies.map(- (dependency) => [dependency.name, dependency] as const,- ),- ).values(),- ),- dimensions,- displayName,- ...(durationInFrames === undefined ? {} : {durationInFrames}),- initialProps,- ...(installationMode === undefined ? {} : {installationMode}),- slug,- sourceCode,- },- };};+const elementAssetSchema = z.union([+ z.strictObject({+ path: z.string().check(z.refine(isValidElementAssetPath)),+ type: z.literal('url'),+ url: z.string().check(z.refine(isValidElementAssetUrl)),+ }),+ z.strictObject({+ path: z.string().check(z.refine(isValidElementAssetPath)),+ type: z.literal('base64'),+ data: z.string().check(z.regex(strictBase64Regex)),+ }),+]);+const elementAssetsSchema = z+ .array(elementAssetSchema)+ .check(z.maxLength(maxElementAssets));++export function assertElementAssets(+ value: unknown,+): asserts value is ElementAsset[] {+ const parsed = z.safeParse(elementAssetsSchema, value);+ if (!parsed.success) {+ throw new TypeError('Invalid Element assets');+ }++ const paths = new Set<string>();+ let embeddedBytes = 0;+ for (const asset of parsed.data) {+ const assetPath = asset.path.toLowerCase();+ if (+ [...paths].some(+ (existingPath) =>+ existingPath === assetPath ||+ existingPath.startsWith(`${assetPath}/`) ||+ assetPath.startsWith(`${existingPath}/`),+ )+ ) {+ throw new TypeError(+ `Element asset destination conflicts with another asset: ${asset.path}`,+ );+ }++ paths.add(assetPath);+ if (asset.type === 'base64') {+ embeddedBytes +=+ (asset.data.length / 4) * 3 -+ (asset.data.endsWith('==') ? 2 : asset.data.endsWith('=') ? 1 : 0);+ }+ }++ if (embeddedBytes > maxElementAssetBytes) {+ throw new TypeError('Element assets exceed the 50MB aggregate limit');+ }+}+const dimensionsSchema = z.object({width: z.number().check(z.positive()),height: z.number().check(z.positive()),@@ -253,6 +326,65 @@ export const isElementInitialProps = (Object.keys(value).every((key) => initialPropNameRegex.test(key)) &&isJsonCompatibleValue(value, new Set()));+export const staticFileRef = (path: string): StaticFileRef => {+ if (typeof path !== 'string' || !isValidElementAssetPath(path)) {+ throw new TypeError('staticFileRef() requires a safe Element asset path');+ }++ return {__remotion_element_asset: path};+};++export const isStaticFileRef = (value: unknown): value is StaticFileRef =>+ typeof value === 'object' &&+ value !== null &&+ !Array.isArray(value) &&+ Object.keys(value).length === 1 &&+ Object.hasOwn(value, '__remotion_element_asset') &&+ typeof (value as StaticFileRef).__remotion_element_asset === 'string' &&+ isValidElementAssetPath((value as StaticFileRef).__remotion_element_asset);++export function assertElementAssetReferences({+ assets,+ initialProps,+}: {+ assets: readonly {readonly path: string}[];+ initialProps: ElementInitialProps | null;+}): void {+ const paths = new Set(assets.map((asset) => asset.path));+ const seen = new Set<object>();+ const visit = (value: unknown): void => {+ if (value === null || typeof value !== 'object') {+ return;+ }++ if (Object.hasOwn(value, '__remotion_element_asset')) {+ if (!isStaticFileRef(value)) {+ throw new TypeError('Invalid staticFileRef() in initialProps');+ }++ if (!paths.has(value.__remotion_element_asset)) {+ throw new TypeError(+ `staticFileRef() path ${JSON.stringify(value.__remotion_element_asset)} is not declared in the Element assets`,+ );+ }++ return;+ }++ if (seen.has(value)) {+ throw new TypeError(+ 'Element initialProps must not contain circular references',+ );+ }++ seen.add(value);+ Object.values(value).forEach(visit);+ seen.delete(value);+ };++ Object.values(initialProps ?? {}).forEach(visit);+}+export const hasValidElementInitialPropsForInstallationMode = ({initialProps,installationMode,@@ -283,10 +415,53 @@ export const hasValidElementInitialPropsForInstallationMode = ({);};+export const makeElementDragData = ({+ assets,+ dependencies,+ dimensions,+ displayName,+ durationInFrames,+ initialProps,+ slug,+ sourceCode,+ installationMode,+}: Omit<ElementDragData['element'], 'dependencies'> & {+ dependencies: ElementDependency[];+}): ElementDragData => {+ assertElementAssets(assets);+ assertElementAssetReferences({assets, initialProps});+ for (const dependency of dependencies) {+ assertElementDependency(dependency);+ }++ return {+ type: 'remotion-element',+ version: assets.length === 0 ? 1 : 2,+ element: {+ assets: [...assets],+ dependencies: Array.from(+ new Map(+ dependencies.map(+ (dependency) => [dependency.name, dependency] as const,+ ),+ ).values(),+ ),+ dimensions,+ displayName,+ ...(durationInFrames === undefined ? {} : {durationInFrames}),+ initialProps,+ ...(installationMode === undefined ? {} : {installationMode}),+ slug,+ sourceCode,+ },+ };+};+const elementDragDataSchema = z.object({type: z.literal('remotion-element'),- version: z.literal(1),+ version: z.union([z.literal(1), z.literal(2)]),element: z.object({+ assets: z.optional(z.array(z.unknown())),dependencies: z.array(z.unknown()).check(z.maxLength(100)),durationInFrames: z.optional(durationSchema),initialProps: z.optional(z.nullable(elementInitialPropsSchema)),@@ -317,6 +492,13 @@ export const parseElementDragData = (value: string): ElementDragData | null => {return null;}+ const assets = parsed.data.element.assets ?? [];+ try {+ assertElementAssets(assets);+ } catch {+ return null;+ }+const dependencies: ElementDependency[] = [];for (const dependency of parsed.data.element.dependencies) {if (!isElementDependency(dependency)) {@@ -337,7 +519,8 @@ export const parseElementDragData = (value: string): ElementDragData | null => {return null;}- return makeElementDragData({+ const result = makeElementDragData({+ assets,dependencies,dimensions: parsed.data.element.dimensions ?? null,displayName: parsed.data.element.displayName,@@ -347,6 +530,7 @@ export const parseElementDragData = (value: string): ElementDragData | null => {sourceCode: parsed.data.element.sourceCode,installationMode: parsed.data.element.installationMode,});+ return result.version === parsed.data.version ? result : null;} catch {return null;}diff --git a/packages/studio-protocol/src/element-payload.ts b/packages/studio-protocol/src/element-payload.tsindex 1b5f84b464..2ed697ed89 100644--- a/packages/studio-protocol/src/element-payload.ts+++ b/packages/studio-protocol/src/element-payload.ts@@ -8,6 +8,7 @@ import {isElementInitialProps,makeElementFileNameFromSlug,parseElementDragData,+ type ElementAsset,type ElementDependency,type ElementDragData,type ElementInitialProps,@@ -19,6 +20,7 @@ const MAX_SOURCE_CODE_SIZE = 200_000;const MAX_DEPENDENCIES = 100;export type CreateElementPayloadInput = {+ readonly assets?: readonly ElementAsset[];readonly displayName: string;readonly slug: string;readonly sourceCode: string;@@ -36,7 +38,7 @@ export type StudioElementPayload = ElementDragData & {const durationSchema = z.int().check(z.positive(), z.lte(100_000_000));const studioElementPayloadEnvelopeSchema = z.object({type: z.literal('remotion-element'),- version: z.literal(1),+ version: z.union([z.literal(1), z.literal(2)]),durationInFrames: durationSchema,element: z.unknown(),});@@ -117,6 +119,7 @@ export const createElementPayload = (assertCreateElementPayloadInput(input);const constructed = makeDragData({type: 'element',+ assets: [...(input.assets ?? [])],dependencies: [...input.dependencies],dimensions: input.dimensions,displayName: input.displayName,diff --git a/packages/studio-protocol/src/index.ts b/packages/studio-protocol/src/index.tsindex e98d65a620..99a4dfa77b 100644--- a/packages/studio-protocol/src/index.ts+++ b/packages/studio-protocol/src/index.ts@@ -15,6 +15,9 @@ import {import {makeDragData, parseDragData} from './drag-data';import {getDragPreviewMetadata} from './drag-preview-metadata';import {+ assertElementAssetReferences,+ assertElementAssets,+ isStaticFileRef,getElementComponentNameFromSourceCode,makeElementFileNameFromSlug,} from './element-drag-data';@@ -26,6 +29,7 @@ import {parseStudioProtocolInstallRequest,} from './install-in-studio';import {isValidPublicLicenseKey} from './license-key';+import {resolveElementAssets} from './resolve-element-assets';import {parseStudioProtocolSetLicenseKeyRequest,setLicenseKeyInStudio,@@ -75,14 +79,16 @@ export type {EffectConfigValue,EffectDragData,} from './effect-drag-data';+export {staticFileRef} from './element-drag-data';export type {+ ElementAsset,+ StaticFileRef,ElementDependency,ElementDragData,ElementInitialProps,ElementInitialPropValue,ElementInstallationMode,} from './element-drag-data';-export type {RenderOutputDragData} from './render-output-drag-data';export {createElementPayload,type CreateElementPayloadInput,@@ -94,6 +100,7 @@ export {type InstallInStudioResult,} from './install-in-studio';export {isInsideStudio} from './is-inside-studio';+export type {RenderOutputDragData} from './render-output-drag-data';export type {SfxDragData} from './sfx-drag-data';export type {StudioProtocolDescriptor,@@ -103,6 +110,9 @@ export type {export const StudioProtocolInternals = {addElementLibraryToStudioWithDependencies,areComponentProps,+ assertElementAssetReferences,+ assertElementAssets,+ isStaticFileRef,getDragPreviewMetadata,getElementComponentNameFromSourceCode,isComponentIdentifier,@@ -122,5 +132,6 @@ export const StudioProtocolInternals = {parseStudioProtocolDescriptor,parseStudioProtocolInstallRequest,parseStudioProtocolSetLicenseKeyRequest,+ resolveElementAssets,setLicenseKeyInStudio,};diff --git a/packages/studio-protocol/src/install-in-studio.ts b/packages/studio-protocol/src/install-in-studio.tsindex 3789fa9064..e44156d628 100644--- a/packages/studio-protocol/src/install-in-studio.ts+++ b/packages/studio-protocol/src/install-in-studio.ts@@ -221,14 +221,18 @@ export const installInStudioWithDependencies = async (const supportedStudios = discovery.studios.flatMap((studio) => {const capability = getInstallCapability(studio.descriptor);- return capability?.payloadVersions.includes(1)+ return capability?.payloadVersions.includes(payload.version)? [{...studio, capability}]: [];});if (supportedStudios.length === 0) {return failure(- 'unsupported-protocol',- 'The running Remotion Studio cannot install this Element payload version.',+ payload.version === 2+ ? 'studio-upgrade-required'+ : 'unsupported-protocol',+ payload.version === 2+ ? 'Upgrade Remotion Studio to install Elements that include assets.'+ : 'The running Remotion Studio cannot install this Element payload version.',);}diff --git a/packages/studio-protocol/src/resolve-element-assets.ts b/packages/studio-protocol/src/resolve-element-assets.tsnew file mode 100644index 0000000000..e086daeaab--- /dev/null+++ b/packages/studio-protocol/src/resolve-element-assets.ts@@ -0,0 +1,31 @@+import {maxElementAssetBytes, type ElementAsset} from './element-drag-data';++export const resolveElementAssets = async ({+ assets,+ downloadAsset,+}: {+ assets: readonly ElementAsset[];+ downloadAsset: (options: {url: URL; maxSize: number}) => Promise<Uint8Array>;+}) => {+ const resolved: Array<{path: string; contents: Uint8Array}> = [];+ let totalBytes = 0;+ for (const asset of assets) {+ const contents =+ asset.type === 'base64'+ ? Uint8Array.from(atob(asset.data), (character) =>+ character.charCodeAt(0),+ )+ : await downloadAsset({+ url: new URL(asset.url),+ maxSize: maxElementAssetBytes - totalBytes,+ });+ totalBytes += contents.byteLength;+ if (totalBytes > maxElementAssetBytes) {+ throw new Error('Element assets exceed the 50MB aggregate limit');+ }++ resolved.push({path: asset.path, contents});+ }++ return resolved;+};diff --git a/packages/studio-protocol/src/test/element-drag-data.test.ts b/packages/studio-protocol/src/test/element-drag-data.test.tsindex 36fffe0dd5..74b1c0f97e 100644--- a/packages/studio-protocol/src/test/element-drag-data.test.ts+++ b/packages/studio-protocol/src/test/element-drag-data.test.ts@@ -4,6 +4,7 @@ import {StudioProtocolInternals, type ElementDragData} from '../index';type ElementInput = Omit<ElementDragData['element'], 'durationInFrames'>;const validElement = {+ assets: [],dependencies: [{name: '@remotion/google-fonts', version: null}],slug: 'overlays/lower-third',displayName: 'Lower Third',diff --git a/packages/studio-protocol/src/test/element-payload.test.ts b/packages/studio-protocol/src/test/element-payload.test.tsindex fed7c8f940..a825a17ad1 100644--- a/packages/studio-protocol/src/test/element-payload.test.ts+++ b/packages/studio-protocol/src/test/element-payload.test.ts@@ -1,6 +1,7 @@import {expect, test} from 'bun:test';import {parseDragData} from '../drag-data';import {setStudioDragData} from '../drag-transport';+import {parseElementDragData, staticFileRef} from '../element-drag-data';import {createElementPayload,parseStudioElementPayload,@@ -35,6 +36,7 @@ test('creates one canonical Element payload for HTTP and drag transports', () =>version: 1,durationInFrames: 90,element: {+ assets: [],dependencies: [{name: '@remotion/google-fonts', version: null},{name: 'lodash', version: '4.17.21'},@@ -79,18 +81,77 @@ test('creates one canonical Element payload for HTTP and drag transports', () =>);});+test('validates asset payloads and references for both transports', () => {+ const payload = createElementPayload({+ ...validInput,+ assets: [+ {+ path: 'my-element/logo.png',+ type: 'url',+ url: 'https://example.com/logo.png',+ },+ {path: 'my-element/data.json', type: 'base64', data: 'eyJvayI6dHJ1ZX0='},+ ],+ initialProps: {media: [{src: staticFileRef('my-element/logo.png')}]},+ });+ const serialized = JSON.stringify(payload);+ expect(payload.version).toBe(2);+ expect(parseStudioElementPayload(JSON.parse(serialized))).toEqual(payload);+ expect(parseElementDragData(serialized)?.element).toEqual(payload.element);+ expect(parseStudioElementPayload({...payload, version: 1})).toBe(null);++ for (const assets of [+ [{path: '../logo.png', type: 'base64', data: 'AA=='}],+ [{path: 'logo.png', type: 'base64', data: 'not base64'}],+ [{path: 'logo.png', type: 'url', url: 'file:///logo.png'}],+ [+ {path: 'nested', type: 'base64', data: 'AA=='},+ {path: 'nested/logo.png', type: 'base64', data: 'AA=='},+ ],+ ] as const) {+ expect(() => createInvalidPayload({...validInput, assets})).toThrow();+ }++ for (const path of ['', '../logo.png', '/logo.png']) {+ expect(() => staticFileRef(path)).toThrow();+ }++ for (const ref of [+ staticFileRef('missing.png'),+ {__remotion_element_asset: '../logo.png'},+ {__remotion_element_asset: 123},+ {__remotion_element_asset: 'my-element/logo.png', extra: true},+ ]) {+ const initialProps = {media: [{src: ref}]};+ expect(() =>+ createElementPayload({+ ...validInput,+ assets: payload.element.assets,+ initialProps,+ }),+ ).toThrow();+ const tampered = {...payload, element: {...payload.element, initialProps}};+ expect(parseStudioElementPayload(tampered)).toBeNull();+ expect(parseElementDragData(JSON.stringify(tampered))).toBeNull();+ }+});+test('defaults new Element payloads to wrapped installation', () => {const {installationMode: _installationMode, ...input} = validInput;const payload = createElementPayload(input);expect(payload.element.installationMode).toBe('wrapped');});-test('normalizes legacy payloads without initial props to null', () => {+test('normalizes legacy payloads without initial props or assets', () => {const payload = createElementPayload(validInput);- const {initialProps: _initialProps, ...legacyElement} = payload.element;+ const {+ initialProps: _initialProps,+ assets: _assets,+ ...legacyElement+ } = payload.element;expect(parseStudioElementPayload({...payload, element: legacyElement}),- ).toMatchObject({element: {initialProps: null}});+ ).toMatchObject({version: 1, element: {initialProps: null, assets: []}});});test('rejects invalid and reserved initial props', () => {diff --git a/packages/studio-protocol/src/test/install-in-studio.test.ts b/packages/studio-protocol/src/test/install-in-studio.test.tsindex 2563e6e712..72ca194798 100644--- a/packages/studio-protocol/src/test/install-in-studio.test.ts+++ b/packages/studio-protocol/src/test/install-in-studio.test.ts@@ -131,6 +131,36 @@ test('delivers the payload when a newer Studio advertises an unknown capability'});});+test('requires a Studio that supports asset payloads', async () => {+ const payload = createElementPayload({+ dependencies: [],+ dimensions: null,+ displayName: 'Asset Element',+ durationInFrames: 30,+ slug: 'asset-element',+ sourceCode: 'export const AssetElement = () => null;',+ assets: [{path: 'asset.bin', type: 'base64', data: 'AA=='}],+ });+ const result = await installInStudioWithDependencies(payload, {+ ...dependencies,+ fetchFn: () =>+ Promise.resolve(+ jsonResponse(+ descriptor({+ compositionId: 'Main',+ lastFocusedAt: 999_000,+ projectName: 'Old Studio',+ targetId: 'old-target',+ }),+ ),+ ),+ });+ expect(result).toMatchObject({+ success: false,+ code: 'studio-upgrade-required',+ });+});+test('distinguishes a compatible Studio without an installable target', async () => {const fetchFn = (input: string | URL | Request) => {const url = String(input);diff --git a/packages/studio-server/src/helpers/open-file-for-writing-without-symlinks.ts b/packages/studio-server/src/helpers/open-file-for-writing-without-symlinks.tsindex 7842a20ded..91ac278b06 100644--- a/packages/studio-server/src/helpers/open-file-for-writing-without-symlinks.ts+++ b/packages/studio-server/src/helpers/open-file-for-writing-without-symlinks.ts@@ -1,7 +1,7 @@import fs from 'node:fs';import path from 'node:path';-const assertNoSymlinks = ({+export const assertNoSymlinks = ({rootDirectory,absolutePath,}: {@@ -40,9 +40,11 @@ const assertNoSymlinks = ({export const openFileForWritingWithoutSymlinks = ({rootDirectory,absolutePath,+ exclusive,}: {rootDirectory: string;absolutePath: string;+ exclusive: boolean;}) => {const resolvedRootDirectory = path.resolve(rootDirectory);const resolvedAbsolutePath = path.resolve(absolutePath);@@ -59,10 +61,12 @@ export const openFileForWritingWithoutSymlinks = ({const flags =process.platform === 'win32'- ? 'w'+ ? exclusive+ ? 'wx'+ : 'w': fs.constants.O_CREAT |fs.constants.O_WRONLY |- fs.constants.O_TRUNC |+ (exclusive ? fs.constants.O_EXCL : fs.constants.O_TRUNC) |fs.constants.O_NOFOLLOW;return fs.openSync(resolvedAbsolutePath, flags);diff --git a/packages/studio-server/src/preview-server/routes/download-remote-asset.ts b/packages/studio-server/src/preview-server/routes/download-remote-asset.tsindex 36d8b3abc4..7233a64ffe 100644--- a/packages/studio-server/src/preview-server/routes/download-remote-asset.ts+++ b/packages/studio-server/src/preview-server/routes/download-remote-asset.ts@@ -102,9 +102,11 @@ const ensureRemoteUrlIsAllowed = async (url: URL) => {};const fetchRemoteAsset = async ({+ acceptHeader,signal,url,}: {+ acceptHeader: string | null;signal: AbortSignal;url: URL;}) => {@@ -114,9 +116,7 @@ const fetchRemoteAsset = async ({await ensureRemoteUrlIsAllowed(currentUrl);const response = await fetch(currentUrl, {- headers: {- accept: remoteAssetAcceptHeader,- },+ headers: acceptHeader === null ? undefined : {accept: acceptHeader},redirect: 'manual',signal,});@@ -144,19 +144,21 @@ const fetchRemoteAsset = async ({const readRemoteAsset = async ({response,abort,+ maxSize,}: {response: Response;abort: () => void;+ maxSize: number;}) => {const contentLength = response.headers.get('content-length');- if (contentLength !== null && Number(contentLength) > maxRemoteAssetSize) {+ if (contentLength !== null && Number(contentLength) > maxSize) {abort();throw new Error('Remote asset exceeds the 50MB size limit');}if (!response.body) {const buffer = await response.arrayBuffer();- if (buffer.byteLength > maxRemoteAssetSize) {+ if (buffer.byteLength > maxSize) {throw new Error('Remote asset exceeds the 50MB size limit');}@@ -178,7 +180,7 @@ const readRemoteAsset = async ({}size += value.byteLength;- if (size > maxRemoteAssetSize) {+ if (size > maxSize) {abort();await reader.cancel();throw new Error('Remote asset exceeds the 50MB size limit');@@ -197,43 +199,40 @@ const readRemoteAsset = async ({return result;};-export const downloadRemoteAssetHandler: ApiHandler<- DownloadRemoteAssetRequest,- DownloadRemoteAssetResponse-> = async ({input, publicDir, request}) => {- validateSameOrigin(request);-- if (typeof input.url !== 'string') {- throw new Error('No `url` provided');- }-+export const downloadRemoteAssetBytes = async ({+ acceptHeader,+ maxSize,+ url,+}: {+ acceptHeader: string | null;+ maxSize: number;+ url: URL;+}) => {if (typeof fetch !== 'function') {throw new Error('Downloading remote assets requires Node.js 18 or newer. Drag a local file instead.',);}- const url = new URL(input.url);-const controller = new AbortController();- const timeout = setTimeout(() => {- controller.abort();- }, remoteAssetDownloadTimeout);-- let contents: Uint8Array;+ const timeout = setTimeout(+ () => controller.abort(),+ remoteAssetDownloadTimeout,+ );try {const response = await fetchRemoteAsset({+ acceptHeader,signal: controller.signal,url,});-if (!response.ok) {throw new Error(`Could not download remote asset: ${response.status}`);}- contents = await readRemoteAsset({+ return await readRemoteAsset({response,abort: () => controller.abort(),+ maxSize,});} catch (err) {if (err instanceof Error && err.name === 'AbortError') {@@ -244,6 +243,24 @@ export const downloadRemoteAssetHandler: ApiHandler<} finally {clearTimeout(timeout);}+};++export const downloadRemoteAssetHandler: ApiHandler<+ DownloadRemoteAssetRequest,+ DownloadRemoteAssetResponse+> = async ({input, publicDir, request}) => {+ validateSameOrigin(request);++ if (typeof input.url !== 'string') {+ throw new Error('No `url` provided');+ }++ const url = new URL(input.url);+ const contents = await downloadRemoteAssetBytes({+ acceptHeader: remoteAssetAcceptHeader,+ maxSize: maxRemoteAssetSize,+ url,+ });const fileType = detectFileType(contents);if (!isImageFileType(fileType)) {diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.tsindex 096b3f53fc..c690208cae 100644--- a/packages/studio-server/src/preview-server/routes/insert-element.ts+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts@@ -1,6 +1,14 @@-import {existsSync, readFileSync} from 'node:fs';+import {+ closeSync,+ existsSync,+ lstatSync,+ readFileSync,+ unlinkSync,+ writeFileSync,+} from 'node:fs';import path from 'node:path';import {RenderInternals} from '@remotion/renderer';+import {StudioProtocolInternals} from '@remotion/studio-protocol';import type {ElementInstallExpectedFileState,InsertElementRequest,@@ -11,17 +19,23 @@ import {resolveFilePathFromSymbolicatedStack,} from '../../codemods/apply-codemod-to-file';import {writeFileAndNotifyFileWatchers} from '../../file-watcher';+import {+ assertNoSymlinks,+ openFileForWritingWithoutSymlinks,+} from '../../helpers/open-file-for-writing-without-symlinks';import {insertJsxElementIntoComposition} from '../../helpers/resolve-composition-component';import type {ApiHandler} from '../api-types';import {formatLogFileLocation} from '../format-log-file-location';import {getProjectInfo} from '../project-info';import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';import {+ discardLastUndoEntryAfterFailedCommit,printUndoHint,pushTransactionToUndoStack,suppressUndoStackInvalidation,} from '../undo-stack';import {checkIfTypeScriptFile} from './can-update-default-props';+import {downloadRemoteAssetBytes} from './download-remote-asset';import {getElementInstallPlan,validateElementInstallPosition,@@ -56,7 +70,7 @@ const hasExpectedFileState = ({export const insertElementHandler: ApiHandler<InsertElementRequest,InsertElementResponse-> = ({+> = async ({input: {compositionFile,compositionId,@@ -72,8 +86,35 @@ export const insertElementHandler: ApiHandler<entryPoint,remotionRoot,logLevel,-}) =>- withSourceFileWriteQueue(async () => {+ publicDir,+}) => {+ let resolvedAssets: Array<{contents: Uint8Array; path: string}>;+ try {+ StudioProtocolInternals.assertElementAssets(element.assets);+ StudioProtocolInternals.assertElementAssetReferences(element);+ resolvedAssets = await StudioProtocolInternals.resolveElementAssets({+ assets: element.assets,+ downloadAsset: (options) =>+ downloadRemoteAssetBytes({...options, acceptHeader: null}),+ });+ } catch (err) {+ return {+ success: false,+ type: 'error',+ reason: (err as Error).message,+ stack: (err as Error).stack ?? '',+ };+ }++ return withSourceFileWriteQueue(async () => {+ const createdAssets: Array<{absolutePath: string; contents: Uint8Array}> =+ [];+ const changedSources: Array<{+ filePath: string;+ newContents: string;+ oldContents: string | null;+ }> = [];+ let undoEntryPushed = false;try {validateElementInstallPosition(position);if (@@ -350,6 +391,56 @@ export const insertElementHandler: ApiHandler<);}+ const assetsToCreate: Array<{+ absolutePath: string;+ contents: Uint8Array;+ }> = [];+ for (const asset of resolvedAssets) {+ const absolutePath = path.resolve(publicDir, ...asset.path.split('/'));+ assertNoSymlinks({+ absolutePath,+ rootDirectory: path.resolve(publicDir),+ });+ if (existsSync(absolutePath)) {+ if (!lstatSync(absolutePath).isFile()) {+ throw new Error(+ `Asset ${asset.path} already exists and is not a file`,+ );+ }++ if (!readFileSync(absolutePath).equals(asset.contents)) {+ throw new Error(+ `Asset ${asset.path} already exists with different contents`,+ );+ }+ } else {+ assetsToCreate.push({absolutePath, contents: asset.contents});+ }+ }++ for (const asset of assetsToCreate) {+ const fileDescriptor = openFileForWritingWithoutSymlinks({+ absolutePath: asset.absolutePath,+ exclusive: true,+ rootDirectory: publicDir,+ });+ try {+ writeFileSync(fileDescriptor, asset.contents);+ } catch (error) {+ closeSync(fileDescriptor);+ try {+ unlinkSync(asset.absolutePath);+ } catch {+ // Keep the original write error.+ }++ throw error;+ }++ closeSync(fileDescriptor);+ createdAssets.push(asset);+ }+const nodePathMutation = broadcastSequenceNodePathMutation([{@@ -360,6 +451,31 @@ export const insertElementHandler: ApiHandler<null,);+ const writeSource = ({+ content,+ file,+ metadata,+ }: {+ content: string;+ file: string;+ metadata: {skipSequencePropsUpdate: true} | null;+ }) => {+ const oldContents = existsSync(file)+ ? readFileSync(file, 'utf8')+ : null;+ changedSources.push({+ filePath: file,+ newContents: content,+ oldContents,+ });+ writeFileAndNotifyFileWatchers({+ file,+ content,+ originatorClientId: undefined,+ metadata,+ });+ };+pushTransactionToUndoStack({snapshots: [...(compositionCreation === null@@ -410,6 +526,7 @@ export const insertElementHandler: ApiHandler<suppressHmrOnFileRestore: false,undoRedoNavigation,});+ undoEntryPushed = true;if (compositionCreation !== null) {suppressUndoStackInvalidation(compositionCreation.registrationFilePath);}@@ -421,27 +538,24 @@ export const insertElementHandler: ApiHandler<suppressUndoStackInvalidation(inserted.fileName);if (compositionCreation !== null) {- writeFileAndNotifyFileWatchers({+ writeSource({file: compositionCreation.registrationFilePath,content: compositionCreation.registrationFileNewContents,- originatorClientId: undefined,metadata: null,});}if (shouldWriteElementFile) {- writeFileAndNotifyFileWatchers({+ writeSource({file: plan.elementFileName,content: element.sourceCode,- originatorClientId: undefined,metadata: null,});}- writeFileAndNotifyFileWatchers({+ writeSource({file: inserted.fileName,content: inserted.output,- originatorClientId: undefined,metadata: {skipSequencePropsUpdate: true},});@@ -485,6 +599,41 @@ export const insertElementHandler: ApiHandler<return {success: true, nodePathMutation};} catch (err) {+ if (undoEntryPushed) {+ discardLastUndoEntryAfterFailedCommit();+ }++ for (const source of changedSources.reverse()) {+ try {+ if (readFileSync(source.filePath, 'utf8') !== source.newContents) {+ continue;+ }++ if (source.oldContents === null) {+ unlinkSync(source.filePath);+ } else {+ writeFileAndNotifyFileWatchers({+ file: source.filePath,+ content: source.oldContents,+ originatorClientId: undefined,+ metadata: null,+ });+ }+ } catch {+ // Preserve subsequent user changes and the original installation error.+ }+ }++ for (const asset of createdAssets.reverse()) {+ try {+ if (readFileSync(asset.absolutePath).equals(asset.contents)) {+ unlinkSync(asset.absolutePath);+ }+ } catch {+ // Preserve subsequent user changes and the original installation error.+ }+ }+return {success: false,type: 'error',@@ -493,3 +642,4 @@ export const insertElementHandler: ApiHandler<};}});+};diff --git a/packages/studio-server/src/preview-server/routes/prepare-element-install.ts b/packages/studio-server/src/preview-server/routes/prepare-element-install.tsindex 3b43ef9996..d728714b77 100644--- a/packages/studio-server/src/preview-server/routes/prepare-element-install.ts+++ b/packages/studio-server/src/preview-server/routes/prepare-element-install.ts@@ -1,3 +1,4 @@+import {StudioProtocolInternals} from '@remotion/studio-protocol';import type {PrepareElementInstallRequest,PrepareElementInstallResponse,@@ -12,6 +13,8 @@ export const prepareElementInstallHandler: ApiHandler<> = ({entryPoint, input, remotionRoot}) =>withSourceFileWriteQueue(async () => {try {+ StudioProtocolInternals.assertElementAssets(input.element.assets);+ StudioProtocolInternals.assertElementAssetReferences(input.element);const plan = await getElementInstallPlan({...input,entryPoint,diff --git a/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.ts b/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.tsindex df994ee2bc..8eadf450f9 100644--- a/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.ts+++ b/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.ts@@ -155,7 +155,7 @@ export const handleStudioProtocolDiscovery = ({{type: 'install-element',payloadType: 'remotion-element',- payloadVersions: [1],+ payloadVersions: [1, 2],target:issuedInstallTarget === null || installTarget === null? nulldiff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.tsindex 915003e550..2e86353d4a 100644--- a/packages/studio-server/src/preview-server/undo-stack.ts+++ b/packages/studio-server/src/preview-server/undo-stack.ts@@ -624,6 +624,25 @@ export function getRedoStack(): readonly UndoEntry[] {return redoStack;}+export function discardLastUndoEntryAfterFailedCommit() {+ const entry = undoStack.pop();+ if (!entry) {+ return;+ }++ for (const filePath of getEntryFilePaths(entry)) {+ const count = suppressedWrites.get(filePath) ?? 0;+ if (count <= 1) {+ suppressedWrites.delete(filePath);+ } else {+ suppressedWrites.set(filePath, count - 1);+ }+ }++ cleanupWatchers();+ broadcastState();+}+export function clearUndoStackForTests() {undoStack.length = 0;redoStack.length = 0;diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.tsindex d6f53eb9f3..8efa666b85 100644--- a/packages/studio-server/src/routes.ts+++ b/packages/studio-server/src/routes.ts@@ -294,6 +294,7 @@ const handleAddAsset = ({const fileDescriptor = openFileForWritingWithoutSymlinks({rootDirectory: publicDir,absolutePath,+ exclusive: false,});const writeStream = createWriteStream(absolutePath, {fd: fileDescriptor,@@ -344,6 +345,7 @@ const handleUploadOutput = ({const fileDescriptor = openFileForWritingWithoutSymlinks({rootDirectory: remotionRoot,absolutePath,+ exclusive: false,});const writeStream = createWriteStream(absolutePath, {fd: fileDescriptor,diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.tsindex ece1cd26e9..8f6215b7d2 100644--- a/packages/studio-server/src/test/insert-element.test.ts+++ b/packages/studio-server/src/test/insert-element.test.ts@@ -10,6 +10,7 @@ import {} from 'node:fs';import {tmpdir} from 'node:os';import path from 'node:path';+import {staticFileRef} from '@remotion/studio-protocol';import type {EventSourceEvent,InsertElementRequest,@@ -71,6 +72,7 @@ const structuredInitialProps = {};const element: InsertElementRequest['element'] = {+ assets: [],dependencies: [],dimensions: {width: 900, height: 260},durationInFrames: 72,@@ -88,6 +90,7 @@ const makeFixture = () => {);const compositionFile = path.join(remotionRoot, 'Root.tsx');const elementFile = path.join(remotionRoot, 'lower-third.element.tsx');+ const publicDir = path.join(remotionRoot, 'custom-public');writeFileSync(compositionFile, compositionSource);const events: EventSourceEvent[] = [];const contentsAtMutation: string[] = [];@@ -132,7 +135,7 @@ const makeFixture = () => {cancelJob: () => undefined,removeJob: () => undefined,},- publicDir: remotionRoot,+ publicDir,remotionRoot,request: {} as never,response: {} as never,@@ -164,11 +167,12 @@ const makeFixture = () => {} as const;const prepareInstall = (destination: PrepareElementInstallRequest['destination'],+ elementToPrepare: InsertElementRequest['element'] = element,) => {const input: PrepareElementInstallRequest = {installationName: null,destination,- element,+ element: elementToPrepare,};return prepareElementInstallHandler({@@ -184,7 +188,7 @@ const makeFixture = () => {cancelJob: () => undefined,removeJob: () => undefined,},- publicDir: remotionRoot,+ publicDir,remotionRoot,request: {} as never,response: {} as never,@@ -211,6 +215,7 @@ const makeFixture = () => {elementFile,events,outsideRoot,+ publicDir,watcherSkipSequencePropsUpdates,};};@@ -237,6 +242,177 @@ test('plans an Element installation without changing the project', async () => {}});+test.each(['wrapped', 'component-owned-sequence'] as const)(+ 'installs asset props in %s mode and retains assets on undo',+ async (installationMode) => {+ const fixture = makeFixture();+ const originalFetch = globalThis.fetch;+ let fetches = 0;+ globalThis.fetch = Object.assign(+ () => {+ fetches++;+ return Promise.resolve(new Response(new Uint8Array([3, 4, 5])));+ },+ {preconnect: originalFetch.preconnect},+ );+ try {+ const assetElement = {+ ...element,+ assets: [+ {+ path: 'elements/embedded.bin',+ type: 'base64' as const,+ data: 'AAEC',+ },+ {+ path: 'elements/remote.bin',+ type: 'url' as const,+ url: 'https://93.184.216.35/remote.bin',+ },+ ],+ installationMode,+ initialProps: {+ logoSrc: staticFileRef('elements/remote.bin'),+ media: {sources: [staticFileRef('elements/embedded.bin')]},+ },+ sourceCode: `import {Img, Sequence, type SequenceProps} from 'remotion';++export const LowerThird = ({logoSrc, ...props}: {logoSrc: string} & SequenceProps) => (+ <Sequence {...props}><Img name="Logo" src={logoSrc} /></Sequence>+);+`,+ };+ const request: InsertElementRequest = {+ installationName: null,+ compositionFile: 'Root.tsx',+ compositionId: 'target',+ element: assetElement,+ expectedFileState: null,+ from: null,+ overwriteExisting: false,+ position: null,+ undoRedoNavigation: null,+ newComposition: null,+ };+ const invalidElement = {+ ...assetElement,+ initialProps: {logoSrc: staticFileRef('elements/undeclared.bin')},+ };+ expect(+ await fixture.prepareInstall(+ fixture.currentDestination,+ invalidElement,+ ),+ ).toMatchObject({success: false});+ expect(+ await fixture.callHandlerWithInput({+ ...request,+ element: invalidElement,+ }),+ ).toMatchObject({success: false});+ expect(fetches).toBe(0);+ expect(existsSync(fixture.publicDir)).toBe(false);++ const preflight = await fixture.prepareInstall(+ fixture.currentDestination,+ assetElement,+ );+ expect(preflight.success).toBe(true);+ expect(existsSync(fixture.publicDir)).toBe(false);++ const response = await fixture.callHandlerWithInput(request);+ expect(response).toMatchObject({success: true});+ expect(+ readFileSync(path.join(fixture.publicDir, 'elements/embedded.bin')),+ ).toEqual(Buffer.from([0, 1, 2]));+ expect(+ readFileSync(path.join(fixture.publicDir, 'elements/remote.bin')),+ ).toEqual(Buffer.from([3, 4, 5]));+ const installedSource = readFileSync(fixture.elementFile, 'utf8');+ expect(installedSource).toBe(assetElement.sourceCode);+ const caller = readFileSync(fixture.compositionFile, 'utf8');+ expect(caller).toMatch(+ /logoSrc=\{staticFile\(["']elements\/remote\.bin["']\)\}/,+ );+ expect(caller).toMatch(+ /sources: \[staticFile\(["']elements\/embedded\.bin["']\)\]/,+ );++ expect(popUndo().success).toBe(true);+ expect(existsSync(fixture.elementFile)).toBe(false);+ expect(+ readFileSync(path.join(fixture.publicDir, 'elements/embedded.bin')),+ ).toEqual(Buffer.from([0, 1, 2]));+ expect(popRedo().success).toBe(true);+ expect(existsSync(fixture.elementFile)).toBe(true);++ const conflict = await fixture.callHandlerWithInput({+ ...request,+ installationName: 'second',+ element: {+ ...assetElement,+ assets: [+ {path: 'elements/embedded.bin', type: 'base64', data: 'CQgH'},+ assetElement.assets[1],+ ],+ },+ });+ expect(conflict).toMatchObject({+ success: false,+ type: 'error',+ reason:+ 'Asset elements/embedded.bin already exists with different contents',+ });+ expect(+ readFileSync(path.join(fixture.publicDir, 'elements/embedded.bin')),+ ).toEqual(Buffer.from([0, 1, 2]));+ } finally {+ globalThis.fetch = originalFetch;+ fixture.cleanup();+ }+ },+);++test('rejects oversized mixed Element assets before writing any files, regardless of order', async () => {+ const fixture = makeFixture();+ const originalFetch = globalThis.fetch;+ globalThis.fetch = Object.assign(+ () => Promise.resolve(new Response(new Uint8Array(50 * 1024 * 1024))),+ {preconnect: originalFetch.preconnect},+ );+ const assets: InsertElementRequest['element']['assets'] = [+ {path: 'remote.bin', type: 'url', url: 'https://93.184.216.35/remote.bin'},+ {path: 'embedded.bin', type: 'base64', data: 'AAEC'},+ ];+ try {+ for (const orderedAssets of [assets, [...assets].reverse()]) {+ expect(+ await fixture.callHandlerWithInput({+ installationName: null,+ compositionFile: 'Root.tsx',+ compositionId: 'target',+ element: {...element, assets: orderedAssets},+ expectedFileState: null,+ from: null,+ overwriteExisting: false,+ position: null,+ undoRedoNavigation: null,+ newComposition: null,+ }),+ ).toMatchObject({success: false, type: 'error'});+ expect(existsSync(fixture.publicDir)).toBe(false);+ expect(existsSync(fixture.elementFile)).toBe(false);+ expect(readFileSync(fixture.compositionFile, 'utf8')).toBe(+ compositionSource,+ );+ expect(getUndoStack()).toHaveLength(0);+ }+ } finally {+ globalThis.fetch = originalFetch;+ fixture.cleanup();+ }+});+test('plans a new-composition install without resolving the selected component', async () => {const fixture = makeFixture();try {diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex c946b851cc..e537f4f173 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -89,6 +89,10 @@ export type ElementDependency =};export type InstallableElement = {+ assets: Array<+ | {path: string; type: 'url'; url: string}+ | {path: string; type: 'base64'; data: string}+ >;dependencies: ElementDependency[];durationInFrames: number | null;initialProps: Readonly<Record<string, ComponentPropValue>> | null;