🎥 Make videos programmatically with React
`@remotion/studio-server`: Preflight Element installations (#9926)
Igor Samokhovetsa25d756cbe1a
diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex 624ec6d41e..0613873214 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -27,6 +27,7 @@ import {moveKeyframesHandler} from './routes/move-keyframes';import {openInEditorHandler} from './routes/open-in-editor';import {handleOpenInFileExplorer} from './routes/open-in-file-explorer';import {pasteEffectsHandler} from './routes/paste-effects';+import {prepareElementInstallHandler} from './routes/prepare-element-install';import {projectInfoHandler} from './routes/project-info';import {redoHandler} from './routes/redo';import {registerClientRenderHandler} from './routes/register-client-render';@@ -109,6 +110,7 @@ export const allApiRoutes: {'/api/install-package': handleInstallPackage,'/api/insert-jsx-element': insertJsxElementHandler,'/api/insert-element': insertElementHandler,+ '/api/prepare-element-install': prepareElementInstallHandler,'/api/update-element-install-target': updateElementInstallTargetHandler,'/api/download-remote-asset': downloadRemoteAssetHandler,'/api/undo': undoHandler,diff --git a/packages/studio-server/src/preview-server/routes/element-install-plan.ts b/packages/studio-server/src/preview-server/routes/element-install-plan.tsnew file mode 100644index 0000000000..1b5f575e3c--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/element-install-plan.ts@@ -0,0 +1,176 @@+import {createHash} from 'node:crypto';+import {existsSync, readFileSync} from 'node:fs';+import path from 'node:path';+import {StudioProtocolInternals} from '@remotion/studio-protocol';+import type {+ ElementInstallExpectedFileState,+ InsertElementRequest,+ PrepareElementInstallRequest,+} from '@remotion/studio-shared';+import {resolveCompositionComponentWithFile} from '../../helpers/resolve-composition-component';+import {getSafeElementInstallPaths} from './safe-element-install-path';++export const normalizeElementSourceForComparison = (source: string) => {+ return source.replace(/\r\n/g, '\n').trim();+};++export const getElementSourceHash = (source: string) => {+ return createHash('sha256').update(source).digest('hex');+};++export const validateElementInstallPosition = (+ position: InsertElementRequest['position'],+) => {+ if (position === null) {+ return;+ }++ if (!Number.isFinite(position.x) || !Number.isFinite(position.y)) {+ throw new Error('Position must be finite');+ }+};++const validateDimensions = (+ dimensions: InsertElementRequest['element']['dimensions'],+) => {+ if (dimensions === null) {+ return;+ }++ if (+ !Number.isFinite(dimensions.width) ||+ !Number.isFinite(dimensions.height) ||+ dimensions.width <= 0 ||+ dimensions.height <= 0+ ) {+ throw new Error('Element dimensions must be positive finite numbers');+ }+};++export const validateElementForInstallation = (+ element: InsertElementRequest['element'],+) => {+ if (+ StudioProtocolInternals.makeElementFileNameFromSlug(element.slug) === null+ ) {+ throw new Error(+ 'Element slug must produce a safe lowercase .tsx file name',+ );+ }++ if (+ typeof element.sourceCode !== 'string' ||+ element.sourceCode.trim().length === 0 ||+ element.sourceCode.length > 200000+ ) {+ throw new Error('Unsupported Element source code');+ }++ if (+ StudioProtocolInternals.getElementComponentNameFromSourceCode(+ element.sourceCode,+ ) === null+ ) {+ throw new Error('Element source must export exactly one named component');+ }++ validateDimensions(element.dimensions);+};++export const makeRelativeElementImportPath = ({+ fromFile,+ toFile,+}: {+ fromFile: string;+ toFile: string;+}) => {+ const withoutExtension = toFile.replace(/\.tsx$/, '');+ let relative = path+ .relative(path.dirname(fromFile), withoutExtension)+ .split(path.sep)+ .join('/');++ if (!relative.startsWith('.')) {+ relative = `./${relative}`;+ }++ return relative;+};++const getExpectedFileState = (+ existingSource: string | null,+): ElementInstallExpectedFileState => {+ if (existingSource === null) {+ return {exists: false};+ }++ return {+ exists: true,+ sourceHash: getElementSourceHash(existingSource),+ };+};++export const getElementInstallPlan = async ({+ compositionFile,+ compositionId,+ element,+ remotionRoot,+}: PrepareElementInstallRequest & {remotionRoot: string}) => {+ validateElementForInstallation(element);++ const componentName =+ StudioProtocolInternals.getElementComponentNameFromSourceCode(+ element.sourceCode,+ );+ if (componentName === null) {+ throw new Error('Element source must export exactly one named component');+ }++ const location = await resolveCompositionComponentWithFile({+ remotionRoot,+ compositionFile,+ compositionId,+ });+ if (!location.canAddSequence) {+ throw new Error('Cannot insert Element into this composition component');+ }++ const derivedElementFileName =+ StudioProtocolInternals.makeElementFileNameFromSlug(element.slug);+ if (derivedElementFileName === null) {+ throw new Error(+ 'Element slug must produce a safe lowercase .tsx file name',+ );+ }++ const safePaths = await getSafeElementInstallPaths({+ compositionFileName: location.fileName,+ elementFileName: path.resolve(+ path.dirname(location.fileName),+ derivedElementFileName,+ ),+ remotionRoot,+ });+ const elementFileExists = existsSync(safePaths.elementFileName);+ const existingElementSource = elementFileExists+ ? readFileSync(safePaths.elementFileName, 'utf-8')+ : null;++ return {+ componentName,+ elementFileExists,+ elementFileName: safePaths.elementFileName,+ existingElementSource,+ expectedFileState: getExpectedFileState(existingElementSource),+ filePath: path+ .relative(safePaths.remotionRoot, safePaths.elementFileName)+ .split(path.sep)+ .join('/'),+ importPath: makeRelativeElementImportPath({+ fromFile: safePaths.compositionFileName,+ toFile: safePaths.elementFileName,+ }),+ location,+ safePaths,+ };+};diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.tsindex 91cd722d81..ab75109108 100644--- a/packages/studio-server/src/preview-server/routes/insert-element.ts+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts@@ -1,17 +1,11 @@-import {existsSync, readFileSync} from 'node:fs';-import path from 'node:path';import {RenderInternals} from '@remotion/renderer';-import {StudioProtocolInternals} from '@remotion/studio-protocol';-import {- type InsertElementRequest,- type InsertElementResponse,- type InsertableCompositionElementPosition,+import type {+ ElementInstallExpectedFileState,+ InsertElementRequest,+ InsertElementResponse,} from '@remotion/studio-shared';import {writeFileAndNotifyFileWatchers} from '../../file-watcher';-import {- insertJsxElementIntoComposition,- resolveCompositionComponentWithFile,-} from '../../helpers/resolve-composition-component';+import {insertJsxElementIntoComposition} from '../../helpers/resolve-composition-component';import type {ApiHandler} from '../api-types';import {formatLogFileLocation} from '../format-log-file-location';import {@@ -19,93 +13,34 @@ import {pushTransactionToUndoStack,suppressUndoStackInvalidation,} from '../undo-stack';+import {+ getElementInstallPlan,+ normalizeElementSourceForComparison,+ validateElementInstallPosition,+} from './element-install-plan';import {warnAboutPrettierOnce} from './log-updates/log-update';-import {getSafeElementInstallPaths} from './safe-element-install-path';import {withSourceFileWriteQueue} from './source-file-write-queue';-const validatePosition = (- position: InsertableCompositionElementPosition | null,-) => {- if (position === null) {- return;- }-- if (!Number.isFinite(position.x) || !Number.isFinite(position.y)) {- throw new Error('Position must be finite');- }-};--const withoutTsxExtension = (fileName: string) => {- return fileName.replace(/\.tsx$/, '');-};--const normalizeSourceForComparison = (source: string) => {- return source.replace(/\r\n/g, '\n').trim();-};--const makeRelativeImportPath = ({- fromFile,- toFile,+const hasExpectedFileState = ({+ expected,+ actual,}: {- fromFile: string;- toFile: string;+ expected: ElementInstallExpectedFileState;+ actual: ElementInstallExpectedFileState;}) => {- const withoutExtension = withoutTsxExtension(toFile);- let relative = path- .relative(path.dirname(fromFile), withoutExtension)- .split(path.sep)- .join('/');-- if (!relative.startsWith('.')) {- relative = `./${relative}`;+ if (expected.exists !== actual.exists) {+ return false;}- return relative;-};--const validateDimensions = (- dimensions: InsertElementRequest['element']['dimensions'],-) => {- if (dimensions === null) {- return;- }-- if (- !Number.isFinite(dimensions.width) ||- !Number.isFinite(dimensions.height) ||- dimensions.width <= 0 ||- dimensions.height <= 0- ) {- throw new Error('Element dimensions must be positive finite numbers');- }-};--const validateElement = (element: InsertElementRequest['element']) => {- if (- StudioProtocolInternals.makeElementFileNameFromSlug(element.slug) === null- ) {- throw new Error(- 'Element slug must produce a safe lowercase .tsx file name',- );+ if (!expected.exists) {+ return true;}- if (- typeof element.sourceCode !== 'string' ||- element.sourceCode.trim().length === 0 ||- element.sourceCode.length > 200000- ) {- throw new Error('Unsupported Element source code');+ if (!actual.exists) {+ return false;}- if (- StudioProtocolInternals.getElementComponentNameFromSourceCode(- element.sourceCode,- ) === null- ) {- throw new Error('Element source must export exactly one named component');- }-- validateDimensions(element.dimensions);+ return actual.sourceHash === expected.sourceHash;};export const insertElementHandler: ApiHandler<@@ -116,6 +51,7 @@ export const insertElementHandler: ApiHandler<compositionFile,compositionId,element,+ expectedFileState,from,position,overwriteExisting,@@ -125,8 +61,7 @@ export const insertElementHandler: ApiHandler<}) =>withSourceFileWriteQueue(async () => {try {- validateElement(element);- validatePosition(position);+ validateElementInstallPosition(position);if (from !== null &&(!Number.isInteger(from) || !Number.isFinite(from) || from < 0)@@ -134,90 +69,72 @@ export const insertElementHandler: ApiHandler<throw new Error('from must be a non-negative integer');}- const componentName =- StudioProtocolInternals.getElementComponentNameFromSourceCode(- element.sourceCode,- );- if (componentName === null) {- throw new Error(- 'Element source must export exactly one named component',- );- }-RenderInternals.Log.trace({indent: false, logLevel},`[insert-element] Received request for compositionFile="${compositionFile}" compositionId="${compositionId}" element="${element.slug}"`,);- const location = await resolveCompositionComponentWithFile({- remotionRoot,+ const plan = await getElementInstallPlan({compositionFile,compositionId,- });- if (!location.canAddSequence) {- throw new Error(- 'Cannot insert Element into this composition component',- );- }-- const derivedElementFileName =- StudioProtocolInternals.makeElementFileNameFromSlug(element.slug);- if (derivedElementFileName === null) {- throw new Error(- 'Element slug must produce a safe lowercase .tsx file name',- );- }-- const safePaths = await getSafeElementInstallPaths({- compositionFileName: location.fileName,- elementFileName: path.resolve(- path.dirname(location.fileName),- derivedElementFileName,- ),+ element,remotionRoot,});- const {elementFileName} = safePaths;+ if (+ expectedFileState !== null &&+ !hasExpectedFileState({+ actual: plan.expectedFileState,+ expected: expectedFileState,+ })+ ) {+ const {existingElementSource} = plan;+ if (existingElementSource !== null) {+ return {+ success: false,+ type: 'file-conflict',+ conflict: {+ filePath: plan.filePath,+ existingSource: existingElementSource,+ incomingSource: element.sourceCode,+ },+ };+ }++ throw new Error('Element source changed during installation');+ }- const elementFileExists = existsSync(elementFileName);- const existingElementSource = elementFileExists- ? readFileSync(elementFileName, 'utf-8')- : null;const elementSourcesDiffer =- existingElementSource !== null &&- normalizeSourceForComparison(existingElementSource) !==- normalizeSourceForComparison(element.sourceCode);+ plan.existingElementSource !== null &&+ normalizeElementSourceForComparison(plan.existingElementSource) !==+ normalizeElementSourceForComparison(element.sourceCode);- if (elementSourcesDiffer && !overwriteExisting) {+ if (+ elementSourcesDiffer &&+ !overwriteExisting &&+ plan.existingElementSource !== null+ ) {return {success: false,type: 'file-conflict',conflict: {- filePath: path- .relative(safePaths.remotionRoot, elementFileName)- .split(path.sep)- .join('/'),- existingSource: existingElementSource,+ filePath: plan.filePath,+ existingSource: plan.existingElementSource,incomingSource: element.sourceCode,},};}- const shouldWriteElementFile = !elementFileExists || elementSourcesDiffer;-- const importPath = makeRelativeImportPath({- fromFile: location.fileName,- toFile: elementFileName,- });-+ const shouldWriteElementFile =+ !plan.elementFileExists || elementSourcesDiffer;const inserted = await insertJsxElementIntoComposition({remotionRoot,compositionFile,compositionId,element: {type: 'component',- componentName,- importName: componentName,- importPath,+ componentName: plan.componentName,+ importName: plan.componentName,+ importPath: plan.importPath,props: [],position: null,},@@ -231,26 +148,37 @@ export const insertElementHandler: ApiHandler<},});- const finalSafePaths = await getSafeElementInstallPaths({- compositionFileName: inserted.fileName,- elementFileName,+ const finalPlan = await getElementInstallPlan({+ compositionFile,+ compositionId,+ element,remotionRoot,});if (- finalSafePaths.compositionFileName !== safePaths.compositionFileName+ finalPlan.safePaths.compositionFileName !==+ plan.safePaths.compositionFileName) {throw new Error('Composition source changed during Element installation',);}+ if (+ !hasExpectedFileState({+ actual: finalPlan.expectedFileState,+ expected: plan.expectedFileState,+ })+ ) {+ throw new Error('Element source changed during installation');+ }+pushTransactionToUndoStack({snapshots: [...(shouldWriteElementFile? [{- filePath: elementFileName,- oldContents: existingElementSource,+ filePath: plan.elementFileName,+ oldContents: plan.existingElementSource,newContents: element.sourceCode,logLine: 1,},@@ -273,14 +201,14 @@ export const insertElementHandler: ApiHandler<suppressHmrOnFileRestore: false,});if (shouldWriteElementFile) {- suppressUndoStackInvalidation(elementFileName);+ suppressUndoStackInvalidation(plan.elementFileName);}suppressUndoStackInvalidation(inserted.fileName);if (shouldWriteElementFile) {writeFileAndNotifyFileWatchers(- elementFileName,+ plan.elementFileName,element.sourceCode,undefined,);@@ -299,12 +227,12 @@ export const insertElementHandler: ApiHandler<});const elementLocationLabel = formatLogFileLocation({remotionRoot,- absolutePath: elementFileName,+ absolutePath: plan.elementFileName,line: 1,});const elementFileAction = elementSourcesDiffer? 'Overwrote existing Element source'- : elementFileExists+ : plan.elementFileExists? 'Reused existing Element source': 'Created Element source';RenderInternals.Log.info(@@ -313,7 +241,7 @@ export const insertElementHandler: ApiHandler<);RenderInternals.Log.info({indent: false, logLevel},- `${RenderInternals.chalk.blueBright(compositionLocationLabel)} Added <${componentName}>`,+ `${RenderInternals.chalk.blueBright(compositionLocationLabel)} Added <${plan.componentName}>`,);if (!inserted.formatted) {warnAboutPrettierOnce(logLevel);@@ -321,9 +249,7 @@ export const insertElementHandler: ApiHandler<printUndoHint(logLevel);- return {- success: true,- };+ return {success: true};} catch (err) {return {success: false,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.tsnew file mode 100644index 0000000000..e42e47b9c8--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/prepare-element-install.ts@@ -0,0 +1,30 @@+import type {+ PrepareElementInstallRequest,+ PrepareElementInstallResponse,+} from '@remotion/studio-shared';+import type {ApiHandler} from '../api-types';+import {getElementInstallPlan} from './element-install-plan';+import {withSourceFileWriteQueue} from './source-file-write-queue';++export const prepareElementInstallHandler: ApiHandler<+ PrepareElementInstallRequest,+ PrepareElementInstallResponse+> = ({input, remotionRoot}) =>+ withSourceFileWriteQueue(async () => {+ try {+ const plan = await getElementInstallPlan({...input, remotionRoot});+ return {+ success: true,+ plan: {+ expectedFileState: plan.expectedFileState,+ filePath: plan.filePath,+ },+ };+ } catch (error) {+ return {+ success: false,+ reason: (error as Error).message,+ stack: (error as Error).stack as string,+ };+ }+ });diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.tsindex 6220c9c66b..21c102b741 100644--- a/packages/studio-server/src/test/insert-element.test.ts+++ b/packages/studio-server/src/test/insert-element.test.ts@@ -9,13 +9,17 @@ import {} from 'node:fs';import {tmpdir} from 'node:os';import path from 'node:path';-import type {InsertElementRequest} from '@remotion/studio-shared';+import type {+ InsertElementRequest,+ PrepareElementInstallRequest,+} from '@remotion/studio-shared';import {createFileWatcherRegistry,setFileWatcherRegistry,} from '../file-watcher';import {setLiveEventsListener} from '../preview-server/live-events';import {insertElementHandler} from '../preview-server/routes/insert-element';+import {prepareElementInstallHandler} from '../preview-server/routes/prepare-element-install';import {clearUndoStackForTests,getUndoStack,@@ -73,11 +77,15 @@ const makeFixture = () => {addNewClientListener: () => () => undefined,});- const callHandler = (overwriteExisting: boolean) => {+ const callHandler = (+ overwriteExisting: boolean,+ expectedFileState: InsertElementRequest['expectedFileState'] = null,+ ) => {const input: InsertElementRequest = {compositionFile: 'Root.tsx',compositionId: 'target',element,+ expectedFileState,from: null,overwriteExisting,position: null,@@ -102,6 +110,31 @@ const makeFixture = () => {});};+ const prepareInstall = () => {+ const input: PrepareElementInstallRequest = {+ compositionFile: 'Root.tsx',+ compositionId: 'target',+ element,+ };++ return prepareElementInstallHandler({+ binariesDirectory: null,+ configFile: null,+ entryPoint: compositionFile,+ input,+ logLevel: 'error',+ methods: {+ addJob: () => undefined,+ cancelJob: () => undefined,+ removeJob: () => undefined,+ },+ publicDir: remotionRoot,+ remotionRoot,+ request: {} as never,+ response: {} as never,+ });+ };+const cleanup = () => {clearUndoStackForTests();cleanupLiveEvents();@@ -113,12 +146,34 @@ const makeFixture = () => {return {callHandler,cleanup,+ prepareInstall,compositionFile,elementFile,outsideRoot,};};+test('plans an Element installation without changing the project', async () => {+ const fixture = makeFixture();+ try {+ const response = await fixture.prepareInstall();++ expect(response).toEqual({+ success: true,+ plan: {+ expectedFileState: {exists: false},+ filePath: 'lower-third.element.tsx',+ },+ });+ expect(existsSync(fixture.elementFile)).toBe(false);+ expect(readFileSync(fixture.compositionFile, 'utf-8')).toBe(+ compositionSource,+ );+ } finally {+ fixture.cleanup();+ }+});+test('creates a new Element file without an overwrite conflict', async () => {const fixture = makeFixture();try {@@ -181,6 +236,40 @@ test('returns a structured conflict without changing the project', async () => {}});+test('does not overwrite a file that changed after planning', async () => {+ const fixture = makeFixture();+ try {+ const planned = await fixture.prepareInstall();+ if (!planned.success) {+ throw new Error(planned.reason);+ }++ writeFileSync(fixture.elementFile, existingElementSource);+ const response = await fixture.callHandler(+ true,+ planned.plan.expectedFileState,+ );++ expect(response).toEqual({+ success: false,+ type: 'file-conflict',+ conflict: {+ filePath: 'lower-third.element.tsx',+ existingSource: existingElementSource,+ incomingSource: incomingElementSource,+ },+ });+ expect(readFileSync(fixture.elementFile, 'utf-8')).toBe(+ existingElementSource,+ );+ expect(readFileSync(fixture.compositionFile, 'utf-8')).toBe(+ compositionSource,+ );+ } finally {+ fixture.cleanup();+ }+});+test('rejects an Element source symlink that escapes the project', async () => {const fixture = makeFixture();try {diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 85bc630dfd..94bc538eae 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -850,10 +850,40 @@ export type ConvertFigmaClipboardToSvgResponse =reason: string;};+export type ElementInstallExpectedFileState =+ | {+ exists: false;+ }+ | {+ exists: true;+ sourceHash: string;+ };++export type PrepareElementInstallRequest = {+ compositionFile: string;+ compositionId: string;+ element: ElementDragData['element'];+};++export type PrepareElementInstallResponse =+ | {+ success: true;+ plan: {+ filePath: string;+ expectedFileState: ElementInstallExpectedFileState;+ };+ }+ | {+ success: false;+ reason: string;+ stack: string;+ };+export type InsertElementRequest = {compositionFile: string;compositionId: string;element: ElementDragData['element'];+ expectedFileState: ElementInstallExpectedFileState | null;from: number | null;position: InsertableCompositionElementPosition | null;overwriteExisting: boolean;@@ -1095,6 +1125,10 @@ export type ApiRoutes = {ConvertFigmaClipboardToSvgResponse>;'/api/insert-element': ReqAndRes<InsertElementRequest, InsertElementResponse>;+ '/api/prepare-element-install': ReqAndRes<+ PrepareElementInstallRequest,+ PrepareElementInstallResponse+ >;'/api/update-element-install-target': ReqAndRes<UpdateElementInstallTargetRequest,UpdateElementInstallTargetResponsediff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 13251c9d90..b26508dfb6 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -48,6 +48,7 @@ export {DuplicateEffectResponse,DuplicateJsxNodeRequest,DuplicateJsxNodeResponse,+ ElementInstallExpectedFileState,ElementInstallRequest,FindInFileRequest,FindInFileResponse,@@ -72,6 +73,8 @@ export {OpenInFileExplorerRequest,PasteEffectsRequest,PasteEffectsResponse,+ PrepareElementInstallRequest,+ PrepareElementInstallResponse,ProjectInfoRequest,ProjectInfoResponse,RedoRequest,diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.tsindex 667634eef1..3706f99e0e 100644--- a/packages/studio/src/components/import-assets.ts+++ b/packages/studio/src/components/import-assets.ts@@ -1339,6 +1339,7 @@ export const insertElement = async ({compositionFile,compositionId,element,+ expectedFileState: null,from,overwriteExisting,position,