🎥 Make videos programmatically with React
`@remotion/codemods`: Migrate tests to public editing workflows
Jonny Burgercf909fe81a1d
diff --git a/bun.lock b/bun.lockindex 76294b99de..90d36ad83f 100644--- a/bun.lock+++ b/bun.lock@@ -1033,6 +1033,7 @@"@remotion/captions": "workspace:*","@remotion/cli": "workspace:*","@remotion/cloudrun": "workspace:*",+ "@remotion/codemods": "workspace:*","@remotion/compositor-darwin-arm64": "workspace:*","@remotion/compositor-darwin-x64": "workspace:*","@remotion/compositor-linux-x64-gnu": "workspace:*",@@ -2473,6 +2474,7 @@"@remotion/animation-utils": "workspace:*","@remotion/captions": "workspace:*","@remotion/cli": "workspace:*",+ "@remotion/codemods": "workspace:*","@remotion/google-fonts": "workspace:*","@remotion/install-whisper-cpp": "workspace:*","@remotion/lambda": "workspace:*",diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 9129620b4a..e3bbeb5a6e 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -1,5 +1,5 @@import {expect, test} from 'bun:test';-import {CodemodsInternals} from '@remotion/codemods';+import {addSolid, CodemodsInternals} from '@remotion/codemods';import {createElementPayload} from '@remotion/studio-protocol';import type {EventSourceEvent} from '@remotion/studio-shared';import type {InteractivitySchema} from 'remotion';@@ -8,30 +8,19 @@ import {createBrowserStudioOperations} from '../browser-studio-operations';import {createBlankTemplateProject} from '../templates/blank';import type {VirtualProject} from '../types';-const {- basicCaptionsElementSource,- insertSolidIntoProject,- insertSolidIntoProjectWithNodePathRemappings,-} = CodemodsInternals;+const {basicCaptionsElementSource} = CodemodsInternals;const insertSolid = (project: VirtualProject,compositionFile = '/project/src/Composition.tsx',) => {- return insertSolidIntoProject({+ return addSolid({project,- request: {- compositionFile,- compositionId: 'MyComp',- element: {- type: 'solid',- width: 1280,- height: 720,- position: null,- },- from: null,- },- });+ compositionFile,+ compositionId: 'MyComp',+ width: 1280,+ height: 720,+ }).project;};test('consumes an initial Element payload only once', () => {@@ -91,20 +80,15 @@ test('adds multiple Solids without duplicating the import', () => {test('adds a Solid at a timeline frame', () => {const project = createBlankTemplateProject();- const updated = insertSolidIntoProject({+ const updated = addSolid({project,- request: {- compositionFile: '/project/src/Composition.tsx',- compositionId: 'MyComp',- from: 42,- element: {- type: 'solid',- width: 1280,- height: 720,- position: {x: 100, y: 50},- },- },- });+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ from: 42,+ width: 1280,+ height: 720,+ position: {x: 100, y: 50},+ }).project;const composition = updated.files['/project/src/Composition.tsx'];expect(composition).toContain('<Sequence from={42}');@@ -201,21 +185,13 @@ registerRoot(Root);`,},};- const {project: updated, nodePathRemappings} =- insertSolidIntoProjectWithNodePathRemappings({- project,- request: {- compositionFile: '/project/src/index.tsx',- compositionId: 'MyComp',- from: null,- element: {- type: 'solid',- width: 1280,- height: 720,- position: null,- },- },- });+ const {project: updated, nodePathRemappings} = addSolid({+ project,+ compositionFile: '/project/src/index.tsx',+ compositionId: 'MyComp',+ width: 1280,+ height: 720,+ });const output = updated.files['/project/src/index.tsx'];expect(output).toContain(@@ -1841,7 +1817,7 @@ export const Root = () => (expect(getProject().files[fileName]).not.toContain('\t');});-test('reports a structured error when a composition has no defaultProps', async () => {+test('adds missing composition defaultProps and restores them through undo and redo', async () => {const {operations, getProject} = makeOperationsForProject(createBlankTemplateProject(),);@@ -1852,13 +1828,15 @@ test('reports a structured error when a composition has no defaultProps', asyncdefaultProps: JSON.stringify({title: 'Hello'}),enumPaths: [],});- expect(result).toEqual({- success: false,- reason:- 'No `defaultProps` prop found in the <Composition/> tag with the ID "MyComp".',- stack: expect.any(String),- });+ expect(result).toEqual({success: true});+ const updatedFiles = getProject().files;+ expect(updatedFiles['/project/src/Composition.tsx']).toContain(+ 'title: "Hello"',+ );+ expect((await operations.undo()).success).toBe(true);expect(getProject().files).toEqual(initialFiles);+ expect((await operations.redo()).success).toBe(true);+ expect(getProject().files).toEqual(updatedFiles);});test('reports structured failures for unsupported codemods', async () => {@@ -2081,7 +2059,7 @@ export const Comp = () => (]),).toEqual({success: false,- reason: 'Cannot duplicate effect: not-found',+ reason: 'Effect index is out of range',stack: expect.any(String),});expect(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 e6246c91db..d5b36761c3 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@@ -9,6 +9,81 @@ import {import {createBlankTemplateProject} from '../templates/blank';import type {VirtualProject} from '../types';+test('previews and creates a Canvas Capture with both files in undo history', async () => {+ const initialProject = createBlankTemplateProject();+ let project = initialProject;+ const operations = createBrowserStudioOperations({+ dependencyVersions: {},+ getStaticFiles: null,+ getProject: () => project,+ initialElement: null,+ onProjectChange: (nextProject) => {+ project = nextProject;+ },+ resolveDependencies: null,+ });+ const request: Parameters<typeof operations.applyCodemod>[0] = {+ codemod: {+ type: 'new-composition',+ newId: 'Capture',+ componentName: 'Capture',+ componentImportPath: './Capture',+ folderName: null,+ parentName: null,+ newDurationInFrames: 90,+ newFps: 30,+ newHeight: 720,+ newWidth: 1280,+ canvasCapture: {+ videoFileName: 'capture.mp4',+ videoHeight: 1080,+ videoWidth: 1920,+ keyframeFps: 30,+ data: {+ captureMetadata: {density: 2},+ mouseMovements: [+ {timeInSeconds: 0, canvasX: 10, canvasY: 20, cursor: 'pointer'},+ ],+ pointerClicks: [],+ },+ },+ },+ dryRun: true,+ undoRedoNavigation: null,+ symbolicatedStack: null,+ };+ const preview = await operations.applyCodemod(request);+ if (!preview.success) {+ throw new Error(preview.reason);+ }++ expect(preview.diff.additions).toBeGreaterThan(0);+ expect(project).toBe(initialProject);+ expect(await operations.applyCodemod({...request, dryRun: false})).toEqual(+ preview,+ );+ expect(project.files['/project/src/Root.tsx']).toContain('<Capture />');+ expect(project.files['/project/src/Root.tsx']).toMatch(+ /from ["']\.\/Capture["']/,+ );+ const generated = project.files['/project/src/Capture.tsx'];+ expect(generated).toContain("id={'Capture'}");+ expect(generated).toContain("staticFile('capture.mp4')");+ expect(generated).toContain('<MacOSCursor');+ const createdProject = project;+ expect((await operations.undo()).success).toBe(true);+ expect(project.files).toEqual(initialProject.files);+ expect((await operations.redo()).success).toBe(true);+ expect(project.files).toEqual(createdProject.files);+ expect(+ await operations.applyCodemod({...request, dryRun: false}),+ ).toMatchObject({+ success: false,+ reason: expect.stringContaining('already exists'),+ });+ expect(project.files).toEqual(createdProject.files);+});+test('mutates virtual files, emits events, and preserves undo and redo history', async () => {const initialProject = createBlankTemplateProject();let project: VirtualProject = {@@ -393,6 +468,21 @@ test('previews and duplicates compositions as an undoable project mutation', asyexpect(project.files['/project/src/Composition.tsx']).toBe(initialProject.files['/project/src/Composition.tsx'],);++ const stillResult = await operations.duplicateComposition({+ ...request,+ codemod: {...request.codemod, newId: 'MyStill', tag: 'Still'},+ dryRun: false,+ });+ expect(stillResult.success).toBe(true);+ const stillSource =+ project.files['/project/src/Composition.tsx'].match(+ /<Still[\s\S]*?\/>/,+ )?.[0];+ expect(stillSource).toContain('id="MyStill"');+ expect(stillSource).toContain('width={1920}');+ expect(stillSource).not.toContain('fps=');+ expect(stillSource).not.toContain('durationInFrames=');});test('imports an Element with pinned Remotion dependencies as one undoable mutation', async () => {diff --git a/packages/codemods/src/add-canvas-capture-composition.ts b/packages/codemods/src/add-canvas-capture-composition.tsindex 19fa17c0f2..572f361cd1 100644--- a/packages/codemods/src/add-canvas-capture-composition.ts+++ b/packages/codemods/src/add-canvas-capture-composition.ts@@ -56,9 +56,19 @@ export const addCanvasCaptureComposition = <Project extends CodemodProject>({);}- if (project.files[component.filePath] !== undefined) {+ let existingComponentFile: string | null = null;+ try {+ existingComponentFile = findProjectFile({+ project,+ filePath: component.filePath,+ });+ } catch {+ // The component is created only when no equivalent project path exists.+ }++ if (existingComponentFile !== null) {throw new Error(- `Cannot create ${component.filePath} because it already exists`,+ `Cannot create ${existingComponentFile} because it already exists`,);}diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.tsindex 6dca267b88..b59a60b3b2 100644--- a/packages/codemods/src/index.ts+++ b/packages/codemods/src/index.ts@@ -25,7 +25,6 @@ import {computeSequencePropsSubscriptionFromContent} from './sequence-props';import {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';import {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';import {simpleDiff} from './simple-diff';-import {updateDefaultProps} from './update-default-props';import {updateInlineCaptionPatches} from './update-inline-caption-patches';export {addSolid, type AddSolidOptions, type AddSolidResult} from './add-solid';@@ -181,7 +180,6 @@ export const CodemodsInternals = {resolveCompositionComponent,resolveCompositionComponentWithFile,simpleDiff,- updateDefaultProps,updateInlineCaptionPatches,};diff --git a/packages/codemods/src/set-composition-default-props.ts b/packages/codemods/src/set-composition-default-props.tsindex ce5ddbef7d..bf4be24799 100644--- a/packages/codemods/src/set-composition-default-props.ts+++ b/packages/codemods/src/set-composition-default-props.ts@@ -1,19 +1,21 @@-import type {EnumPath} from '@remotion/studio-shared';+import type {JSXElement} from '@babel/types';+import {stringifyDefaultProps, type EnumPath} from '@remotion/studio-shared';import type {CodemodProject} from './codemod-project';import type {CodemodValue} from './codemod-value';import {type CompositionTarget,requireComposition,} from './composition-editing';+import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';+import {formatSerializedValue} from './format-serialized-value';+import {getJsxNodeProps} from './get-jsx-node-props';import {getNodeEditResult,getUnchangedStructureRemappings,getUpdatedNodeReference,} from './node-references';-import {- getCompositionDefaultPropsLine,- updateDefaultProps,-} from './update-default-props';+import {recastLocToOffset} from './recast-loc-to-offset';+import {parseAst} from './sequence-props/parse-ast';import {updateJsxNodeProps} from './update-jsx-node-props';export type SetCompositionDefaultPropsOptions<Project extends CodemodProject> =@@ -31,25 +33,82 @@ export const setCompositionDefaultProps = <Project extends CodemodProject>({enumPaths,}: SetCompositionDefaultPropsOptions<Project>) => {const node = requireComposition({project, compositionFile, compositionId});- if (enumPaths === undefined) {- return updateJsxNodeProps({project, node, props: {defaultProps}});+ const status = getJsxNodeProps({+ project,+ node,+ keys: ['defaultProps'],+ assetKeys: ['defaultProps'],+ }).props.defaultProps;+ if (status.status === 'computed') {+ throw new Error('Cannot update computed prop "defaultProps"');+ }++ let input = project.files[node.filePath];+ let element = findJsxElementPathForDeletion(parseAst(input), node.nodePath)+ ?.node as JSXElement | undefined;+ const logLine = element?.openingElement.loc?.start.line ?? 1;+ let attribute = element?.openingElement.attributes.find(+ (attr) =>+ attr.type === 'JSXAttribute' &&+ attr.name.type === 'JSXIdentifier' &&+ attr.name.name === 'defaultProps',+ );+ if (!attribute || (attribute.type === 'JSXAttribute' && !attribute.value)) {+ const inserted = updateJsxNodeProps({+ project,+ node,+ props: {defaultProps: {}},+ });+ input = inserted.project.files[node.filePath];+ element = findJsxElementPathForDeletion(+ parseAst(input),+ inserted.updatedNode.nodePath,+ )?.node as JSXElement | undefined;+ attribute = element?.openingElement.attributes.find(+ (attr) =>+ attr.type === 'JSXAttribute' &&+ attr.name.type === 'JSXIdentifier' &&+ attr.name.name === 'defaultProps',+ );+ }++ if (+ attribute?.type !== 'JSXAttribute' ||+ attribute.value?.type !== 'JSXExpressionContainer' ||+ !attribute.value.loc+ ) {+ throw new Error('Could not locate the defaultProps expression');+ }++ const serialized = stringifyDefaultProps({+ props: defaultProps,+ enumPaths: enumPaths ?? [],+ });+ if (serialized === undefined) {+ throw new Error('Could not serialize the updated defaultProps value');}- const input = project.files[node.filePath];- const logLine = getCompositionDefaultPropsLine({input, compositionId});- const {output} = updateDefaultProps({+ const start = recastLocToOffset(input, attribute.value.loc.start);+ const end = recastLocToOffset(input, attribute.value.loc.end);+ const lineStart = input.lastIndexOf('\n', start) + 1;+ const formatted = formatSerializedValue({input,- compositionId,- newDefaultProps: defaultProps,- enumPaths,+ linePrefix: input.slice(lineStart, start + 1),+ previousValue: input.slice(start + 1, end - 1).trim(),+ serialized,});+ const output =+ input.slice(0, start) + '{' + formatted + '}' + input.slice(end);const result = getNodeEditResult({project,edits: [{filePath: node.filePath,output,- nodePathRemappings: getUnchangedStructureRemappings({input, output}),+ nodePathRemappings: getUnchangedStructureRemappings({+ input: project.files[node.filePath],+ output,+ }),},],});diff --git a/packages/studio-server/src/test/add-effect.test.ts b/packages/codemods/src/test/add-effect.test.tssimilarity index 96%rename from packages/studio-server/src/test/add-effect.test.tsrename to packages/codemods/src/test/add-effect.test.tsindex 634c1e734a..f9462f79bc 100644--- a/packages/studio-server/src/test/add-effect.test.ts+++ b/packages/codemods/src/test/add-effect.test.ts@@ -1,8 +1,6 @@import {expect, test} from 'bun:test';-import {CodemodsInternals} from '@remotion/codemods';-import {lineColumnToNodePath} from './test-utils';--const {addEffect} = CodemodsInternals;+import {addEffect} from '../effect-operations';+import {lineColumnToNodePath} from './node-path-test-utils';const buildInput = (jsx: string) => `import {Solid} from 'remotion';diff --git a/packages/codemods/src/test/apply-visual-control.test.ts b/packages/codemods/src/test/apply-visual-control.test.tsindex 310ef62f6e..ddd21fa28d 100644--- a/packages/codemods/src/test/apply-visual-control.test.ts+++ b/packages/codemods/src/test/apply-visual-control.test.ts@@ -1,7 +1,5 @@import {expect, test} from 'bun:test';-import {applyVisualControl} from '../apply-visual-control';-import {parseAndApplyCodemod} from '../parse-and-apply-codemod';-import {parseAst} from '../sequence-props/parse-ast';+import {updateVisualControls} from '../index';test('updates visual controls without changing surrounding source', () => {const input = [@@ -13,73 +11,68 @@ test('updates visual controls without changing surrounding source', () => {"const optional = visualControl('optional')",'',].join('\r\n');- const {changesMade, newContents} = applyVisualControl({- input,- transformation: {- type: 'apply-visual-control',- changes: [- {- id: 'opacity',- newValueSerialized: '0.5',- newValueIsUndefined: false,- enumPaths: [],- },- {- id: 'mode',- newValueSerialized: '"fast"',- newValueIsUndefined: false,- enumPaths: [[]],- },- {- id: 'optional',- newValueSerialized: '',- newValueIsUndefined: true,- enumPaths: [],- },- ],- },+ const {project, updatedControls} = updateVisualControls({+ project: {rootDir: '/', files: {'Root.tsx': input}},+ filePath: 'Root.tsx',+ changes: [+ {+ id: 'opacity',+ newValueSerialized: '0.5',+ newValueIsUndefined: false,+ enumPaths: [],+ },+ {+ id: 'mode',+ newValueSerialized: '"fast"',+ newValueIsUndefined: false,+ enumPaths: [[]],+ },+ {+ id: 'optional',+ newValueSerialized: '',+ newValueIsUndefined: true,+ enumPaths: [],+ },+ ],});- expect(changesMade).toEqual([- {description: 'Applied visual control opacity'},- {description: 'Applied visual control mode'},- {description: 'Applied visual control optional'},+ expect(updatedControls).toEqual([+ {id: 'opacity', line: 4},+ {id: 'mode', line: 5},+ {id: 'optional', line: 6},]);- expect(newContents).toBe(+ expect(project.files['Root.tsx']).toBe(input.replace('OPACITY', '0.5').replace('"slow"', "'fast' as const").replace("'optional')", "'optional', undefined)"),);- expect(() => parseAst(newContents)).not.toThrow();});test('formats object values using the existing source style', () => {const input = `const untouched = {keep:"this spacing"}const settings = visualControl("settings", { old: true })`;- const {newContents} = applyVisualControl({- input,- transformation: {- type: 'apply-visual-control',- changes: [- {- id: 'settings',- newValueSerialized: JSON.stringify({- title: 'Hello',- 'dash-key': true,- }),- newValueIsUndefined: false,- enumPaths: [],- },- ],- },+ const {project} = updateVisualControls({+ project: {rootDir: '/', files: {'Root.tsx': input}},+ filePath: 'Root.tsx',+ changes: [+ {+ id: 'settings',+ newValueSerialized: JSON.stringify({+ title: 'Hello',+ 'dash-key': true,+ }),+ newValueIsUndefined: false,+ enumPaths: [],+ },+ ],});- expect(newContents).toBe(`const untouched = {keep:"this spacing"}+ expect(project.files['Root.tsx'])+ .toBe(`const untouched = {keep:"this spacing"}const settings = visualControl("settings", { title: "Hello", "dash-key": true })`);- expect(() => parseAst(newContents)).not.toThrow();});test('wraps long visual-control values using CRLF and tab indentation', () => {@@ -92,27 +85,25 @@ test('wraps long visual-control values using CRLF and tab indentation', () => {')','',].join('\r\n');- const {newContents} = applyVisualControl({- input,- transformation: {- type: 'apply-visual-control',- changes: [- {- id: 'settings',- newValueSerialized: JSON.stringify({- title:- 'A long visual control title that requires wrapping across multiple lines',- 'dash-key': true,- items: [1, 2, 3],- }),- newValueIsUndefined: false,- enumPaths: [],- },- ],- },+ const {project} = updateVisualControls({+ project: {rootDir: '/', files: {'Root.tsx': input}},+ filePath: 'Root.tsx',+ changes: [+ {+ id: 'settings',+ newValueSerialized: JSON.stringify({+ title:+ 'A long visual control title that requires wrapping across multiple lines',+ 'dash-key': true,+ items: [1, 2, 3],+ }),+ newValueIsUndefined: false,+ enumPaths: [],+ },+ ],});- expect(newContents).toBe(+ expect(project.files['Root.tsx']).toBe(['import {visualControl} from "@remotion/studio"','',@@ -127,70 +118,71 @@ test('wraps long visual-control values using CRLF and tab indentation', () => {'',].join('\r\n'),);- expect(() => parseAst(newContents)).not.toThrow();});test('an outer visual control replacement supersedes nested controls', () => {const input ="const value = visualControl('outer', {nested: visualControl('inner', 1)});\n";- const {changesMade, newContents} = applyVisualControl({- input,- transformation: {- type: 'apply-visual-control',+ const {project, updatedControls} = updateVisualControls({+ project: {rootDir: '/', files: {'Root.tsx': input}},+ filePath: 'Root.tsx',+ changes: [+ {+ id: 'outer',+ newValueSerialized: '2',+ newValueIsUndefined: false,+ enumPaths: [],+ },+ {+ id: 'inner',+ newValueSerialized: '3',+ newValueIsUndefined: false,+ enumPaths: [],+ },+ ],+ });++ expect(updatedControls).toEqual([{id: 'outer', line: 1}]);+ expect(project.files['Root.tsx']).toBe(+ "const value = visualControl('outer', 2);\n",+ );+});++test('rejects dynamic identifiers and leaves unmatched visual controls unchanged', () => {+ const dynamicIdentifier = `const value = visualControl(\`value-\${suffix}\`, 1);\n`;+ expect(() =>+ updateVisualControls({+ project: {rootDir: '/', files: {'Root.tsx': dynamicIdentifier}},+ filePath: 'Root.tsx',changes: [{- id: 'outer',+ id: 'value',newValueSerialized: '2',newValueIsUndefined: false,enumPaths: [],},- {- id: 'inner',- newValueSerialized: '3',- newValueIsUndefined: false,- enumPaths: [],- },],- },- });-- expect(changesMade).toEqual([{description: 'Applied visual control outer'}]);- expect(newContents).toBe("const value = visualControl('outer', 2);\n");-});--test('rejects dynamic and unmatched visual control identifiers', () => {- const dynamicIdentifier = `const value = visualControl(\`value-\${suffix}\`, 1);\n`;- expect(() =>- applyVisualControl({- input: dynamicIdentifier,- transformation: {- type: 'apply-visual-control',- changes: [- {- id: 'value',- newValueSerialized: '2',- newValueIsUndefined: false,- enumPaths: [],- },- ],- },}),).toThrow('the string may not be dynamic');- expect(() =>- parseAndApplyCodemod({- input: "const value = visualControl('other', 1);\n",- codeMod: {- type: 'apply-visual-control',- changes: [- {- id: 'value',- newValueSerialized: '2',- newValueIsUndefined: false,- enumPaths: [],- },- ],+ const unchanged = updateVisualControls({+ project: {+ rootDir: '/',+ files: {'Root.tsx': "const value = visualControl('other', 1);\n"},+ },+ filePath: 'Root.tsx',+ changes: [+ {+ id: 'value',+ newValueSerialized: '2',+ newValueIsUndefined: false,+ enumPaths: [],},- }),- ).toThrow('Unable to calculate the changes');+ ],+ });+ expect(unchanged.changes).toEqual([]);+ expect(unchanged.updatedControls).toEqual([]);+ expect(unchanged.project.files['Root.tsx']).toBe(+ "const value = visualControl('other', 1);\n",+ );});diff --git a/packages/codemods/src/test/composition-source-edits.test.ts b/packages/codemods/src/test/composition-source-edits.test.tsindex 3249b921e2..eecef94a92 100644--- a/packages/codemods/src/test/composition-source-edits.test.ts+++ b/packages/codemods/src/test/composition-source-edits.test.ts@@ -1,6 +1,13 @@import {expect, test} from 'bun:test';-import {parseAndApplyCodemod} from '../parse-and-apply-codemod';-import {parseAst} from '../sequence-props/parse-ast';+import {+ addComposition,+ deleteComposition,+ duplicateComposition,+ renameComposition,+ updateCompositionMetadata,+} from '../index';++const compositionFile = 'Root.tsx';for (const [indent, eol] of [['\t', '\n'],@@ -28,42 +35,37 @@ for (const [indent, eol] of ['</>;','',].join(eol);- const renamed = parseAndApplyCodemod({- input,- codeMod: {- type: 'rename-composition',- idToRename: 'Original',- newId: 'Renamed',- },- }).newContents;- expect(renamed).toBe(input.replace('id="Original"', 'id="Renamed"'));- const duplicated = parseAndApplyCodemod({- input: renamed,- codeMod: {- type: 'duplicate-composition',- idToDuplicate: 'Renamed',- newId: 'Copy',- tag: 'Composition',- newFps: null,- newHeight: null,- newWidth: null,- newDurationInFrames: null,- },- }).newContents;- expect(duplicated).toBe(- renamed.replace(+ const renamed = renameComposition({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ compositionId: 'Original',+ newId: 'Renamed',+ });+ expect(renamed.project.files[compositionFile]).toBe(+ input.replace('id="Original"', 'id="Renamed"'),+ );+ const duplicated = duplicateComposition({+ project: renamed.project,+ compositionFile,+ compositionId: 'Renamed',+ newId: 'Copy',+ });+ expect(duplicated.project.files[compositionFile]).toBe(+ renamed.project.files[compositionFile].replace(composition.replace('Original', 'Renamed'),composition.replace('Original', 'Renamed') +eol +composition.replace('Original', 'Copy'),),);- const deleted = parseAndApplyCodemod({- input: duplicated,- codeMod: {type: 'delete-composition', idToDelete: 'Copy'},- }).newContents;- expect(deleted).toBe(renamed);- parseAst(duplicated);+ const deleted = deleteComposition({+ project: duplicated.project,+ compositionFile,+ compositionId: 'Copy',+ });+ expect(deleted.project.files[compositionFile]).toBe(+ renamed.project.files[compositionFile],+ );});}@@ -87,29 +89,21 @@ test('new compositions append to fragments and folders and wrap standalone roots],] as const) {const input = `import {Composition, Folder} from 'remotion';\nexport const Root = () => (${root});\n`;- const output = parseAndApplyCodemod({- input,- codeMod: {- type: 'new-composition',- componentName: 'Fresh',- componentImportPath: './Fresh',- newId: 'Fresh',- newWidth: 1920,- newHeight: 1080,- newDurationInFrames: 90,- newFps: 30,- folderName,- parentName: null,- canvasCapture: null,- },- }).newContents;+ const result = addComposition({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ compositionId: 'Fresh',+ component: {importName: 'Fresh', importPath: './Fresh'},+ metadata: {width: 1920, height: 1080, durationInFrames: 90, fps: 30},+ folder:+ folderName === null ? undefined : {name: folderName, parentName: null},+ });const inserted ='<Composition\n id="Fresh"\n component={Fresh}\n durationInFrames={90}\n fps={30}\n width={1920}\n height={1080}\n />';- expect(output).toBe(+ expect(result.project.files[compositionFile]).toBe("import {Fresh} from './Fresh';\n" +input.replace(root, expected.replace('INSERT', inserted)),);- parseAst(output);}});@@ -122,19 +116,15 @@ export const Root = () => (</Composition>);`;- const output = parseAndApplyCodemod({- input,- codeMod: {- type: 'duplicate-composition',- idToDuplicate: 'Original',- newId: 'Poster',- tag: 'Still',- newFps: null,- newDurationInFrames: null,- newWidth: 500,- newHeight: 400,- },- }).newContents;+ const result = duplicateComposition({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ compositionId: 'Original',+ newId: 'Poster',+ tag: 'Still',+ metadata: {width: 500, height: 400},+ });+ const output = result.project.files[compositionFile];expect(output).toContain("import {Composition, Still} from 'remotion';");expect(output).toContain(' <Still id="Poster" width={500} height={400}>\n {/* keep the child */}\n <Child />\n </Still>',@@ -142,10 +132,10 @@ export const Root = () => (expect(output).toContain(' <Composition id="Original" fps={30} durationInFrames={90}>',);- parseAst(output);});test('rename preserves expression quotes and delete replaces standalone and conditional JSX with null', () => {+ const imports = "import {Composition, Still} from 'remotion';\n";for (const original of ['<Composition id={"Original"} />',"<Still id={'Original'} />",@@ -155,71 +145,56 @@ test('rename preserves expression quotes and delete replaces standalone and cond`(${original})`,`enabled ? ${original} : null`,]) {- const input = `export const Root = () => ${expression};\n`;- const renamed = parseAndApplyCodemod({- input,- codeMod: {- type: 'rename-composition',- idToRename: 'Original',- newId: 'Renamed',- },- }).newContents;- expect(renamed).toBe(input.replace('Original', 'Renamed'));- const deleted = parseAndApplyCodemod({- input: renamed,- codeMod: {type: 'delete-composition', idToDelete: 'Renamed'},- }).newContents;- expect(deleted).toBe(- expression.startsWith('enabled')- ? 'export const Root = () => enabled ? null : null;\n'- : 'export const Root = () => null;\n',+ const input = `${imports}export const Root = () => ${expression};\n`;+ const renamed = renameComposition({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ compositionId: 'Original',+ newId: 'Renamed',+ });+ expect(renamed.project.files[compositionFile]).toBe(+ input.replace('Original', 'Renamed'),+ );+ const deleted = deleteComposition({+ project: renamed.project,+ compositionFile,+ compositionId: 'Renamed',+ });+ expect(deleted.project.files[compositionFile]).toBe(+ imports ++ (expression.startsWith('enabled')+ ? 'export const Root = () => enabled ? null : null;\n'+ : 'export const Root = () => null;\n'),);}}});-test('updates existing composition metadata without changing surrounding source', () => {+test('updates computed and shorthand metadata while adding missing values without changing surrounding source', () => {const input = ['import { Composition } from "remotion"','','const preserve = { value : "keep" }','export const Root = () => (',- ' <Composition',- ' id={"Original"}',- ' durationInFrames = { DURATION }',- ' fps={FPS}',- ' width',- ' height="720"',- ' />',+ ' <Composition id={"Original"} width = { WIDTH } height>',+ ' {/* keep child */}',+ ' <Child />',+ ' </Composition>',')','',].join('\r\n');- const {changesMade, newContents} = parseAndApplyCodemod({- input,- codeMod: {- type: 'update-composition-metadata',- idToUpdate: 'Original',- newDurationInFrames: 240,- newFps: 60,- newWidth: 1920,- newHeight: 1080,- },+ const result = updateCompositionMetadata({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ compositionId: 'Original',+ metadata: {durationInFrames: 240, fps: 60, width: 1920, height: 1080},});-- expect(changesMade).toEqual([- {description: 'Replaced durationInFrames'},- {description: 'Replaced FPS'},- {description: 'Replaced width'},- {description: 'Replaced height'},- ]);- expect(newContents).toBe(- input- .replace('{ DURATION }', '{240}')- .replace('{FPS}', '{60}')- .replace(' width\r\n', ' width={1920}\r\n')- .replace('height="720"', 'height={1080}'),+ expect(result.project.files[compositionFile]).toBe(+ input.replace(+ '{ WIDTH } height>',+ '{1920} height={1080} fps={60} durationInFrames={240}>',+ ),);- expect(() => parseAst(newContents)).not.toThrow();});test('adds missing composition metadata using multiline source style', () => {@@ -229,6 +204,7 @@ test('adds missing composition metadata using multiline source style', () => {[' ', '\r\n'],]) {const input = [+ "import {Composition} from 'remotion';",'export const Root = () => (',`${indent}<Composition`,`${indent}${indent}id="Original"`,@@ -236,25 +212,13 @@ test('adds missing composition metadata using multiline source style', () => {')','',].join(eol);- const {changesMade, newContents} = parseAndApplyCodemod({- input,- codeMod: {- type: 'update-composition-metadata',- idToUpdate: 'Original',- newDurationInFrames: 90,- newFps: 30,- newWidth: 1920,- newHeight: 1080,- },+ const result = updateCompositionMetadata({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ compositionId: 'Original',+ metadata: {durationInFrames: 90, fps: 30, width: 1920, height: 1080},});-- expect(changesMade).toEqual([- {description: 'Added FPS'},- {description: 'Added durationInFrames'},- {description: 'Added width'},- {description: 'Added height'},- ]);- expect(newContents).toBe(+ expect(result.project.files[compositionFile]).toBe(input.replace(`${indent}/>`,[@@ -266,32 +230,56 @@ test('adds missing composition metadata using multiline source style', () => {].join(eol),),);- expect(() => parseAst(newContents)).not.toThrow();}});-test('adds missing composition metadata without reformatting an inline tag', () => {- const input = `const preserve = { value : "keep" };+test('updates an inline Still without adding timing props or reformatting its tag', () => {+ const input = `import {Still} from 'remotion';+const preserve = { value : "keep" };export const Root=()=> <Still id={'Original'} height = "720"/>;`;- const {changesMade, newContents} = parseAndApplyCodemod({- input,- codeMod: {- type: 'update-composition-metadata',- idToUpdate: 'Original',- newDurationInFrames: null,- newFps: null,- newWidth: 1920,- newHeight: 1080,- },+ const result = updateCompositionMetadata({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ compositionId: 'Original',+ metadata: {width: 1920, height: 1080},});+ expect(result.project.files[compositionFile]).toBe(+ input.replace('height = "720"', 'height = {1080} width={1920}'),+ );+});- expect(changesMade).toEqual([- {description: 'Replaced height'},- {description: 'Added width'},- ]);- expect(newContents).toBe(`const preserve = { value : "keep" };-export const Root=()=> <Still id={'Original'} height = {1080} width={1920}/>;-`);- expect(() => parseAst(newContents)).not.toThrow();+test('composition edits resolve named aliases and namespace imports without changing the original registration', () => {+ for (const [imports, originalTag, expectedTag] of [+ [+ "import {Composition as Comp, Still as Poster} from 'remotion';",+ 'Comp',+ 'Poster',+ ],+ ["import * as R from 'remotion';", 'R.Composition', 'Still'],+ ]) {+ const original = `<${originalTag} id="Original" fps={30} durationInFrames={90}><Child /></${originalTag}>`;+ const input = `${imports}\nexport const Root = () => ${original};\n`;+ const copy = duplicateComposition({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ compositionId: 'Original',+ newId: 'Poster',+ tag: 'Still',+ metadata: {width: 500, height: 400},+ });+ const renamed = renameComposition({+ project: copy.project,+ compositionFile,+ compositionId: 'Poster',+ newId: 'Renamed',+ });+ expect(renamed.project.files[compositionFile]).toContain(original);+ expect(renamed.project.files[compositionFile]).toContain(+ `<${expectedTag} id="Renamed" width={500} height={400}>`,+ );+ expect(renamed.project.files[compositionFile]).toContain(+ `</${expectedTag}>`,+ );+ }});diff --git a/packages/codemods/src/test/default-props.test.ts b/packages/codemods/src/test/default-props.test.tsindex 1ac2d0cd10..eef96380c0 100644--- a/packages/codemods/src/test/default-props.test.ts+++ b/packages/codemods/src/test/default-props.test.ts@@ -1,7 +1,5 @@import {expect, test} from 'bun:test';-import {CodemodsInternals} from '..';--const {computeCanUpdateDefaultPropsFromContent} = CodemodsInternals;+import {computeCanUpdateDefaultPropsFromContent} from '../internals';test('extracts editable default props including special values', () => {const source = `import {Composition, staticFile} from 'remotion';diff --git a/packages/studio-server/src/test/delete-effect.test.ts b/packages/codemods/src/test/delete-effect.test.tssimilarity index 95%rename from packages/studio-server/src/test/delete-effect.test.tsrename to packages/codemods/src/test/delete-effect.test.tsindex c5e0e04bb4..a83c86491c 100644--- a/packages/studio-server/src/test/delete-effect.test.ts+++ b/packages/codemods/src/test/delete-effect.test.ts@@ -1,8 +1,6 @@import {expect, test} from 'bun:test';-import {CodemodsInternals} from '@remotion/codemods';-import {lineColumnToNodePath} from './test-utils';--const {deleteEffect, deleteEffects} = CodemodsInternals;+import {deleteEffect, deleteEffects} from '../effect-operations';+import {lineColumnToNodePath} from './node-path-test-utils';const buildInput = (effects: string,diff --git a/packages/codemods/src/test/delete-jsx-nodes.test.ts b/packages/codemods/src/test/delete-jsx-nodes.test.tsnew file mode 100644index 0000000000..3e0b8d63ec--- /dev/null+++ b/packages/codemods/src/test/delete-jsx-nodes.test.ts@@ -0,0 +1,290 @@+import {expect, test} from 'bun:test';+import {deleteJsxNodes} from '../delete-jsx-nodes-internal';+import {+ lineColumnToNodePath,+ lineContainingToNodePath,+} from './node-path-test-utils';++const sample = `import React from 'react';+import {AbsoluteFill} from 'remotion';++export const X: React.FC = () => {+ return (+ <AbsoluteFill>+ <div />+ </AbsoluteFill>+ );+};+`;++test('deleteJsxNodes removes a JSX child from a parent element', async () => {+ const {output} = await deleteJsxNodes({+ input: sample,+ nodePaths: [lineColumnToNodePath(sample, 7)],+ });++ expect(output).not.toContain('<div');+ expect(output).toContain('<AbsoluteFill>');+});++const onlyReturn = `import React from 'react';++export const X: React.FC = () => {+ return <div />;+};+`;++test('deleteJsxNodes replaces sole return JSX with null', async () => {+ const {output} = await deleteJsxNodes({+ input: onlyReturn,+ nodePaths: [lineColumnToNodePath(onlyReturn, 4)],+ });++ expect(output).toContain('return null');+ expect(output).not.toContain('<div');+});++const conditional = `import React from 'react';++export const X: React.FC<{show: boolean}> = ({show}) => {+ return <>{show && <div />}</>;+};+`;++test('deleteJsxNodes turns conditional JSX into null', async () => {+ const {output} = await deleteJsxNodes({+ input: conditional,+ nodePaths: [lineColumnToNodePath(conditional, 4)],+ });++ expect(output).toContain('&& null');+ expect(output).not.toContain('<div');+});++const ternary = `import React from 'react';++export const X: React.FC<{show: boolean}> = ({show}) => {+ return <>{show ? <div /> : null}</>;+};+`;++test('deleteJsxNodes replaces JSX in ternary consequent with null', async () => {+ const {output} = await deleteJsxNodes({+ input: ternary,+ nodePaths: [lineColumnToNodePath(ternary, 4)],+ });++ expect(output).toMatch(/\?\s*null/);+ expect(output).not.toContain('<div');+});++const mapCase = `import React from 'react';++export const X: React.FC = () => {+ return (+ <>+ {[1].map((i) => (+ <div key={i} />+ ))}+ </>+ );+};+`;++test('deleteJsxNodes replaces JSX inside map callback', async () => {+ const {output} = await deleteJsxNodes({+ input: mapCase,+ nodePaths: [lineColumnToNodePath(mapCase, 7)],+ });++ expect(output).not.toContain('<div');+ expect(output).toMatch(/=>\s*\(?\s*null/);+});++const multipleSiblings = `import React from 'react';+import {AbsoluteFill} from 'remotion';++export const X: React.FC = () => {+ return (+ <AbsoluteFill>+ <div />+ <span />+ <p />+ </AbsoluteFill>+ );+};+`;++test('deleteJsxNodes removes multiple JSX children in one transform', async () => {+ const {output, nodeLabels, logLines} = await deleteJsxNodes({+ input: multipleSiblings,+ nodePaths: [+ lineColumnToNodePath(multipleSiblings, 7),+ lineColumnToNodePath(multipleSiblings, 8),+ ],+ });++ expect(output).not.toContain('<div');+ expect(output).not.toContain('<span');+ expect(output).toContain('<p');+ expect(nodeLabels).toEqual(['<div>', '<span>']);+ expect(logLines).toEqual([7, 8]);+});++test('deleteJsxNodes preserves source formatting and removes standalone JSX lines', async () => {+ const cases = [+ {+ input: `export const Comp = () => {+ return (+ <div>+ <Keep />+ <RemoveOne />+ <RemoveTwo />+ <Keep />+ </div>+ );+};+`,+ markers: ['<RemoveOne', '<RemoveTwo'],+ expected: `export const Comp = () => {+ return (+ <div>+ <Keep />+ <Keep />+ </div>+ );+};+`,+ },+ {+ input: `export const Comp = () => {+ return (+ <div>+ <Remove />+ </div>+ )+}+`,+ markers: ['<Remove'],+ expected: `export const Comp = () => {+ return (+ <div>+ </div>+ )+}+`,+ },+ {+ input: `export const Comp = () => {+ return [1].map((item) => (+ <Remove key={item} />+ ));+};+`,+ markers: ['<Remove'],+ expected: `export const Comp = () => {+ return [1].map((item) => null);+};+`,+ },+ {+ input: `const AnimatedBar = () => {+ return (+ <Remove />+ );+};+`,+ markers: ['<Remove'],+ expected: `const AnimatedBar = () => {+ return null;+};+`,+ },+ {+ input: `const AnimatedBar = () => {+ return (+ // Keep this explanation.+ <Remove />+ );+};+`,+ markers: ['<Remove'],+ expected: `const AnimatedBar = () => {+ return (+ // Keep this explanation.+ null+ );+};+`,+ },+ {+ input: `export const Comp = () => <div><Keep /><Remove /><Keep /></div>;+`,+ markers: ['<Remove'],+ expected: `export const Comp = () => <div><Keep /><Keep /></div>;+`,+ },+ {+ input:+ 'export const Comp = () => <div><Keep />\t<Remove /><Keep /></div>;\n',+ markers: ['<Remove'],+ expected: 'export const Comp = () => <div><Keep />\t<Keep /></div>;\n',+ },+ {+ input: `export const Comp = () => (+ <div>+ <Remove /> {/* keep this comment */}+ </div>+);+`,+ markers: ['<Remove'],+ expected: `export const Comp = () => (+ <div>+ {/* keep this comment */}+ </div>+);+`,+ },+ {+ input: `export const Comp = () => {+ return (+ <div>+ <RemoveParent>+ <RemoveChild />+ </RemoveParent>+ <Keep />+ </div>+ );+};+`,+ markers: ['<RemoveParent', '<RemoveChild'],+ expected: `export const Comp = () => {+ return (+ <div>+ <Keep />+ </div>+ );+};+`,+ },+ {+ input:+ 'export const Comp = () => {\r\n\treturn (\r\n\t\t<div>\r\n\t\t\t<Remove />\r\n\t\t</div>\r\n\t);\r\n};\r\n',+ markers: ['<Remove'],+ expected:+ 'export const Comp = () => {\r\n\treturn (\r\n\t\t<div>\r\n\t\t</div>\r\n\t);\r\n};\r\n',+ },+ ] as const;++ for (const item of cases) {+ const {output, formatted} = await deleteJsxNodes({+ input: item.input,+ nodePaths: item.markers.map((marker) =>+ lineContainingToNodePath(item.input, marker),+ ),+ });++ expect(output).toBe(item.expected);+ expect(formatted).toBe(true);+ }+});diff --git a/packages/studio-server/src/test/duplicate-effect.test.ts b/packages/codemods/src/test/duplicate-effect.test.tssimilarity index 94%rename from packages/studio-server/src/test/duplicate-effect.test.tsrename to packages/codemods/src/test/duplicate-effect.test.tsindex 096c30681e..08dc5076dd 100644--- a/packages/studio-server/src/test/duplicate-effect.test.ts+++ b/packages/codemods/src/test/duplicate-effect.test.ts@@ -1,8 +1,6 @@import {expect, test} from 'bun:test';-import {CodemodsInternals} from '@remotion/codemods';-import {lineColumnToNodePath} from './test-utils';--const {duplicateEffect, duplicateEffects} = CodemodsInternals;+import {duplicateEffect, duplicateEffects} from '../effect-operations';+import {lineColumnToNodePath} from './node-path-test-utils';const buildInput = (effects: string,diff --git a/packages/studio-server/src/test/duplicate-jsx-node.test.ts b/packages/codemods/src/test/duplicate-jsx-node.test.tssimilarity index 96%rename from packages/studio-server/src/test/duplicate-jsx-node.test.tsrename to packages/codemods/src/test/duplicate-jsx-node.test.tsindex 33c817d5da..5457d96fb6 100644--- a/packages/studio-server/src/test/duplicate-jsx-node.test.ts+++ b/packages/codemods/src/test/duplicate-jsx-node.test.ts@@ -1,8 +1,9 @@import {expect, test} from 'bun:test';-import {CodemodsInternals} from '@remotion/codemods';-import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';--const {duplicateJsxNodes} = CodemodsInternals;+import {duplicateJsxNodes} from '../duplicate-jsx-node';+import {+ lineColumnToNodePath,+ lineContainingToNodePath,+} from './node-path-test-utils';const sample = `import React from 'react';import {AbsoluteFill} from 'remotion';diff --git a/packages/studio-server/src/test/fixtures/canvas-capture-composition.txt b/packages/codemods/src/test/fixtures/canvas-capture-composition.txtsimilarity index 100%rename from packages/studio-server/src/test/fixtures/canvas-capture-composition.txtrename to packages/codemods/src/test/fixtures/canvas-capture-composition.txtdiff --git a/packages/studio-server/src/test/fixtures/canvas-capture-metadata.json b/packages/codemods/src/test/fixtures/canvas-capture-metadata.jsonsimilarity index 100%rename from packages/studio-server/src/test/fixtures/canvas-capture-metadata.jsonrename to packages/codemods/src/test/fixtures/canvas-capture-metadata.jsondiff --git a/packages/studio-server/src/test/snapshots/fixed.tsx b/packages/codemods/src/test/fixtures/fixed.tsx.txtsimilarity index 100%rename from packages/studio-server/src/test/snapshots/fixed.tsxrename to packages/codemods/src/test/fixtures/fixed.tsx.txtdiff --git a/packages/studio-server/src/test/snapshots/problematic.tsx b/packages/codemods/src/test/fixtures/problematic.tsx.txtsimilarity index 100%rename from packages/studio-server/src/test/snapshots/problematic.tsxrename to packages/codemods/src/test/fixtures/problematic.tsx.txtdiff --git a/packages/studio-server/src/test/snapshots/root-after.tsx b/packages/codemods/src/test/fixtures/root-after.tsx.txtsimilarity index 100%rename from packages/studio-server/src/test/snapshots/root-after.tsxrename to packages/codemods/src/test/fixtures/root-after.tsx.txtdiff --git a/packages/studio-server/src/test/snapshots/root-before.tsx b/packages/codemods/src/test/fixtures/root-before.tsx.txtsimilarity index 100%rename from packages/studio-server/src/test/snapshots/root-before.tsxrename to packages/codemods/src/test/fixtures/root-before.tsx.txtdiff --git a/packages/codemods/src/test/folder-source-edits.test.ts b/packages/codemods/src/test/folder-source-edits.test.tsindex 2fa3bed134..035a60886e 100644--- a/packages/codemods/src/test/folder-source-edits.test.ts+++ b/packages/codemods/src/test/folder-source-edits.test.ts@@ -1,6 +1,13 @@import {expect, test} from 'bun:test';-import {parseAndApplyCodemod} from '../parse-and-apply-codemod';-import {parseAst} from '../sequence-props/parse-ast';+import {+ addFolder,+ moveComposition,+ moveFolder,+ renameFolder,+ unwrapFolder,+} from '../index';++const compositionFile = 'Root.tsx';const untouched = 'const untouched = { value : "keep" }; // preserve';@@ -14,18 +21,14 @@ export const Root = () => (</Folder>);`;- const output = parseAndApplyCodemod({- input,- codeMod: {- type: 'rename-folder',- folderName: 'Old name',- parentName: null,- newName: 'New name',- },- }).newContents;+ const output = renameFolder({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ folder: {name: 'Old name', parentName: null},+ newName: 'New name',+ }).project.files[compositionFile];expect(output).toBe(input.replace("'Old name'", "'New name'"));- parseAst(output);});test('creates top-level and nested folders without formatting the file', () => {@@ -41,14 +44,11 @@ test('creates top-level and nested folders without formatting the file', () => {')','',].join('\r\n');- const topLevel = parseAndApplyCodemod({- input,- codeMod: {- type: 'new-folder',- folderName: 'Top level',- parentName: null,- },- }).newContents;+ const topLevel = addFolder({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ folder: {name: 'Top level', parentName: null},+ }).project.files[compositionFile];expect(topLevel).toBe(input.replace(@@ -61,14 +61,11 @@ test('creates top-level and nested folders without formatting the file', () => {),);- const nested = parseAndApplyCodemod({- input: topLevel,- codeMod: {- type: 'new-folder',- folderName: 'Nested',- parentName: 'Existing',- },- }).newContents;+ const nested = addFolder({+ project: {rootDir: '/', files: {[compositionFile]: topLevel}},+ compositionFile,+ folder: {name: 'Nested', parentName: 'Existing'},+ }).project.files[compositionFile];expect(nested).toBe(topLevel.replace(' <Folder name="Existing" />',@@ -79,7 +76,6 @@ test('creates top-level and nested folders without formatting the file', () => {].join('\r\n'),),);- parseAst(nested);});test('deletes a folder by unwrapping its source without formatting it', () => {@@ -98,14 +94,11 @@ export const Root = () => (</>);`;- const output = parseAndApplyCodemod({- input,- codeMod: {- type: 'delete-folder',- folderName: 'Remove',- parentName: null,- },- }).newContents;+ const output = unwrapFolder({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ folder: {name: 'Remove', parentName: null},+ }).project.files[compositionFile];expect(output).toBe(input.replace(@@ -123,7 +116,6 @@ export const Root = () => (`,),);- parseAst(output);});test('moves a composition into a folder without formatting either node', () => {@@ -144,15 +136,12 @@ export const Root = () => {);};`;- const output = parseAndApplyCodemod({- input,- codeMod: {- type: 'move-composition-to-folder',- idToMove: 'Move',- folderName: 'Target',- parentName: null,- },- }).newContents;+ const output = moveComposition({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ compositionId: 'Move',+ destination: {type: 'folder', folder: {name: 'Target', parentName: null}},+ }).project.files[compositionFile];expect(output).toBe(input@@ -173,7 +162,6 @@ export const Root = () => {</Folder>`,),);- parseAst(output);});test('moves a folder next to another item without formatting it', () => {@@ -192,17 +180,15 @@ export const Root = () => {);};`;- const output = parseAndApplyCodemod({- input,- codeMod: {- type: 'move-composition-or-folder',- source: {type: 'folder', folderName: 'Move', parentName: null},- destination: {- type: 'after',- target: {type: 'folder', folderName: 'Target', parentName: null},- },+ const output = moveFolder({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ folder: {name: 'Move', parentName: null},+ destination: {+ type: 'after',+ target: {type: 'folder', name: 'Target', parentName: null},},- }).newContents;+ }).project.files[compositionFile];expect(output).toBe(input@@ -221,5 +207,59 @@ export const Root = () => {</Folder>`,),);- parseAst(output);+});++test('folder moves reject self, descendants, attribute targets, and standalone sources atomically', () => {+ const input = `import {Composition, Folder} from 'remotion';+export const Root = () => <>+ <Folder name="Parent"><Folder name="Child" /></Folder>+ <Wrapper content={<Folder name="Attribute" />} />+ <Composition id="Move" />+</>;+export const Standalone = () => <Composition id="Standalone" />;+`;+ const project = {rootDir: '/', files: {[compositionFile]: input}};+ for (const folder of [+ {name: 'Parent', parentName: null},+ {name: 'Child', parentName: 'Parent'},+ ]) {+ expect(() =>+ moveFolder({+ project,+ compositionFile,+ folder: {name: 'Parent', parentName: null},+ destination: {type: 'folder', folder},+ }),+ ).toThrow('inside itself');+ }++ expect(() =>+ moveComposition({+ project,+ compositionFile,+ compositionId: 'Move',+ destination: {+ type: 'folder',+ folder: {name: 'Attribute', parentName: null},+ },+ }),+ ).toThrow('direct JSX child');+ expect(() =>+ moveComposition({+ project,+ compositionFile,+ compositionId: 'Standalone',+ destination: {type: 'folder', folder: {name: 'Parent', parentName: null}},+ }),+ ).toThrow('direct JSX child');+ const moved = moveComposition({+ project,+ compositionFile,+ compositionId: 'Move',+ destination: {type: 'folder', folder: {name: 'Parent', parentName: null}},+ });+ expect(moved.project.files[compositionFile]).toContain(+ '<Folder name="Child" />\n <Composition id="Move" />\n </Folder>',+ );+ expect(project.files[compositionFile]).toBe(input);});diff --git a/packages/codemods/src/test/generate-canvas-capture-composition.test.ts b/packages/codemods/src/test/generate-canvas-capture-composition.test.tsnew file mode 100644index 0000000000..67ba41a512--- /dev/null+++ b/packages/codemods/src/test/generate-canvas-capture-composition.test.ts@@ -0,0 +1,95 @@+import {expect, test} from 'bun:test';+import {readFileSync} from 'node:fs';+import path from 'node:path';+import {+ CANVAS_CAPTURE_METADATA_TAG,+ parseCanvasCaptureData,+} from '@remotion/studio-shared';+import {addCanvasCaptureComposition, type CodemodProject} from '../index';++test('creates and registers an interactive Canvas Capture composition', () => {+ const fixtureDirectory = path.join(__dirname, 'fixtures');+ const metadata = readFileSync(+ path.join(fixtureDirectory, 'canvas-capture-metadata.json'),+ 'utf-8',+ );+ const data = parseCanvasCaptureData({+ raw: {[CANVAS_CAPTURE_METADATA_TAG]: metadata},+ });+ if (data === null) {+ throw new Error('Could not parse the Canvas Capture metadata fixture');+ }++ const compositionFile = 'src/Root.tsx';+ const componentFile = 'src/CanvasCaptureComposition.tsx';+ const root =+ 'import {Folder} from \'remotion\';\nexport const Root = () => <Folder name="Captures" />;\n';+ const project: CodemodProject = {+ rootDir: '/',+ files: {[compositionFile]: root},+ };+ const options = {+ project,+ compositionFile,+ compositionId: 'canvas-capture-promo',+ component: {+ filePath: componentFile,+ importName: 'CanvasCaptureComposition',+ importPath: './CanvasCaptureComposition',+ },+ metadata: {durationInFrames: 500, fps: 60, height: 1080, width: 1920},+ folder: {name: 'Captures', parentName: null},+ capture: {+ data,+ keyframeFps: 30,+ videoFileName: 'remotion-capture-editor-starter.mp4',+ videoHeight: 1386,+ videoWidth: 3026,+ },+ };+ const result = addCanvasCaptureComposition(options);+ const expected = readFileSync(+ path.join(fixtureDirectory, 'canvas-capture-composition.txt'),+ 'utf-8',+ )+ .replaceAll('\r\n', '\n')+ .replaceAll('\r', '\n');++ expect(result.project.files[componentFile]).toBe(expected);+ expect(result.project.files[compositionFile]).toContain(+ "import {CanvasCaptureComposition} from './CanvasCaptureComposition';",+ );+ expect(result.project.files[compositionFile]).toMatch(+ /<Folder name="Captures">\s*<CanvasCaptureComposition \/>\s*<\/Folder>/,+ );+ expect(result.changes.map((change) => change.filePath)).toEqual([+ compositionFile,+ componentFile,+ ]);+ expect(project.files).toEqual({[compositionFile]: root});++ for (const [existingPath, requestedPath] of [+ [componentFile, componentFile],+ [componentFile, `/project/${componentFile}`],+ [componentFile, `./${componentFile}`],+ [componentFile, `src/../${componentFile}`],+ [`/project/${componentFile}`, componentFile],+ ]) {+ const existingSource = 'export const Existing = () => null;';+ const existingProject = {+ rootDir: '/project',+ files: {[compositionFile]: root, [existingPath]: existingSource},+ };+ expect(() =>+ addCanvasCaptureComposition({+ ...options,+ project: existingProject,+ component: {...options.component, filePath: requestedPath},+ }),+ ).toThrow('already exists');+ expect(existingProject.files).toEqual({+ [compositionFile]: root,+ [existingPath]: existingSource,+ });+ }+});diff --git a/packages/codemods/src/test/get-jsx-elements-with-node-paths.test.ts b/packages/codemods/src/test/get-jsx-nodes.test.tssimilarity index 56%rename from packages/codemods/src/test/get-jsx-elements-with-node-paths.test.tsrename to packages/codemods/src/test/get-jsx-nodes.test.tsindex df3a5f8144..63edb1cac3 100644--- a/packages/codemods/src/test/get-jsx-elements-with-node-paths.test.ts+++ b/packages/codemods/src/test/get-jsx-nodes.test.ts@@ -1,14 +1,20 @@import {expect, test} from 'bun:test';-import {getJsxElementsWithNodePaths} from '../get-jsx-elements-with-node-paths';+import {getJsxNodes} from '../index';-test('lists JSX elements with their deletion paths in source order', () => {- const elements = getJsxElementsWithNodePaths({- source: `export const Video = () => (+test('lists JSX nodes with their deletion paths in source order', () => {+ const elements = getJsxNodes({+ filePath: 'Video.tsx',+ project: {+ rootDir: '/',+ files: {+ 'Video.tsx': `export const Video = () => (<AbsoluteFill><Sequence name="Intro" /><Series.Sequence durationInFrames={30} /></AbsoluteFill>);`,+ },+ },});expect(elements.map(({tagName}) => tagName)).toEqual([diff --git a/packages/codemods/src/test/insert-solid.test.ts b/packages/codemods/src/test/insert-solid.test.tsindex 1b45307648..21dccc57ed 100644--- a/packages/codemods/src/test/insert-solid.test.ts+++ b/packages/codemods/src/test/insert-solid.test.ts@@ -1,10 +1,6 @@import {expect, test} from 'bun:test';-import {CodemodsInternals} from '..';--const {- insertJsxElementIntoProjectWithNodePathRemappings,- insertSolidIntoSource,-} = CodemodsInternals;+import {insertJsxElementIntoProjectWithNodePathRemappings} from '../insert-jsx-element';+import {insertSolidIntoSource} from '../internals';test('inserts a Solid into a component source file', () => {const result = insertSolidIntoSource({diff --git a/packages/codemods/src/test/node-path-test-utils.ts b/packages/codemods/src/test/node-path-test-utils.tsnew file mode 100644index 0000000000..6809ba3544--- /dev/null+++ b/packages/codemods/src/test/node-path-test-utils.ts@@ -0,0 +1,44 @@+import type {SequenceNodePath} from 'remotion';+import {getJsxNodes} from '../get-jsx-nodes';+import {lineColumnToNodePath as _lineColumnToNodePath} from '../sequence-props';+import {parseAst} from '../sequence-props/parse-ast';++export const lineColumnToNodePath = (+ input: string,+ line: number,+): SequenceNodePath => {+ const ast = parseAst(input);+ const result = _lineColumnToNodePath(ast, line);+ if (!result) {+ throw new Error(`No JSX element found at line ${line}`);+ }++ return result;+};++export const lineContainingToNodePath = (+ input: string,+ search: string,+): SequenceNodePath => {+ const sourceLines = input.split('\n');+ const line = sourceLines.findIndex((sourceLine) =>+ sourceLine.includes(search),+ );+ if (line === -1) {+ throw new Error(`Could not find ${JSON.stringify(search)} in source`);+ }++ const column = sourceLines[line].indexOf(search);+ const result = getJsxNodes({+ project: {rootDir: '/', files: {'/test.tsx': input}},+ filePath: '/test.tsx',+ }).findLast(+ (node) =>+ node.location?.line === line + 1 && node.location.column <= column,+ )?.nodePath;+ if (!result) {+ throw new Error(`No JSX element found for ${JSON.stringify(search)}`);+ }++ return result;+};diff --git a/packages/codemods/src/test/public-editing.test.ts b/packages/codemods/src/test/public-editing.test.tsindex bab99441de..e6a7d6b65e 100644--- a/packages/codemods/src/test/public-editing.test.ts+++ b/packages/codemods/src/test/public-editing.test.ts@@ -30,6 +30,7 @@ import {updateEffectProps,updateJsxNodeKeyframes,updateJsxNodeProps,+ updateMultipleJsxNodeProps,type CodemodProject,} from '../index';@@ -268,6 +269,13 @@ export const VideoComposition = () => <><Video src="video.mp4" from={10} duratiotest('manage composition registrations and nested folders without changing components', () => {const original = makeProject();+ const helper = 'const Helper = () => <div>Keep this helper unchanged</div>;';+ original.files[compositionFile] = original.files[compositionFile]+ .replace(+ 'export const Root = () => ',+ `export const Root = () => {\n${helper}\nreturn `,+ )+ .replace('/>;\n', '/>;\n};\n');let {project} = addComposition({project: original,compositionFile,@@ -275,6 +283,7 @@ test('manage composition registrations and nested folders without changing compocomponent: {importName: 'Title', importPath: './Title'},metadata: {width: 1920, height: 1080, fps: 30, durationInFrames: 60},});+ expect(project.files[compositionFile]).toContain(helper);project = setCompositionDefaultProps({project,compositionFile,@@ -563,7 +572,8 @@ test('nested copies return root references and insertion preserves relative keystest('reject ambiguous registration roots and unsupported splitting or audio detachment', async () => {const project = makeProject();- project.files[compositionFile] += '\nconst AnotherComponent = () => <div />;';+ project.files[compositionFile] +=+ '\nconst AnotherRoot = () => <Composition id="Other" component={Video} />;';expect(() =>addComposition({project,@@ -595,3 +605,140 @@ test('node discovery and edits use original source locations with tabs and CRLF'expect(edited.project.files[filePath].startsWith('\uFEFF')).toBe(true);expect(edited.project.files[filePath]).toContain('\r\n');});++test('batch structured prop edits across files and preserve edit results in request order', () => {+ const project = {+ rootDir: '/',+ files: {+ 'first.tsx':+ 'export const First = () => <div style={{opacity: 0.5}} title="first" />;',+ 'second.tsx': 'export const Second = () => <div title="second" />;',+ },+ };+ const first = getJsxNodes({project, filePath: 'first.tsx'})[0];+ const second = getJsxNodes({project, filePath: 'second.tsx'})[0];+ const result = updateMultipleJsxNodeProps({+ project,+ changes: [+ {+ node: first,+ updates: [{key: 'style.opacity', value: 1, defaultValue: 1}],+ },+ {node: second, props: {title: 'updated second'}},+ {node: first, props: {title: 'updated first'}},+ ],+ });++ expect(result.changes).toHaveLength(2);+ expect(result.results[0].oldValueStrings).toEqual(['0.5']);+ expect(result.updatedNodes.map((node) => node.filePath)).toEqual([+ 'first.tsx',+ 'second.tsx',+ 'first.tsx',+ ]);+ expect(+ getJsxNodeProps({+ project: result.project,+ node: result.updatedNodes[0],+ keys: ['style.opacity', 'title'],+ }).props,+ ).toMatchObject({+ 'style.opacity': {codeValue: undefined},+ title: {codeValue: 'updated first'},+ });+ expect(+ getJsxNodeProps({+ project: result.project,+ node: result.updatedNodes[1],+ keys: ['title'],+ }).props.title,+ ).toMatchObject({codeValue: 'updated second'});+ expect(project.files['first.tsx']).toContain('opacity: 0.5');+});++test('set composition default props preserves serialized dates and enum assertions', () => {+ const input = `import {Composition} from 'remotion';+const untouched = "keep this spacing";+export const Root = () => <Composition id="Comp" defaultProps={{mode: 'old'}} />;+`;+ const result = setCompositionDefaultProps({+ project: {rootDir: '/', files: {'Root.tsx': input}},+ compositionFile: 'Root.tsx',+ compositionId: 'Comp',+ defaultProps: {+ mode: 'fast',+ date: 'remotion-date:2026-07-29T00:00:00.000Z',+ },+ enumPaths: [['mode']],+ });+ expect(result.logLine).toBe(3);+ expect(result.project.files['Root.tsx']).toContain(+ 'const untouched = "keep this spacing";',+ );+ expect(result.project.files['Root.tsx']).toContain("mode: 'fast' as const");+ expect(result.project.files['Root.tsx']).toMatch(+ /date: new Date\(\s*'2026-07-29T00:00:00\.000Z',?\s*\)/,+ );+});++test('default prop enum serialization shares node lookup, insertion, and spread protections', () => {+ for (const [imports, tag] of [+ ["import {Composition as Comp} from 'remotion';", 'Comp'],+ ["import * as R from 'remotion';", 'R.Composition'],+ ]) {+ for (const enumPaths of [undefined, [], [['mode']]]) {+ const input = `${imports}\nconst untouched = 'keep spacing';\nexport const Root = () => <${tag} id={'Target'} />;\n`;+ const original = {rootDir: '/', files: {[compositionFile]: input}};+ const inserted = setCompositionDefaultProps({+ project: original,+ compositionFile,+ compositionId: 'Target',+ defaultProps: {mode: 'fast'},+ enumPaths,+ });+ const updated = setCompositionDefaultProps({+ project: inserted.project,+ compositionFile,+ compositionId: 'Target',+ defaultProps: {mode: 'slow'},+ enumPaths,+ });+ expect(+ getJsxNodeProps({+ project: updated.project,+ node: updated.updatedNode,+ keys: ['defaultProps'],+ }).props.defaultProps,+ ).toMatchObject({status: 'static', codeValue: {mode: 'slow'}});+ expect(updated.project.files[compositionFile]).toContain(+ "const untouched = 'keep spacing';",+ );+ if (enumPaths?.length) {+ expect(updated.project.files[compositionFile]).toContain(+ "mode: 'slow' as const",+ );+ }++ expect(original.files[compositionFile]).toBe(input);++ for (const attributes of [+ "defaultProps={{...defaults}} id={'Target'}",+ "{...props} id={'Target'}",+ "defaultProps={{mode: 'old'}} {...props} id={'Target'}",+ ]) {+ const unsafeInput = `${imports}\nexport const Root = () => <${tag} ${attributes} />;\n`;+ const project = {rootDir: '/', files: {[compositionFile]: unsafeInput}};+ expect(() =>+ setCompositionDefaultProps({+ project,+ compositionFile,+ compositionId: 'Target',+ defaultProps: {mode: 'fast'},+ enumPaths,+ }),+ ).toThrow('computed');+ expect(project.files[compositionFile]).toBe(unsafeInput);+ }+ }+ }+});diff --git a/packages/codemods/src/test/registration-workflows.test.ts b/packages/codemods/src/test/registration-workflows.test.tsnew file mode 100644index 0000000000..b2b89964b2--- /dev/null+++ b/packages/codemods/src/test/registration-workflows.test.ts@@ -0,0 +1,113 @@+import {expect, test} from 'bun:test';+import {+ addComposition,+ moveComposition,+ moveFolder,+ renameFolder,+ unwrapFolder,+} from '../index';++const compositionFile = 'src/Root.tsx';++test('resolves same-named nested folders by parent throughout registration edits', () => {+ const input = `import {Composition, Folder} from 'remotion';+export const Root = () => (+ <>+ <Folder name="Parent">+ <Folder name="Shared">+ <Composition id="NestedA" component={Video} />+ </Folder>+ </Folder>+ <Folder name="Other">+ <Folder name="Shared">+ <Composition id="NestedB" component={Video} />+ </Folder>+ </Folder>+ </>+);+`;+ const original = {rootDir: '/', files: {[compositionFile]: input}};+ expect(() =>+ moveFolder({+ project: original,+ compositionFile,+ folder: {name: 'Shared', parentName: 'Parent'},+ destination: {+ type: 'folder',+ folder: {name: 'Other', parentName: null},+ },+ }),+ ).toThrow('A folder named "Shared" already exists in the destination');++ let {project} = addComposition({+ project: original,+ compositionFile,+ compositionId: 'Fresh',+ component: {importName: 'Fresh', importPath: './Fresh'},+ metadata: {durationInFrames: 90, fps: 30, width: 1920, height: 1080},+ folder: {name: 'Shared', parentName: 'Other'},+ });+ const added = project.files[compositionFile];+ expect(added).toContain(` <Folder name="Other">+ <Folder name="Shared">+ <Composition id="NestedB" component={Video} />+ <Composition+ id="Fresh"`);++ project = renameFolder({+ project,+ compositionFile,+ folder: {name: 'Shared', parentName: 'Parent'},+ newName: 'Renamed',+ }).project;+ expect(project.files[compositionFile]).toBe(+ added.replace('<Folder name="Shared">', '<Folder name="Renamed">'),+ );+ project = unwrapFolder({+ project,+ compositionFile,+ folder: {name: 'Renamed', parentName: 'Parent'},+ }).project;+ expect(project.files[compositionFile]).toContain(` <Folder name="Parent">+ <Composition id="NestedA" component={Video} />+ </Folder>`);+ expect(+ project.files[compositionFile].slice(+ project.files[compositionFile].indexOf('<Folder name="Other">'),+ ),+ ).toBe(added.slice(added.indexOf('<Folder name="Other">')));+ expect(original.files[compositionFile]).toBe(input);+});++test('moves a composition to its registration root after an unrelated JSX component', () => {+ const helper = 'const Component = () => {return <><div>Content</div></>;};';+ const input = `import {Composition, Folder} from 'remotion';+${helper}+export const Root = () => {+ return (+ <>+ <Folder name="Parent">+ <Composition id="Nested" component={Component} />+ </Folder>+ </>+ );+};+`;+ const {project} = moveComposition({+ project: {rootDir: '/', files: {[compositionFile]: input}},+ compositionFile,+ compositionId: 'Nested',+ destination: {type: 'root'},+ });+ expect(project.files[compositionFile]).toBe(+ input+ .replace(+ ' <Composition id="Nested" component={Component} />\n',+ '',+ )+ .replace(+ ' </Folder>',+ ' </Folder>\n <Composition id="Nested" component={Component} />',+ ),+ );+});diff --git a/packages/studio-server/src/test/reorder-effect.test.ts b/packages/codemods/src/test/reorder-effect.test.tssimilarity index 93%rename from packages/studio-server/src/test/reorder-effect.test.tsrename to packages/codemods/src/test/reorder-effect.test.tsindex 582569acde..9d3ffb3cf0 100644--- a/packages/studio-server/src/test/reorder-effect.test.ts+++ b/packages/codemods/src/test/reorder-effect.test.ts@@ -1,8 +1,6 @@import {expect, test} from 'bun:test';-import {CodemodsInternals} from '@remotion/codemods';-import {lineColumnToNodePath} from './test-utils';--const {reorderEffect} = CodemodsInternals;+import {reorderEffect} from '../effect-operations';+import {lineColumnToNodePath} from './node-path-test-utils';const buildInput = (effects: string,diff --git a/packages/studio-server/src/test/reorder-sequence.test.ts b/packages/codemods/src/test/reorder-sequence.test.tssimilarity index 91%rename from packages/studio-server/src/test/reorder-sequence.test.tsrename to packages/codemods/src/test/reorder-sequence.test.tsindex 14a1c31c6a..ec163cc939 100644--- a/packages/studio-server/src/test/reorder-sequence.test.ts+++ b/packages/codemods/src/test/reorder-sequence.test.ts@@ -1,10 +1,7 @@import {expect, test} from 'bun:test';-import {CodemodsInternals} from '@remotion/codemods';-import {parseAst} from '../codemods/parse-ast';-import {lineColumnToNodePath as getNodePathAtPosition} from '../preview-server/routes/can-update-sequence-props';-import {lineColumnToNodePath} from './test-utils';--const {reorderSequence} = CodemodsInternals;+import {getJsxNodes} from '../get-jsx-nodes';+import {reorderSequence} from '../reorder-sequence';+import {lineColumnToNodePath} from './node-path-test-utils';const sequenceContaining = (input: string, search: string) => {const searchOffset = input.indexOf(search);@@ -20,12 +17,14 @@ const sequenceContaining = (input: string, search: string) => {}const sourceBeforeOpening = input.slice(0, openingOffset).split('\n');- const nodePath = getNodePathAtPosition(- parseAst(input),- sourceBeforeOpening.length,- sourceBeforeOpening.at(-1)?.length ?? 0,- input,- );+ const nodePath = getJsxNodes({+ project: {rootDir: '/', files: {'/test.tsx': input}},+ filePath: '/test.tsx',+ }).find(+ (node) =>+ node.location?.line === sourceBeforeOpening.length &&+ node.location.column === (sourceBeforeOpening.at(-1)?.length ?? 0),+ )?.nodePath;if (!nodePath) {throw new Error(`Could not resolve a Sequence containing ${JSON.stringify(search)}`,diff --git a/packages/studio-server/src/test/update-default-props.test.ts b/packages/codemods/src/test/set-composition-default-props.test.tssimilarity index 54%rename from packages/studio-server/src/test/update-default-props.test.tsrename to packages/codemods/src/test/set-composition-default-props.test.tsindex 0028042141..38b2259f85 100644--- a/packages/studio-server/src/test/update-default-props.test.ts+++ b/packages/codemods/src/test/set-composition-default-props.test.ts@@ -1,63 +1,50 @@import {expect, test} from 'bun:test';import {readFileSync} from 'node:fs';import path from 'node:path';-import {CodemodsInternals} from '@remotion/codemods';-import {parseAst} from '../codemods/parse-ast';--const {getCompositionDefaultPropsLine, updateDefaultProps} = CodemodsInternals;+import {setCompositionDefaultProps} from '../index';test('updates default props without changing surrounding source', () => {- const file = readFileSync(- path.join(__dirname, 'snapshots', 'root-before.tsx'),+ const input = readFileSync(+ path.join(__dirname, 'fixtures', 'root-before.tsx.txt'),'utf-8',);const expected = readFileSync(- path.join(__dirname, 'snapshots', 'root-after.tsx'),+ path.join(__dirname, 'fixtures', 'root-after.tsx.txt'),'utf-8',);- const {output} = updateDefaultProps({- input: file,+ const result = setCompositionDefaultProps({+ project: {rootDir: '/', files: {'Root.tsx': input}},+ compositionFile: 'Root.tsx',compositionId: 'Comp3',- newDefaultProps: {abc: 'def', newDate: 'remotion-date:2022-01-02'},+ defaultProps: {abc: 'def', newDate: 'remotion-date:2022-01-02'},enumPaths: [],});- expect(output).toBe(expected);-});--test('getCompositionDefaultPropsLine returns the opening tag line (ast-types visitor must traverse)', () => {- const file = readFileSync(- path.join(__dirname, 'snapshots', 'root-before.tsx'),- 'utf-8',- );-- expect(- getCompositionDefaultPropsLine({- input: file,- compositionId: 'Comp3',- }),- ).toBe(27);+ expect(result.project.files['Root.tsx']).toBe(expected);+ expect(result.logLine).toBe(27);});test('replaces multiline default props with a compact value', () => {- const file = readFileSync(- path.join(__dirname, 'snapshots', 'problematic.tsx'),- 'utf-8',- );- const expected = readFileSync(- path.join(__dirname, 'snapshots', 'fixed.tsx'),- 'utf-8',- );-- const {output} = updateDefaultProps({- input: file,+ const input =+ "import {Composition} from 'remotion';\n" ++ readFileSync(+ path.join(__dirname, 'fixtures', 'problematic.tsx.txt'),+ 'utf-8',+ );+ const expected =+ "import {Composition} from 'remotion';\n" ++ readFileSync(path.join(__dirname, 'fixtures', 'fixed.tsx.txt'), 'utf-8');++ const result = setCompositionDefaultProps({+ project: {rootDir: '/', files: {'Root.tsx': input}},+ compositionFile: 'Root.tsx',compositionId: 'schema-test',- newDefaultProps: {abc: 'def', newDate: 'remotion-date:2022-01-02'},+ defaultProps: {abc: 'def', newDate: 'remotion-date:2022-01-02'},enumPaths: [],});- expect(output).toBe(expected);+ expect(result.project.files['Root.tsx']).toBe(expected);});test('formats multiline default props without Prettier', () => {@@ -72,10 +59,11 @@ export const Root=()=>(/>)`;- const {output} = updateDefaultProps({- input,+ const result = setCompositionDefaultProps({+ project: {rootDir: '/', files: {'Root.tsx': input}},+ compositionFile: 'Root.tsx',compositionId: 'Comp',- newDefaultProps: {+ defaultProps: {title: 'Hello',publishedAt: 'remotion-date:2026-07-29T00:00:00.000Z',audio: 'remotion-file:my%20folder/audio%20%231.wav',@@ -84,7 +72,8 @@ export const Root=()=>(enumPaths: [['mode']],});- expect(output).toBe(`import {Composition} from 'remotion'+ expect(result.project.files['Root.tsx'])+ .toBe(`import {Composition} from 'remotion'const untouched = {keep:"this spacing"}@@ -117,14 +106,15 @@ test('preserves CRLF, spaces, double quotes, and bracket spacing', () => {'',].join('\r\n');- const {output} = updateDefaultProps({- input,+ const result = setCompositionDefaultProps({+ project: {rootDir: '/', files: {'Root.tsx': input}},+ compositionFile: 'Root.tsx',compositionId: 'Comp',- newDefaultProps: {title: 'Hello'},+ defaultProps: {title: 'Hello'},enumPaths: [],});- expect(output).toBe(+ expect(result.project.files['Root.tsx']).toBe(input.replace('defaultProps={{ old: "value" }}','defaultProps={{ title: "Hello" }}',@@ -133,15 +123,17 @@ test('preserves CRLF, spaces, double quotes, and bracket spacing', () => {});test('formats nested arrays and keeps non-identifier keys quoted', () => {- const input = `export const Root = () => (+ const input = `import {Composition} from "remotion";+export const Root = () => (<Composition id="Comp" defaultProps={{ old: true }} />)`;- const {output} = updateDefaultProps({- input,+ const result = setCompositionDefaultProps({+ project: {rootDir: '/', files: {'Root.tsx': input}},+ compositionFile: 'Root.tsx',compositionId: 'Comp',- newDefaultProps: {+ defaultProps: {items: [{mode: 'fast', label: 'hello'},{mode: 'slow', label: 'world'},@@ -151,7 +143,9 @@ test('formats nested arrays and keeps non-identifier keys quoted', () => {enumPaths: [['items', '[]', 'mode']],});- expect(output).toBe(`export const Root = () => (+ expect(result.project.files['Root.tsx'])+ .toBe(`import {Composition} from "remotion";+export const Root = () => (<Composition id="Comp" defaultProps={{items: [{mode: "fast" as const,@@ -164,5 +158,4 @@ test('formats nested arrays and keeps non-identifier keys quoted', () => {}} />)`);- expect(() => parseAst(output)).not.toThrow();});diff --git a/packages/codemods/src/test/split-jsx-sequence.test.ts b/packages/codemods/src/test/split-jsx-sequence.test.tsindex f778ec527f..abbd008bd6 100644--- a/packages/codemods/src/test/split-jsx-sequence.test.ts+++ b/packages/codemods/src/test/split-jsx-sequence.test.ts@@ -3,6 +3,10 @@ import * as recast from 'recast';import {getNodePathForRecastPath} from '../sequence-props';import {parseAst} from '../sequence-props/parse-ast';import {splitJsxSequence, splitJsxSequences} from '../split-jsx-sequence';+import {+ lineColumnToNodePath,+ lineContainingToNodePath,+} from './node-path-test-utils';test('splits fractional timing without persisting arithmetic noise', async () => {const input =@@ -75,3 +79,254 @@ test('splits multiple sibling sequences from the same source snapshot', async ()nodePathRemappings.filter((remapping) => remapping.oldNodePath === null),).toHaveLength(2);});++const wrap = (+ sequence: string,+) => `import {AbsoluteFill, Img, Interactive, Sequence, Series, Solid} from 'remotion';+import {Gif} from '@remotion/gif';++export const Comp = () => {+ return (+ <>+ ${sequence}+ </>+ );+};+`;++const sequenceLine = 7;+const sequenceTimingKeys = ['from', 'durationInFrames', 'trimBefore'];++const split = async (+ sequence: string,+ splitFrame: number,+ sequenceKeys = sequenceTimingKeys,+) => {+ const input = wrap(sequence);+ const {output} = await splitJsxSequence({+ input,+ nodePath: lineColumnToNodePath(input, sequenceLine),+ sequenceKeys,+ splitFrame,+ });++ return output;+};++test('splitJsxSequence splits a sequence with no duration', async () => {+ const output = await split('<Sequence from={0} />', 30);++ expect(output).toContain('<Sequence from={0} durationInFrames={30} />');+ expect(output).toContain('<Sequence from={30} trimBefore={30} />');+});++test('splitJsxSequence remaps following JSX siblings', async () => {+ const input = wrap(+ '<Sequence name="split" from={0} durationInFrames={50} />\n\t\t\t<Sequence name="following" />',+ );+ const {output, nodePathRemappings} = await splitJsxSequence({+ input,+ nodePath: lineContainingToNodePath(input, 'name="split"'),+ sequenceKeys: sequenceTimingKeys,+ splitFrame: 30,+ });++ expect(nodePathRemappings).toEqual([+ {+ oldNodePath: lineContainingToNodePath(input, 'name="split"'),+ newNodePath: lineContainingToNodePath(output, 'name="split"'),+ },+ {+ oldNodePath: lineContainingToNodePath(input, 'name="following"'),+ newNodePath: lineContainingToNodePath(output, 'name="following"'),+ },+ {+ oldNodePath: null,+ newNodePath: lineContainingToNodePath(output, 'from={30}'),+ },+ ]);+});++test('splitJsxSequence omits right Infinity duration', async () => {+ const output = await split(+ '<Sequence from={0} durationInFrames={Infinity} />',+ 30,+ );++ expect(output).toContain('<Sequence from={0} durationInFrames={30} />');+ expect(output).toContain('<Sequence from={30} trimBefore={30} />');+ expect(output).not.toContain('durationInFrames={Infinity}');+});++test('splitJsxSequence keeps missing left from omitted', async () => {+ const output = await split('<Sequence durationInFrames={50} />', 30);++ expect(output).toContain('<Sequence durationInFrames={30} />');+ expect(output).toContain(+ '<Sequence from={30} durationInFrames={20} trimBefore={30} />',+ );+});++test('splitJsxSequence splits finite duration and trimBefore', async () => {+ const output = await split(+ '<Sequence from={10} durationInFrames={50} trimBefore={5} />',+ 30,+ );++ expect(output).toContain(+ '<Sequence from={10} durationInFrames={20} trimBefore={5} />',+ );+ expect(output).toContain(+ '<Sequence from={30} durationInFrames={30} trimBefore={25} />',+ );+});++test('splitJsxSequence preserves surrounding formatting without calling Prettier', async () => {+ const input = `const deliberatelyUnformatted = {value : true}++export const Comp = () => {+ return (+ <>+ <Sequence+ name="clip"+ from={0}+ durationInFrames={50}+ >+ <div>Child</div>+ </Sequence>+ <Keep prop = {1}/>+ </>+ )+}+`;+ const {output} = await splitJsxSequence({+ input,+ nodePath: lineContainingToNodePath(input, '<Sequence'),+ sequenceKeys: sequenceTimingKeys,+ splitFrame: 30,+ });++ expect(output).toStartWith(+ 'const deliberatelyUnformatted = {value : true}\n',+ );+ expect(output).toContain(+ '<Sequence name="clip" from={0} durationInFrames={30}>\n',+ );+ expect(output).toContain(+ '<Sequence name="clip" from={30} durationInFrames={20} trimBefore={30}>\n',+ );+ expect(output).toContain(' <Keep prop = {1}/>');+ expect(output).toEndWith(' )\n}\n');+});++test('splitJsxSequence formats a split component root as a fragment', async () => {+ const input = `export const Comp = () => <Sequence from={0} durationInFrames={50}><span>Hi</span></Sequence>;++const keep = { value : true }+`;+ const {output} = await splitJsxSequence({+ input,+ nodePath: lineContainingToNodePath(input, '<Sequence'),+ sequenceKeys: sequenceTimingKeys,+ splitFrame: 30,+ });++ expect(output).toBe(`export const Comp = () => <>+ <Sequence from={0} durationInFrames={30}>+ <span>Hi</span>+ </Sequence>+ <Sequence from={30} durationInFrames={20} trimBefore={30}>+ <span>Hi</span>+ </Sequence>+</>;++const keep = { value : true }+`);+});++test('splitJsxSequence splits a video with a negative from', async () => {+ const output = await split(+ '<Video src="video.mov" from={-2644} trimBefore={272} />',+ 100,+ );++ expect(output).toContain('from={-2644}');+ expect(output).toContain('durationInFrames={2744}');+ expect(output).toContain('trimBefore={272}');+ expect(output).toContain(+ '<Video src="video.mov" from={100} trimBefore={3016} />',+ );+});++test('splitJsxSequence splits from-only sequence', async () => {+ const output = await split('<Sequence from={10} />', 30);++ expect(output).toContain('<Sequence from={10} durationInFrames={20} />');+ expect(output).toContain('<Sequence from={30} trimBefore={20} />');+});++test('splitJsxSequence splits sequence-backed components', async () => {+ expect(+ await split('<AbsoluteFill from={0} durationInFrames={50} />', 30),+ ).toContain(+ '<AbsoluteFill from={30} durationInFrames={20} trimBefore={30} />',+ );+ expect(+ await split('<Img src="image.png" from={0} durationInFrames={50} />', 30),+ ).toContain(+ '<Img src="image.png" from={30} durationInFrames={20} trimBefore={30} />',+ );+ expect(+ await split('<Gif src="anim.gif" from={0} durationInFrames={50} />', 30),+ ).toContain(+ '<Gif src="anim.gif" from={30} durationInFrames={20} trimBefore={30} />',+ );+ const solidOutput = await split(+ '<Solid width={100} height={100} from={0} durationInFrames={50} />',+ 30,+ );+ expect(solidOutput).toContain(+ '<Solid width={100} height={100} from={0} durationInFrames={30} />',+ );+ expect(solidOutput).toContain('from={30}');+ expect(solidOutput).toContain('durationInFrames={20}');+ expect(solidOutput).toContain('trimBefore={30}');+ expect(+ await split('<Interactive.Div from={0} durationInFrames={50} />', 30),+ ).toContain(+ '<Interactive.Div from={30} durationInFrames={20} trimBefore={30} />',+ );+});++test('splitJsxSequence rejects boundary and dynamic splits', async () => {+ await expect(+ split('<Sequence from={10} durationInFrames={20} />', 10),+ ).rejects.toThrow(/sequence start/);+ await expect(+ split('<Sequence from={10} durationInFrames={20} />', 30),+ ).rejects.toThrow(/sequence end/);+ await expect(+ split('<Sequence from={10} durationInFrames={20} />', 8),+ ).rejects.toThrow(/sequence start/);+ await expect(+ split('<Sequence from={10} durationInFrames={20} />', 10.5),+ ).rejects.toThrow(/integer/);+ await expect(+ split('<Sequence from={start} durationInFrames={20} />', 15),+ ).rejects.toThrow(/dynamic from/);+});++test('splitJsxSequence rejects Series.Sequence', async () => {+ await expect(+ split('<Series.Sequence durationInFrames={50} />', 30, [+ 'durationInFrames',+ 'trimBefore',+ ]),+ ).rejects.toThrow('<Series.Sequence> cannot be split');+});++test('splitJsxSequence rejects regular DOM elements', async () => {+ await expect(+ split('<div from={0} durationInFrames={50} />', 30, []),+ ).rejects.toThrow('<div> cannot be split');+});diff --git a/packages/codemods/src/test/split-video-from-audio.test.ts b/packages/codemods/src/test/split-video-from-audio.test.tsnew file mode 100644index 0000000000..b7c6369d7b--- /dev/null+++ b/packages/codemods/src/test/split-video-from-audio.test.ts@@ -0,0 +1,266 @@+import {expect, test} from 'bun:test';+import {splitVideoFromAudio} from '../split-video-from-audio';+import {lineContainingToNodePath} from './node-path-test-utils';++const wrap = (+ element: string,+ imports = `import {Video} from '@remotion/media';`,+) => `${imports}++export const Comp = () => {+ return (+ <>+ ${element}+ </>+ );+};+`;++const split = async (element: string, imports?: string) => {+ const input = wrap(element, imports);+ const {output} = await splitVideoFromAudio({+ input,+ nodePath: lineContainingToNodePath(input, element),+ });++ return output;+};++test('splitVideoFromAudio mutes the video and adds an Audio with the same timing', async () => {+ const output = await split(+ '<Video src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} style={{opacity: 0.5}} />',+ );++ const singleLine = output.replace(/\s+/g, ' ');++ expect(output).toContain(`import {Video, Audio} from '@remotion/media';`);+ expect(singleLine).toContain(+ '<Video src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} style={{opacity: 0.5}} muted />',+ );+ expect(singleLine).toContain(+ '<Audio src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} />',+ );+});++test('splitVideoFromAudio preserves unrelated source formatting without calling the formatter', async () => {+ const input = `import{Video}from"@remotion/media"++const untouched = {keep : "spacing"}+export const Comp=()=>(+ <>+ <Video+ src = {"video.mp4"}+ from = {10}+ style = {{opacity:.5}}+ />+ <div data-value = "unchanged"/>+ </>+)+`;+ let formatCalls = 0;+ const {formatted, nodePathRemappings, output} = await splitVideoFromAudio({+ input,+ nodePath: lineContainingToNodePath(input, '<Video'),+ formatFile: () => {+ formatCalls++;+ throw new Error('Prettier must not be called');+ },+ });++ expect(formatCalls).toBe(0);+ expect(formatted).toBe(true);+ expect(output).toBe(`import{Video, Audio}from"@remotion/media"++const untouched = {keep : "spacing"}+export const Comp=()=>(+ <>+ <Video+ src = {"video.mp4"}+ from = {10}+ style = {{opacity:.5}}+ muted+ />+ <Audio src={"video.mp4"} from={10} />+ <div data-value = "unchanged"/>+ </>+)+`);+ expect(nodePathRemappings).toEqual([+ {+ oldNodePath: lineContainingToNodePath(input, '<Video'),+ newNodePath: lineContainingToNodePath(output, '<Video'),+ },+ {+ oldNodePath: lineContainingToNodePath(input, '<div'),+ newNodePath: lineContainingToNodePath(output, '<div'),+ },+ {+ oldNodePath: null,+ newNodePath: lineContainingToNodePath(output, '<Audio'),+ },+ ]);+});++test('splitVideoFromAudio does not copy non-audio props', async () => {+ const output = await split(+ '<Video src="video.mp4" name="my video" freeze={20} crop={{x: 0, y: 0, width: 100, height: 100}} />',+ );++ expect(output).toContain('<Audio src="video.mp4" />');+});++test('splitVideoFromAudio wraps a root video in a fragment', async () => {+ const input = `import {Video} from '@remotion/media';++export const Comp = () => <Video src="video.mp4" />;+`;+ const {output} = await splitVideoFromAudio({+ input,+ nodePath: lineContainingToNodePath(input, '<Video'),+ });++ expect(output).toBe(`import {Video, Audio} from '@remotion/media';++export const Comp = () => <>+ <Video src="video.mp4" muted />+ <Audio src="video.mp4" />+</>;+`);+});++test('splitVideoFromAudio separates siblings with one space on a shared line', async () => {+ const input = `import {Video} from '@remotion/media';++export const Comp = () => (+ <div>+ <Video src="video.mp4" /></div>+);+`;+ const {output} = await splitVideoFromAudio({+ input,+ nodePath: lineContainingToNodePath(input, '<Video'),+ });++ expect(output).toBe(`import {Video, Audio} from '@remotion/media';++export const Comp = () => (+ <div>+ <Video src="video.mp4" muted /> <Audio src="video.mp4" /></div>+);+`);+});++test('splitVideoFromAudio preserves CRLF and tab indentation', async () => {+ const input = [+ `import {Video} from '@remotion/media';`,+ '',+ 'export const Comp = () => {',+ '\treturn (',+ '\t\t<>',+ '\t\t\t<Video',+ '\t\t\t\tsrc="video.mp4"',+ '\t\t\t\ttrimBefore={10}',+ '\t\t\t/>',+ '\t\t</>',+ '\t);',+ '};',+ '',+ ].join('\r\n');+ const {output} = await splitVideoFromAudio({+ input,+ nodePath: lineContainingToNodePath(input, '<Video'),+ });++ expect(output).toBe(+ [+ `import {Video, Audio} from '@remotion/media';`,+ '',+ 'export const Comp = () => {',+ '\treturn (',+ '\t\t<>',+ '\t\t\t<Video',+ '\t\t\t\tsrc="video.mp4"',+ '\t\t\t\ttrimBefore={10}',+ '\t\t\t\tmuted',+ '\t\t\t/>',+ '\t\t\t<Audio src="video.mp4" trimBefore={10} />',+ '\t\t</>',+ '\t);',+ '};',+ '',+ ].join('\r\n'),+ );+});++test('splitVideoFromAudio replaces an existing muted prop', async () => {+ const output = await split('<Video src="video.mp4" muted={false} />');++ expect(output).toContain('<Video src="video.mp4" muted />');+ expect(output).not.toContain('muted={false}');+});++test('splitVideoFromAudio reuses an existing Audio import', async () => {+ const output = await split(+ '<Video src="video.mp4" />',+ `import {Audio, Video} from '@remotion/media';`,+ );++ expect(output).toContain(`import {Audio, Video} from '@remotion/media';`);+ expect(output.match(/from '@remotion\/media'/g)?.length).toBe(1);+});++test('splitVideoFromAudio uses an aliased Audio import', async () => {+ const output = await split(+ '<Video src="video.mp4" />',+ `import {Audio as Sound, Video} from '@remotion/media';`,+ );++ expect(output).toContain(+ `import {Audio as Sound, Video} from '@remotion/media';`,+ );+ expect(output).toContain('<Sound src="video.mp4" />');+});++test('splitVideoFromAudio imports Audio from the same module as the tag', async () => {+ const output = await split(+ '<OffthreadVideo src="video.mp4" from={5} />',+ `import {OffthreadVideo} from 'remotion';`,+ );++ expect(output).toContain(`import {OffthreadVideo, Audio} from 'remotion';`);+ expect(output).toContain('<OffthreadVideo src="video.mp4" from={5} muted />');+ expect(output).toContain('<Audio src="video.mp4" from={5} />');+});++test('splitVideoFromAudio follows import aliases', async () => {+ const output = await split(+ '<V src="video.mp4" />',+ `import {Video as V} from '@remotion/media';`,+ );++ expect(output).toContain(+ `import {Video as V, Audio} from '@remotion/media';`,+ );+ expect(output).toContain('<Audio src="video.mp4" />');+});++test('splitVideoFromAudio rejects elements without a src attribute', async () => {+ await expect(split('<Video from={0} />')).rejects.toThrow(+ '<Video> has no src attribute',+ );+});++test('splitVideoFromAudio rejects unimported tags', async () => {+ await expect(split('<video src="video.mp4" />')).rejects.toThrow(+ 'Could not find the import of <video>',+ );+});++test('splitVideoFromAudio rejects an Audio import from another module', async () => {+ await expect(+ split(+ '<Video src="video.mp4" />',+ `import {Video} from '@remotion/media';\nimport {Audio} from 'remotion';`,+ ),+ ).rejects.toThrow('Audio is already imported from "remotion"');+});diff --git a/packages/studio-server/src/test/update-effect-props.test.ts b/packages/codemods/src/test/update-effect-props.test.tssimilarity index 98%rename from packages/studio-server/src/test/update-effect-props.test.tsrename to packages/codemods/src/test/update-effect-props.test.tsindex 958e2deb0c..5d93ccd50c 100644--- a/packages/studio-server/src/test/update-effect-props.test.ts+++ b/packages/codemods/src/test/update-effect-props.test.ts@@ -1,6 +1,6 @@import {expect, test} from 'bun:test';-import {updateEffectPropsAst} from '../codemods/update-effect-props/update-effect-props';-import {lineColumnToNodePath} from './test-utils';+import {updateEffectPropsAst} from '../effect-operations';+import {lineColumnToNodePath} from './node-path-test-utils';const tintSchema = {color: {diff --git a/packages/studio-server/src/test/update-keyframes-imports.test.ts b/packages/codemods/src/test/update-keyframes-imports.test.tssimilarity index 99%rename from packages/studio-server/src/test/update-keyframes-imports.test.tsrename to packages/codemods/src/test/update-keyframes-imports.test.tsindex 1f3eabd1b7..65b3b41d74 100644--- a/packages/studio-server/src/test/update-keyframes-imports.test.ts+++ b/packages/codemods/src/test/update-keyframes-imports.test.ts@@ -3,8 +3,8 @@ import type {InteractivitySchema} from 'remotion';import {updateEffectKeyframesAst,updateSequenceKeyframesAst,-} from '../codemods/update-keyframes/update-keyframes';-import {lineColumnToNodePath} from './test-utils';+} from '../update-keyframes';+import {lineColumnToNodePath} from './node-path-test-utils';const getLine = (input: string, needle: string): number => {const lineIndex = inputdiff --git a/packages/codemods/src/update-default-props.ts b/packages/codemods/src/update-default-props.tsdeleted file mode 100644index 8b54f73d01..0000000000--- a/packages/codemods/src/update-default-props.ts+++ /dev/null@@ -1,241 +0,0 @@-import {stringifyDefaultProps, type EnumPath} from '@remotion/studio-shared';-import * as recast from 'recast';-import {formatSerializedValue} from './format-serialized-value';-import {recastLocToOffset} from './recast-loc-to-offset';-import {parseAst} from './sequence-props/parse-ast';--export const updateDefaultProps = ({- input,- compositionId,- newDefaultProps,- enumPaths,-}: {- input: string;- compositionId: string;- newDefaultProps: Record<string, unknown>;- enumPaths: EnumPath[];-}): {output: string} => {- const ast = parseAst(input);- const stringified = stringifyDefaultProps({- props: newDefaultProps,- enumPaths,- });-- let replaceStart: number | undefined;- let replaceEnd: number | undefined;-- recast.types.visit(ast, {- visitJSXElement(path) {- const {openingElement} = path.node;- // 1: ensure its the element we're looking for- const openingName = openingElement.name;- if (- openingName.type !== 'JSXIdentifier' &&- openingName.type !== 'JSXNamespacedName'- ) {- this.traverse(path); // Continue traversing the AST- return;- }-- if (openingName.name !== 'Composition' && openingName.name !== 'Still') {- this.traverse(path); // Continue traversing the AST- return;- }-- if (- !openingElement.attributes?.some((attr) => {- if (attr.type === 'JSXSpreadAttribute') {- return;- }-- if (!attr.value) {- return;- }-- if (attr.value.type === 'JSXElement') {- return;- }-- if (attr.value.type === 'JSXExpressionContainer') {- return;- }-- if (attr.value.type === 'JSXFragment') {- return;- }-- return attr.name.name === 'id' && attr.value.value === compositionId;- })- ) {- this.traverse(path); // Continue traversing the AST- return;- }-- // 2: Find the defaultProps attribute and handle related errors- const defaultPropsAttr = openingElement.attributes.find((attr) => {- if (attr.type === 'JSXSpreadAttribute') {- this.traverse(path); // Continue traversing the AST- return;- }-- return attr.name.name === 'defaultProps';- });-- if (!defaultPropsAttr) {- throw new Error(- `No \`defaultProps\` prop found in the <Composition/> tag with the ID "${compositionId}".`,- );- }-- if (defaultPropsAttr.type === 'JSXSpreadAttribute') {- this.traverse(path); // Continue traversing the AST- return;- }-- // 3: ensure only hardcoded values are provided- if (- !defaultPropsAttr.value ||- defaultPropsAttr.value.type === 'JSXElement' ||- defaultPropsAttr.value.type === 'JSXText' ||- defaultPropsAttr.value.type === 'StringLiteral' ||- defaultPropsAttr.value.type === 'NumericLiteral' ||- defaultPropsAttr.value.type === 'BigIntLiteral' ||- defaultPropsAttr.value.type === 'DecimalLiteral' ||- defaultPropsAttr.value.type === 'NullLiteral' ||- defaultPropsAttr.value.type === 'BooleanLiteral' ||- defaultPropsAttr.value.type === 'RegExpLiteral' ||- defaultPropsAttr.value.type === 'JSXFragment' ||- defaultPropsAttr.value.type === 'Literal'- ) {- throw new Error(- `\`defaultProps\` prop must be a hardcoded value in the <Composition/> tag, but it is a ${defaultPropsAttr.value?.type}".`,- );- }-- const defaultPropsValue = defaultPropsAttr.value.expression;- if (- defaultPropsValue.type !== 'ObjectExpression' &&- defaultPropsValue.type !== 'TSAsExpression'- ) {- throw new Error(- `\`defaultProps\` prop must be a hardcoded value in the <Composition/> tag with the ID "${compositionId}".`,- );- }-- // Capture source positions for direct string replacement- // instead of modifying the AST and serializing (avoids recast artifacts)- const valueLoc = defaultPropsAttr.value.loc;- if (!valueLoc) {- throw new Error('Could not determine source location of defaultProps');- }-- replaceStart = recastLocToOffset(input, valueLoc.start);- replaceEnd = recastLocToOffset(input, valueLoc.end);-- this.traverse(path); // Continue traversing the AST- },- });-- if (replaceStart === undefined || replaceEnd === undefined) {- throw new Error(- `Could not find defaultProps for composition "${compositionId}"`,- );- }-- // linePrefix includes the JSX container opening brace- const lineStart = input.lastIndexOf('\n', replaceStart) + 1;- const linePrefix = input.substring(lineStart, replaceStart + 1);- const previousValue = input.slice(replaceStart + 1, replaceEnd - 1).trim();- if (stringified === undefined) {- throw new Error('Could not serialize the updated defaultProps value');- }-- const formatted = formatSerializedValue({- input,- linePrefix,- previousValue,- serialized: stringified,- });-- // Replace the JSX expression container in the original input- const output =- input.substring(0, replaceStart) +- '{' +- formatted +- '}' +- input.substring(replaceEnd);-- return {output};-};--/** Line of the matching `<Composition>` / `<Still>` opening tag (for log links). */-export const getCompositionDefaultPropsLine = ({- input,- compositionId,-}: {- input: string;- compositionId: string;-}): number => {- const ast = parseAst(input);- let line = 1;- let found = false;-- recast.types.visit(ast, {- visitJSXElement(path) {- if (found) {- this.traverse(path);- return;- }-- const {openingElement} = path.node;- const openingName = openingElement.name;- if (- openingName.type !== 'JSXIdentifier' &&- openingName.type !== 'JSXNamespacedName'- ) {- this.traverse(path);- return;- }-- if (openingName.name !== 'Composition' && openingName.name !== 'Still') {- this.traverse(path);- return;- }-- if (- !openingElement.attributes?.some((attr) => {- if (attr.type === 'JSXSpreadAttribute') {- return;- }-- if (!attr.value) {- return;- }-- if (attr.value.type === 'JSXElement') {- return;- }-- if (attr.value.type === 'JSXExpressionContainer') {- return;- }-- if (attr.value.type === 'JSXFragment') {- return;- }-- return attr.name.name === 'id' && attr.value.value === compositionId;- })- ) {- this.traverse(path);- return;- }-- found = true;- line = openingElement.loc?.start.line ?? path.node.loc?.start.line ?? 1;- this.traverse(path);- },- });-- return line;-};diff --git a/packages/docs/docs/codemods/add-canvas-capture-composition.mdx b/packages/docs/docs/codemods/add-canvas-capture-composition.mdxnew file mode 100644index 0000000000..011c1de93d--- /dev/null+++ b/packages/docs/docs/codemods/add-canvas-capture-composition.mdx@@ -0,0 +1,129 @@+---+image: /generated/articles-docs-codemods-add-canvas-capture-composition.png+title: 'addCanvasCaptureComposition()'+crumb: '@remotion/codemods'+---++# addCanvasCaptureComposition()<AvailableFrom v="4.0.528" />++Creates an interactive Canvas Capture component and registers it in the project. Both files are returned in one result.++:::warning++_Draft API_: This API is experimental and may change.++:::++```ts twoslash title="add-canvas-capture-composition.ts"+import {addCanvasCaptureComposition, type CodemodProject} from '@remotion/codemods';++declare const project: CodemodProject;++const result = addCanvasCaptureComposition({+ project,+ compositionFile: 'src/Root.tsx',+ compositionId: 'Capture',+ component: {+ filePath: 'src/Capture.tsx',+ importName: 'Capture',+ importPath: './Capture',+ },+ metadata: {width: 1920, height: 1080, fps: 30, durationInFrames: 90},+ capture: {+ videoFileName: 'capture.mp4',+ videoWidth: 1920,+ videoHeight: 1080,+ keyframeFps: 30,+ data: {+ captureMetadata: {density: 1},+ mouseMovements: [{timeInSeconds: 0, canvasX: 100, canvasY: 200, cursor: 'pointer'}],+ pointerClicks: [],+ },+ },+});++console.log(result.changes);+```++## Options++### project++An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project is not mutated.++### compositionFile++The project file containing the registration component.++### compositionId++The new composition ID. Must contain only letters, numbers, or hyphens and be unused in the registration file.++### component++The component file and import to create.++#### filePath++The new project file path. An existing file cannot be overwritten.++#### importName++The named component export, beginning with an uppercase letter, `_`, or `$`.++#### importPath++The module specifier to use in the registration file, such as `./Capture`.++### metadata++The composition's `width`, `height`, `fps`, and `durationInFrames`. See [`addComposition()`](/docs/codemods/add-composition#metadata).++### folder?++An existing folder reference `{name, parentName}`. By default, inserts at the registration root.++### capture++The recorded video and cursor data. The video must already be available in the [public folder](/docs/importing-assets).++#### videoFileName++The path to the video within the public folder, passed to [`staticFile()`](/docs/staticfile).++#### videoWidth++The recorded video's width in pixels.++#### videoHeight++The recorded video's height in pixels.++#### keyframeFps++The frame rate used to convert recording timestamps into cursor keyframes.++#### data++Capture data containing `captureMetadata.density`, `mouseMovements`, and `pointerClicks`. Mouse movements have `timeInSeconds`, `canvasX`, `canvasY`, and `cursor`. Clicks have `timeInSeconds` and `type: 'pointer-down' | 'pointer-up'`. At least one movement must have non-null canvas coordinates.++The generated component uses `@remotion/media` and `@remotion/mac-cursors`. These packages must be installed in the project.++## Return value++### project++The updated project. Unchanged files and extra project fields are preserved.++### changes++An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />++## See also++- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/add-canvas-capture-composition.ts)+- [`@remotion/codemods`](/docs/codemods)diff --git a/packages/docs/docs/codemods/add-composition.mdx b/packages/docs/docs/codemods/add-composition.mdxindex b3399a5985..ca9ffb8964 100644--- a/packages/docs/docs/codemods/add-composition.mdx+++ b/packages/docs/docs/codemods/add-composition.mdx@@ -40,7 +40,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### compositionFile-The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with their original import names and static IDs or folder names.+The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with static IDs or folder names. Aliased and namespace imports from `remotion` are supported.### compositionIddiff --git a/packages/docs/docs/codemods/add-folder.mdx b/packages/docs/docs/codemods/add-folder.mdxindex 2f80293165..3cd7092806 100644--- a/packages/docs/docs/codemods/add-folder.mdx+++ b/packages/docs/docs/codemods/add-folder.mdx@@ -38,7 +38,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### compositionFile-The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with their original import names and static IDs or folder names.+The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with static IDs or folder names. Aliased and namespace imports from `remotion` are supported.### folderdiff --git a/packages/docs/docs/codemods/delete-composition.mdx b/packages/docs/docs/codemods/delete-composition.mdxindex 8345856d55..1ed89aa35b 100644--- a/packages/docs/docs/codemods/delete-composition.mdx+++ b/packages/docs/docs/codemods/delete-composition.mdx@@ -38,7 +38,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### compositionFile-The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with their original import names and static IDs or folder names.+The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with static IDs or folder names. Aliased and namespace imports from `remotion` are supported.### compositionIddiff --git a/packages/docs/docs/codemods/delete-effects.mdx b/packages/docs/docs/codemods/delete-effects.mdxindex 1adc63e395..a1196e8e59 100644--- a/packages/docs/docs/codemods/delete-effects.mdx+++ b/packages/docs/docs/codemods/delete-effects.mdx@@ -30,6 +30,8 @@ console.log(result);Indices of later effects shift after deletion. Read effects again with [`getJsxNodeProps()`](/docs/codemods/get-jsx-node-props) before using old effect indices. Imports are preserved.+The `effects` attribute must contain an inline array. An attribute followed by a JSX spread is rejected because the spread may override it.+## Options### project@@ -38,7 +40,21 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### effects-Effect references to remove. References may span files and nodes; indices refer to the input project. Duplicate references are deduplicated.+A non-empty array of effect references to remove. References may span files and nodes; indices refer to the input project. Duplicate references are deduplicated.++Set `effectIndex: null` to remove the entire `effects` attribute from a node, including spread entries in its inline array. The node must have at least one effect. Selecting every effect individually also removes the attribute when its array becomes empty.++```ts twoslash title="delete-all-effects.ts"+import {deleteEffects, type CodemodProject, type JsxNodeReference} from '@remotion/codemods';++declare const project: CodemodProject;+declare const node: JsxNodeReference;+// ---cut---+const result = await deleteEffects({+ project,+ effects: [{...node, effectIndex: null}],+});+```## Return value@@ -56,6 +72,26 @@ An array of `{filePath, previousContents, nextContents}` file changes. A `null`An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).+### editDetails++An array with one entry per edited file.++#### filePath++The file's path in the project.++#### effectLabels++Display labels for the removed effects, such as `'blur()'`. Unsupported entries removed by `effectIndex: null` use `'effect'`.++#### logLines++One-based source lines for the removed effects, in the same order as `effectLabels`.++#### formatted++Whether the generated edit was formatted.+## ErrorsThrows or rejects when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.diff --git a/packages/docs/docs/codemods/duplicate-composition.mdx b/packages/docs/docs/codemods/duplicate-composition.mdxindex 69513520fe..ac7bcd3e18 100644--- a/packages/docs/docs/codemods/duplicate-composition.mdx+++ b/packages/docs/docs/codemods/duplicate-composition.mdx@@ -30,7 +30,7 @@ const result = duplicateComposition({console.log(result);```-Both registrations reference the same component implementation. Default props and other registration props are copied. The original registration kind is preserved: a [`<Still>`](/docs/still) remains a [`<Still>`](/docs/still).+Both registrations reference the same component implementation. Default props and other registration props are copied. By default, the original registration kind is preserved: a [`<Still>`](/docs/still) remains a [`<Still>`](/docs/still).[`<Still>`](/docs/still) registrations only support width and height overrides; supplying FPS or duration throws an error.@@ -42,7 +42,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### compositionFile-The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with their original import names and static IDs or folder names.+The project file containing the [`<Composition>`](/docs/composition) or [`<Still>`](/docs/still) registration. Static IDs, named import aliases, and namespace imports from `remotion` are supported.### compositionId@@ -56,6 +56,10 @@ The new ID, containing only letters, numbers, or hyphens. It must be unused in tOverrides for `width`, `height`, `fps`, and `durationInFrames`. Omitted values are copied from the original.+### tag?++`'Composition'` or `'Still'`. Defaults to the original registration kind. Choosing `'Still'` removes `fps` and `durationInFrames` from the copy. When converting a still to a composition, provide these values through `metadata`.+## Return valueReturns an object with the following properties.diff --git a/packages/docs/docs/codemods/get-jsx-node-props.mdx b/packages/docs/docs/codemods/get-jsx-node-props.mdxindex 45ede2e267..461199573f 100644--- a/packages/docs/docs/codemods/get-jsx-node-props.mdx+++ b/packages/docs/docs/codemods/get-jsx-node-props.mdx@@ -49,6 +49,14 @@ The JSX props to inspect. Use `children` for static text or a one-level path sucAn array of prop-name arrays indexed by effect position. By default, inline effect calls and their explicit configuration keys are discovered from source.+### assetKeys?++Prop names for which [`staticFile()`](/docs/staticfile) calls and `new Date()` expressions should be read as serialized asset and date values. Defaults to `[]`; these expressions are otherwise treated as computed.++### componentIdentity?++The expected component identity, such as `'dev.remotion.remotion.Sequence'`. Remotion imports are resolved through named aliases and namespace imports. Throws if the node now refers to a different component. Defaults to `null`, which skips this check.+### videoConfig?The composition's `width`, `height`, `fps`, and `durationInFrames`. Supply these to interpret supported expressions using [`useVideoConfig()`](/docs/use-video-config). By default, those runtime values are unknown.@@ -57,6 +65,10 @@ The composition's `width`, `height`, `fps`, and `durationInFrames`. Supply theseReturns an object with the following properties.+### canUpdate++Always `true` when inspection succeeds. Check each prop's `status` and each effect's `canUpdate` before editing; this value does not mean every prop is static.+### propsA record keyed by the requested names. Each value has `status: 'static'` with `codeValue`, `status: 'keyframed'` with keyframes and interpolation settings, or `status: 'computed'` when the value cannot be statically understood. A missing prop is static with `codeValue: undefined`.@@ -67,7 +79,7 @@ An array of effect descriptions. Editable entries include `canUpdate: true`, `ef## Errors-Throws when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.+Throws when the target cannot be resolved, its component identity does not match, or the source cannot be parsed. Computed prop values are reported in `props` rather than causing an error.## Compatibilitydiff --git a/packages/docs/docs/codemods/move-composition.mdx b/packages/docs/docs/codemods/move-composition.mdxindex 67ca96febd..15088267ac 100644--- a/packages/docs/docs/codemods/move-composition.mdx+++ b/packages/docs/docs/codemods/move-composition.mdx@@ -39,7 +39,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### compositionFile-The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with their original import names and static IDs or folder names.+The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with static IDs or folder names. Aliased and namespace imports from `remotion` are supported.### compositionIddiff --git a/packages/docs/docs/codemods/move-folder.mdx b/packages/docs/docs/codemods/move-folder.mdxindex 23e5c95faf..3431fcc9b8 100644--- a/packages/docs/docs/codemods/move-folder.mdx+++ b/packages/docs/docs/codemods/move-folder.mdx@@ -39,7 +39,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### compositionFile-The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with their original import names and static IDs or folder names.+The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with static IDs or folder names. Aliased and namespace imports from `remotion` are supported.### folderdiff --git a/packages/docs/docs/codemods/rename-composition.mdx b/packages/docs/docs/codemods/rename-composition.mdxindex cb1588feed..281db74ceb 100644--- a/packages/docs/docs/codemods/rename-composition.mdx+++ b/packages/docs/docs/codemods/rename-composition.mdx@@ -39,7 +39,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### compositionFile-The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with their original import names and static IDs or folder names.+The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with static IDs or folder names. Aliased and namespace imports from `remotion` are supported.### compositionIddiff --git a/packages/docs/docs/codemods/rename-folder.mdx b/packages/docs/docs/codemods/rename-folder.mdxindex d8e2c3c66f..259fb128cf 100644--- a/packages/docs/docs/codemods/rename-folder.mdx+++ b/packages/docs/docs/codemods/rename-folder.mdx@@ -39,7 +39,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### compositionFile-The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with their original import names and static IDs or folder names.+The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with static IDs or folder names. Aliased and namespace imports from `remotion` are supported.### folderdiff --git a/packages/docs/docs/codemods/set-composition-default-props.mdx b/packages/docs/docs/codemods/set-composition-default-props.mdxindex efcc604d25..39a0a80bc6 100644--- a/packages/docs/docs/codemods/set-composition-default-props.mdx+++ b/packages/docs/docs/codemods/set-composition-default-props.mdx@@ -39,7 +39,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### compositionFile-The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with their original import names and static IDs or folder names.+The project file containing the [`<Composition>`](/docs/composition) or [`<Still>`](/docs/still) registration. Static IDs, named import aliases, and namespace imports from `remotion` are supported.### compositionId@@ -49,6 +49,10 @@ The static ID of the composition to edit.The complete replacement object of serializable prop values. This replaces the object rather than merging it.+### enumPaths?++Paths whose values should be written with an `as const` assertion to preserve literal types. For example, `[['mode']]` writes a string `mode` value as `'value' as const`. Use `'[]'` to match array indices and `'{}'` to match object keys, such as `[['items', '[]', 'mode']]`. By default, no assertions are added.+## Return valueReturns an object with the following properties.@@ -69,6 +73,10 @@ An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path iThe composition registration's node reference.+### logLine++The one-based line of the composition registration in the input source.+## ErrorsThrows when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.diff --git a/packages/docs/docs/codemods/table-of-contents.tsx b/packages/docs/docs/codemods/table-of-contents.tsxindex 11e85ca204..1c7a30e348 100644--- a/packages/docs/docs/codemods/table-of-contents.tsx+++ b/packages/docs/docs/codemods/table-of-contents.tsx@@ -5,6 +5,12 @@ import {TOCItem} from '../../components/TableOfContents/TOCItem';export const TableOfContents: React.FC = () => {return (<Grid>+ <TOCItem link="/docs/codemods/add-canvas-capture-composition">+ <strong>addCanvasCaptureComposition()</strong>+ <div>+ Creates and registers an interactive Canvas Capture component.+ </div>+ </TOCItem><TOCItem link="/docs/codemods/add-component"><strong>addComponent()</strong><div>@@ -165,6 +171,16 @@ export const TableOfContents: React.FC = () => {children.</div></TOCItem>+ <TOCItem link="/docs/codemods/update-multiple-jsx-node-props">+ <strong>updateMultipleJsxNodeProps()</strong>+ <div>Updates props on multiple JSX nodes in one operation.</div>+ </TOCItem>+ <TOCItem link="/docs/codemods/update-visual-controls">+ <strong>updateVisualControls()</strong>+ <div>+ Updates visual control defaults while preserving surrounding source.+ </div>+ </TOCItem></Grid>);};diff --git a/packages/docs/docs/codemods/unwrap-folder.mdx b/packages/docs/docs/codemods/unwrap-folder.mdxindex bd10c71269..f5de09ea2d 100644--- a/packages/docs/docs/codemods/unwrap-folder.mdx+++ b/packages/docs/docs/codemods/unwrap-folder.mdx@@ -38,7 +38,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### compositionFile-The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with their original import names and static IDs or folder names.+The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with static IDs or folder names. Aliased and namespace imports from `remotion` are supported.### folderdiff --git a/packages/docs/docs/codemods/update-composition-metadata.mdx b/packages/docs/docs/codemods/update-composition-metadata.mdxindex 1462a618b3..70a85315b9 100644--- a/packages/docs/docs/codemods/update-composition-metadata.mdx+++ b/packages/docs/docs/codemods/update-composition-metadata.mdx@@ -41,7 +41,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project### compositionFile-The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with their original import names and static IDs or folder names.+The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with static IDs or folder names. Aliased and namespace imports from `remotion` are supported.### compositionIddiff --git a/packages/docs/docs/codemods/update-effect-props.mdx b/packages/docs/docs/codemods/update-effect-props.mdxindex 554a1b1bda..f67a06da56 100644--- a/packages/docs/docs/codemods/update-effect-props.mdx+++ b/packages/docs/docs/codemods/update-effect-props.mdx@@ -41,9 +41,29 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input projectAn [`EffectReference`](/docs/codemods#effect-references): `filePath`, `nodePath`, and a zero-based `effectIndex` in the node's inline `effects` array.-### props+### props?-A non-empty record of serializable values. Keys must be JavaScript identifiers. Computed values are rejected; recognized keyframed values are replaced with static values.+A non-empty record of serializable values. Keys must be JavaScript identifiers. Computed values are rejected; recognized keyframed values are replaced with static values. Provide exactly one of `props` or `updates`.++### updates?++A non-empty array of explicit effect prop edits. Use this form to reset a prop to its default or paste a structured animation. Unlike `props`, this form permits replacing computed prop values. The effect call and its configuration must still be editable.++#### key++The effect prop name. Must be a JavaScript identifier.++#### value++The replacement value. Provide exactly one of `value` or `effectParam` for each update.++#### effectParam++A structured static or keyframed parameter to paste instead of `value`. Required animation imports are added.++#### defaultValue++The effect prop's default value, or `null` when no default is known. An explicit prop is removed when `value` equals a non-null default.### schema?@@ -69,6 +89,38 @@ An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path iThe effect reference in the updated project.+### results++One entry per prop update, in input order.++#### oldValueString++The previous source value, or the supplied default when the prop was absent.++#### newValueString++The replacement expression, or the supplied default when an explicit prop was removed.++#### removedProps++An array of `{key, valueString}` entries for additional props removed when a schema enum changes variants.++#### effectCallee++The effect call's name in the source.++#### logLine++The one-based line of the effect call in the source before this update.++#### output++The file contents after this prop update. The final project contains the result after all updates.++#### formatted++Whether the generated edit was formatted.+## ErrorsThrows or rejects when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.diff --git a/packages/docs/docs/codemods/update-jsx-node-props.mdx b/packages/docs/docs/codemods/update-jsx-node-props.mdxindex e896da9f22..dbb1b59ed7 100644--- a/packages/docs/docs/codemods/update-jsx-node-props.mdx+++ b/packages/docs/docs/codemods/update-jsx-node-props.mdx@@ -29,7 +29,7 @@ const result = updateJsxNodeProps({console.log(result);```-Throws for computed props, including props potentially overridden by a spread. Setting a keyframed prop replaces the animation with the supplied static value; use [`updateJsxNodeKeyframes()`](/docs/codemods/update-jsx-node-keyframes) to edit its animation. Unchanged surrounding source is preserved.+The `props` form rejects computed props, including props potentially overridden by a spread. Setting a keyframed prop replaces the animation with the supplied static value; use [`updateJsxNodeKeyframes()`](/docs/codemods/update-jsx-node-keyframes) to edit its animation. Unchanged surrounding source is preserved.## Options@@ -41,9 +41,33 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input projectA [`JsxNodeReference`](/docs/codemods#node-references) from [`getJsxNodes()`](/docs/codemods/get-jsx-nodes) or a previous operation. It contains `filePath` and `nodePath`.-### props+### props?-A record of new values, such as `{from: 30, 'style.opacity': 0.5}`. A value of `undefined` removes the prop or nested property. Only one level of nested keys is supported. Use `children` to replace static text.+A non-empty record of new values, such as `{from: 30, 'style.opacity': 0.5}`. A value of `undefined` removes the prop or nested property. Only one level of nested keys is supported. Use `children` to replace static text. Provide exactly one of `props` or `updates`.++### updates?++A non-empty array of explicit prop edits. Use this form to remove a value when it matches a known default or to paste a structured animation. Unlike `props`, this form permits replacing computed prop values.++#### key++The prop name, `children`, or a one-level nested path such as `style.opacity`.++#### value++The new value. Set to `undefined` with `defaultValue: null` to remove the prop.++#### defaultValue++The component's default value, or `null` when no default is known. An explicit prop is removed when its new value equals a non-null default.++#### googleFont?++A Google Font selection with `fontFamily`, `importName`, `style`, `weights`, and `subsets`. Adds the font import and loading code needed for the selected font. Defaults to no font source edit.++#### clipboardParam?++A structured static or keyframed parameter to paste. When supplied, its expression is used instead of `value`, and the required animation imports are added. Defaults to no pasted parameter.### schema?@@ -53,6 +77,10 @@ A Remotion `InteractivitySchema` for schema-specific defaults and enum variants.The composition's `width`, `height`, `fps`, and `durationInFrames`. Supply these to interpret supported expressions using [`useVideoConfig()`](/docs/use-video-config). By default, those runtime values are unknown.+### prettierConfigOverride?++Formatting options for generated source. Defaults to `null`, which follows the existing source style.+## Return valueReturns an object with the following properties.@@ -73,6 +101,34 @@ An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path iThe edited node's reference in the new project.+### oldValueStrings++The previous source values in update order, for displaying the changes.++### removedProps++An array of `{key, valueString}` entries for additional props removed when a schema enum changes variants.++### logLine++The one-based line of the JSX opening tag in the input source.++### newNodePath++The edited node's path in the updated source.++### formatted++`true` when the edit succeeds. Generated source follows the selected formatting options.++### results++A one-element array containing `oldValueStrings`, `removedProps`, `logLine`, and `newNodePath`. This matches the per-node results returned by [`updateMultipleJsxNodeProps()`](/docs/codemods/update-multiple-jsx-node-props).++### updatedNodes++A one-element array containing `updatedNode`.+## ErrorsThrows when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.diff --git a/packages/docs/docs/codemods/update-multiple-jsx-node-props.mdx b/packages/docs/docs/codemods/update-multiple-jsx-node-props.mdxnew file mode 100644index 0000000000..52c712df77--- /dev/null+++ b/packages/docs/docs/codemods/update-multiple-jsx-node-props.mdx@@ -0,0 +1,104 @@+---+image: /generated/articles-docs-codemods-update-multiple-jsx-node-props.png+title: 'updateMultipleJsxNodeProps()'+crumb: '@remotion/codemods'+---++# updateMultipleJsxNodeProps()<AvailableFrom v="4.0.528" />++Updates props on multiple JSX nodes across project files in one operation. Node references refer to the input project; the result includes their new paths.++:::warning++_Draft API_: This API is experimental and may change.++:::++```ts twoslash title="update-multiple-jsx-node-props.ts"+import {updateMultipleJsxNodeProps, type CodemodProject, type JsxNodeReference} from '@remotion/codemods';++declare const project: CodemodProject;+declare const title: JsxNodeReference;+declare const background: JsxNodeReference;++const result = updateMultipleJsxNodeProps({+ project,+ changes: [+ {node: title, props: {children: 'Hello'}},+ {node: background, props: {'style.opacity': 0.5}},+ ],+});++console.log(result.project, result.updatedNodes);+```++## Options++### project++An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project is not mutated.++### changes++A non-empty array of node edits.++#### node++The [`JsxNodeReference`](/docs/codemods#node-references) to edit, containing `filePath` and `nodePath`.++#### props++A record of prop values, such as `{from: 30, 'style.opacity': 0.5}`. A value of `undefined` removes a prop. Supply either `props` or `updates` for each edit.++#### updates++Structured [`SequencePropUpdate`](/docs/codemods/update-jsx-node-props#updates) entries for edits that need default values, enum handling, or other update metadata. Supply this instead of `props`.++#### schema?++A Remotion `InteractivitySchema` for schema-specific defaults and enum variants. By default, no schema-specific behavior is applied.++#### videoConfig?++The composition's `width`, `height`, `fps`, and `durationInFrames`, for evaluating supported expressions. By default, those runtime values are unknown.++### prettierConfigOverride?++Formatting options for inserted or changed source. By default, formatting is inferred from the source.++If any edit fails, no updated project is returned and the input project remains unchanged.++## Return value++### project++The updated project. Unchanged files and extra project fields are preserved.++### changes++An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.++### nodePathRemappings++An array of `{filePath, oldNodePath, newNodePath}` mappings. See [node references](/docs/codemods#node-references).++### updatedNodes++Updated node references in the same order as the requested edits.++### results++Per-node edit details in the same order as the requested edits: `oldValueStrings`, `logLine`, `removedProps`, and `newNodePath`. See [`updateJsxNodeProps()`](/docs/codemods/update-jsx-node-props).++### formatted++`true` when the operation succeeds.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />++## See also++- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/update-jsx-node-props.ts)+- [`@remotion/codemods`](/docs/codemods)diff --git a/packages/docs/docs/codemods/update-visual-controls.mdx b/packages/docs/docs/codemods/update-visual-controls.mdxnew file mode 100644index 0000000000..100c9c1c66--- /dev/null+++ b/packages/docs/docs/codemods/update-visual-controls.mdx@@ -0,0 +1,89 @@+---+image: /generated/articles-docs-codemods-update-visual-controls.png+title: 'updateVisualControls()'+crumb: '@remotion/codemods'+---++# updateVisualControls()<AvailableFrom v="4.0.528" />++Updates the default values of [`visualControl()`](/docs/studio/visual-control) calls in a source file while preserving surrounding source.++:::warning++_Draft API_: This API is experimental and may change.++:::++```ts twoslash title="update-visual-controls.ts"+import {updateVisualControls, type CodemodProject} from '@remotion/codemods';++declare const project: CodemodProject;++const result = updateVisualControls({+ project,+ filePath: 'src/Video.tsx',+ changes: [+ {+ id: 'opacity',+ newValueSerialized: JSON.stringify(0.5),+ newValueIsUndefined: false,+ enumPaths: [],+ },+ ],+});++console.log(result.project, result.updatedControls);+```++## Options++### project++An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project is not mutated.++### filePath++The project source file containing the `visualControl()` calls.++### changes++An array of requested value changes. Calls are matched by a static string or template-literal identifier. If an identifier has multiple requested changes, the last value wins. Identifiers with no matching call leave the source unchanged.++#### id++The visual control identifier.++#### newValueSerialized++The new value serialized as JSON. Ignored when `newValueIsUndefined` is `true`.++#### newValueIsUndefined++Whether to write `undefined` as the default value.++#### enumPaths++Paths within the value to preserve as enum literals with `as const`. Each path is an array of string keys or numeric indices. Use `[]` for no enum values, or `[[]]` when the whole value is an enum literal.++## Return value++### project++The updated project. Unchanged files and extra project fields are preserved.++### changes++An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.++### updatedControls++An array of `{id, line}` entries for the requested changes that matched a call. `line` is the call's one-based source line. A matched call can be reported even if its value was already equal to the requested value.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />++## See also++- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/update-visual-controls.ts)+- [`@remotion/codemods`](/docs/codemods)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 3b9a05f216..96073a98ce 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -2053,6 +2053,7 @@ const sidebars: SidebarsConfig = {id: 'codemods/index',},items: [+ 'codemods/add-canvas-capture-composition','codemods/add-component','codemods/add-composition','codemods/add-effect',@@ -2083,6 +2084,8 @@ const sidebars: SidebarsConfig = {'codemods/update-effect-props','codemods/update-jsx-node-keyframes','codemods/update-jsx-node-props',+ 'codemods/update-multiple-jsx-node-props',+ 'codemods/update-visual-controls',],},],diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex 82efe05125..a8a940d1c0 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -1404,6 +1404,15 @@ export const articles = [noAi: false,slug: 'cloudrun/upgrading',},+ {+ id: 'codemods/add-canvas-capture-composition',+ title: 'addCanvasCaptureComposition()',+ relativePath: 'docs/codemods/add-canvas-capture-composition.mdx',+ compId: 'articles-docs-codemods-add-canvas-capture-composition',+ crumb: '@remotion/codemods',+ noAi: false,+ slug: 'codemods/add-canvas-capture-composition',+ },{id: 'codemods/add-component',title: 'addComponent()',@@ -1683,6 +1692,24 @@ export const articles = [noAi: false,slug: 'codemods/update-jsx-node-props',},+ {+ id: 'codemods/update-multiple-jsx-node-props',+ title: 'updateMultipleJsxNodeProps()',+ relativePath: 'docs/codemods/update-multiple-jsx-node-props.mdx',+ compId: 'articles-docs-codemods-update-multiple-jsx-node-props',+ crumb: '@remotion/codemods',+ noAi: false,+ slug: 'codemods/update-multiple-jsx-node-props',+ },+ {+ id: 'codemods/update-visual-controls',+ title: 'updateVisualControls()',+ relativePath: 'docs/codemods/update-visual-controls.mdx',+ compId: 'articles-docs-codemods-update-visual-controls',+ crumb: '@remotion/codemods',+ noAi: false,+ slug: 'codemods/update-visual-controls',+ },{id: 'color-correction',title: 'Color correction',diff --git a/packages/docs/static/generated/articles-docs-codemods-add-canvas-capture-composition.png b/packages/docs/static/generated/articles-docs-codemods-add-canvas-capture-composition.pngnew file mode 100644index 0000000000..6e160eaaaeBinary files /dev/null and b/packages/docs/static/generated/articles-docs-codemods-add-canvas-capture-composition.png differdiff --git a/packages/docs/static/generated/articles-docs-codemods-update-multiple-jsx-node-props.png b/packages/docs/static/generated/articles-docs-codemods-update-multiple-jsx-node-props.pngnew file mode 100644index 0000000000..9e698ccf80Binary files /dev/null and b/packages/docs/static/generated/articles-docs-codemods-update-multiple-jsx-node-props.png differdiff --git a/packages/docs/static/generated/articles-docs-codemods-update-visual-controls.png b/packages/docs/static/generated/articles-docs-codemods-update-visual-controls.pngnew file mode 100644index 0000000000..d675596c07Binary files /dev/null and b/packages/docs/static/generated/articles-docs-codemods-update-visual-controls.png differdiff --git a/packages/it-tests/package.json b/packages/it-tests/package.jsonindex a839a79477..600d3b8758 100644--- a/packages/it-tests/package.json+++ b/packages/it-tests/package.json@@ -22,6 +22,7 @@"@types/node": "catalog:","@remotion/bundler": "workspace:*","@remotion/cli": "workspace:*",+ "@remotion/codemods": "workspace:*","@remotion/lambda": "workspace:*","@remotion/lambda-client": "workspace:*","@remotion/compositor-darwin-arm64": "workspace:*",diff --git a/packages/it-tests/src/codemods/codemods.test.ts b/packages/it-tests/src/codemods/codemods.test.tsindex 289c083cc5..1539164615 100644--- a/packages/it-tests/src/codemods/codemods.test.ts+++ b/packages/it-tests/src/codemods/codemods.test.ts@@ -1,9 +1,15 @@import {expect, test} from 'bun:test';import {readFileSync} from 'fs';import {resolve} from 'path';-import {StudioServerInternals} from '@remotion/studio-server';+import {+ deleteComposition,+ duplicateComposition,+ getJsxNodeProps,+ getJsxNodes,+ renameComposition,+} from '@remotion/codemods';-const rootFile = resolve(+const compositionFile = resolve(__dirname,'..','..',@@ -12,147 +18,96 @@ const rootFile = resolve('src','CodemodTestbed.tsx',);+const contents = readFileSync(compositionFile, 'utf-8');+const original = {rootDir: '/', files: {[compositionFile]: contents}};-const getCompositionCount = (comp: string) => {- const lines = comp.split('\n');- const compositions = lines.filter(- (l) => l.includes('<Composition') || l.includes('<Still'),- );- return compositions.length;-};--const contents = readFileSync(rootFile, 'utf-8');-const compCount = getCompositionCount(contents);--test('Should be able to delete composition', () => {- expect(contents).toContain('"one"');-- const {changesMade, newContents} = StudioServerInternals.parseAndApplyCodemod(- {- input: contents,- codeMod: {- type: 'delete-composition',- idToDelete: 'one',- },- },- );- expect(changesMade.length).toBe(1);- expect(getCompositionCount(newContents)).toBe(compCount - 1);- expect(newContents).not.toContain('"one"');-});--test('Should be able to rename composition', () => {- const {changesMade, newContents} = StudioServerInternals.parseAndApplyCodemod(- {- input: contents,- codeMod: {- type: 'rename-composition',- idToRename: 'one',- newId: 'abc',- },- },+test('edits composition registrations through the packaged public API', () => {+ let {project} = renameComposition({+ project: original,+ compositionFile,+ compositionId: 'one',+ newId: 'Renamed',+ });+ expect(project.files[compositionFile]).toBe(+ contents.replace('id="one"', 'id="Renamed"'),);- expect(changesMade.length).toBe(1);- expect(getCompositionCount(newContents)).toBe(compCount);- expect(newContents).not.toContain('"one"');- expect(newContents).toContain('"abc"');-});+ project = duplicateComposition({+ project,+ compositionFile,+ compositionId: 'Renamed',+ newId: 'Copy',+ metadata: {width: 998, height: 999, fps: 24, durationInFrames: 200},+ }).project;+ project = duplicateComposition({+ project,+ compositionFile,+ compositionId: 'Copy',+ newId: 'Poster',+ tag: 'Still',+ metadata: {width: 500, height: 400},+ }).project;-test('Should be able to duplicate composition', () => {- const {newContents} = StudioServerInternals.parseAndApplyCodemod({- input: contents,- codeMod: {- type: 'duplicate-composition',- idToDuplicate: 'one',- newDurationInFrames: 200,- newFps: 24,- newHeight: 999,- newWidth: 998,- newId: 'def',- tag: 'Composition',- },+ const registrations = getJsxNodes({project, filePath: compositionFile})+ .filter(+ (node) => node.tagName === 'Composition' || node.tagName === 'Still',+ )+ .map((node) => ({+ tagName: node.tagName,+ props: getJsxNodeProps({+ project,+ node,+ keys: ['id', 'width', 'height', 'fps', 'durationInFrames'],+ }).props,+ }));+ expect(registrations).toContainEqual({+ tagName: 'Composition',+ props: expect.objectContaining({+ id: expect.objectContaining({codeValue: 'Copy'}),+ width: expect.objectContaining({codeValue: 998}),+ height: expect.objectContaining({codeValue: 999}),+ fps: expect.objectContaining({codeValue: 24}),+ durationInFrames: expect.objectContaining({codeValue: 200}),+ }),});-- expect(getCompositionCount(newContents)).toBe(compCount + 1);- expect(newContents).toContain('"def"');- expect(newContents).toContain('width={998}');- expect(newContents).toContain('height={999}');- expect(newContents).toContain('fps={24}');- expect(newContents).toContain('durationInFrames={200}');-});--test('Should be able to duplicate composition into a still', () => {- const {newContents} = StudioServerInternals.parseAndApplyCodemod({- input: contents,- codeMod: {- type: 'duplicate-composition',- idToDuplicate: 'one',- newDurationInFrames: 200,- newFps: 24,- newHeight: 999,- newWidth: 998,- newId: 'def',- tag: 'Still',- },+ expect(registrations).toContainEqual({+ tagName: 'Still',+ props: expect.objectContaining({+ id: expect.objectContaining({codeValue: 'Poster'}),+ width: expect.objectContaining({codeValue: 500}),+ height: expect.objectContaining({codeValue: 400}),+ fps: expect.objectContaining({status: 'static', codeValue: undefined}),+ durationInFrames: expect.objectContaining({+ status: 'static',+ codeValue: undefined,+ }),+ }),});-- expect(getCompositionCount(newContents)).toBe(compCount + 1);- expect(newContents).toContain('"def"');- expect(newContents).toContain('width={998}');- expect(newContents).toContain('height={999}');- expect(newContents).not.toContain('fps={24}');- expect(newContents).not.toContain('durationInFrames={200}');-});--test('Should be able to recognize non-arrow function', () => {- const {changesMade, newContents} = StudioServerInternals.parseAndApplyCodemod(- {- input: contents,- codeMod: {- type: 'rename-composition',- idToRename: 'four',- newId: 'ghi',- },- },- );- expect(changesMade.length).toBe(1);- expect(getCompositionCount(newContents)).toBe(compCount);- expect(newContents).not.toContain('"four"');- expect(newContents).toContain('"ghi"');+ project = deleteComposition({+ project,+ compositionFile,+ compositionId: 'Renamed',+ }).project;+ expect(project.files[compositionFile]).not.toContain('id="Renamed"');+ expect(project.files[compositionFile]).toContain('id="Copy"');+ expect(project.files[compositionFile]).toContain('id="Poster"');+ expect(original.files[compositionFile]).toBe(contents);});-// test.todo('should work if there is no fragment');--test('in non-return statement', () => {- const {changesMade, newContents} = StudioServerInternals.parseAndApplyCodemod(- {- input: contents,- codeMod: {- type: 'rename-composition',- idToRename: 'six',- newId: 'jkl',- },- },- );- expect(changesMade.length).toBe(1);- expect(getCompositionCount(newContents)).toBe(compCount);- expect(newContents).not.toContain('"six"');- expect(newContents).toContain('"jkl"');-});--test("curly braces id={'seven'}", () => {- const {changesMade, newContents} = StudioServerInternals.parseAndApplyCodemod(- {- input: contents,- codeMod: {- type: 'rename-composition',- idToRename: 'seven',- newId: 'mno',- },- },- );- expect(changesMade.length).toBe(1);- expect(getCompositionCount(newContents)).toBe(compCount);- expect(newContents).not.toContain('"seven"');- expect(newContents).toBe(contents.replace("id={'seven'}", "id={'mno'}"));+test('renames registrations in functions, variables, and expression attributes', () => {+ let project = original;+ let expected = contents;+ for (const [compositionId, newId, before, after] of [+ ['four', 'Function', 'id="four"', 'id="Function"'],+ ['six', 'Variable', 'id="six"', 'id="Variable"'],+ ['seven', 'Expression', "id={'seven'}", "id={'Expression'}"],+ ]) {+ project = renameComposition({+ project,+ compositionFile,+ compositionId,+ newId,+ }).project;+ expected = expected.replace(before, after);+ expect(project.files[compositionFile]).toBe(expected);+ }});diff --git a/packages/it-tests/src/codemods/visual-controls.test.ts b/packages/it-tests/src/codemods/visual-controls.test.tsindex e0e9726693..34f60bd459 100644--- a/packages/it-tests/src/codemods/visual-controls.test.ts+++ b/packages/it-tests/src/codemods/visual-controls.test.ts@@ -1,5 +1,5 @@import {expect, test} from 'bun:test';-import {StudioServerInternals} from '@remotion/studio-server';+import {updateVisualControls} from '@remotion/codemods';const contents = `import {makeTransform, matrix3d} from '@remotion/animation-utils';@@ -36,30 +36,30 @@ export const VisualControls = () => {};`;-test('Should be able to create visual control', () => {- const {newContents} = StudioServerInternals.parseAndApplyCodemod({- input: contents,- codeMod: {- type: 'apply-visual-control',- changes: [- {- id: 'my-matrix-4',- newValueSerialized: JSON.stringify(123),- newValueIsUndefined: false,- enumPaths: [],- },- {- id: 'my-matrix-2',- newValueSerialized: JSON.stringify(456),- newValueIsUndefined: false,- enumPaths: [[]],- },- ],- },+test('updates multiple visual controls through the packaged public API', () => {+ const {project} = updateVisualControls({+ project: {rootDir: '/', files: {'Root.tsx': contents}},+ filePath: 'Root.tsx',+ changes: [+ {+ id: 'my-matrix-4',+ newValueSerialized: JSON.stringify(123),+ newValueIsUndefined: false,+ enumPaths: [],+ },+ {+ id: 'my-matrix-2',+ newValueSerialized: JSON.stringify(456),+ newValueIsUndefined: false,+ enumPaths: [[]],+ },+ ],});- expect(newContents).toContain(`visualControl('my-matrix-4', 123`);- expect(newContents).toContain(+ expect(project.files['Root.tsx']).toContain(+ `visualControl('my-matrix-4', 123`,+ );+ expect(project.files['Root.tsx']).toContain('const matrix2 = visualControl(`my-matrix-2`, 456 as const',);});diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.tsindex b266b7aa58..560de19c9a 100644--- a/packages/studio-server/src/index.ts+++ b/packages/studio-server/src/index.ts@@ -23,14 +23,12 @@ export type {UiOpenGlOptions,} from '@remotion/studio-shared';-import {CodemodsInternals} from '@remotion/codemods';import {AnsiDiff} from './ansi-diff';import {addCompletedClientRender,getCompletedClientRenders,removeCompletedClientRender,} from './client-render-queue';-import {applyCodemodToFile} from './codemods/apply-codemod-to-file';import {detectOutdatedRemotionSkills,parseRemotionSkillVersion,@@ -64,8 +62,6 @@ import {getRemotionVersion} from './preview-server/update-available';import {remotionSkillNames} from './remotion-skill-names';import {startStudio} from './start-studio';-const {updateDefaultProps} = CodemodsInternals;-export type {RemotionSkillsScope,RemotionSkillsStatus,@@ -94,8 +90,6 @@ export const StudioServerInternals = {setFileWatcherRegistry,AnsiDiff,formatBytes,- applyCodemodToFile,- updateDefaultProps,getInstalledDependencies,getInstalledDependenciesWithVersions,getInstallCommand,diff --git a/packages/studio-server/src/test/apply-codemod.test.ts b/packages/studio-server/src/test/apply-codemod.test.tsindex 6eb74cff9e..ae8bceef73 100644--- a/packages/studio-server/src/test/apply-codemod.test.ts+++ b/packages/studio-server/src/test/apply-codemod.test.ts@@ -8,7 +8,6 @@ import {} from 'node:fs';import {tmpdir} from 'node:os';import path from 'node:path';-import {CodemodsInternals} from '@remotion/codemods';import type {RecastCodemod} from '@remotion/studio-shared';import {applyCodemodToFile} from '../codemods/apply-codemod-to-file';import {@@ -25,8 +24,6 @@ import {redoHandler} from '../preview-server/routes/redo';import {undoHandler} from '../preview-server/routes/undo';import {getRedoStack, getUndoStack} from '../preview-server/undo-stack';-const {parseAndApplyCodemod} = CodemodsInternals;-const rootContents = `import React from 'react';import {Composition} from 'remotion';@@ -93,97 +90,6 @@ export const RemotionRoot: React.FC = () => {};`;-const selfClosingFolderRootContents = `import React from 'react';-import {Composition, Folder} from 'remotion';--const Component = () => null;--export const RemotionRoot: React.FC = () => {- return (- <>- <Folder name="Empty" />- <Composition- id="KeepMe"- component={Component}- durationInFrames={120}- fps={30}- width={1280}- height={720}- />- </>- );-};-`;--const attributeFolderRootContents = `import React from 'react';-import {Composition, Folder} from 'remotion';--const Component = () => null;--export const RemotionRoot: React.FC = () => {- return (- <>- <Folder- name="Parent"- preview={<Folder name="Shared" />}- />- <Composition- id="MoveMe"- component={Component}- durationInFrames={120}- fps={30}- width={1280}- height={720}- />- </>- );-};-`;--const standaloneCompositionRootContents = `import React from 'react';-import {Composition} from 'remotion';--const Component = () => null;--export const RemotionRoot: React.FC = () => {- return (- <Composition- id="Standalone"- component={Component}- durationInFrames={120}- fps={30}- width={1280}- height={720}- />- );-};-`;--const folderRootWithEarlierComponentContents = `import React from 'react';-import {Composition, Folder} from 'remotion';--const Component = () => {- return <><div>Content</div></>;-};--export const RemotionRoot: React.FC = () => {- return (- <>- <Folder name="Parent">- <Composition- id="Nested"- component={Component}- durationInFrames={120}- fps={30}- width={1280}- height={720}- />- </Folder>- </>- );-};-`;-const clearUndoRedoStacks = () => {(getUndoStack() as unknown as unknown[]).length = 0;(getRedoStack() as unknown as unknown[]).length = 0;@@ -210,7 +116,7 @@ export const Root = () => <Folder name="Before" />;},});- expect(output).toBe(input.replace('"Before"', '"After"'));+ expect(output.files[filePath]).toBe(input.replace('"Before"', '"After"'));} finally {rmSync(remotionRoot, {recursive: true, force: true});}@@ -219,7 +125,8 @@ export const Root = () => <Folder name="Before" />;test('metadata codemods do not run Prettier after applying source edits', async () => {const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));const filePath = path.join(remotionRoot, 'Root.tsx');- const input = `const untouched = { value : "keep" };+ const input = `import {Composition} from 'remotion';+const untouched = { value : "keep" };export const Root=()=> <Composition id='Comp' width = { WIDTH }/>;`;@@ -237,7 +144,8 @@ export const Root=()=> <Composition id='Comp' width = { WIDTH }/>;},});- expect(output).toBe(`const untouched = { value : "keep" };+ expect(output.files[filePath]).toBe(`import {Composition} from 'remotion';+const untouched = { value : "keep" };export const Root=()=> <Composition id='Comp' width = {1920} durationInFrames={90} height={1080}/>;`);} finally {@@ -269,7 +177,7 @@ export const Root=()=> visualControl('opacity', OPACITY);},});- expect(output).toBe(input.replace('OPACITY', '0.5'));+ expect(output.files[filePath]).toBe(input.replace('OPACITY', '0.5'));} finally {rmSync(remotionRoot, {recursive: true, force: true});}@@ -631,26 +539,34 @@ test('applyCodemodHandler logs composition renames and pushes them to the undo a});});-test('applyCodemodHandler pushes composition duplications to undo and redo stacks', async () => {- await runCompositionCodemodUndoRedoTest({- codemod: {- type: 'duplicate-composition',- idToDuplicate: 'DeleteMe',- newId: 'Duplicated',- newDurationInFrames: null,- newFps: null,- newHeight: null,- newWidth: null,- tag: 'Composition',- },- assertApplied: (contents) => {- expect(contents).toContain('id="DeleteMe"');- expect(contents).toContain('id="Duplicated"');- expect(contents).toContain('id="KeepMe"');- },- expectedUndoMessage:- '↩️ Duplication of composition "DeleteMe" to "Duplicated"',- });+test('applyCodemodHandler pushes composition and still duplications to undo and redo stacks', async () => {+ for (const tag of ['Composition', 'Still'] as const) {+ await runCompositionCodemodUndoRedoTest({+ codemod: {+ type: 'duplicate-composition',+ idToDuplicate: 'DeleteMe',+ newId: 'Duplicated',+ newDurationInFrames: 120,+ newFps: 30,+ newHeight: null,+ newWidth: null,+ tag,+ },+ assertApplied: (contents) => {+ expect(contents).toContain('id="DeleteMe"');+ expect(contents).toContain('id="Duplicated"');+ expect(contents).toContain('id="KeepMe"');+ if (tag === 'Still') {+ const still = contents.match(/<Still[\s\S]*?\/>/)?.[0];+ expect(still).toContain('id="Duplicated"');+ expect(still).not.toContain('fps=');+ expect(still).not.toContain('durationInFrames=');+ }+ },+ expectedUndoMessage:+ '↩️ Duplication of composition "DeleteMe" to "Duplicated"',+ });+ }});test('applyCodemodHandler pushes folder creations to undo and redo stacks', async () => {@@ -1006,411 +922,3 @@ test('applyCodemodHandler creates an interactive Canvas Capture composition', asrmSync(remotionRoot, {recursive: true, force: true});}});--test('creates a composition in a top-level folder', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: folderRootContents,- codeMod: {- type: 'new-composition',- canvasCapture: null,- newId: 'FreshVideo',- componentName: 'FreshVideo',- componentImportPath: './FreshVideo',- folderName: 'Parent',- parentName: null,- newDurationInFrames: 150,- newFps: 30,- newHeight: 1080,- newWidth: 1920,- },- });-- expect(changesMade.length).toBe(1);- expect(newContents).toContain('id="FreshVideo"');- expect(newContents).toContain('component={FreshVideo}');- expect(newContents.indexOf('<Folder name="Parent">')).toBeLessThan(- newContents.indexOf('id="FreshVideo"'),- );- expect(newContents.indexOf('id="FreshVideo"')).toBeLessThan(- newContents.indexOf('<Folder name="Other">'),- );-});--test('creates a composition in a nested folder by parent path', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: folderRootContents,- codeMod: {- type: 'new-composition',- canvasCapture: null,- newId: 'FreshVideo',- componentName: 'FreshVideo',- componentImportPath: './FreshVideo',- folderName: 'Shared',- parentName: 'Other',- newDurationInFrames: 150,- newFps: 30,- newHeight: 1080,- newWidth: 1920,- },- });-- expect(changesMade.length).toBe(1);- expect(newContents).toContain('id="FreshVideo"');- expect(newContents.indexOf('id="NestedB"')).toBeLessThan(- newContents.indexOf('id="FreshVideo"'),- );- expect(newContents.indexOf('id="NestedA"')).toBeLessThan(- newContents.indexOf('id="NestedB"'),- );-});--test('creates a top-level folder', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: rootContents,- codeMod: {- type: 'new-folder',- folderName: 'FreshFolder',- parentName: null,- },- });-- expect(changesMade.length).toBe(1);- expect(newContents).toMatch(- /import\s*\{[^}]*Folder[^}]*\}\s*from\s*['"]remotion['"]/,- );- expect(newContents).toContain('<Folder name="FreshFolder" />');- expect(newContents.indexOf('id="KeepMe"')).toBeLessThan(- newContents.indexOf('<Folder name="FreshFolder" />'),- );-});--test('creates a folder in a nested folder by parent path', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: folderRootContents,- codeMod: {- type: 'new-folder',- folderName: 'FreshFolder',- parentName: 'Parent/Shared',- },- });-- expect(changesMade.length).toBe(1);- expect(newContents).toContain('<Folder name="FreshFolder" />');- expect(newContents.indexOf('id="NestedA"')).toBeLessThan(- newContents.indexOf('<Folder name="FreshFolder" />'),- );- expect(newContents.indexOf('<Folder name="FreshFolder" />')).toBeLessThan(- newContents.indexOf('<Folder name="Other">'),- );-});--test('creates a composition in a self-closing folder', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: selfClosingFolderRootContents,- codeMod: {- type: 'new-composition',- canvasCapture: null,- newId: 'FreshVideo',- componentName: 'FreshVideo',- componentImportPath: './FreshVideo',- folderName: 'Empty',- parentName: null,- newDurationInFrames: 150,- newFps: 30,- newHeight: 1080,- newWidth: 1920,- },- });-- expect(changesMade.length).toBe(1);- expect(newContents).toContain('<Folder name="Empty">');- expect(newContents).toContain('id="FreshVideo"');- expect(newContents.indexOf('<Folder name="Empty">')).toBeLessThan(- newContents.indexOf('id="FreshVideo"'),- );- expect(newContents.indexOf('id="FreshVideo"')).toBeLessThan(- newContents.indexOf('id="KeepMe"'),- );-});--test('moves a composition into a nested folder', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: folderRootContents,- codeMod: {- type: 'move-composition-to-folder',- idToMove: 'NestedA',- folderName: 'Shared',- parentName: 'Other',- },- });-- expect(changesMade.length).toBe(1);- expect(newContents.indexOf('id="NestedB"')).toBeLessThan(- newContents.indexOf('id="NestedA"'),- );- expect(newContents.match(/id="NestedA"/g)?.length).toBe(1);- expect(newContents.indexOf('<Folder name="Parent">')).toBeLessThan(- newContents.indexOf('<Folder name="Other">'),- );-});--test('moves a composition to root', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: folderRootContents,- codeMod: {- type: 'move-composition-to-folder',- idToMove: 'NestedA',- folderName: null,- parentName: null,- },- });-- expect(changesMade.length).toBe(1);- expect(newContents.indexOf('id="NestedB"')).toBeLessThan(- newContents.indexOf('id="NestedA"'),- );- expect(newContents.match(/id="NestedA"/g)?.length).toBe(1);-});--test('moves a composition to its registration root when another component appears first', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: folderRootWithEarlierComponentContents,- codeMod: {- type: 'move-composition-or-folder',- source: {type: 'composition', compositionId: 'Nested'},- destination: {type: 'root'},- },- });-- expect(changesMade).toHaveLength(1);- expect(newContents.match(/id="Nested"/g)).toHaveLength(1);- expect(newContents.indexOf('id="Nested"')).toBeGreaterThan(- newContents.indexOf('export const RemotionRoot'),- );- expect(newContents.indexOf('id="Nested"')).toBeGreaterThan(- newContents.indexOf('</Folder>'),- );-});--test('visually reorders compositions and folders', () => {- const compositionBeforeFolder = parseAndApplyCodemod({- input: selfClosingFolderRootContents,- codeMod: {- type: 'move-composition-or-folder',- source: {type: 'composition', compositionId: 'KeepMe'},- destination: {- type: 'before',- target: {type: 'folder', folderName: 'Empty', parentName: null},- },- },- });-- expect(compositionBeforeFolder.changesMade).toHaveLength(1);- expect(- compositionBeforeFolder.newContents.indexOf('id="KeepMe"'),- ).toBeLessThan(- compositionBeforeFolder.newContents.indexOf('<Folder name="Empty"'),- );-- const folderAfterComposition = parseAndApplyCodemod({- input: selfClosingFolderRootContents,- codeMod: {- type: 'move-composition-or-folder',- source: {type: 'folder', folderName: 'Empty', parentName: null},- destination: {- type: 'after',- target: {type: 'composition', compositionId: 'KeepMe'},- },- },- });-- expect(folderAfterComposition.changesMade).toHaveLength(1);- expect(- folderAfterComposition.newContents.indexOf('id="KeepMe"'),- ).toBeLessThan(- folderAfterComposition.newContents.indexOf('<Folder name="Empty"'),- );-});--test('moves a folder into another folder with its descendants', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: folderRootContents,- codeMod: {- type: 'move-composition-or-folder',- source: {type: 'folder', folderName: 'Parent', parentName: null},- destination: {- type: 'folder',- folderName: 'Shared',- parentName: 'Other',- },- },- });-- expect(changesMade).toHaveLength(1);- expect(newContents.match(/<Folder name="Parent">/g)).toHaveLength(1);- expect(newContents.match(/id="NestedA"/g)).toHaveLength(1);- expect(newContents.indexOf('id="NestedB"')).toBeLessThan(- newContents.indexOf('<Folder name="Parent">'),- );-});--test('rejects moving a folder into its descendant', () => {- expect(() =>- parseAndApplyCodemod({- input: folderRootContents,- codeMod: {- type: 'move-composition-or-folder',- source: {type: 'folder', folderName: 'Parent', parentName: null},- destination: {- type: 'folder',- folderName: 'Shared',- parentName: 'Parent',- },- },- }),- ).toThrow('A folder cannot be moved inside itself');-});--test('rejects duplicate folder names at the destination', () => {- expect(() =>- parseAndApplyCodemod({- input: folderRootContents,- codeMod: {- type: 'move-composition-or-folder',- source: {- type: 'folder',- folderName: 'Shared',- parentName: 'Parent',- },- destination: {- type: 'folder',- folderName: 'Other',- parentName: null,- },- },- }),- ).toThrow('A folder named "Shared" already exists in the destination');-});--test('does not use folders inside JSX attributes as move targets', () => {- expect(() =>- parseAndApplyCodemod({- input: attributeFolderRootContents,- codeMod: {- type: 'move-composition-to-folder',- idToMove: 'MoveMe',- folderName: 'Shared',- parentName: 'Parent',- },- }),- ).toThrow('Could not find folder "Parent/Shared"');-});--test('rejects moving a composition from a standalone JSX position', () => {- expect(() =>- parseAndApplyCodemod({- input: standaloneCompositionRootContents,- codeMod: {- type: 'move-composition-to-folder',- idToMove: 'Standalone',- folderName: null,- parentName: null,- },- }),- ).toThrow(- 'Cannot move composition "Standalone" because it is not a direct JSX child',- );-});--test('moves a composition into a self-closing folder', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: selfClosingFolderRootContents,- codeMod: {- type: 'move-composition-to-folder',- idToMove: 'KeepMe',- folderName: 'Empty',- parentName: null,- },- });-- expect(changesMade.length).toBe(1);- expect(newContents).toContain('<Folder name="Empty">');- expect(newContents).toContain('</Folder>');- expect(newContents.indexOf('<Folder name="Empty">')).toBeLessThan(- newContents.indexOf('id="KeepMe"'),- );- expect(newContents.match(/id="KeepMe"/g)?.length).toBe(1);-});--test('creates a folder in a self-closing folder', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: selfClosingFolderRootContents,- codeMod: {- type: 'new-folder',- folderName: 'Nested',- parentName: 'Empty',- },- });-- expect(changesMade.length).toBe(1);- expect(newContents).toContain('<Folder name="Empty">');- expect(newContents).toContain('<Folder name="Nested" />');- expect(newContents.indexOf('<Folder name="Empty">')).toBeLessThan(- newContents.indexOf('<Folder name="Nested" />'),- );- expect(newContents.indexOf('<Folder name="Nested" />')).toBeLessThan(- newContents.indexOf('id="KeepMe"'),- );-});--test('renames a nested folder by parent path', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: folderRootContents,- codeMod: {- type: 'rename-folder',- folderName: 'Shared',- parentName: 'Parent',- newName: 'Renamed',- },- });-- expect(changesMade.length).toBe(1);- expect(newContents).toContain('<Folder name="Renamed">');- expect(newContents.match(/<Folder name="Shared">/g)?.length).toBe(1);- expect(newContents).toContain('id="NestedA"');- expect(newContents).toContain('id="NestedB"');-});--test('deletes a nested folder by unwrapping its children', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: folderRootContents,- codeMod: {- type: 'delete-folder',- folderName: 'Shared',- parentName: 'Parent',- },- });-- expect(changesMade.length).toBe(1);- expect(newContents.match(/<Folder name="Shared">/g)?.length).toBe(1);- expect(newContents).toContain('<Folder name="Parent">');- expect(newContents).toContain('id="NestedA"');- expect(newContents).toContain('id="NestedB"');-});--test('deletes a top-level folder by unwrapping its children', () => {- const {changesMade, newContents} = parseAndApplyCodemod({- input: folderRootContents,- codeMod: {- type: 'delete-folder',- folderName: 'Parent',- parentName: null,- },- });-- expect(changesMade.length).toBe(1);- expect(newContents).not.toContain('<Folder name="Parent">');- expect(newContents.match(/<Folder name="Shared">/g)?.length).toBe(2);- expect(newContents).toContain('id="NestedA"');- expect(newContents).toContain('id="NestedB"');-});diff --git a/packages/studio-server/src/test/delete-jsx-nodes.test.ts b/packages/studio-server/src/test/delete-jsx-nodes.test.tsindex 5f2261a354..23b8f5bd3c 100644--- a/packages/studio-server/src/test/delete-jsx-nodes.test.ts+++ b/packages/studio-server/src/test/delete-jsx-nodes.test.ts@@ -6,7 +6,6 @@ import type {EventSourceEvent,SubscribeToSequencePropsRequest,} from '@remotion/studio-shared';-import {deleteJsxNodes} from '../codemods/delete-jsx-nodes';import {createFileWatcherRegistry,setFileWatcherRegistry,@@ -20,291 +19,7 @@ import {popRedo,popUndo,} from '../preview-server/undo-stack';-import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';--const sample = `import React from 'react';-import {AbsoluteFill} from 'remotion';--export const X: React.FC = () => {- return (- <AbsoluteFill>- <div />- </AbsoluteFill>- );-};-`;--test('deleteJsxNodes removes a JSX child from a parent element', async () => {- const {output} = await deleteJsxNodes({- input: sample,- nodePaths: [lineColumnToNodePath(sample, 7)],- });-- expect(output).not.toContain('<div');- expect(output).toContain('<AbsoluteFill>');-});--const onlyReturn = `import React from 'react';--export const X: React.FC = () => {- return <div />;-};-`;--test('deleteJsxNodes replaces sole return JSX with null', async () => {- const {output} = await deleteJsxNodes({- input: onlyReturn,- nodePaths: [lineColumnToNodePath(onlyReturn, 4)],- });-- expect(output).toContain('return null');- expect(output).not.toContain('<div');-});--const conditional = `import React from 'react';--export const X: React.FC<{show: boolean}> = ({show}) => {- return <>{show && <div />}</>;-};-`;--test('deleteJsxNodes turns conditional JSX into null', async () => {- const {output} = await deleteJsxNodes({- input: conditional,- nodePaths: [lineColumnToNodePath(conditional, 4)],- });-- expect(output).toContain('&& null');- expect(output).not.toContain('<div');-});--const ternary = `import React from 'react';--export const X: React.FC<{show: boolean}> = ({show}) => {- return <>{show ? <div /> : null}</>;-};-`;--test('deleteJsxNodes replaces JSX in ternary consequent with null', async () => {- const {output} = await deleteJsxNodes({- input: ternary,- nodePaths: [lineColumnToNodePath(ternary, 4)],- });-- expect(output).toMatch(/\?\s*null/);- expect(output).not.toContain('<div');-});--const mapCase = `import React from 'react';--export const X: React.FC = () => {- return (- <>- {[1].map((i) => (- <div key={i} />- ))}- </>- );-};-`;--test('deleteJsxNodes replaces JSX inside map callback', async () => {- const {output} = await deleteJsxNodes({- input: mapCase,- nodePaths: [lineColumnToNodePath(mapCase, 7)],- });-- expect(output).not.toContain('<div');- expect(output).toMatch(/=>\s*\(?\s*null/);-});--const multipleSiblings = `import React from 'react';-import {AbsoluteFill} from 'remotion';--export const X: React.FC = () => {- return (- <AbsoluteFill>- <div />- <span />- <p />- </AbsoluteFill>- );-};-`;--test('deleteJsxNodes removes multiple JSX children in one transform', async () => {- const {output, nodeLabels, logLines} = await deleteJsxNodes({- input: multipleSiblings,- nodePaths: [- lineColumnToNodePath(multipleSiblings, 7),- lineColumnToNodePath(multipleSiblings, 8),- ],- });-- expect(output).not.toContain('<div');- expect(output).not.toContain('<span');- expect(output).toContain('<p');- expect(nodeLabels).toEqual(['<div>', '<span>']);- expect(logLines).toEqual([7, 8]);-});--test('deleteJsxNodes preserves source formatting and removes standalone JSX lines', async () => {- const cases = [- {- input: `export const Comp = () => {- return (- <div>- <Keep />- <RemoveOne />- <RemoveTwo />- <Keep />- </div>- );-};-`,- markers: ['<RemoveOne', '<RemoveTwo'],- expected: `export const Comp = () => {- return (- <div>- <Keep />- <Keep />- </div>- );-};-`,- },- {- input: `export const Comp = () => {- return (- <div>- <Remove />- </div>- )-}-`,- markers: ['<Remove'],- expected: `export const Comp = () => {- return (- <div>- </div>- )-}-`,- },- {- input: `export const Comp = () => {- return [1].map((item) => (- <Remove key={item} />- ));-};-`,- markers: ['<Remove'],- expected: `export const Comp = () => {- return [1].map((item) => null);-};-`,- },- {- input: `const AnimatedBar = () => {- return (- <Remove />- );-};-`,- markers: ['<Remove'],- expected: `const AnimatedBar = () => {- return null;-};-`,- },- {- input: `const AnimatedBar = () => {- return (- // Keep this explanation.- <Remove />- );-};-`,- markers: ['<Remove'],- expected: `const AnimatedBar = () => {- return (- // Keep this explanation.- null- );-};-`,- },- {- input: `export const Comp = () => <div><Keep /><Remove /><Keep /></div>;-`,- markers: ['<Remove'],- expected: `export const Comp = () => <div><Keep /><Keep /></div>;-`,- },- {- input:- 'export const Comp = () => <div><Keep />\t<Remove /><Keep /></div>;\n',- markers: ['<Remove'],- expected: 'export const Comp = () => <div><Keep />\t<Keep /></div>;\n',- },- {- input: `export const Comp = () => (- <div>- <Remove /> {/* keep this comment */}- </div>-);-`,- markers: ['<Remove'],- expected: `export const Comp = () => (- <div>- {/* keep this comment */}- </div>-);-`,- },- {- input: `export const Comp = () => {- return (- <div>- <RemoveParent>- <RemoveChild />- </RemoveParent>- <Keep />- </div>- );-};-`,- markers: ['<RemoveParent', '<RemoveChild'],- expected: `export const Comp = () => {- return (- <div>- <Keep />- </div>- );-};-`,- },- {- input:- 'export const Comp = () => {\r\n\treturn (\r\n\t\t<div>\r\n\t\t\t<Remove />\r\n\t\t</div>\r\n\t);\r\n};\r\n',- markers: ['<Remove'],- expected:- 'export const Comp = () => {\r\n\treturn (\r\n\t\t<div>\r\n\t\t</div>\r\n\t);\r\n};\r\n',- },- ] as const;-- for (const item of cases) {- const {output, formatted} = await deleteJsxNodes({- input: item.input,- nodePaths: item.markers.map((marker) =>- lineContainingToNodePath(item.input, marker),- ),- });-- expect(output).toBe(item.expected);- expect(formatted).toBe(true);- }-});+import {lineColumnToNodePath} from './test-utils';const interactiveSiblings = `import {Interactive} from 'remotion';diff --git a/packages/studio-server/src/test/discriminated-union-update.test.ts b/packages/studio-server/src/test/discriminated-union-update.test.tsindex ce025b2b68..a2060fd0f0 100644--- a/packages/studio-server/src/test/discriminated-union-update.test.ts+++ b/packages/studio-server/src/test/discriminated-union-update.test.ts@@ -5,7 +5,7 @@ import path from 'node:path';import {getFieldsToShow} from '@remotion/studio-shared';import {NoReactInternals} from 'remotion/no-react';import {parseAst} from '../codemods/parse-ast';-import {updateSequencePropsAst} from '../codemods/update-sequence-props/update-sequence-props';+import {updateSequenceProps} from '../codemods/update-sequence-props/update-sequence-props';import {lineColumnToNodePath} from '../preview-server/routes/can-update-sequence-props';import {prettify} from './test-utils';@@ -75,8 +75,9 @@ test('Should be able to update a discriminated union', async () => {const nodePath = lineColumnToNodePath(ast, 3);assert(nodePath, 'No node path found');- const update = updateSequencePropsAst({+ const update = await updateSequenceProps({videoConfigValues: null,+ prettierConfigOverride: null,input: file,nodePath,updates: [@@ -94,7 +95,7 @@ test('Should be able to update a discriminated union', async () => {'utf-8',);- expect(await prettify(update.serialized)).toBe(await prettify(expected));+ expect(await prettify(update.output)).toBe(await prettify(expected));});test('Should remove variant-specific props when switching enum value', async () => {@@ -108,8 +109,9 @@ test('Should remove variant-specific props when switching enum value', async ()const nodePath = lineColumnToNodePath(ast, 3);assert(nodePath, 'No node path found');- const update = updateSequencePropsAst({+ const update = await updateSequenceProps({videoConfigValues: null,+ prettierConfigOverride: null,input: file,nodePath,updates: [@@ -131,7 +133,7 @@ test('Should remove variant-specific props when switching enum value', async ()'utf-8',);- expect(await prettify(update.serialized)).toBe(await prettify(expected));+ expect(await prettify(update.output)).toBe(await prettify(expected));});test('Should remove premountFor and preserve styleWhile* when switching to layout="none"', async () => {@@ -145,8 +147,9 @@ test('Should remove premountFor and preserve styleWhile* when switching to layouconst nodePath = lineColumnToNodePath(ast, 3);assert(nodePath, 'No node path found');- const update = updateSequencePropsAst({+ const update = await updateSequenceProps({videoConfigValues: null,+ prettierConfigOverride: null,input: file,nodePath,updates: [@@ -168,5 +171,5 @@ test('Should remove premountFor and preserve styleWhile* when switching to layou'utf-8',);- expect(await prettify(update.serialized)).toBe(await prettify(expected));+ expect(await prettify(update.output)).toBe(await prettify(expected));});diff --git a/packages/studio-server/src/test/effect-editing-routes.test.ts b/packages/studio-server/src/test/effect-editing-routes.test.tsnew file mode 100644index 0000000000..55be86273a--- /dev/null+++ b/packages/studio-server/src/test/effect-editing-routes.test.ts@@ -0,0 +1,164 @@+import {expect, test} from 'bun:test';+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import {+ createFileWatcherRegistry,+ setFileWatcherRegistry,+} from '../file-watcher';+import {setLiveEventsListener} from '../preview-server/live-events';+import {addEffectHandler} from '../preview-server/routes/add-effect';+import {deleteEffectHandler} from '../preview-server/routes/delete-effect';+import {duplicateEffectHandler} from '../preview-server/routes/duplicate-effect';+import {reorderEffectHandler} from '../preview-server/routes/reorder-effect';+import {clearUndoStackForTests, popUndo} from '../preview-server/undo-stack';+import {lineContainingToNodePath} from './test-utils';++test('effect routes persist additions, duplication, reordering, deletion, and undo', async () => {+ const remotionRoot = mkdtempSync(join(tmpdir(), 'remotion-effect-routes-'));+ const filePath = join(remotionRoot, 'Comp.tsx');+ const cleanupFileWatcher = setFileWatcherRegistry(+ createFileWatcherRegistry(),+ );+ const cleanupLiveEvents = setLiveEventsListener({+ sendEventToClient: () => undefined,+ sendEventToClientId: () => true,+ router: () => Promise.resolve(),+ closeConnections: () => Promise.resolve(),+ addNewClientListener: () => () => undefined,+ });+ const context = {+ entryPoint: filePath,+ remotionRoot,+ request: {} as never,+ response: {} as never,+ logLevel: 'error' as const,+ methods: {+ removeJob: () => undefined,+ cancelJob: () => undefined,+ addJob: () => undefined,+ },+ publicDir: remotionRoot,+ binariesDirectory: null,+ configFile: null,+ getDefaultCodingAgent: () => null,+ getDefaultEditor: () => null,+ };+ const input = `import {Solid} from 'remotion';+const untouched = { value : 'keep' };+const dimensions = {width: 100, height: 100};+const presets = [];+export const Comp = () => <>+ <Solid {...dimensions} />+ <Solid name="preset" effects={[...presets]} />+ <Solid name="overridden" effects={[...presets]} {...dimensions} />+</>;+`;++ try {+ clearUndoStackForTests();+ writeFileSync(filePath, input);+ const sequenceNodePath = {+ absolutePath: filePath,+ nodePath: lineContainingToNodePath(input, '<Solid'),+ sequenceKeys: [],+ effectKeys: [],+ videoConfigValues: null,+ };+ for (const effectName of ['brightness', 'contrast']) {+ const result = await addEffectHandler({+ ...context,+ input: {+ fileName: filePath,+ sequenceNodePath,+ effectName,+ effectImportPath: `@remotion/effects/${effectName}`,+ effectConfig: {amount: 1.2},+ clientId: 'effect-routes-test',+ },+ });+ expect(result.success).toBe(true);+ }++ const duplicate = await duplicateEffectHandler({+ ...context,+ input: [{fileName: filePath, sequenceNodePath, effectIndex: 0}],+ });+ expect(duplicate.success).toBe(true);+ expect(+ readFileSync(filePath, 'utf-8').match(/brightness\(\{/g),+ ).toHaveLength(2);++ const reorder = await reorderEffectHandler({+ ...context,+ input: {+ fileName: filePath,+ sequenceNodePath,+ fromIndex: 1,+ toIndex: 2,+ clientId: 'effect-routes-test',+ },+ });+ expect(reorder.success).toBe(true);+ const reordered = readFileSync(filePath, 'utf-8');+ expect(reordered.indexOf('brightness({')).toBeLessThan(+ reordered.indexOf('contrast({'),+ );+ expect(reordered.lastIndexOf('brightness({')).toBeGreaterThan(+ reordered.indexOf('contrast({'),+ );+ expect(reordered).toContain("const untouched = { value : 'keep' };");++ const overridden = await addEffectHandler({+ ...context,+ input: {+ fileName: filePath,+ sequenceNodePath: {+ ...sequenceNodePath,+ nodePath: lineContainingToNodePath(+ reordered,+ '<Solid name="overridden"',+ ),+ },+ effectName: 'brightness',+ effectImportPath: '@remotion/effects/brightness',+ effectConfig: {amount: 2},+ clientId: 'effect-routes-test',+ },+ });+ expect(overridden.success).toBe(false);+ expect(readFileSync(filePath, 'utf-8')).toBe(reordered);++ const deleted = await deleteEffectHandler({+ ...context,+ input: [+ {type: 'all-effects', fileName: filePath, sequenceNodePath},+ {+ type: 'all-effects',+ fileName: filePath,+ sequenceNodePath: {+ ...sequenceNodePath,+ nodePath: lineContainingToNodePath(+ reordered,+ '<Solid name="preset"',+ ),+ },+ },+ ],+ });+ expect(deleted.success).toBe(true);+ expect(readFileSync(filePath, 'utf-8')).toContain(+ '<Solid {...dimensions} />',+ );+ expect(readFileSync(filePath, 'utf-8')).toContain(+ '<Solid name="preset" />',+ );+ expect(popUndo().success).toBe(true);+ expect(readFileSync(filePath, 'utf-8')).toBe(reordered);+ } finally {+ clearUndoStackForTests();+ cleanupFileWatcher();+ cleanupLiveEvents();+ rmSync(remotionRoot, {recursive: true, force: true});+ }+});diff --git a/packages/studio-server/src/test/generate-canvas-capture-composition.test.ts b/packages/studio-server/src/test/generate-canvas-capture-composition.test.tsdeleted file mode 100644index 95c74e6f16..0000000000--- a/packages/studio-server/src/test/generate-canvas-capture-composition.test.ts+++ /dev/null@@ -1,46 +0,0 @@-import {expect, test} from 'bun:test';-import {readFileSync} from 'node:fs';-import path from 'node:path';-import {CodemodsInternals} from '@remotion/codemods';-import {- CANVAS_CAPTURE_METADATA_TAG,- parseCanvasCaptureData,-} from '@remotion/studio-shared';--const {generateCanvasCaptureComposition} = CodemodsInternals;--test('generates the ideal interactive Canvas Capture composition markup', async () => {- const fixtureDirectory = path.join(__dirname, 'fixtures');- const metadata = readFileSync(- path.join(fixtureDirectory, 'canvas-capture-metadata.json'),- 'utf-8',- );- const data = parseCanvasCaptureData({- raw: {[CANVAS_CAPTURE_METADATA_TAG]: metadata},- });- if (data === null) {- throw new Error('Could not parse the Canvas Capture metadata fixture');- }-- const generated = await generateCanvasCaptureComposition({- componentName: 'CanvasCaptureComposition',- compositionId: 'canvas-capture-promo',- data,- durationInFrames: 500,- fps: 60,- height: 1080,- keyframeFps: 30,- videoFileName: 'remotion-capture-editor-starter.mp4',- videoHeight: 1386,- videoWidth: 3026,- width: 1920,- });- const expected = readFileSync(- path.join(fixtureDirectory, 'canvas-capture-composition.txt'),- 'utf-8',- )- .replaceAll('\r\n', '\n')- .replaceAll('\r', '\n');-- expect(generated).toBe(expected);-});diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.tsindex 9f5f6c04a5..ece1cd26e9 100644--- a/packages/studio-server/src/test/insert-element.test.ts+++ b/packages/studio-server/src/test/insert-element.test.ts@@ -326,6 +326,10 @@ test('invalidates a new-composition install after an external component edit', a);}+ const registration = readFileSync(fixture.compositionFile, 'utf-8');+ expect(registration).toContain('const Target = () => <div>Hello</div>;');+ expect(registration.match(/id="ElementScene"/g)).toHaveLength(1);+const componentFile = path.join(path.dirname(fixture.compositionFile),'ElementScene.tsx',diff --git a/packages/studio-server/src/test/log-effect-update.test.ts b/packages/studio-server/src/test/log-effect-update.test.tsindex bbcd4ac97f..6a573e115a 100644--- a/packages/studio-server/src/test/log-effect-update.test.ts+++ b/packages/studio-server/src/test/log-effect-update.test.ts@@ -1,7 +1,7 @@import {afterAll, beforeAll, expect, spyOn, test} from 'bun:test';const originalForceColor = process.env.FORCE_COLOR;-process.env.FORCE_COLOR = '1';+const originalNoColor = process.env.NO_COLOR;import {RenderInternals} from '@remotion/renderer';import {formatEffectPropChange} from '../preview-server/routes/log-updates/format-effect-prop-change';@@ -17,6 +17,7 @@ const {chalk} = RenderInternals;beforeAll(() => {process.env.FORCE_COLOR = '1';+ delete process.env.NO_COLOR;});afterAll(() => {@@ -25,6 +26,12 @@ afterAll(() => {} else {process.env.FORCE_COLOR = originalForceColor;}++ if (originalNoColor === undefined) {+ delete process.env.NO_COLOR;+ } else {+ process.env.NO_COLOR = originalNoColor;+ }});const halftoneCall = (propKey: string, value: string) => {diff --git a/packages/studio-server/src/test/log-update.test.ts b/packages/studio-server/src/test/log-update.test.tsindex df47c48125..0dca793015 100644--- a/packages/studio-server/src/test/log-update.test.ts+++ b/packages/studio-server/src/test/log-update.test.ts@@ -1,7 +1,7 @@import {afterAll, beforeAll, expect, spyOn, test} from 'bun:test';const originalForceColor = process.env.FORCE_COLOR;-process.env.FORCE_COLOR = '1';+const originalNoColor = process.env.NO_COLOR;import {readFileSync} from 'node:fs';import path from 'node:path';@@ -27,6 +27,7 @@ const {chalk} = RenderInternals;beforeAll(() => {process.env.FORCE_COLOR = '1';+ delete process.env.NO_COLOR;});afterAll(() => {@@ -35,6 +36,12 @@ afterAll(() => {} else {process.env.FORCE_COLOR = originalForceColor;}++ if (originalNoColor === undefined) {+ delete process.env.NO_COLOR;+ } else {+ process.env.NO_COLOR = originalNoColor;+ }});const input = `import {LightLeak} from '@remotion/light-leaks';diff --git a/packages/studio-server/src/test/recast-mods.test.ts b/packages/studio-server/src/test/recast-mods.test.tsdeleted file mode 100644index e5a7df4c0a..0000000000--- a/packages/studio-server/src/test/recast-mods.test.ts+++ /dev/null@@ -1,321 +0,0 @@-import {expect, test} from 'bun:test';-import {CodemodsInternals} from '@remotion/codemods';--const {parseAndApplyCodemod} = CodemodsInternals;--const compositionInRoot = `import {Composition} from 'remotion';-import {NewVideo} from './NewVideo';--export const RemotionRoot: React.FC = () => {- return (- <>- <Composition- id="NewVideo"- component={NewVideo}- durationInFrames={120}- fps={30}- width={1280}- height={720}- />- <Composition- id="Other"- component={NewVideo}- durationInFrames={120}- fps={30}- width={1280}- height={720}- />- </>- );-};-`;--const compositionInOwnFile = `import {Composition} from 'remotion';--const Component = () => null;--export const NewVideoComp = () => {- return (- <Composition- component={Component}- id="NewVideo"- durationInFrames={120}- fps={30}- width={1280}- height={720}- />- );-};-`;--const compositionInConciseArrow = `import {Composition} from 'remotion';--const Component = () => null;--export const NewVideoComp = () => (- <Composition- component={Component}- id="NewVideo"- durationInFrames={120}- fps={30}- width={1280}- height={720}- />-);-`;--test('Delete composition that is a child of a Fragment in Root.tsx', () => {- const {newContents, changesMade} = parseAndApplyCodemod({- input: compositionInRoot,- codeMod: {type: 'delete-composition', idToDelete: 'NewVideo'},- });-- expect(changesMade.length).toBeGreaterThan(0);- expect(newContents).not.toContain('id="NewVideo"');- expect(newContents).toContain('id="Other"');-});--test('Delete composition that is the sole return value of a wrapper component', () => {- const {newContents, changesMade} = parseAndApplyCodemod({- input: compositionInOwnFile,- codeMod: {type: 'delete-composition', idToDelete: 'NewVideo'},- });-- expect(changesMade.length).toBeGreaterThan(0);- expect(newContents).not.toContain('id="NewVideo"');-});--test('Delete composition that is a concise arrow body', () => {- const {newContents, changesMade} = parseAndApplyCodemod({- input: compositionInConciseArrow,- codeMod: {type: 'delete-composition', idToDelete: 'NewVideo'},- });-- expect(changesMade.length).toBeGreaterThan(0);- expect(newContents).not.toContain('id="NewVideo"');-});--test('Rename composition that is the sole return value of a wrapper component', () => {- const {newContents, changesMade} = parseAndApplyCodemod({- input: compositionInOwnFile,- codeMod: {- type: 'rename-composition',- idToRename: 'NewVideo',- newId: 'Renamed',- },- });-- expect(changesMade.length).toBeGreaterThan(0);- expect(newContents).not.toContain('id="NewVideo"');- expect(newContents).toContain('id="Renamed"');-});--test('Update composition metadata', () => {- const {newContents, changesMade} = parseAndApplyCodemod({- input: compositionInOwnFile,- codeMod: {- type: 'update-composition-metadata',- idToUpdate: 'NewVideo',- newDurationInFrames: 240,- newFps: 60,- newWidth: 1920,- newHeight: 1080,- },- });-- expect(changesMade).toHaveLength(4);- expect(newContents).toContain('width={1920}');- expect(newContents).toContain('height={1080}');- expect(newContents).toContain('fps={60}');- expect(newContents).toContain('durationInFrames={240}');-});--test('Update a composition dimension that is not a numeric literal', () => {- const input = compositionInOwnFile.replace('width={1280}', 'width={WIDTH}');- const {newContents} = parseAndApplyCodemod({- input,- codeMod: {- type: 'update-composition-metadata',- idToUpdate: 'NewVideo',- newDurationInFrames: null,- newFps: null,- newWidth: 1920,- newHeight: null,- },- });-- expect(newContents).toContain('width={1920}');- expect(newContents).not.toContain('width={WIDTH}');-});--test('Add a missing composition dimension', () => {- const input = compositionInOwnFile.replace('\n\t\t\theight={720}', '');- const {newContents} = parseAndApplyCodemod({- input,- codeMod: {- type: 'update-composition-metadata',- idToUpdate: 'NewVideo',- newDurationInFrames: null,- newFps: null,- newWidth: null,- newHeight: 1080,- },- });-- expect(newContents).toContain('height={1080}');-});--test('Duplicate composition that is the sole return value of a wrapper component', () => {- const {newContents, changesMade} = parseAndApplyCodemod({- input: compositionInOwnFile,- codeMod: {- type: 'duplicate-composition',- idToDuplicate: 'NewVideo',- newId: 'Duplicated',- newDurationInFrames: null,- newFps: null,- newHeight: null,- newWidth: null,- tag: 'Composition',- },- });-- expect(changesMade.length).toBeGreaterThan(0);- expect(newContents).toContain('id="NewVideo"');- expect(newContents).toContain('id="Duplicated"');-});--test('Delete composition leaves a returns-null wrapper that still parses', () => {- const {newContents} = parseAndApplyCodemod({- input: compositionInOwnFile,- codeMod: {type: 'delete-composition', idToDelete: 'NewVideo'},- });-- expect(newContents).toContain('return null');- expect(newContents).not.toContain('<Composition');-});--test('Delete unmatched composition leaves the file unchanged', () => {- expect(() =>- parseAndApplyCodemod({- input: compositionInOwnFile,- codeMod: {type: 'delete-composition', idToDelete: 'DoesNotExist'},- }),- ).toThrow('Unable to calculate the changes');-});--test('Rename concise-arrow composition keeps the arrow expression body', () => {- const {newContents} = parseAndApplyCodemod({- input: compositionInConciseArrow,- codeMod: {- type: 'rename-composition',- idToRename: 'NewVideo',- newId: 'Renamed',- },- });-- expect(newContents).toContain('id="Renamed"');- expect(newContents).not.toContain('id="NewVideo"');-});--test('Duplicate composition as Still adds Still import', () => {- const {newContents, changesMade} = parseAndApplyCodemod({- input: compositionInOwnFile,- codeMod: {- type: 'duplicate-composition',- idToDuplicate: 'NewVideo',- newId: 'Duplicated',- newDurationInFrames: null,- newFps: null,- newHeight: null,- newWidth: null,- tag: 'Still',- },- });-- expect(changesMade.length).toBeGreaterThan(0);- expect(newContents).toContain('id="NewVideo"');- expect(newContents).toContain('id="Duplicated"');- expect(newContents).toContain('<Still');- expect(newContents).toContain('Still');- expect(newContents).toMatch(- /import\s*\{[^}]*Still[^}]*\}\s*from\s*['"]remotion['"]/,- );-});--test('Duplicate composition as Still does not duplicate import if Still already imported', () => {- const inputWithStill = `import {Composition, Still} from 'remotion';--const Component = () => null;--export const NewVideoComp = () => {- return (- <Composition- component={Component}- id="NewVideo"- durationInFrames={120}- fps={30}- width={1280}- height={720}- />- );-};-`;-- const {newContents} = parseAndApplyCodemod({- input: inputWithStill,- codeMod: {- type: 'duplicate-composition',- idToDuplicate: 'NewVideo',- newId: 'Duplicated',- newDurationInFrames: null,- newFps: null,- newHeight: null,- newWidth: null,- tag: 'Still',- },- });-- // Should only have one import of Still, not two- // Still appears in: import + JSX tag opening- expect(newContents).toContain('<Still');- expect(newContents).toMatch(- /import\s*\{[^}]*Still[^}]*\}\s*from\s*['"]remotion['"]/,- );- // Ensure no duplicate import declarations- const importLines = newContents- .split('\n')- .filter((l: string) => l.includes('import') && l.includes('remotion'));- expect(importLines.length).toBe(1);-});--test('New composition appends to root and adds imports', () => {- const {newContents, changesMade} = parseAndApplyCodemod({- input: compositionInRoot,- codeMod: {- type: 'new-composition',- canvasCapture: null,- newId: 'FreshVideo',- componentName: 'FreshVideo',- componentImportPath: './FreshVideo',- folderName: null,- parentName: null,- newDurationInFrames: 150,- newFps: 30,- newHeight: 1080,- newWidth: 1920,- },- });-- expect(changesMade.length).toBeGreaterThan(0);- expect(newContents).toMatch(- /import\s*\{[^}]*FreshVideo[^}]*\}\s*from\s*['"].\/FreshVideo['"]/,- );- expect(newContents).toMatch(- /import\s*\{[^}]*Composition[^}]*\}\s*from\s*['"]remotion['"]/,- );- expect(newContents).toContain('id="FreshVideo"');- expect(newContents).toContain('component={FreshVideo}');- expect(newContents).toContain('durationInFrames={150}');- expect(newContents).toContain('width={1920}');-});diff --git a/packages/studio-server/src/test/split-jsx-sequence.test.ts b/packages/studio-server/src/test/split-jsx-sequence.test.tsindex cb7adff0da..ab4fd96f5a 100644--- a/packages/studio-server/src/test/split-jsx-sequence.test.ts+++ b/packages/studio-server/src/test/split-jsx-sequence.test.ts@@ -2,8 +2,6 @@ import {expect, test} from 'bun:test';import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';import {tmpdir} from 'node:os';import path from 'node:path';-import {CodemodsInternals} from '@remotion/codemods';-import {splitJsxSequence} from '../codemods/split-jsx-sequence';import {createFileWatcherRegistry,setFileWatcherRegistry,@@ -11,9 +9,7 @@ import {import {setLiveEventsListener} from '../preview-server/live-events';import {splitJsxSequenceHandler} from '../preview-server/routes/split-jsx-sequence';import {getUndoStack} from '../preview-server/undo-stack';-import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';--const {splitJsxSequence: splitJsxSequenceCodemod} = CodemodsInternals;+import {lineContainingToNodePath} from './test-utils';const wrap = (sequence: string,@@ -29,243 +25,8 @@ export const Comp = () => {};`;-const sequenceLine = 7;const sequenceTimingKeys = ['from', 'durationInFrames', 'trimBefore'];-const split = async (- sequence: string,- splitFrame: number,- sequenceKeys = sequenceTimingKeys,-) => {- const input = wrap(sequence);- const {output} = await splitJsxSequence({- input,- nodePath: lineColumnToNodePath(input, sequenceLine),- sequenceKeys,- splitFrame,- });-- return output;-};--test('splitJsxSequence splits a sequence with no duration', async () => {- const output = await split('<Sequence from={0} />', 30);-- expect(output).toContain('<Sequence from={0} durationInFrames={30} />');- expect(output).toContain('<Sequence from={30} trimBefore={30} />');-});--test('splitJsxSequence remaps following JSX siblings', async () => {- const input = wrap(- '<Sequence name="split" from={0} durationInFrames={50} />\n\t\t\t<Sequence name="following" />',- );- const {output, nodePathRemappings} = await splitJsxSequence({- input,- nodePath: lineContainingToNodePath(input, 'name="split"'),- sequenceKeys: sequenceTimingKeys,- splitFrame: 30,- });-- expect(nodePathRemappings).toEqual([- {- oldNodePath: lineContainingToNodePath(input, 'name="split"'),- newNodePath: lineContainingToNodePath(output, 'name="split"'),- },- {- oldNodePath: lineContainingToNodePath(input, 'name="following"'),- newNodePath: lineContainingToNodePath(output, 'name="following"'),- },- {- oldNodePath: null,- newNodePath: lineContainingToNodePath(output, 'from={30}'),- },- ]);-});--test('splitJsxSequence omits right Infinity duration', async () => {- const output = await split(- '<Sequence from={0} durationInFrames={Infinity} />',- 30,- );-- expect(output).toContain('<Sequence from={0} durationInFrames={30} />');- expect(output).toContain('<Sequence from={30} trimBefore={30} />');- expect(output).not.toContain('durationInFrames={Infinity}');-});--test('splitJsxSequence keeps missing left from omitted', async () => {- const output = await split('<Sequence durationInFrames={50} />', 30);-- expect(output).toContain('<Sequence durationInFrames={30} />');- expect(output).toContain(- '<Sequence from={30} durationInFrames={20} trimBefore={30} />',- );-});--test('splitJsxSequence splits finite duration and trimBefore', async () => {- const output = await split(- '<Sequence from={10} durationInFrames={50} trimBefore={5} />',- 30,- );-- expect(output).toContain(- '<Sequence from={10} durationInFrames={20} trimBefore={5} />',- );- expect(output).toContain(- '<Sequence from={30} durationInFrames={30} trimBefore={25} />',- );-});--test('splitJsxSequence preserves surrounding formatting without calling Prettier', async () => {- const input = `const deliberatelyUnformatted = {value : true}--export const Comp = () => {- return (- <>- <Sequence- name="clip"- from={0}- durationInFrames={50}- >- <div>Child</div>- </Sequence>- <Keep prop = {1}/>- </>- )-}-`;- const {output} = await splitJsxSequenceCodemod({- input,- nodePath: lineContainingToNodePath(input, '<Sequence'),- sequenceKeys: sequenceTimingKeys,- splitFrame: 30,- });-- expect(output).toStartWith(- 'const deliberatelyUnformatted = {value : true}\n',- );- expect(output).toContain(- '<Sequence name="clip" from={0} durationInFrames={30}>\n',- );- expect(output).toContain(- '<Sequence name="clip" from={30} durationInFrames={20} trimBefore={30}>\n',- );- expect(output).toContain(' <Keep prop = {1}/>');- expect(output).toEndWith(' )\n}\n');-});--test('splitJsxSequence formats a split component root as a fragment', async () => {- const input = `export const Comp = () => <Sequence from={0} durationInFrames={50}><span>Hi</span></Sequence>;--const keep = { value : true }-`;- const {output} = await splitJsxSequenceCodemod({- input,- nodePath: lineContainingToNodePath(input, '<Sequence'),- sequenceKeys: sequenceTimingKeys,- splitFrame: 30,- });-- expect(output).toBe(`export const Comp = () => <>- <Sequence from={0} durationInFrames={30}>- <span>Hi</span>- </Sequence>- <Sequence from={30} durationInFrames={20} trimBefore={30}>- <span>Hi</span>- </Sequence>-</>;--const keep = { value : true }-`);-});--test('splitJsxSequence splits a video with a negative from', async () => {- const output = await split(- '<Video src="video.mov" from={-2644} trimBefore={272} />',- 100,- );-- expect(output).toContain('from={-2644}');- expect(output).toContain('durationInFrames={2744}');- expect(output).toContain('trimBefore={272}');- expect(output).toContain(- '<Video src="video.mov" from={100} trimBefore={3016} />',- );-});--test('splitJsxSequence splits from-only sequence', async () => {- const output = await split('<Sequence from={10} />', 30);-- expect(output).toContain('<Sequence from={10} durationInFrames={20} />');- expect(output).toContain('<Sequence from={30} trimBefore={20} />');-});--test('splitJsxSequence splits sequence-backed components', async () => {- expect(- await split('<AbsoluteFill from={0} durationInFrames={50} />', 30),- ).toContain(- '<AbsoluteFill from={30} durationInFrames={20} trimBefore={30} />',- );- expect(- await split('<Img src="image.png" from={0} durationInFrames={50} />', 30),- ).toContain(- '<Img src="image.png" from={30} durationInFrames={20} trimBefore={30} />',- );- expect(- await split('<Gif src="anim.gif" from={0} durationInFrames={50} />', 30),- ).toContain(- '<Gif src="anim.gif" from={30} durationInFrames={20} trimBefore={30} />',- );- const solidOutput = await split(- '<Solid width={100} height={100} from={0} durationInFrames={50} />',- 30,- );- expect(solidOutput).toContain(- '<Solid width={100} height={100} from={0} durationInFrames={30} />',- );- expect(solidOutput).toContain('from={30}');- expect(solidOutput).toContain('durationInFrames={20}');- expect(solidOutput).toContain('trimBefore={30}');- expect(- await split('<Interactive.Div from={0} durationInFrames={50} />', 30),- ).toContain(- '<Interactive.Div from={30} durationInFrames={20} trimBefore={30} />',- );-});--test('splitJsxSequence rejects boundary and dynamic splits', async () => {- await expect(- split('<Sequence from={10} durationInFrames={20} />', 10),- ).rejects.toThrow(/sequence start/);- await expect(- split('<Sequence from={10} durationInFrames={20} />', 30),- ).rejects.toThrow(/sequence end/);- await expect(- split('<Sequence from={10} durationInFrames={20} />', 8),- ).rejects.toThrow(/sequence start/);- await expect(- split('<Sequence from={10} durationInFrames={20} />', 10.5),- ).rejects.toThrow(/integer/);- await expect(- split('<Sequence from={start} durationInFrames={20} />', 15),- ).rejects.toThrow(/dynamic from/);-});--test('splitJsxSequence rejects Series.Sequence', async () => {- await expect(- split('<Series.Sequence durationInFrames={50} />', 30, [- 'durationInFrames',- 'trimBefore',- ]),- ).rejects.toThrow('<Series.Sequence> cannot be split');-});--test('splitJsxSequence rejects regular DOM elements', async () => {- await expect(- split('<div from={0} durationInFrames={50} />', 30, []),- ).rejects.toThrow('<div> cannot be split');-});-const clearUndoStack = () => {(getUndoStack() as unknown as unknown[]).length = 0;};diff --git a/packages/studio-server/src/test/split-video-from-audio.test.ts b/packages/studio-server/src/test/split-video-from-audio.test.tsindex 97e206d193..0aaa2a34e0 100644--- a/packages/studio-server/src/test/split-video-from-audio.test.ts+++ b/packages/studio-server/src/test/split-video-from-audio.test.ts@@ -2,7 +2,6 @@ import {expect, test} from 'bun:test';import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';import {tmpdir} from 'node:os';import path from 'node:path';-import {CodemodsInternals} from '@remotion/codemods';import {createFileWatcherRegistry,setFileWatcherRegistry,@@ -12,8 +11,6 @@ import {splitVideoFromAudioHandler} from '../preview-server/routes/split-video-fimport {getUndoStack} from '../preview-server/undo-stack';import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';-const {splitVideoFromAudio} = CodemodsInternals;-const wrap = (element: string,imports = `import {Video} from '@remotion/media';`,@@ -30,255 +27,6 @@ export const Comp = () => {const elementLine = 6;-const split = async (element: string, imports?: string) => {- const input = wrap(element, imports);- const {output} = await splitVideoFromAudio({- input,- nodePath: lineContainingToNodePath(input, element),- });-- return output;-};--test('splitVideoFromAudio mutes the video and adds an Audio with the same timing', async () => {- const output = await split(- '<Video src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} style={{opacity: 0.5}} />',- );-- const singleLine = output.replace(/\s+/g, ' ');-- expect(output).toContain(`import {Video, Audio} from '@remotion/media';`);- expect(singleLine).toContain(- '<Video src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} style={{opacity: 0.5}} muted />',- );- expect(singleLine).toContain(- '<Audio src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} />',- );-});--test('splitVideoFromAudio preserves unrelated source formatting without calling the formatter', async () => {- const input = `import{Video}from"@remotion/media"--const untouched = {keep : "spacing"}-export const Comp=()=>(- <>- <Video- src = {"video.mp4"}- from = {10}- style = {{opacity:.5}}- />- <div data-value = "unchanged"/>- </>-)-`;- let formatCalls = 0;- const {formatted, nodePathRemappings, output} = await splitVideoFromAudio({- input,- nodePath: lineContainingToNodePath(input, '<Video'),- formatFile: () => {- formatCalls++;- throw new Error('Prettier must not be called');- },- });-- expect(formatCalls).toBe(0);- expect(formatted).toBe(true);- expect(output).toBe(`import{Video, Audio}from"@remotion/media"--const untouched = {keep : "spacing"}-export const Comp=()=>(- <>- <Video- src = {"video.mp4"}- from = {10}- style = {{opacity:.5}}- muted- />- <Audio src={"video.mp4"} from={10} />- <div data-value = "unchanged"/>- </>-)-`);- expect(nodePathRemappings).toEqual([- {- oldNodePath: lineContainingToNodePath(input, '<Video'),- newNodePath: lineContainingToNodePath(output, '<Video'),- },- {- oldNodePath: lineContainingToNodePath(input, '<div'),- newNodePath: lineContainingToNodePath(output, '<div'),- },- {- oldNodePath: null,- newNodePath: lineContainingToNodePath(output, '<Audio'),- },- ]);-});--test('splitVideoFromAudio does not copy non-audio props', async () => {- const output = await split(- '<Video src="video.mp4" name="my video" freeze={20} crop={{x: 0, y: 0, width: 100, height: 100}} />',- );-- expect(output).toContain('<Audio src="video.mp4" />');-});--test('splitVideoFromAudio wraps a root video in a fragment', async () => {- const input = `import {Video} from '@remotion/media';--export const Comp = () => <Video src="video.mp4" />;-`;- const {output} = await splitVideoFromAudio({- input,- nodePath: lineContainingToNodePath(input, '<Video'),- });-- expect(output).toBe(`import {Video, Audio} from '@remotion/media';--export const Comp = () => <>- <Video src="video.mp4" muted />- <Audio src="video.mp4" />-</>;-`);-});--test('splitVideoFromAudio separates siblings with one space on a shared line', async () => {- const input = `import {Video} from '@remotion/media';--export const Comp = () => (- <div>- <Video src="video.mp4" /></div>-);-`;- const {output} = await splitVideoFromAudio({- input,- nodePath: lineContainingToNodePath(input, '<Video'),- });-- expect(output).toBe(`import {Video, Audio} from '@remotion/media';--export const Comp = () => (- <div>- <Video src="video.mp4" muted /> <Audio src="video.mp4" /></div>-);-`);-});--test('splitVideoFromAudio preserves CRLF and tab indentation', async () => {- const input = [- `import {Video} from '@remotion/media';`,- '',- 'export const Comp = () => {',- '\treturn (',- '\t\t<>',- '\t\t\t<Video',- '\t\t\t\tsrc="video.mp4"',- '\t\t\t\ttrimBefore={10}',- '\t\t\t/>',- '\t\t</>',- '\t);',- '};',- '',- ].join('\r\n');- const {output} = await splitVideoFromAudio({- input,- nodePath: lineContainingToNodePath(input, '<Video'),- });-- expect(output).toBe(- [- `import {Video, Audio} from '@remotion/media';`,- '',- 'export const Comp = () => {',- '\treturn (',- '\t\t<>',- '\t\t\t<Video',- '\t\t\t\tsrc="video.mp4"',- '\t\t\t\ttrimBefore={10}',- '\t\t\t\tmuted',- '\t\t\t/>',- '\t\t\t<Audio src="video.mp4" trimBefore={10} />',- '\t\t</>',- '\t);',- '};',- '',- ].join('\r\n'),- );-});--test('splitVideoFromAudio replaces an existing muted prop', async () => {- const output = await split('<Video src="video.mp4" muted={false} />');-- expect(output).toContain('<Video src="video.mp4" muted />');- expect(output).not.toContain('muted={false}');-});--test('splitVideoFromAudio reuses an existing Audio import', async () => {- const output = await split(- '<Video src="video.mp4" />',- `import {Audio, Video} from '@remotion/media';`,- );-- expect(output).toContain(`import {Audio, Video} from '@remotion/media';`);- expect(output.match(/from '@remotion\/media'/g)?.length).toBe(1);-});--test('splitVideoFromAudio uses an aliased Audio import', async () => {- const output = await split(- '<Video src="video.mp4" />',- `import {Audio as Sound, Video} from '@remotion/media';`,- );-- expect(output).toContain(- `import {Audio as Sound, Video} from '@remotion/media';`,- );- expect(output).toContain('<Sound src="video.mp4" />');-});--test('splitVideoFromAudio imports Audio from the same module as the tag', async () => {- const output = await split(- '<OffthreadVideo src="video.mp4" from={5} />',- `import {OffthreadVideo} from 'remotion';`,- );-- expect(output).toContain(`import {OffthreadVideo, Audio} from 'remotion';`);- expect(output).toContain('<OffthreadVideo src="video.mp4" from={5} muted />');- expect(output).toContain('<Audio src="video.mp4" from={5} />');-});--test('splitVideoFromAudio follows import aliases', async () => {- const output = await split(- '<V src="video.mp4" />',- `import {Video as V} from '@remotion/media';`,- );-- expect(output).toContain(- `import {Video as V, Audio} from '@remotion/media';`,- );- expect(output).toContain('<Audio src="video.mp4" />');-});--test('splitVideoFromAudio rejects elements without a src attribute', async () => {- await expect(split('<Video from={0} />')).rejects.toThrow(- '<Video> has no src attribute',- );-});--test('splitVideoFromAudio rejects unimported tags', async () => {- await expect(split('<video src="video.mp4" />')).rejects.toThrow(- 'Could not find the import of <video>',- );-});--test('splitVideoFromAudio rejects an Audio import from another module', async () => {- await expect(- split(- '<Video src="video.mp4" />',- `import {Video} from '@remotion/media';\nimport {Audio} from 'remotion';`,- ),- ).rejects.toThrow('Audio is already imported from "remotion"');-});-const clearUndoStack = () => {(getUndoStack() as unknown as unknown[]).length = 0;};diff --git a/packages/studio-server/src/test/update-keyframes.test.ts b/packages/studio-server/src/test/update-keyframes.test.tsindex 45e6cf1736..87a19099e3 100644--- a/packages/studio-server/src/test/update-keyframes.test.ts+++ b/packages/studio-server/src/test/update-keyframes.test.ts@@ -2,7 +2,7 @@ import {expect, test} from 'bun:test';import type {InteractivitySchema} from 'remotion';import {NoReactInternals} from 'remotion/no-react';import {- updateEffectKeyframesAst,+ updateEffectKeyframes,updateSequenceKeyframes,} from '../codemods/update-keyframes/update-keyframes';import {computeSequencePropsStatusFromContent} from '../preview-server/routes/can-update-sequence-props';@@ -1849,12 +1849,12 @@ test('updateSequenceKeyframes keeps a color interpolation when one keyframe remaexpect(output).toContain("color={interpolateColors(frame, [100], ['blue'])}");});-test('updateEffectKeyframes converts a static value to a clamped interpolation', () => {+test('updateEffectKeyframes converts a static value to a clamped interpolation', async () => {const input = effectInput.replace('interpolate(frame, [0, 50, 100], [0.2, 0.5, 0.8])','0.2',);- const {serialized, oldValueStrings} = updateEffectKeyframesAst({+ const {output: serialized, oldValueStrings} = await updateEffectKeyframes({videoConfigValues: null,input,sequenceNodePath: lineColumnToNodePath(@@ -1877,8 +1877,8 @@ test('updateEffectKeyframes converts a static value to a clamped interpolation',expect(serialized).not.toContain('perceptual-scale');});-test('updateEffectKeyframes uses the schema keyframe output default', () => {- const {serialized} = updateEffectKeyframesAst({+test('updateEffectKeyframes uses the schema keyframe output default', async () => {+ const {output: serialized} = await updateEffectKeyframes({videoConfigValues: null,input: scaleEffectInput,sequenceNodePath: lineColumnToNodePath(@@ -1899,8 +1899,8 @@ test('updateEffectKeyframes uses the schema keyframe output default', () => {expect(serialized).toContain("output: 'perceptual-scale'");});-test('updateEffectKeyframes adds a missing prop before keyframing it', () => {- const {serialized, oldValueStrings} = updateEffectKeyframesAst({+test('updateEffectKeyframes adds a missing prop before keyframing it', async () => {+ const {output: serialized, oldValueStrings} = await updateEffectKeyframes({videoConfigValues: null,input: waveEffectInput,sequenceNodePath: lineColumnToNodePath(@@ -1925,9 +1925,9 @@ test('updateEffectKeyframes adds a missing prop before keyframing it', () => {expect(serialized).toContain("extrapolateRight: 'clamp'");});-test('updateEffectKeyframes adds props to a zero-argument effect', () => {+test('updateEffectKeyframes adds props to a zero-argument effect', async () => {const input = waveEffectInput.replace('wave({})', 'wave()');- const {serialized, oldValueStrings} = updateEffectKeyframesAst({+ const {output: serialized, oldValueStrings} = await updateEffectKeyframes({videoConfigValues: null,input,sequenceNodePath: lineColumnToNodePath(input, getLine(input, '<Solid')),@@ -1946,8 +1946,8 @@ test('updateEffectKeyframes adds props to a zero-argument effect', () => {expect(serialized).toContain('phase: interpolate(frame, [15], [45], {');});-test('updateEffectKeyframes sets one easing segment and fills linear segments', () => {- const {serialized} = updateEffectKeyframesAst({+test('updateEffectKeyframes sets one easing segment and fills linear segments', async () => {+ const {output: serialized} = await updateEffectKeyframes({videoConfigValues: null,input: effectInput,sequenceNodePath: lineColumnToNodePath(@@ -2013,8 +2013,12 @@ test('updateSequenceKeyframes converts the last color keyframe to a static value});});-test('updateEffectKeyframes removes a keyframe from an effect prop interpolation', () => {- const {serialized, oldValueStrings, effectCallee} = updateEffectKeyframesAst({+test('updateEffectKeyframes removes a keyframe from an effect prop interpolation', async () => {+ const {+ output: serialized,+ oldValueStrings,+ effectCallee,+ } = await updateEffectKeyframes({videoConfigValues: null,input: effectInput,sequenceNodePath: lineColumnToNodePath(@@ -2043,8 +2047,8 @@ test('updateEffectKeyframes removes a keyframe from an effect prop interpolation);});-test('updateEffectKeyframes allows moving keyframes outside the sequence range', () => {- const {serialized, newValueStrings} = updateEffectKeyframesAst({+test('updateEffectKeyframes allows moving keyframes outside the sequence range', async () => {+ const {output: serialized, newValueStrings} = await updateEffectKeyframes({videoConfigValues: null,input: effectInput,sequenceNodePath: lineColumnToNodePath(@@ -2074,8 +2078,8 @@ test('updateEffectKeyframes allows moving keyframes outside the sequence range',);});-test('updateEffectKeyframes replaces an existing keyframe when moving onto it', () => {- const {serialized, newValueStrings} = updateEffectKeyframesAst({+test('updateEffectKeyframes replaces an existing keyframe when moving onto it', async () => {+ const {output: serialized, newValueStrings} = await updateEffectKeyframes({videoConfigValues: null,input: effectInput,sequenceNodePath: lineColumnToNodePath(@@ -2102,12 +2106,12 @@ test('updateEffectKeyframes replaces an existing keyframe when moving onto it',);});-test('updateEffectKeyframes keeps an effect prop interpolation with one keyframe', () => {+test('updateEffectKeyframes keeps an effect prop interpolation with one keyframe', async () => {const input = effectInput.replace('interpolate(frame, [0, 50, 100], [0.2, 0.5, 0.8])','interpolate(frame, [0, 100], [0.2, 0.8])',);- const {serialized} = updateEffectKeyframesAst({+ const {output: serialized} = await updateEffectKeyframes({videoConfigValues: null,input,sequenceNodePath: lineColumnToNodePath(@@ -2130,31 +2134,35 @@ test('updateEffectKeyframes keeps an effect prop interpolation with one keyframeexpect(serialized).toContain('amount: interpolate(frame, [0], [0.2])');});-test('updateEffectKeyframes converts the last effect keyframe to a static value', () => {+test('updateEffectKeyframes converts the last effect keyframe to a static value', async () => {const input = effectInput.replace('interpolate(frame, [0, 50, 100], [0.2, 0.5, 0.8])','interpolate(frame, [40], [0.6])',);- const {serialized, oldValueStrings, newValueStrings, effectCallee} =- updateEffectKeyframesAst({- videoConfigValues: null,+ const {+ output: serialized,+ oldValueStrings,+ newValueStrings,+ effectCallee,+ } = await updateEffectKeyframes({+ videoConfigValues: null,+ input,+ sequenceNodePath: lineColumnToNodePath(input,- sequenceNodePath: lineColumnToNodePath(- input,- getLine(input, '<HtmlInCanvas'),- ),- effectIndex: 0,- updates: [- {- key: 'amount',- operation: {- type: 'remove',- frame: 40,- valueWhenLastKeyframeDeleted: null,- },+ getLine(input, '<HtmlInCanvas'),+ ),+ effectIndex: 0,+ updates: [+ {+ key: 'amount',+ operation: {+ type: 'remove',+ frame: 40,+ valueWhenLastKeyframeDeleted: null,},- ],- });+ },+ ],+ });expect(effectCallee).toBe('tint');expect(oldValueStrings).toEqual(['interpolate(frame, [40], [0.6])']);diff --git a/packages/studio-server/src/test/update-sequence-props.test.ts b/packages/studio-server/src/test/update-sequence-props.test.tsindex 689621064d..c437553e89 100644--- a/packages/studio-server/src/test/update-sequence-props.test.ts+++ b/packages/studio-server/src/test/update-sequence-props.test.ts@@ -1,14 +1,9 @@import {expect, test} from 'bun:test';-import * as recast from 'recast';import {NoReactInternals} from 'remotion/no-react';import {updateMultipleSequenceProps,updateSequenceProps,} from '../codemods/update-sequence-props/update-sequence-props';-import {- computeSequencePropsStatusFromContent,- takeCachedSequencePropsStatusAst,-} from '../preview-server/routes/can-update-sequence-props';import {lineColumnToNodePath} from './test-utils';const lightLeakInput = `import {LightLeak} from '@remotion/light-leaks';@@ -726,41 +721,6 @@ test('updateMultipleSequenceProps formats a multiline non-self-closing opening eexpect(formatted).toBe(true);});-test('updateMultipleSequenceProps reuses the status AST across the shared Recast runtime', async () => {- const nodePath = lineColumnToNodePath(lightLeakInput, 8);- computeSequencePropsStatusFromContent({- fileContents: lightLeakInput,- nodePath,- componentIdentity: null,- keys: ['hueShift'],- effects: [],- videoConfigValues: null,- });- expect(takeCachedSequencePropsStatusAst(`${lightLeakInput}\n`)).toBeNull();- const cachedAst = takeCachedSequencePropsStatusAst(lightLeakInput);- if (!cachedAst) {- throw new Error('Expected the status AST to be reusable');- }-- const {ast} = await updateMultipleSequenceProps({- input: lightLeakInput,- changes: [- {- nodePath,- updates: [{key: 'hueShift', value: 90, defaultValue: null}],- schema: NoReactInternals.sequenceSchema,- videoConfigValues: null,- },- ],- prettierConfigOverride: null,- ast: cachedAst,- });-- expect(ast).toBe(cachedAst);- expect(() => recast.print(ast).code).not.toThrow();- expect(takeCachedSequencePropsStatusAst(lightLeakInput)).toBeNull();-});-test('updateSequenceProps should update JSX text children', async () => {const input = `import React from 'react';import {Interactive} from 'remotion';diff --git a/packages/template-recorder/package.json b/packages/template-recorder/package.jsonindex f93d94af98..551a794cef 100644--- a/packages/template-recorder/package.json+++ b/packages/template-recorder/package.json@@ -20,6 +20,7 @@"@remotion/animation-utils": "workspace:*","@remotion/captions": "workspace:*","@remotion/cli": "workspace:*",+ "@remotion/codemods": "workspace:*","@remotion/google-fonts": "workspace:*","@remotion/install-whisper-cpp": "workspace:*","@remotion/lambda": "workspace:*",diff --git a/packages/template-recorder/scripts/server/register-composition.ts b/packages/template-recorder/scripts/server/register-composition.tsindex ba1b319e86..783cd85996 100644--- a/packages/template-recorder/scripts/server/register-composition.ts+++ b/packages/template-recorder/scripts/server/register-composition.ts@@ -1,86 +1,84 @@-import {existsSync, readFileSync, writeFileSync} from 'fs';-import path from 'path';-import {StudioServerInternals} from '@remotion/studio-server';+import { existsSync, readFileSync, writeFileSync } from "fs";+import path from "path";+import {+ duplicateComposition,+ setCompositionDefaultProps,+} from "@remotion/codemods";-const ROOT_RELATIVE_PATH = path.join('remotion', 'Root.tsx');-const TEMPLATE_COMPOSITION_ID = 'empty';+const ROOT_RELATIVE_PATH = path.join("remotion", "Root.tsx");+const TEMPLATE_COMPOSITION_ID = "empty";const compositionExists = (src: string, compositionId: string) => {- return (- src.includes(`id="${compositionId}"`) ||- src.includes(`id={'${compositionId}'}`) ||- src.includes(`id={"${compositionId}"}`)- );+ return (+ src.includes(`id="${compositionId}"`) ||+ src.includes(`id={'${compositionId}'}`) ||+ src.includes(`id={"${compositionId}"}`)+ );};const getDefaultPropsForNewProject = () => ({- theme: 'light',- canvasLayout: 'square',- platform: 'youtube',- scenes: [- {- type: 'videoscene',- webcamPosition: 'bottom-right',- endOffset: 0,- transitionToNextScene: false,- newChapter: '',- stopChapteringAfterThis: false,- music: 'none',- startOffset: 0,- bRolls: [],- },- ],- scenesAndMetadata: [],+ theme: "light",+ canvasLayout: "square",+ platform: "youtube",+ scenes: [+ {+ type: "videoscene",+ webcamPosition: "bottom-right",+ endOffset: 0,+ transitionToNextScene: false,+ newChapter: "",+ stopChapteringAfterThis: false,+ music: "none",+ startOffset: 0,+ bRolls: [],+ },+ ],+ scenesAndMetadata: [],});export const registerComposition = async ({- rootDir,- projectName,+ rootDir,+ projectName,}: {- rootDir: string;- projectName: string;-}): Promise<{registered: boolean; reason?: string}> => {- const rootPath = path.join(rootDir, ROOT_RELATIVE_PATH);+ rootDir: string;+ projectName: string;+}): Promise<{ registered: boolean; reason?: string }> => {+ const rootPath = path.join(rootDir, ROOT_RELATIVE_PATH);- if (!existsSync(rootPath)) {- return {registered: false, reason: 'Root.tsx not found'};- }+ if (!existsSync(rootPath)) {+ return { registered: false, reason: "Root.tsx not found" };+ }- const src = readFileSync(rootPath, 'utf-8');+ const src = readFileSync(rootPath, "utf-8");- if (compositionExists(src, projectName)) {- return {registered: false, reason: 'Composition already exists'};- }+ if (compositionExists(src, projectName)) {+ return { registered: false, reason: "Composition already exists" };+ }- try {- const duplicated = await StudioServerInternals.applyCodemodToFile({- filePath: rootPath,- codeMod: {- type: 'duplicate-composition',- idToDuplicate: TEMPLATE_COMPOSITION_ID,- newId: projectName,- newHeight: null,- newWidth: null,- newFps: null,- newDurationInFrames: null,- tag: 'Composition',- },- });+ try {+ const duplicated = duplicateComposition({+ project: { rootDir, files: { [rootPath]: src } },+ compositionFile: rootPath,+ compositionId: TEMPLATE_COMPOSITION_ID,+ newId: projectName,+ });+ const result = setCompositionDefaultProps({+ project: duplicated.project,+ compositionFile: rootPath,+ compositionId: projectName,+ defaultProps: getDefaultPropsForNewProject(),+ });+ const withDefaultScene = result.project.files[rootPath];+ if (withDefaultScene === undefined) {+ throw new Error("Could not find the updated composition file");+ }- const {output: withDefaultScene} =- await StudioServerInternals.updateDefaultProps({- input: duplicated.files[rootPath],- compositionId: projectName,- newDefaultProps: getDefaultPropsForNewProject(),- enumPaths: [],- });-- writeFileSync(rootPath, withDefaultScene, 'utf-8');- return {registered: true};- } catch (err) {- return {- registered: false,- reason: err instanceof Error ? err.message : String(err),- };- }+ writeFileSync(rootPath, withDefaultScene, "utf-8");+ return { registered: true };+ } catch (err) {+ return {+ registered: false,+ reason: err instanceof Error ? err.message : String(err),+ };+ }};