Skip to content

🎥 Make videos programmatically with React

refactor(codemods): align exports with package conventions

JonnyBurgerd99575cf4f96
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index b2e357fa00..8d57871d74 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -1,41 +1,8 @@
import {
- addEffect as addEffectCodemod,
- basicCaptionsElementSource,
- computeSequencePropsStatusFromContent,
- computeSequencePropsSubscriptionFromContent,
- deleteJsxNodes,
- deleteEffects as deleteEffectsCodemod,
- duplicateEffects as duplicateEffectsCodemod,
- duplicateCompositionInSource,
- duplicateJsxNodes as duplicateJsxNodesCodemod,
- findProjectFile,
- getCanUpdateDefaultPropsForProject,
- getBasicCaptionsElementFile,
- getCompositionComponentInfo,
- getCompositionFile,
- getFolderFile,
- getRootFileForProject,
- insertJsxElementIntoProjectWithNodePathRemappings,
- insertBasicCaptions as insertBasicCaptionsCodemod,
- JsxElementIdentityMismatchError,
- JsxElementNotFoundAtLocationError,
- makeInMemoryInsertJsxElementCodemodEnvironment,
- makeNewCompositionComponentSource,
- parseAndApplyCodemod,
- pasteEffects as pasteEffectsCodemod,
- reorderEffect as reorderEffectCodemod,
- reorderSequence as reorderSequenceCodemod,
- resolveCompositionComponentWithFile,
- simpleDiff,
- splitJsxSequences as splitJsxSequencesCodemod,
- splitVideoFromAudio as splitVideoFromAudioCodemod,
- updateDefaultProps as updateDefaultPropsCodemod,
- updateEffectProps as updateEffectPropsCodemod,
- updateEffectKeyframes,
- updateSequenceKeyframes,
+ CodeModsInternals,
type EffectKeyframeUpdate,
type SequenceKeyframeUpdate,
-} from '@remotion/codemods/internal';
+} from '@remotion/codemods';
import {
StudioProtocolInternals,
type StudioElementPayload,
@@ -71,6 +38,43 @@ import {downloadRemoteAssetInBrowserStudio} from './download-remote-asset';
import {saveSequencePropsInProject} from './save-sequence-props';
import type {VirtualProject} from './types';
+const {
+ addEffect: addEffectCodemod,
+ basicCaptionsElementSource,
+ computeSequencePropsStatusFromContent,
+ computeSequencePropsSubscriptionFromContent,
+ deleteEffects: deleteEffectsCodemod,
+ deleteJsxNodes,
+ duplicateCompositionInSource,
+ duplicateEffects: duplicateEffectsCodemod,
+ duplicateJsxNodes: duplicateJsxNodesCodemod,
+ findProjectFile,
+ getBasicCaptionsElementFile,
+ getCanUpdateDefaultPropsForProject,
+ getCompositionComponentInfo,
+ getCompositionFile,
+ getFolderFile,
+ getRootFileForProject,
+ insertBasicCaptions: insertBasicCaptionsCodemod,
+ insertJsxElementIntoProjectWithNodePathRemappings,
+ JsxElementIdentityMismatchError,
+ JsxElementNotFoundAtLocationError,
+ makeInMemoryInsertJsxElementCodemodEnvironment,
+ makeNewCompositionComponentSource,
+ parseAndApplyCodemod,
+ pasteEffects: pasteEffectsCodemod,
+ reorderEffect: reorderEffectCodemod,
+ reorderSequence: reorderSequenceCodemod,
+ resolveCompositionComponentWithFile,
+ simpleDiff,
+ splitJsxSequences: splitJsxSequencesCodemod,
+ splitVideoFromAudio: splitVideoFromAudioCodemod,
+ updateDefaultProps: updateDefaultPropsCodemod,
+ updateEffectKeyframes,
+ updateEffectProps: updateEffectPropsCodemod,
+ updateSequenceKeyframes,
+} = CodeModsInternals;
+
/*
* SVG conversion uses SVGR in desktop Studio. SVGR depends on Node APIs, so
* Browser Studio deliberately reports the unsupported operation instead.
@@ -97,11 +101,6 @@ const getStructuredError = (error: unknown) => ({
stack: error instanceof Error && error.stack ? error.stack : '',
});
-export {
- insertSolidIntoProject,
- insertSolidIntoProjectWithNodePathRemappings,
-} from '@remotion/codemods/internal';
-
export type BrowserStudioOperationsController = BrowserStudioOperations & {
emitEvent: (event: EventSourceEvent) => void;
resetHistory: () => void;
diff --git a/packages/browser-studio/src/browser-studio-project-controller.ts b/packages/browser-studio/src/browser-studio-project-controller.ts
index bc796395df..1bb93f099c 100644
--- a/packages/browser-studio/src/browser-studio-project-controller.ts
+++ b/packages/browser-studio/src/browser-studio-project-controller.ts
@@ -1,4 +1,4 @@
-import {findSearchPosition} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import type {
BrowserStudioOperations,
EventSourceEvent,
@@ -21,6 +21,8 @@ import type {
VirtualProjectPublicFile,
} from './types';
+const {findSearchPosition} = CodeModsInternals;
+
type ProjectNodePathMutationFiles = SequenceNodePathMutation['files'];
type HistoryEntry = {
diff --git a/packages/browser-studio/src/save-sequence-props.ts b/packages/browser-studio/src/save-sequence-props.ts
index 31051ad716..df8d3ef6e4 100644
--- a/packages/browser-studio/src/save-sequence-props.ts
+++ b/packages/browser-studio/src/save-sequence-props.ts
@@ -1,10 +1,7 @@
import {
- computeSequencePropsStatusFromContent,
- findProjectFile,
- updateInlineCaptionPatches,
+ CodeModsInternals,
type SequencePropsNodeUpdate,
- updateMultipleSequenceProps,
-} from '@remotion/codemods/internal';
+} from '@remotion/codemods';
import type {
SaveSequencePropEdit,
SaveSequencePropsRequest,
@@ -15,6 +12,13 @@ import {getAllSchemaKeys, getAssetSchemaKeys} from '@remotion/studio-shared';
import type {SequenceNodePath} from 'remotion';
import type {VirtualProject} from './types';
+const {
+ computeSequencePropsStatusFromContent,
+ findProjectFile,
+ updateInlineCaptionPatches,
+ updateMultipleSequenceProps,
+} = CodeModsInternals;
+
const parseSequencePropEditValue = (
value: SaveSequencePropEdit['value'],
): unknown => {
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index d41951ea88..494453104e 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -1,17 +1,19 @@
import {expect, test} from 'bun:test';
-import {basicCaptionsElementSource} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import {createElementPayload} from '@remotion/studio-protocol';
import type {EventSourceEvent} from '@remotion/studio-shared';
import type {InteractivitySchema} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
-import {
- createBrowserStudioOperations,
- insertSolidIntoProject,
- insertSolidIntoProjectWithNodePathRemappings,
-} from '../browser-studio-operations';
+import {createBrowserStudioOperations} from '../browser-studio-operations';
import {createBlankTemplateProject} from '../templates/blank';
import type {VirtualProject} from '../types';
+const {
+ basicCaptionsElementSource,
+ insertSolidIntoProject,
+ insertSolidIntoProjectWithNodePathRemappings,
+} = CodeModsInternals;
+
const insertSolid = (
project: VirtualProject,
compositionFile = '/project/src/Composition.tsx',
diff --git a/packages/codemods/bundle.ts b/packages/codemods/bundle.ts
index 28a5a8b1ea..35f2c00014 100644
--- a/packages/codemods/bundle.ts
+++ b/packages/codemods/bundle.ts
@@ -10,7 +10,6 @@ const external = ['@remotion/studio-shared', 'recast'];
console.time('Generated.');
const esmOutput = await build({
entrypoints: [
- 'src/public.ts',
'src/index.ts',
'src/resolve-composition-component-location.ts',
],
@@ -19,7 +18,6 @@ const esmOutput = await build({
});
const cjsOutput = await build({
entrypoints: [
- 'src/public.ts',
'src/index.ts',
'src/resolve-composition-component-location.ts',
],
diff --git a/packages/codemods/package.json b/packages/codemods/package.json
index b6484a5532..24f510be27 100644
--- a/packages/codemods/package.json
+++ b/packages/codemods/package.json
@@ -2,9 +2,9 @@
"name": "@remotion/codemods",
"version": "4.0.526",
"description": "Codemods for Remotion projects",
- "main": "dist/public.cjs",
- "types": "dist/public.d.ts",
- "module": "dist/esm/public.mjs",
+ "main": "dist/index.cjs",
+ "types": "dist/index.d.ts",
+ "module": "dist/esm/index.mjs",
"repository": {
"url": "https://github.com/remotion-dev/remotion/tree/main/packages/codemods"
},
@@ -33,12 +33,6 @@
},
"exports": {
".": {
- "types": "./dist/public.d.ts",
- "require": "./dist/public.cjs",
- "module": "./dist/esm/public.mjs",
- "import": "./dist/esm/public.mjs"
- },
- "./internal": {
"types": "./dist/index.d.ts",
"require": "./dist/index.cjs",
"module": "./dist/esm/index.mjs",
diff --git a/packages/codemods/src/add-solid.ts b/packages/codemods/src/add-solid.ts
new file mode 100644
index 0000000000..f158293954
--- /dev/null
+++ b/packages/codemods/src/add-solid.ts
@@ -0,0 +1,61 @@
+import type {SequenceNodePath} from 'remotion';
+import type {CodemodProject, CodemodResult} from './codemod-project';
+import {getCodemodResult} from './codemod-project';
+import {insertSolidIntoProjectWithNodePathRemappings} from './internals';
+
+export type AddSolidOptions<Project extends CodemodProject> = {
+ project: Project;
+ compositionId: string;
+ compositionFile: string;
+ width: number;
+ height: number;
+ from?: number;
+ position?: {x: number; y: number};
+};
+
+export type AddSolidResult<Project extends CodemodProject> =
+ CodemodResult<Project> & {
+ insertedNode: {
+ filePath: string;
+ nodePath: SequenceNodePath;
+ };
+ };
+
+export const addSolid = <Project extends CodemodProject>({
+ project,
+ compositionId,
+ compositionFile,
+ width,
+ height,
+ from,
+ position,
+}: AddSolidOptions<Project>): AddSolidResult<Project> => {
+ const insertion = insertSolidIntoProjectWithNodePathRemappings({
+ project,
+ request: {
+ compositionFile,
+ compositionId,
+ element: {
+ height,
+ position: position ?? null,
+ type: 'solid',
+ width,
+ },
+ from: from ?? null,
+ },
+ });
+ const insertedNodePath = insertion.nodePathRemappings.find(
+ (remapping) => remapping.oldNodePath === null,
+ )?.newNodePath;
+ if (!insertedNodePath) {
+ throw new Error('Could not determine the inserted JSX node path');
+ }
+
+ return {
+ ...getCodemodResult({nextProject: insertion.project, project}),
+ insertedNode: {
+ filePath: insertion.filePath,
+ nodePath: insertedNodePath,
+ },
+ };
+};
diff --git a/packages/codemods/src/codemod-project.ts b/packages/codemods/src/codemod-project.ts
new file mode 100644
index 0000000000..7aff311c44
--- /dev/null
+++ b/packages/codemods/src/codemod-project.ts
@@ -0,0 +1,37 @@
+export type CodemodProject = {
+ files: Record<string, string>;
+ rootDir: string;
+};
+
+export type CodemodFileChange = {
+ filePath: string;
+ previousContents: string | null;
+ nextContents: string | null;
+};
+
+export type CodemodResult<Project extends CodemodProject> = {
+ project: Project;
+ changes: CodemodFileChange[];
+};
+
+export const getCodemodResult = <Project extends CodemodProject>({
+ project,
+ nextProject,
+}: {
+ project: Project;
+ nextProject: Project;
+}): CodemodResult<Project> => {
+ const filePaths = new Set([
+ ...Object.keys(project.files),
+ ...Object.keys(nextProject.files),
+ ]);
+ const changes = [...filePaths].flatMap((filePath): CodemodFileChange[] => {
+ const previousContents = project.files[filePath] ?? null;
+ const nextContents = nextProject.files[filePath] ?? null;
+ return previousContents === nextContents
+ ? []
+ : [{filePath, previousContents, nextContents}];
+ });
+
+ return {changes, project: nextProject};
+};
diff --git a/packages/codemods/src/composition-source-edits.ts b/packages/codemods/src/composition-source-edits.ts
index 60076acc16..100635dc81 100644
--- a/packages/codemods/src/composition-source-edits.ts
+++ b/packages/codemods/src/composition-source-edits.ts
@@ -2,7 +2,7 @@ import type {JSXElement} from '@babel/types';
import type {RecastCodemod} from '@remotion/studio-shared';
import {namedTypes} from 'ast-types';
import * as recast from 'recast';
-import {getNodeSourceEdit} from './delete-jsx-node';
+import {getNodeSourceEdit} from './delete-jsx-node-internal';
import {getCompositionId} from './duplicate-composition';
import {getInsertionRootSourceEdit} from './insert-jsx-element';
import {printInsertedJsx} from './print-jsx';
diff --git a/packages/codemods/src/delete-jsx-node-internal.ts b/packages/codemods/src/delete-jsx-node-internal.ts
new file mode 100644
index 0000000000..498ddec60d
--- /dev/null
+++ b/packages/codemods/src/delete-jsx-node-internal.ts
@@ -0,0 +1,627 @@
+import type {
+ ArrayExpression,
+ ArrowFunctionExpression,
+ AssignmentExpression,
+ CallExpression,
+ ConditionalExpression,
+ ExportDefaultDeclaration,
+ Expression,
+ ExpressionStatement,
+ File,
+ JSXElement,
+ JSXExpressionContainer,
+ JSXFragment,
+ JSXIdentifier,
+ JSXMemberExpression,
+ JSXOpeningElement,
+ LogicalExpression,
+ NewExpression,
+ Node,
+ OptionalCallExpression,
+ ParenthesizedExpression,
+ ReturnStatement,
+ SequenceExpression,
+ TSAsExpression,
+ VariableDeclarator,
+} from '@babel/types';
+import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
+import * as recast from 'recast';
+import type {SequenceNodePath} from 'remotion';
+import {
+ captureJsxNodePaths,
+ getNodePathRemappings,
+} from './get-node-path-remappings';
+import {recastLocToOffset} from './recast-loc-to-offset';
+import {getAstNodePath} from './sequence-props/get-ast-node-path';
+import {parseAst} from './sequence-props/parse-ast';
+
+const {builders: b, namedTypes} = recast.types;
+
+/** Recast `builders.nullLiteral()` is typed against ast-types; normalize to Babel `Expression`. */
+const nullLiteralExpr = (): Expression =>
+ b.nullLiteral() as unknown as Expression;
+
+const jsxOpeningNameToString = (name: JSXOpeningElement['name']): string => {
+ if (name.type === 'JSXIdentifier') {
+ return name.name;
+ }
+
+ if (name.type === 'JSXNamespacedName') {
+ return `${name.namespace.name}:${name.name.name}`;
+ }
+
+ if (name.type === 'JSXMemberExpression') {
+ const memberToString = (
+ expr: JSXMemberExpression | JSXIdentifier,
+ ): string => {
+ if (expr.type === 'JSXIdentifier') {
+ return expr.name;
+ }
+
+ return `${memberToString(expr.object)}.${expr.property.name}`;
+ };
+
+ return memberToString(name);
+ }
+
+ return 'Unknown';
+};
+
+/** e.g. `<Video>` or `<Remotion.Sequence>` for logs and undo copy. */
+export const getJsxElementTagLabel = (element: JSXElement): string => {
+ return `<${jsxOpeningNameToString(element.openingElement.name)}>`;
+};
+
+export const findJsxElementPathForDeletion = (
+ ast: File,
+ nodePath: SequenceNodePath,
+): recast.types.NodePath | null => {
+ const current = getAstNodePath(ast, nodePath);
+ if (!current) {
+ return null;
+ }
+
+ if (namedTypes.JSXOpeningElement.check(current.value)) {
+ const parent = current.parentPath;
+ if (parent && namedTypes.JSXElement.check(parent.value)) {
+ return parent;
+ }
+
+ return null;
+ }
+
+ if (namedTypes.JSXElement.check(current.value)) {
+ return current;
+ }
+
+ return null;
+};
+
+const replaceInLogicalExpression = (
+ parent: LogicalExpression,
+ node: JSXElement,
+): boolean => {
+ const nl = nullLiteralExpr();
+ if (parent.left === node) {
+ parent.left = nl;
+ return true;
+ }
+
+ if (parent.right === node) {
+ parent.right = nl;
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInConditionalExpression = (
+ parent: ConditionalExpression,
+ node: JSXElement,
+): boolean => {
+ const nl = nullLiteralExpr();
+ if (parent.consequent === node) {
+ parent.consequent = nl;
+ return true;
+ }
+
+ if (parent.alternate === node) {
+ parent.alternate = nl;
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInArrowFunctionExpression = (
+ parent: ArrowFunctionExpression,
+ node: JSXElement,
+): boolean => {
+ if (parent.body === node) {
+ parent.body = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInReturnStatement = (
+ parent: ReturnStatement,
+ node: JSXElement,
+): boolean => {
+ if (parent.argument === node) {
+ parent.argument = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInCallExpression = (
+ parent: CallExpression,
+ node: JSXElement,
+): boolean => {
+ const idx = parent.arguments.indexOf(node);
+ if (idx !== -1) {
+ parent.arguments[idx] = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInOptionalCallExpression = (
+ parent: OptionalCallExpression,
+ node: JSXElement,
+): boolean => {
+ const idx = parent.arguments.indexOf(node);
+ if (idx !== -1) {
+ parent.arguments[idx] = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInArrayExpression = (
+ parent: ArrayExpression,
+ node: JSXElement,
+): boolean => {
+ const idx = parent.elements.indexOf(node);
+ if (idx !== -1) {
+ parent.elements[idx] = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInAssignmentExpression = (
+ parent: AssignmentExpression,
+ node: JSXElement,
+): boolean => {
+ if (parent.right === node) {
+ parent.right = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInVariableDeclarator = (
+ parent: VariableDeclarator,
+ node: JSXElement,
+): boolean => {
+ if (parent.init === node) {
+ parent.init = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInExportDefaultDeclaration = (
+ parent: ExportDefaultDeclaration,
+ node: JSXElement,
+): boolean => {
+ if (parent.declaration === node) {
+ parent.declaration = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInSequenceExpression = (
+ parent: SequenceExpression,
+ node: JSXElement,
+): boolean => {
+ const idx = parent.expressions.indexOf(node);
+ if (idx !== -1) {
+ parent.expressions[idx] = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInNewExpression = (
+ parent: NewExpression,
+ node: JSXElement,
+): boolean => {
+ const idx = parent.arguments.indexOf(node);
+ if (idx !== -1) {
+ parent.arguments[idx] = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInExpressionStatement = (
+ parent: ExpressionStatement,
+ node: JSXElement,
+): boolean => {
+ if (parent.expression === node) {
+ parent.expression = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInParenthesizedExpression = (
+ parent: ParenthesizedExpression,
+ node: JSXElement,
+): boolean => {
+ if (parent.expression === node) {
+ parent.expression = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInJSXExpressionContainer = (
+ parent: JSXExpressionContainer,
+ node: JSXElement,
+): boolean => {
+ if (parent.expression === node) {
+ parent.expression = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInTSAsExpression = (
+ parent: TSAsExpression,
+ node: JSXElement,
+): boolean => {
+ if (parent.expression === node) {
+ parent.expression = nullLiteralExpr();
+ return true;
+ }
+
+ return false;
+};
+
+const replaceInJSXParentChildren = (
+ parent: JSXElement | JSXFragment,
+ node: JSXElement,
+): boolean => {
+ const idx = parent.children.indexOf(node);
+ if (idx !== -1) {
+ parent.children.splice(idx, 1);
+ return true;
+ }
+
+ return false;
+};
+
+const replaceNodeWithNull = (parentNode: Node, node: JSXElement): boolean => {
+ if (namedTypes.LogicalExpression.check(parentNode)) {
+ return replaceInLogicalExpression(parentNode, node);
+ }
+
+ if (namedTypes.ConditionalExpression.check(parentNode)) {
+ return replaceInConditionalExpression(parentNode, node);
+ }
+
+ if (namedTypes.ArrowFunctionExpression.check(parentNode)) {
+ return replaceInArrowFunctionExpression(parentNode, node);
+ }
+
+ if (namedTypes.ReturnStatement.check(parentNode)) {
+ return replaceInReturnStatement(parentNode, node);
+ }
+
+ if (namedTypes.CallExpression.check(parentNode)) {
+ return replaceInCallExpression(parentNode, node);
+ }
+
+ if (parentNode.type === 'OptionalCallExpression') {
+ return replaceInOptionalCallExpression(parentNode, node);
+ }
+
+ if (namedTypes.ArrayExpression.check(parentNode)) {
+ return replaceInArrayExpression(parentNode, node);
+ }
+
+ if (namedTypes.AssignmentExpression.check(parentNode)) {
+ return replaceInAssignmentExpression(parentNode, node);
+ }
+
+ if (namedTypes.VariableDeclarator.check(parentNode)) {
+ return replaceInVariableDeclarator(parentNode, node);
+ }
+
+ if (namedTypes.ExportDefaultDeclaration.check(parentNode)) {
+ return replaceInExportDefaultDeclaration(parentNode, node);
+ }
+
+ if (namedTypes.SequenceExpression.check(parentNode)) {
+ return replaceInSequenceExpression(parentNode, node);
+ }
+
+ if (namedTypes.NewExpression.check(parentNode)) {
+ return replaceInNewExpression(parentNode, node);
+ }
+
+ if (namedTypes.ExpressionStatement.check(parentNode)) {
+ return replaceInExpressionStatement(parentNode, node);
+ }
+
+ if (namedTypes.ParenthesizedExpression.check(parentNode)) {
+ return replaceInParenthesizedExpression(parentNode, node);
+ }
+
+ if (namedTypes.JSXExpressionContainer.check(parentNode)) {
+ return replaceInJSXExpressionContainer(parentNode, node);
+ }
+
+ if (namedTypes.TSAsExpression.check(parentNode)) {
+ return replaceInTSAsExpression(parentNode, node);
+ }
+
+ if (namedTypes.JSXElement.check(parentNode)) {
+ return replaceInJSXParentChildren(parentNode, node);
+ }
+
+ if (namedTypes.JSXFragment.check(parentNode)) {
+ return replaceInJSXParentChildren(parentNode, node);
+ }
+
+ return false;
+};
+
+export const deleteJsxElementAtPath = (
+ jsxPath: recast.types.NodePath,
+): void => {
+ const {node, parentPath} = jsxPath;
+ if (!parentPath) {
+ throw new Error('Cannot delete JSX element with no parent');
+ }
+
+ const jsxNode = node as JSXElement;
+
+ if (replaceNodeWithNull(parentPath.node, jsxNode)) {
+ return;
+ }
+
+ // Recast can replace this node in arbitrary parent contexts.
+ jsxPath.replace(b.nullLiteral());
+};
+
+type SourceEdit = {
+ end: number;
+ replacement: string;
+ start: number;
+};
+
+export const getNodeSourceEdit = ({
+ input,
+ jsxPath,
+}: {
+ input: string;
+ jsxPath: recast.types.NodePath;
+}): SourceEdit => {
+ const node = jsxPath.node as JSXElement;
+ if (!node.loc) {
+ throw new Error('Cannot delete a JSX element without a source location');
+ }
+
+ const start = recastLocToOffset(input, node.loc.start);
+ const end = recastLocToOffset(input, node.loc.end);
+ const parentNode = jsxPath.parentPath?.node;
+ const isJsxChild =
+ parentNode !== undefined &&
+ (namedTypes.JSXElement.check(parentNode) ||
+ namedTypes.JSXFragment.check(parentNode));
+
+ if (!isJsxChild) {
+ const {extra} = node as JSXElement & {
+ extra?: {parenthesized?: boolean};
+ };
+ if (extra?.parenthesized) {
+ let openingParenthesis = start - 1;
+ while (openingParenthesis >= 0 && /\s/.test(input[openingParenthesis])) {
+ openingParenthesis--;
+ }
+
+ let closingParenthesis = end;
+ while (
+ closingParenthesis < input.length &&
+ /\s/.test(input[closingParenthesis])
+ ) {
+ closingParenthesis++;
+ }
+
+ if (
+ input[openingParenthesis] === '(' &&
+ input[closingParenthesis] === ')'
+ ) {
+ return {
+ end: closingParenthesis + 1,
+ replacement: 'null',
+ start: openingParenthesis,
+ };
+ }
+ }
+
+ return {end, replacement: 'null', start};
+ }
+
+ const lineStart = input.lastIndexOf('\n', start - 1) + 1;
+ const nextLineStart = input.indexOf('\n', end);
+ const lineEnd = nextLineStart === -1 ? input.length : nextLineStart;
+ const beforeNode = input.slice(lineStart, start);
+ const afterNode = input.slice(end, lineEnd);
+
+ if (beforeNode.trim() === '' && afterNode.trim() === '') {
+ return {
+ end: nextLineStart === -1 ? input.length : nextLineStart + 1,
+ replacement: '',
+ start: lineStart,
+ };
+ }
+
+ return {end, replacement: '', start};
+};
+
+const applySourceEdits = ({
+ edits,
+ input,
+}: {
+ edits: SourceEdit[];
+ input: string;
+}): string => {
+ const sorted = edits
+ .slice()
+ .sort((left, right) => left.start - right.start || right.end - left.end);
+ const nonOverlapping: SourceEdit[] = [];
+
+ for (const edit of sorted) {
+ const previous = nonOverlapping[nonOverlapping.length - 1];
+ if (previous && edit.start < previous.end) {
+ if (edit.end <= previous.end) {
+ continue;
+ }
+
+ throw new Error('Overlapping JSX deletion source ranges');
+ }
+
+ nonOverlapping.push(edit);
+ }
+
+ let output = input;
+ for (let i = nonOverlapping.length - 1; i >= 0; i--) {
+ const edit = nonOverlapping[i];
+ output =
+ output.slice(0, edit.start) + edit.replacement + output.slice(edit.end);
+ }
+
+ return output;
+};
+
+export const deleteJsxNodes = ({
+ input,
+ nodePaths,
+}: {
+ input: string;
+ nodePaths: SequenceNodePath[];
+ // Kept optional for compatibility with callers from before source edits
+ // replaced the full-file formatting pass.
+ formatFile?: (input: {
+ contents: string;
+ prettierConfigOverride: Record<string, unknown> | null;
+ }) => Promise<{output: string; formatted: boolean}>;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}): Promise<{
+ output: string;
+ formatted: boolean;
+ nodeLabels: string[];
+ logLines: number[];
+ nodePathRemappings: SequenceNodePathRemapping[];
+}> => {
+ if (nodePaths.length === 0) {
+ throw new Error('No JSX nodes were specified for deletion');
+ }
+
+ const ast = parseAst(input);
+ const capturedNodePaths = captureJsxNodePaths(ast);
+ const pathsToDelete = nodePaths.map((nodePath) => {
+ const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
+ if (!jsxPath) {
+ throw new Error(
+ 'Could not find a JSX element at the specified location to delete',
+ );
+ }
+
+ const jsxElement = jsxPath.node as JSXElement;
+
+ return {
+ jsxPath,
+ nodeLabel: getJsxElementTagLabel(jsxElement),
+ logLine:
+ jsxElement.openingElement.loc?.start.line ??
+ jsxElement.loc?.start.line ??
+ 1,
+ };
+ });
+
+ const sourceEdits = pathsToDelete.map(({jsxPath}) =>
+ getNodeSourceEdit({input, jsxPath}),
+ );
+
+ for (const {jsxPath} of pathsToDelete) {
+ deleteJsxElementAtPath(jsxPath);
+ }
+
+ const output = applySourceEdits({edits: sourceEdits, input});
+ const {nodePathRemappings} = getNodePathRemappings({
+ ast,
+ captured: capturedNodePaths,
+ output,
+ });
+
+ return Promise.resolve({
+ output,
+ formatted: true,
+ nodeLabels: pathsToDelete.map(({nodeLabel}) => nodeLabel),
+ logLines: pathsToDelete.map(({logLine}) => logLine),
+ nodePathRemappings,
+ });
+};
+
+export const deleteJsxNode = async ({
+ input,
+ nodePath,
+}: {
+ input: string;
+ nodePath: SequenceNodePath;
+ // Kept optional for compatibility with callers from before source edits
+ // replaced the full-file formatting pass.
+ formatFile?: (input: {
+ contents: string;
+ prettierConfigOverride: Record<string, unknown> | null;
+ }) => Promise<{output: string; formatted: boolean}>;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}): Promise<{
+ output: string;
+ formatted: boolean;
+ nodeLabel: string;
+ logLine: number;
+}> => {
+ const {output, formatted, nodeLabels, logLines} = await deleteJsxNodes({
+ input,
+ nodePaths: [nodePath],
+ });
+
+ return {
+ output,
+ formatted,
+ nodeLabel: nodeLabels[0],
+ logLine: logLines[0],
+ };
+};
diff --git a/packages/codemods/src/delete-jsx-node.ts b/packages/codemods/src/delete-jsx-node.ts
index 498ddec60d..f6b5b6675b 100644
--- a/packages/codemods/src/delete-jsx-node.ts
+++ b/packages/codemods/src/delete-jsx-node.ts
@@ -1,627 +1,32 @@
-import type {
- ArrayExpression,
- ArrowFunctionExpression,
- AssignmentExpression,
- CallExpression,
- ConditionalExpression,
- ExportDefaultDeclaration,
- Expression,
- ExpressionStatement,
- File,
- JSXElement,
- JSXExpressionContainer,
- JSXFragment,
- JSXIdentifier,
- JSXMemberExpression,
- JSXOpeningElement,
- LogicalExpression,
- NewExpression,
- Node,
- OptionalCallExpression,
- ParenthesizedExpression,
- ReturnStatement,
- SequenceExpression,
- TSAsExpression,
- VariableDeclarator,
-} from '@babel/types';
-import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
-import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
-import {
- captureJsxNodePaths,
- getNodePathRemappings,
-} from './get-node-path-remappings';
-import {recastLocToOffset} from './recast-loc-to-offset';
-import {getAstNodePath} from './sequence-props/get-ast-node-path';
-import {parseAst} from './sequence-props/parse-ast';
-
-const {builders: b, namedTypes} = recast.types;
-
-/** Recast `builders.nullLiteral()` is typed against ast-types; normalize to Babel `Expression`. */
-const nullLiteralExpr = (): Expression =>
- b.nullLiteral() as unknown as Expression;
-
-const jsxOpeningNameToString = (name: JSXOpeningElement['name']): string => {
- if (name.type === 'JSXIdentifier') {
- return name.name;
- }
-
- if (name.type === 'JSXNamespacedName') {
- return `${name.namespace.name}:${name.name.name}`;
- }
-
- if (name.type === 'JSXMemberExpression') {
- const memberToString = (
- expr: JSXMemberExpression | JSXIdentifier,
- ): string => {
- if (expr.type === 'JSXIdentifier') {
- return expr.name;
- }
-
- return `${memberToString(expr.object)}.${expr.property.name}`;
- };
-
- return memberToString(name);
- }
-
- return 'Unknown';
-};
-
-/** e.g. `<Video>` or `<Remotion.Sequence>` for logs and undo copy. */
-export const getJsxElementTagLabel = (element: JSXElement): string => {
- return `<${jsxOpeningNameToString(element.openingElement.name)}>`;
-};
-
-export const findJsxElementPathForDeletion = (
- ast: File,
- nodePath: SequenceNodePath,
-): recast.types.NodePath | null => {
- const current = getAstNodePath(ast, nodePath);
- if (!current) {
- return null;
- }
-
- if (namedTypes.JSXOpeningElement.check(current.value)) {
- const parent = current.parentPath;
- if (parent && namedTypes.JSXElement.check(parent.value)) {
- return parent;
- }
-
- return null;
- }
-
- if (namedTypes.JSXElement.check(current.value)) {
- return current;
- }
-
- return null;
-};
-
-const replaceInLogicalExpression = (
- parent: LogicalExpression,
- node: JSXElement,
-): boolean => {
- const nl = nullLiteralExpr();
- if (parent.left === node) {
- parent.left = nl;
- return true;
- }
-
- if (parent.right === node) {
- parent.right = nl;
- return true;
- }
-
- return false;
-};
-
-const replaceInConditionalExpression = (
- parent: ConditionalExpression,
- node: JSXElement,
-): boolean => {
- const nl = nullLiteralExpr();
- if (parent.consequent === node) {
- parent.consequent = nl;
- return true;
- }
-
- if (parent.alternate === node) {
- parent.alternate = nl;
- return true;
- }
-
- return false;
-};
-
-const replaceInArrowFunctionExpression = (
- parent: ArrowFunctionExpression,
- node: JSXElement,
-): boolean => {
- if (parent.body === node) {
- parent.body = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInReturnStatement = (
- parent: ReturnStatement,
- node: JSXElement,
-): boolean => {
- if (parent.argument === node) {
- parent.argument = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInCallExpression = (
- parent: CallExpression,
- node: JSXElement,
-): boolean => {
- const idx = parent.arguments.indexOf(node);
- if (idx !== -1) {
- parent.arguments[idx] = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInOptionalCallExpression = (
- parent: OptionalCallExpression,
- node: JSXElement,
-): boolean => {
- const idx = parent.arguments.indexOf(node);
- if (idx !== -1) {
- parent.arguments[idx] = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInArrayExpression = (
- parent: ArrayExpression,
- node: JSXElement,
-): boolean => {
- const idx = parent.elements.indexOf(node);
- if (idx !== -1) {
- parent.elements[idx] = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInAssignmentExpression = (
- parent: AssignmentExpression,
- node: JSXElement,
-): boolean => {
- if (parent.right === node) {
- parent.right = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInVariableDeclarator = (
- parent: VariableDeclarator,
- node: JSXElement,
-): boolean => {
- if (parent.init === node) {
- parent.init = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInExportDefaultDeclaration = (
- parent: ExportDefaultDeclaration,
- node: JSXElement,
-): boolean => {
- if (parent.declaration === node) {
- parent.declaration = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInSequenceExpression = (
- parent: SequenceExpression,
- node: JSXElement,
-): boolean => {
- const idx = parent.expressions.indexOf(node);
- if (idx !== -1) {
- parent.expressions[idx] = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInNewExpression = (
- parent: NewExpression,
- node: JSXElement,
-): boolean => {
- const idx = parent.arguments.indexOf(node);
- if (idx !== -1) {
- parent.arguments[idx] = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInExpressionStatement = (
- parent: ExpressionStatement,
- node: JSXElement,
-): boolean => {
- if (parent.expression === node) {
- parent.expression = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInParenthesizedExpression = (
- parent: ParenthesizedExpression,
- node: JSXElement,
-): boolean => {
- if (parent.expression === node) {
- parent.expression = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInJSXExpressionContainer = (
- parent: JSXExpressionContainer,
- node: JSXElement,
-): boolean => {
- if (parent.expression === node) {
- parent.expression = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInTSAsExpression = (
- parent: TSAsExpression,
- node: JSXElement,
-): boolean => {
- if (parent.expression === node) {
- parent.expression = nullLiteralExpr();
- return true;
- }
-
- return false;
-};
-
-const replaceInJSXParentChildren = (
- parent: JSXElement | JSXFragment,
- node: JSXElement,
-): boolean => {
- const idx = parent.children.indexOf(node);
- if (idx !== -1) {
- parent.children.splice(idx, 1);
- return true;
- }
-
- return false;
-};
-
-const replaceNodeWithNull = (parentNode: Node, node: JSXElement): boolean => {
- if (namedTypes.LogicalExpression.check(parentNode)) {
- return replaceInLogicalExpression(parentNode, node);
- }
-
- if (namedTypes.ConditionalExpression.check(parentNode)) {
- return replaceInConditionalExpression(parentNode, node);
- }
-
- if (namedTypes.ArrowFunctionExpression.check(parentNode)) {
- return replaceInArrowFunctionExpression(parentNode, node);
- }
-
- if (namedTypes.ReturnStatement.check(parentNode)) {
- return replaceInReturnStatement(parentNode, node);
- }
-
- if (namedTypes.CallExpression.check(parentNode)) {
- return replaceInCallExpression(parentNode, node);
- }
-
- if (parentNode.type === 'OptionalCallExpression') {
- return replaceInOptionalCallExpression(parentNode, node);
- }
-
- if (namedTypes.ArrayExpression.check(parentNode)) {
- return replaceInArrayExpression(parentNode, node);
- }
-
- if (namedTypes.AssignmentExpression.check(parentNode)) {
- return replaceInAssignmentExpression(parentNode, node);
- }
-
- if (namedTypes.VariableDeclarator.check(parentNode)) {
- return replaceInVariableDeclarator(parentNode, node);
- }
-
- if (namedTypes.ExportDefaultDeclaration.check(parentNode)) {
- return replaceInExportDefaultDeclaration(parentNode, node);
- }
-
- if (namedTypes.SequenceExpression.check(parentNode)) {
- return replaceInSequenceExpression(parentNode, node);
- }
-
- if (namedTypes.NewExpression.check(parentNode)) {
- return replaceInNewExpression(parentNode, node);
- }
-
- if (namedTypes.ExpressionStatement.check(parentNode)) {
- return replaceInExpressionStatement(parentNode, node);
- }
-
- if (namedTypes.ParenthesizedExpression.check(parentNode)) {
- return replaceInParenthesizedExpression(parentNode, node);
- }
-
- if (namedTypes.JSXExpressionContainer.check(parentNode)) {
- return replaceInJSXExpressionContainer(parentNode, node);
- }
-
- if (namedTypes.TSAsExpression.check(parentNode)) {
- return replaceInTSAsExpression(parentNode, node);
- }
-
- if (namedTypes.JSXElement.check(parentNode)) {
- return replaceInJSXParentChildren(parentNode, node);
- }
-
- if (namedTypes.JSXFragment.check(parentNode)) {
- return replaceInJSXParentChildren(parentNode, node);
- }
-
- return false;
-};
-
-export const deleteJsxElementAtPath = (
- jsxPath: recast.types.NodePath,
-): void => {
- const {node, parentPath} = jsxPath;
- if (!parentPath) {
- throw new Error('Cannot delete JSX element with no parent');
- }
-
- const jsxNode = node as JSXElement;
-
- if (replaceNodeWithNull(parentPath.node, jsxNode)) {
- return;
- }
-
- // Recast can replace this node in arbitrary parent contexts.
- jsxPath.replace(b.nullLiteral());
-};
-
-type SourceEdit = {
- end: number;
- replacement: string;
- start: number;
-};
-
-export const getNodeSourceEdit = ({
- input,
- jsxPath,
-}: {
- input: string;
- jsxPath: recast.types.NodePath;
-}): SourceEdit => {
- const node = jsxPath.node as JSXElement;
- if (!node.loc) {
- throw new Error('Cannot delete a JSX element without a source location');
- }
-
- const start = recastLocToOffset(input, node.loc.start);
- const end = recastLocToOffset(input, node.loc.end);
- const parentNode = jsxPath.parentPath?.node;
- const isJsxChild =
- parentNode !== undefined &&
- (namedTypes.JSXElement.check(parentNode) ||
- namedTypes.JSXFragment.check(parentNode));
-
- if (!isJsxChild) {
- const {extra} = node as JSXElement & {
- extra?: {parenthesized?: boolean};
- };
- if (extra?.parenthesized) {
- let openingParenthesis = start - 1;
- while (openingParenthesis >= 0 && /\s/.test(input[openingParenthesis])) {
- openingParenthesis--;
- }
-
- let closingParenthesis = end;
- while (
- closingParenthesis < input.length &&
- /\s/.test(input[closingParenthesis])
- ) {
- closingParenthesis++;
- }
-
- if (
- input[openingParenthesis] === '(' &&
- input[closingParenthesis] === ')'
- ) {
- return {
- end: closingParenthesis + 1,
- replacement: 'null',
- start: openingParenthesis,
- };
- }
- }
-
- return {end, replacement: 'null', start};
- }
-
- const lineStart = input.lastIndexOf('\n', start - 1) + 1;
- const nextLineStart = input.indexOf('\n', end);
- const lineEnd = nextLineStart === -1 ? input.length : nextLineStart;
- const beforeNode = input.slice(lineStart, start);
- const afterNode = input.slice(end, lineEnd);
-
- if (beforeNode.trim() === '' && afterNode.trim() === '') {
- return {
- end: nextLineStart === -1 ? input.length : nextLineStart + 1,
- replacement: '',
- start: lineStart,
- };
- }
-
- return {end, replacement: '', start};
-};
-
-const applySourceEdits = ({
- edits,
- input,
-}: {
- edits: SourceEdit[];
- input: string;
-}): string => {
- const sorted = edits
- .slice()
- .sort((left, right) => left.start - right.start || right.end - left.end);
- const nonOverlapping: SourceEdit[] = [];
-
- for (const edit of sorted) {
- const previous = nonOverlapping[nonOverlapping.length - 1];
- if (previous && edit.start < previous.end) {
- if (edit.end <= previous.end) {
- continue;
- }
-
- throw new Error('Overlapping JSX deletion source ranges');
- }
-
- nonOverlapping.push(edit);
- }
-
- let output = input;
- for (let i = nonOverlapping.length - 1; i >= 0; i--) {
- const edit = nonOverlapping[i];
- output =
- output.slice(0, edit.start) + edit.replacement + output.slice(edit.end);
- }
-
- return output;
-};
-
-export const deleteJsxNodes = ({
- input,
- nodePaths,
-}: {
- input: string;
- nodePaths: SequenceNodePath[];
- // Kept optional for compatibility with callers from before source edits
- // replaced the full-file formatting pass.
- formatFile?: (input: {
- contents: string;
- prettierConfigOverride: Record<string, unknown> | null;
- }) => Promise<{output: string; formatted: boolean}>;
- prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{
- output: string;
- formatted: boolean;
- nodeLabels: string[];
- logLines: number[];
- nodePathRemappings: SequenceNodePathRemapping[];
-}> => {
- if (nodePaths.length === 0) {
- throw new Error('No JSX nodes were specified for deletion');
- }
-
- const ast = parseAst(input);
- const capturedNodePaths = captureJsxNodePaths(ast);
- const pathsToDelete = nodePaths.map((nodePath) => {
- const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
- if (!jsxPath) {
- throw new Error(
- 'Could not find a JSX element at the specified location to delete',
- );
- }
-
- const jsxElement = jsxPath.node as JSXElement;
-
- return {
- jsxPath,
- nodeLabel: getJsxElementTagLabel(jsxElement),
- logLine:
- jsxElement.openingElement.loc?.start.line ??
- jsxElement.loc?.start.line ??
- 1,
- };
- });
-
- const sourceEdits = pathsToDelete.map(({jsxPath}) =>
- getNodeSourceEdit({input, jsxPath}),
- );
-
- for (const {jsxPath} of pathsToDelete) {
- deleteJsxElementAtPath(jsxPath);
- }
-
- const output = applySourceEdits({edits: sourceEdits, input});
- const {nodePathRemappings} = getNodePathRemappings({
- ast,
- captured: capturedNodePaths,
- output,
- });
-
- return Promise.resolve({
- output,
- formatted: true,
- nodeLabels: pathsToDelete.map(({nodeLabel}) => nodeLabel),
- logLines: pathsToDelete.map(({logLine}) => logLine),
- nodePathRemappings,
- });
+import type {CodemodProject, CodemodResult} from './codemod-project';
+import {getCodemodResult} from './codemod-project';
+import {deleteJsxNode as deleteJsxNodeFromSource} from './delete-jsx-node-internal';
+import {findProjectFile} from './internals';
+
+export type DeleteJsxNodeOptions<Project extends CodemodProject> = {
+ project: Project;
+ filePath: string;
+ nodePath: SequenceNodePath;
};
-export const deleteJsxNode = async ({
- input,
+export const deleteJsxNode = async <Project extends CodemodProject>({
+ project,
+ filePath,
nodePath,
-}: {
- input: string;
- nodePath: SequenceNodePath;
- // Kept optional for compatibility with callers from before source edits
- // replaced the full-file formatting pass.
- formatFile?: (input: {
- contents: string;
- prettierConfigOverride: Record<string, unknown> | null;
- }) => Promise<{output: string; formatted: boolean}>;
- prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{
- output: string;
- formatted: boolean;
- nodeLabel: string;
- logLine: number;
-}> => {
- const {output, formatted, nodeLabels, logLines} = await deleteJsxNodes({
- input,
- nodePaths: [nodePath],
+}: DeleteJsxNodeOptions<Project>): Promise<CodemodResult<Project>> => {
+ const resolvedFilePath = findProjectFile({filePath, project});
+ const {output} = await deleteJsxNodeFromSource({
+ input: project.files[resolvedFilePath],
+ nodePath,
});
-
- return {
- output,
- formatted,
- nodeLabel: nodeLabels[0],
- logLine: logLines[0],
+ const nextProject = {
+ ...project,
+ files: {
+ ...project.files,
+ [resolvedFilePath]: output,
+ },
};
+
+ return getCodemodResult({nextProject, project});
};
diff --git a/packages/codemods/src/duplicate-jsx-node.ts b/packages/codemods/src/duplicate-jsx-node.ts
index f176d6ef16..7228de16fe 100644
--- a/packages/codemods/src/duplicate-jsx-node.ts
+++ b/packages/codemods/src/duplicate-jsx-node.ts
@@ -5,7 +5,7 @@ import type {SequenceNodePath} from 'remotion';
import {
findJsxElementPathForDeletion,
getJsxElementTagLabel,
-} from './delete-jsx-node';
+} from './delete-jsx-node-internal';
import {
captureJsxNodePaths,
getNodePathRemappings,
diff --git a/packages/codemods/src/folder-source-edits.ts b/packages/codemods/src/folder-source-edits.ts
index 5ed6c9915d..224b5e8527 100644
--- a/packages/codemods/src/folder-source-edits.ts
+++ b/packages/codemods/src/folder-source-edits.ts
@@ -6,7 +6,7 @@ import type {
} from '@babel/types';
import type {CompositionOrFolder, RecastCodemod} from '@remotion/studio-shared';
import * as recast from 'recast';
-import {getNodeSourceEdit} from './delete-jsx-node';
+import {getNodeSourceEdit} from './delete-jsx-node-internal';
import {getInsertionRootSourceEdit} from './insert-jsx-element';
import {indentInsertedJsx, printInsertedJsx} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.ts
index 48f9bbcf8b..53c0ff0fbd 100644
--- a/packages/codemods/src/index.ts
+++ b/packages/codemods/src/index.ts
@@ -1,1511 +1,170 @@
-import {parse} from '@babel/parser';
-import type {JSXOpeningElement} from '@babel/types';
-import type {
- CanUpdateDefaultPropsResponse,
- CompositionComponentInfoRequest,
- InsertJsxElementRequest,
- SequenceNodePathRemapping,
-} from '@remotion/studio-shared';
-import * as recast from 'recast';
-import type {SequenceNodePath} from 'remotion';
-import {resolveCompositionComponentInProject} from './resolve-composition-component-location';
-import {getNodePathForRecastPath} from './sequence-props';
-import {parseAst} from './sequence-props/parse-ast';
-
-export {applyVisualControl} from './apply-visual-control';
-export {
- deleteJsxElementAtPath,
- deleteJsxNode,
- deleteJsxNodes,
- findJsxElementPathForDeletion,
- getJsxElementTagLabel,
-} from './delete-jsx-node';
-export {duplicateCompositionInSource} from './duplicate-composition';
-export {
- duplicateJsxElementAtPath,
- duplicateJsxNodes,
-} from './duplicate-jsx-node';
-export {
+import {
+ JsxElementIdentityMismatchError,
+ JsxElementNotFoundAtLocationError,
addEffect,
+ applyCodemod,
+ applyVisualControl,
assertValidEffect,
+ basicCaptionsElementSource,
+ computeCanUpdateDefaultPropsFromContent,
+ computeSequencePropsStatusFromContent,
+ computeSequencePropsSubscriptionFromContent,
deleteEffect,
deleteEffects,
+ deleteJsxElementAtPath,
+ deleteJsxNode as deleteJsxNodeFromSource,
+ deleteJsxNodes,
+ duplicateCompositionInSource,
duplicateEffect,
duplicateEffects,
+ duplicateJsxElementAtPath,
+ duplicateJsxNodes,
ensureEffectImport,
+ ensureRemotionImports,
+ ensureUseCurrentFrameHook,
enumerateEffectArrayElements,
findEffectCallExpression,
findEffectsAttr,
+ findEnclosingFunctionPath,
+ findJsxElementPathForDeletion,
+ findProjectFile,
+ findSearchPosition,
+ generateCanvasCaptureComposition,
+ getBasicCaptionsElementFile,
+ getCanUpdateDefaultPropsForProject,
+ getCompositionComponentInfo,
+ getCompositionDefaultPropsLine,
+ getCompositionFile,
+ getFolderFile,
+ getJsxElementTagLabel,
+ getRootFileForProject,
+ insertBasicCaptions,
+ insertJsxElementIntoComposition,
+ insertJsxElementIntoProjectWithNodePathRemappings,
+ insertSolidIntoProject,
+ insertSolidIntoProjectWithNodePathRemappings,
+ insertSolidIntoSource,
makeConfigObjectExpression,
+ makeInMemoryInsertJsxElementCodemodEnvironment,
+ makeNewCompositionComponentSource,
+ parseAndApplyCodemod,
pasteEffects,
reorderEffect,
+ reorderSequence,
+ resolveCompositionComponent,
+ resolveCompositionComponentWithFile,
+ simpleDiff,
+ splitJsxSequence,
+ splitJsxSequences,
+ splitVideoFromAudio,
+ updateDefaultProps,
+ updateEffectKeyframes,
+ updateEffectKeyframesAst,
updateEffectProps,
updateEffectPropsAst,
- type EffectDeletionTarget,
- type EffectArrayElement,
- type EffectPropUpdate,
- type EffectTarget,
- type FormatEffectFile,
- type PropDelta,
- type UpdateEffectPropsResult,
-} from './effect-operations';
-export {
+ updateInlineCaptionPatches,
+ updateMultipleSequenceProps,
+ updateSequenceKeyframes,
+ updateSequenceKeyframesAst,
+ updateSequencePropsAst,
+} from './internals';
+
+export {addSolid, type AddSolidOptions, type AddSolidResult} from './add-solid';
+export type {
+ CodemodFileChange,
+ CodemodProject,
+ CodemodResult,
+} from './codemod-project';
+export {deleteJsxNode, type DeleteJsxNodeOptions} from './delete-jsx-node';
+export type {
+ EffectArrayElement,
+ EffectDeletionTarget,
+ EffectKeyframeUpdate,
+ EffectPropUpdate,
+ EffectTarget,
+ FormatEffectFile,
+ FormatKeyframesFile,
+ InsertJsxElementCodemodEnvironment,
+ IntroducedKeyframeIdentifiers,
+ KeyframeOperation,
+ PropDelta,
+ RemovedProp,
+ ResolvedCompositionComponent,
+ ResolvedCompositionComponentWithFile,
+ SequenceKeyframeUpdate,
+ SequencePropsNodeUpdate,
+ SequencePropsNodeUpdateResult,
+ SequencePropUpdate,
+ UpdateEffectPropsResult,
+} from './internals';
+
+export const CodeModsInternals = {
+ JsxElementIdentityMismatchError,
+ JsxElementNotFoundAtLocationError,
+ addEffect,
+ applyCodemod,
+ applyVisualControl,
+ assertValidEffect,
+ basicCaptionsElementSource,
+ computeCanUpdateDefaultPropsFromContent,
+ computeSequencePropsStatusFromContent,
+ computeSequencePropsSubscriptionFromContent,
+ deleteEffect,
+ deleteEffects,
+ deleteJsxElementAtPath,
+ deleteJsxNode: deleteJsxNodeFromSource,
+ deleteJsxNodes,
+ duplicateCompositionInSource,
+ duplicateEffect,
+ duplicateEffects,
+ duplicateJsxElementAtPath,
+ duplicateJsxNodes,
+ ensureEffectImport,
ensureRemotionImports,
ensureUseCurrentFrameHook,
+ enumerateEffectArrayElements,
+ findEffectCallExpression,
+ findEffectsAttr,
findEnclosingFunctionPath,
-} from './ensure-imports-and-frame-hook';
-export {findSearchPosition} from './find-search-position';
-export {
+ findJsxElementPathForDeletion,
+ findProjectFile,
+ findSearchPosition,
generateCanvasCaptureComposition,
- makeNewCompositionComponentSource,
-} from './generate-canvas-capture-composition';
-export {parseAndApplyCodemod} from './parse-and-apply-codemod';
-export {
- applyCodemod,
- type ApplyCodeModReturnType,
- type Change,
-} from './recast-mods';
-export {reorderSequence} from './reorder-sequence';
-export {
+ getBasicCaptionsElementFile,
+ getCanUpdateDefaultPropsForProject,
+ getCompositionComponentInfo,
+ getCompositionDefaultPropsLine,
+ getCompositionFile,
+ getFolderFile,
+ getJsxElementTagLabel,
+ getRootFileForProject,
+ insertBasicCaptions,
insertJsxElementIntoComposition,
insertJsxElementIntoProjectWithNodePathRemappings,
+ insertSolidIntoProject,
+ insertSolidIntoProjectWithNodePathRemappings,
+ insertSolidIntoSource,
+ makeConfigObjectExpression,
makeInMemoryInsertJsxElementCodemodEnvironment,
+ makeNewCompositionComponentSource,
+ parseAndApplyCodemod,
+ pasteEffects,
+ reorderEffect,
+ reorderSequence,
resolveCompositionComponent,
resolveCompositionComponentWithFile,
- type InsertJsxElementCodemodEnvironment,
- type ResolvedCompositionComponent,
- type ResolvedCompositionComponentWithFile,
-} from './insert-jsx-element';
-export {
- computeSequencePropsStatusFromContent,
- computeSequencePropsSubscriptionFromContent,
-} from './sequence-props';
-export {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';
-export {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';
-export {simpleDiff} from './simple-diff';
-export {splitJsxSequence, splitJsxSequences} from './split-jsx-sequence';
-export {splitVideoFromAudio} from './split-video-from-audio';
-export {insertBasicCaptions} from './insert-basic-captions';
-export {
- basicCaptionsElementSource,
- getBasicCaptionsElementFile,
-} from './basic-captions-element-source';
-export {
- getCompositionDefaultPropsLine,
+ simpleDiff,
+ splitJsxSequence,
+ splitJsxSequences,
+ splitVideoFromAudio,
updateDefaultProps,
-} from './update-default-props';
-export {updateInlineCaptionPatches} from './update-inline-caption-patches';
-export {
- type EffectKeyframeUpdate,
- type FormatKeyframesFile,
- type IntroducedKeyframeIdentifiers,
- type KeyframeOperation,
- type SequenceKeyframeUpdate,
updateEffectKeyframes,
updateEffectKeyframesAst,
+ updateEffectProps,
+ updateEffectPropsAst,
+ updateInlineCaptionPatches,
+ updateMultipleSequenceProps,
updateSequenceKeyframes,
updateSequenceKeyframesAst,
-} from './update-keyframes';
-export {
- type RemovedProp,
- type SequencePropsNodeUpdate,
- type SequencePropsNodeUpdateResult,
- type SequencePropUpdate,
- updateMultipleSequenceProps,
updateSequencePropsAst,
-} from './update-sequence-props';
-
-export type CodemodProject = {
- files: Record<string, string>;
- rootDir: string;
-};
-
-type AstNode = {
- type: string;
- start?: number | null;
- end?: number | null;
- loc?: {
- start: {line: number; column: number};
- end: {line: number; column: number};
- } | null;
- [key: string]: unknown;
-};
-
-type TextEdit = {
- end: number;
- start: number;
- text: string;
-};
-
-const isAstNode = (value: unknown): value is AstNode => {
- return (
- typeof value === 'object' &&
- value !== null &&
- 'type' in value &&
- typeof value.type === 'string'
- );
-};
-
-const getNode = (node: AstNode, key: string): AstNode | null => {
- const value = node[key];
- return isAstNode(value) ? value : null;
-};
-
-const getNodes = (node: AstNode, key: string): AstNode[] => {
- const value = node[key];
- return Array.isArray(value) ? value.filter(isAstNode) : [];
-};
-
-const getString = (node: AstNode | null, key: string): string | null => {
- if (!node) {
- return null;
- }
-
- const value = node[key];
- return typeof value === 'string' ? value : null;
-};
-
-const getPosition = (node: AstNode, key: 'start' | 'end'): number => {
- const value = node[key];
- if (typeof value !== 'number') {
- throw new Error(`Could not determine the ${key} of a source node`);
- }
-
- return value;
-};
-
-const visit = (
- value: unknown,
- visitor: (node: AstNode) => boolean | void,
-): boolean => {
- if (Array.isArray(value)) {
- for (const item of value) {
- if (visit(item, visitor)) {
- return true;
- }
- }
-
- return false;
- }
-
- if (!isAstNode(value)) {
- return false;
- }
-
- if (visitor(value)) {
- return true;
- }
-
- for (const [key, child] of Object.entries(value)) {
- if (
- key === 'loc' ||
- key === 'start' ||
- key === 'end' ||
- key === 'extra' ||
- key === 'comments'
- ) {
- continue;
- }
-
- if (visit(child, visitor)) {
- return true;
- }
- }
-
- return false;
-};
-
-const parseSource = (source: string): AstNode => {
- return parse(source, {
- errorRecovery: false,
- plugins: ['decorators-legacy', 'jsx', 'typescript', 'importAttributes'],
- sourceType: 'module',
- }) as unknown as AstNode;
-};
-
-const normalizePath = (input: string) => {
- const hasLeadingSlash = input.startsWith('/');
- const parts: string[] = [];
-
- for (const part of input.replaceAll('\\', '/').split('/')) {
- if (!part || part === '.') {
- continue;
- }
-
- if (part === '..') {
- parts.pop();
- continue;
- }
-
- parts.push(part);
- }
-
- return `${hasLeadingSlash ? '/' : ''}${parts.join('/')}`;
-};
-
-const dirname = (filePath: string) => {
- const normalized = normalizePath(filePath);
- const lastSlash = normalized.lastIndexOf('/');
- return lastSlash === -1 ? '' : normalized.slice(0, lastSlash);
-};
-
-const stripSourceProtocol = (filePath: string) => {
- return filePath
- .replace(/^webpack:\/\/\/?/, '/')
- .replace(/^file:\/\//, '')
- .split(/[?#]/, 1)[0];
-};
-
-export const findProjectFile = ({
- filePath,
- project,
-}: {
- filePath: string;
- project: CodemodProject;
-}) => {
- const normalizedInput = normalizePath(stripSourceProtocol(filePath));
- const rootDir = normalizePath(project.rootDir);
- const candidates = [
- normalizedInput,
- normalizePath(normalizedInput.replace(/^\/+/, '')),
- normalizePath(`/${normalizedInput}`),
- normalizePath(`${rootDir}/${normalizedInput.replace(/^\//, '')}`),
- ];
- const normalizedFiles = new Map(
- Object.keys(project.files).map((key) => [normalizePath(key), key]),
- );
-
- for (const candidate of candidates) {
- const match = normalizedFiles.get(candidate);
- if (match) {
- return match;
- }
- }
-
- const suffix = `/${normalizedInput.replace(/^\//, '')}`;
- const suffixMatches = [...normalizedFiles.entries()].filter(([key]) =>
- key.endsWith(suffix),
- );
- if (suffixMatches.length === 1) {
- return suffixMatches[0][1];
- }
-
- throw new Error(`Could not find source file "${filePath}"`);
-};
-
-const resolveImportFile = ({
- fromFile,
- importPath,
- project,
-}: {
- fromFile: string;
- importPath: string;
- project: CodemodProject;
-}) => {
- if (!importPath.startsWith('.')) {
- throw new Error(`Cannot resolve package import "${importPath}"`);
- }
-
- const basePath = normalizePath(`${dirname(fromFile)}/${importPath}`);
- const candidates = [
- basePath,
- ...['.tsx', '.ts', '.jsx', '.js'].map(
- (extension) => `${basePath}${extension}`,
- ),
- ...['.tsx', '.ts', '.jsx', '.js'].map(
- (extension) => `${basePath}/index${extension}`,
- ),
- ];
- const normalizedFiles = new Map(
- Object.keys(project.files).map((key) => [normalizePath(key), key]),
- );
-
- for (const candidate of candidates) {
- const match = normalizedFiles.get(candidate);
- if (match) {
- return match;
- }
- }
-
- throw new Error(`Could not find imported component file "${importPath}"`);
-};
-
-const jsxName = (name: AstNode | null): string | null => {
- if (!name) {
- return null;
- }
-
- if (name.type === 'JSXIdentifier') {
- return getString(name, 'name');
- }
-
- if (name.type === 'JSXMemberExpression') {
- const object = jsxName(getNode(name, 'object'));
- const property = jsxName(getNode(name, 'property'));
- return object && property ? `${object}.${property}` : null;
- }
-
- return null;
-};
-
-const getJsxAttribute = (openingElement: AstNode, name: string) => {
- return (
- getNodes(openingElement, 'attributes').find((attribute) => {
- return (
- attribute.type === 'JSXAttribute' &&
- jsxName(getNode(attribute, 'name')) === name
- );
- }) ?? null
- );
-};
-
-const jsxAttributeString = (attribute: AstNode | null) => {
- const value = attribute ? getNode(attribute, 'value') : null;
- if (!value) {
- return null;
- }
-
- if (value.type === 'StringLiteral') {
- return getString(value, 'value');
- }
-
- if (value.type !== 'JSXExpressionContainer') {
- return null;
- }
-
- const expression = getNode(value, 'expression');
- return expression?.type === 'StringLiteral'
- ? getString(expression, 'value')
- : null;
-};
-
-const findCompositionElement = ({
- ast,
- compositionId,
-}: {
- ast: AstNode;
- compositionId: string;
-}) => {
- let result: AstNode | null = null;
- visit(ast, (node) => {
- if (node.type !== 'JSXOpeningElement') {
- return false;
- }
-
- const name = jsxName(getNode(node, 'name'));
- if (
- name !== 'Composition' &&
- name !== 'Still' &&
- !name?.endsWith('.Composition') &&
- !name?.endsWith('.Still')
- ) {
- return false;
- }
-
- if (jsxAttributeString(getJsxAttribute(node, 'id')) === compositionId) {
- result = node;
- return true;
- }
-
- return false;
- });
-
- return result;
-};
-
-const programStatements = (ast: AstNode) => {
- const program = ast.type === 'File' ? getNode(ast, 'program') : ast;
- if (!program || program.type !== 'Program') {
- throw new Error('Could not parse source file');
- }
-
- return getNodes(program, 'body');
-};
-
-const unwrapDeclaration = (statement: AstNode) => {
- if (
- statement.type === 'ExportNamedDeclaration' &&
- getNode(statement, 'declaration')
- ) {
- return getNode(statement, 'declaration');
- }
-
- return statement;
-};
-
-const findNamedDeclaration = (ast: AstNode, name: string) => {
- for (const statement of programStatements(ast)) {
- const declaration = unwrapDeclaration(statement);
- if (!declaration) {
- continue;
- }
-
- if (
- (declaration.type === 'FunctionDeclaration' ||
- declaration.type === 'ClassDeclaration') &&
- getString(getNode(declaration, 'id'), 'name') === name
- ) {
- return declaration;
- }
-
- if (declaration.type === 'VariableDeclaration') {
- const variable = getNodes(declaration, 'declarations').find(
- (item) => getString(getNode(item, 'id'), 'name') === name,
- );
- if (variable) {
- return variable;
- }
- }
- }
-
- return null;
-};
-
-const findDefaultDeclaration = (ast: AstNode) => {
- for (const statement of programStatements(ast)) {
- if (statement.type !== 'ExportDefaultDeclaration') {
- continue;
- }
-
- const declaration = getNode(statement, 'declaration');
- if (declaration?.type === 'Identifier') {
- const name = getString(declaration, 'name');
- return name ? findNamedDeclaration(ast, name) : null;
- }
-
- return declaration;
- }
-
- return null;
-};
-
-const unwrapExpression = (node: AstNode | null): AstNode | null => {
- let current = node;
- while (
- current &&
- (current.type === 'TSAsExpression' ||
- current.type === 'TSSatisfiesExpression' ||
- current.type === 'TypeCastExpression' ||
- current.type === 'ParenthesizedExpression')
- ) {
- current = getNode(current, 'expression');
- }
-
- return current;
-};
-
-const getReturnedRoot = (declaration: AstNode) => {
- let fn: AstNode | null = declaration;
- if (declaration.type === 'VariableDeclarator') {
- fn = unwrapExpression(getNode(declaration, 'init'));
- }
-
- if (
- !fn ||
- (fn.type !== 'ArrowFunctionExpression' &&
- fn.type !== 'FunctionExpression' &&
- fn.type !== 'FunctionDeclaration')
- ) {
- return null;
- }
-
- const body = unwrapExpression(getNode(fn, 'body'));
- if (!body) {
- return null;
- }
-
- if (body.type !== 'BlockStatement') {
- return body;
- }
-
- const statements = getNodes(body, 'body');
- const returnStatements = statements.filter(
- (statement) => statement.type === 'ReturnStatement',
- );
- if (
- returnStatements.length !== 1 ||
- returnStatements[0] !== statements.at(-1)
- ) {
- return null;
- }
-
- return unwrapExpression(getNode(returnStatements[0], 'argument'));
-};
-
-const isCanvasRoot = (root: AstNode) => {
- if (root.type !== 'JSXElement') {
- return false;
- }
-
- const openingElement = getNode(root, 'openingElement');
- const name = jsxName(getNode(openingElement ?? root, 'name'));
- return (
- name === 'ThreeCanvas' ||
- name === 'RiveCanvas' ||
- name === 'SkiaCanvas' ||
- name === 'canvas'
- );
-};
-
-const canAddToRoot = (root: AstNode | null): root is AstNode => {
- if (!root) {
- return false;
- }
-
- if (root.type === 'NullLiteral') {
- return true;
- }
-
- return (
- (root.type === 'JSXElement' || root.type === 'JSXFragment') &&
- !isCanvasRoot(root)
- );
-};
-
-const collectBindings = (ast: AstNode) => {
- const bindings = new Set<string>();
- visit(ast, (node) => {
- if (
- node.type === 'VariableDeclarator' ||
- node.type === 'FunctionDeclaration' ||
- node.type === 'ClassDeclaration' ||
- node.type === 'ImportSpecifier' ||
- node.type === 'ImportDefaultSpecifier' ||
- node.type === 'ImportNamespaceSpecifier'
- ) {
- const identifier = node.type.startsWith('Import')
- ? getNode(node, 'local')
- : getNode(node, 'id');
- const name = getString(identifier, 'name');
- if (name) {
- bindings.add(name);
- }
- }
-
- return false;
- });
-
- return bindings;
-};
-
-const findImportedLocalName = ({
- ast,
- importedName,
-}: {
- ast: AstNode;
- importedName: string;
-}) => {
- for (const statement of programStatements(ast)) {
- if (
- statement.type !== 'ImportDeclaration' ||
- getString(getNode(statement, 'source'), 'value') !== 'remotion'
- ) {
- continue;
- }
-
- for (const specifier of getNodes(statement, 'specifiers')) {
- if (
- specifier.type === 'ImportSpecifier' &&
- (getString(getNode(specifier, 'imported'), 'name') ??
- getString(getNode(specifier, 'imported'), 'value')) === importedName
- ) {
- return getString(getNode(specifier, 'local'), 'name');
- }
- }
- }
-
- return null;
-};
-
-const chooseLocalName = ({
- ast,
- candidates,
- importedName,
-}: {
- ast: AstNode;
- candidates: string[];
- importedName: string;
-}) => {
- const existing = findImportedLocalName({ast, importedName});
- if (existing) {
- return {addImport: false, localName: existing};
- }
-
- const bindings = collectBindings(ast);
- const localName = candidates.find((candidate) => !bindings.has(candidate));
- if (!localName) {
- throw new Error(
- `Cannot add <${importedName}> because all supported local names are defined`,
- );
- }
-
- return {addImport: true, localName};
-};
-
-const getImportEdit = ({
- ast,
- imports,
-}: {
- ast: AstNode;
- imports: {importedName: string; localName: string}[];
-}): TextEdit | null => {
- if (imports.length === 0) {
- return null;
- }
-
- const specifiers = imports
- .map(({importedName, localName}) =>
- importedName === localName
- ? importedName
- : `${importedName} as ${localName}`,
- )
- .join(', ');
- const existingImport = programStatements(ast).find(
- (statement) =>
- statement.type === 'ImportDeclaration' &&
- getString(getNode(statement, 'source'), 'value') === 'remotion' &&
- getString(statement, 'importKind') !== 'type' &&
- !getNodes(statement, 'specifiers').some(
- (specifier) => specifier.type === 'ImportNamespaceSpecifier',
- ),
- );
- if (existingImport) {
- const existingSpecifiers = getNodes(existingImport, 'specifiers');
- const namedSpecifiers = existingSpecifiers.filter(
- (specifier) => specifier.type === 'ImportSpecifier',
- );
- const lastNamedSpecifier = namedSpecifiers.at(-1);
- if (lastNamedSpecifier) {
- const end = getPosition(lastNamedSpecifier, 'end');
- return {end, start: end, text: `, ${specifiers}`};
- }
-
- const defaultSpecifier = existingSpecifiers.find(
- (specifier) => specifier.type === 'ImportDefaultSpecifier',
- );
- if (defaultSpecifier) {
- const end = getPosition(defaultSpecifier, 'end');
- return {end, start: end, text: `, {${specifiers}}`};
- }
- }
-
- const firstImport = programStatements(ast).find(
- (statement) => statement.type === 'ImportDeclaration',
- );
- const start = firstImport ? getPosition(firstImport, 'start') : 0;
-
- return {
- end: start,
- start,
- text: `import {${specifiers}} from 'remotion';\n`,
- };
-};
-
-const lineIndentAt = (source: string, position: number) => {
- const lineStart = source.lastIndexOf('\n', position - 1) + 1;
- return source.slice(lineStart, position).match(/^\s*/)?.[0] ?? '';
-};
-
-const indentationUnit = (source: string) => {
- if (/^\t+/m.test(source)) {
- return '\t';
- }
-
- const indentation = source.match(/^([ ]+)\S/m)?.[1].length;
- return ' '.repeat(indentation && indentation > 1 ? indentation : 2);
-};
-
-const roundCoordinate = (value: number) => {
- const rounded = Math.round(value * 10) / 10;
- return Object.is(rounded, -0) ? 0 : rounded;
-};
-
-const solidElement = ({
- from,
- height,
- localName,
- position,
- sequenceLocalName,
- width,
-}: {
- from: number | null;
- height: number;
- localName: string;
- position: {x: number; y: number} | null;
- sequenceLocalName: string | null;
- width: number;
-}) => {
- const translate = position
- ? `, translate: '${roundCoordinate(position.x)}px ${roundCoordinate(position.y)}px'`
- : '';
- const solid = `<${localName} width={${width}} height={${height}} color="gray" style={{position: 'absolute'${translate}}} />`;
- if (from === null || sequenceLocalName === null) {
- return solid;
- }
-
- return `<${sequenceLocalName} from={${from}} style={{position: 'absolute'${translate}}}>${solid}</${sequenceLocalName}>`;
-};
-
-const appendToJsxRoot = ({
- element,
- root,
- source,
- unit,
-}: {
- element: string;
- root: AstNode;
- source: string;
- unit: string;
-}): TextEdit => {
- const closing =
- root.type === 'JSXFragment'
- ? getNode(root, 'closingFragment')
- : getNode(root, 'closingElement');
- if (!closing) {
- throw new Error('Composition component root does not accept children');
- }
-
- const closingStart = getPosition(closing, 'start');
- const lineStart = source.lastIndexOf('\n', closingStart - 1) + 1;
- const beforeClosing = source.slice(lineStart, closingStart);
- const closingIndent = beforeClosing.match(/^\s*$/)
- ? beforeClosing
- : lineIndentAt(source, getPosition(root, 'start'));
-
- if (/^\s*$/.test(beforeClosing) && lineStart > 0) {
- return {
- start: lineStart,
- end: closingStart,
- text: `${closingIndent}${unit}${element}\n${closingIndent}`,
- };
- }
-
- return {
- start: closingStart,
- end: closingStart,
- text: `\n${closingIndent}${unit}${element}\n${closingIndent}`,
- };
-};
-
-const replaceNullRoot = ({
- element,
- root,
- source,
- unit,
-}: {
- element: string;
- root: AstNode;
- source: string;
- unit: string;
-}): TextEdit => {
- const indent = lineIndentAt(source, getPosition(root, 'start'));
- return {
- start: getPosition(root, 'start'),
- end: getPosition(root, 'end'),
- text: `(\n${indent}${unit}<>\n${indent}${unit}${unit}${element}\n${indent}${unit}</>\n${indent})`,
- };
-};
-
-const replaceJsxElementRoot = ({
- element,
- root,
- source,
- unit,
-}: {
- element: string;
- root: AstNode;
- source: string;
- unit: string;
-}): TextEdit => {
- const start = getPosition(root, 'start');
- const indent = lineIndentAt(source, start);
- const original = source.slice(start, getPosition(root, 'end'));
-
- return {
- start,
- end: getPosition(root, 'end'),
- text: [
- '<>',
- `${indent}${unit}${original}`,
- `${indent}${unit}${element}`,
- `${indent}</>`,
- ].join('\n'),
- };
-};
-
-const applyTextEdits = (source: string, edits: TextEdit[]) => {
- const sorted = [...edits].sort((a, b) => b.start - a.start);
- let output = source;
- let previousStart = source.length + 1;
-
- for (const edit of sorted) {
- if (edit.end > previousStart) {
- throw new Error('Overlapping source edits');
- }
-
- output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
- previousStart = edit.start;
- }
-
- return output;
-};
-
-export const insertSolidIntoSource = ({
- exportName,
- from = null,
- height,
- position,
- source,
- width,
-}: {
- exportName: string | 'default';
- from?: number | null;
- height: number;
- position: {x: number; y: number} | null;
- source: string;
- width: number;
-}): {output: string; line: number} => {
- const ast = parseSource(source);
- const declaration =
- exportName === 'default'
- ? findDefaultDeclaration(ast)
- : findNamedDeclaration(ast, exportName);
- if (!declaration) {
- throw new Error(`Could not find composition component "${exportName}"`);
- }
-
- const root = getReturnedRoot(declaration);
- if (!canAddToRoot(root)) {
- throw new Error(
- 'Cannot insert JSX element into this composition component',
- );
- }
-
- const solidImport = chooseLocalName({
- ast,
- candidates: ['Solid', 'RemotionSolid'],
- importedName: 'Solid',
- });
- const sequenceImport =
- from !== null
- ? chooseLocalName({
- ast,
- candidates: ['Sequence', 'RemotionSequence'],
- importedName: 'Sequence',
- })
- : null;
- const imports = [
- ...(solidImport.addImport
- ? [{importedName: 'Solid', localName: solidImport.localName}]
- : []),
- ...(sequenceImport?.addImport
- ? [{importedName: 'Sequence', localName: sequenceImport.localName}]
- : []),
- ];
- const unit = indentationUnit(source);
- const element = solidElement({
- from,
- height,
- localName: solidImport.localName,
- position,
- sequenceLocalName: sequenceImport?.localName ?? null,
- width,
- });
- const rootEdit =
- root.type === 'NullLiteral'
- ? replaceNullRoot({
- element,
- root,
- source,
- unit,
- })
- : root.type === 'JSXElement'
- ? replaceJsxElementRoot({
- element,
- root,
- source,
- unit,
- })
- : appendToJsxRoot({
- element,
- root,
- source,
- unit,
- });
- const importEdit = getImportEdit({ast, imports});
- return {
- line: root.loc?.start.line ?? 1,
- output: applyTextEdits(source, [
- rootEdit,
- ...(importEdit ? [importEdit] : []),
- ]),
- };
-};
-
-const getNodePathRemappings = ({
- afterSource,
- beforeSource,
-}: {
- afterSource: string;
- beforeSource: string;
-}) => {
- const astBefore = parseAst(beforeSource);
- const astAfter = parseAst(afterSource);
- const before: Array<{nodePath: SequenceNodePath; signature: string}> = [];
- const after: Array<{nodePath: SequenceNodePath; signature: string}> = [];
- recast.visit(astBefore, {
- visitJSXOpeningElement(path) {
- before.push({
- nodePath: getNodePathForRecastPath(path, astBefore),
- signature: recast.prettyPrint(path.node as JSXOpeningElement).code,
- });
- return this.traverse(path);
- },
- });
- recast.visit(astAfter, {
- visitJSXOpeningElement(path) {
- after.push({
- nodePath: getNodePathForRecastPath(path, astAfter),
- signature: recast.prettyPrint(path.node as JSXOpeningElement).code,
- });
- return this.traverse(path);
- },
- });
-
- let nextAfterIndex = 0;
- const matchedAfterIndexes = new Set<number>();
- const remappings = before.flatMap(
- ({nodePath, signature}): SequenceNodePathRemapping[] => {
- const matchedIndex = after.findIndex(
- (item, index) =>
- index >= nextAfterIndex && item.signature === signature,
- );
- if (matchedIndex === -1) {
- throw new Error(
- 'Could not map JSX node paths after inserting an element',
- );
- }
-
- nextAfterIndex = matchedIndex + 1;
- matchedAfterIndexes.add(matchedIndex);
- const newNodePath = after[matchedIndex].nodePath;
- if (JSON.stringify(nodePath) === JSON.stringify(newNodePath)) {
- return [];
- }
-
- return [{oldNodePath: nodePath, newNodePath}];
- },
- );
-
- for (let i = 0; i < after.length; i++) {
- if (!matchedAfterIndexes.has(i)) {
- remappings.push({oldNodePath: null, newNodePath: after[i].nodePath});
- }
- }
-
- return remappings;
-};
-
-const insertSolidIntoProjectWithoutNodePathRemappings = <
- Project extends CodemodProject,
->({
- project,
- request,
-}: {
- project: Project;
- request: InsertJsxElementRequest;
-}): {
- project: Project;
- filePath: string;
- previousSource: string;
- nextSource: string;
-} => {
- if (request.element.type !== 'solid') {
- throw new Error('This codemod only supports adding <Solid>');
- }
-
- if (!Number.isFinite(request.element.width) || request.element.width < 1) {
- throw new Error('width must be a positive number');
- }
-
- if (!Number.isFinite(request.element.height) || request.element.height < 1) {
- throw new Error('height must be a positive number');
- }
-
- if (
- request.element.position !== null &&
- (!Number.isFinite(request.element.position.x) ||
- !Number.isFinite(request.element.position.y))
- ) {
- throw new Error('Position must be finite');
- }
-
- if (
- request.from !== null &&
- (!Number.isInteger(request.from) || request.from < 0)
- ) {
- throw new Error('from must be a non-negative integer');
- }
-
- const resolved = resolveCompositionComponentInProject({
- compositionFile: request.compositionFile,
- compositionId: request.compositionId,
- project,
- });
- const {output} = insertSolidIntoSource({
- exportName: resolved.exportName,
- from: request.from,
- height: request.element.height,
- position: request.element.position,
- source: resolved.source,
- width: request.element.width,
- });
- return {
- filePath: resolved.filePath,
- nextSource: output,
- previousSource: resolved.source,
- project: {
- ...project,
- files: {
- ...project.files,
- [resolved.filePath]: output,
- },
- },
- };
-};
-
-export const insertSolidIntoProjectWithNodePathRemappings = <
- Project extends CodemodProject,
->({
- project,
- request,
-}: {
- project: Project;
- request: InsertJsxElementRequest;
-}): {
- project: Project;
- filePath: string;
- nodePathRemappings: SequenceNodePathRemapping[];
-} => {
- const result = insertSolidIntoProjectWithoutNodePathRemappings({
- project,
- request,
- });
-
- return {
- filePath: result.filePath,
- nodePathRemappings: getNodePathRemappings({
- afterSource: result.nextSource,
- beforeSource: result.previousSource,
- }),
- project: result.project,
- };
-};
-
-export const insertSolidIntoProject = <Project extends CodemodProject>({
- project,
- request,
-}: {
- project: Project;
- request: InsertJsxElementRequest;
-}): Project => {
- return insertSolidIntoProjectWithoutNodePathRemappings({project, request})
- .project;
-};
-
-const relativeToRoot = (filePath: string, rootDir: string) => {
- const normalizedFile = normalizePath(filePath);
- const normalizedRoot = normalizePath(rootDir).replace(/\/$/, '');
- if (normalizedFile.startsWith(`${normalizedRoot}/`)) {
- return normalizedFile.slice(normalizedRoot.length + 1);
- }
-
- return normalizedFile.replace(/^\//, '');
-};
-
-export const getCompositionComponentInfo = ({
- project,
- request,
-}: {
- project: CodemodProject;
- request: CompositionComponentInfoRequest;
-}) => {
- const resolved = resolveCompositionComponentInProject({
- compositionFile: request.compositionFile,
- compositionId: request.compositionId,
- project,
- });
-
- return {
- canAddSequence: resolved.canAddSequence,
- location: resolved.location,
- };
-};
-
-export const getCompositionFile = ({
- compositionId,
- project,
-}: {
- compositionId: string;
- project: CodemodProject;
-}) => {
- for (const [filePath, source] of Object.entries(project.files)) {
- if (typeof source !== 'string') {
- continue;
- }
-
- try {
- const ast = parseSource(source);
- if (findCompositionElement({ast, compositionId})) {
- return relativeToRoot(filePath, project.rootDir);
- }
- } catch {
- // Ignore files that are not parseable source modules.
- }
- }
-
- return null;
-};
-
-export const getFolderFile = ({
- folderName,
- project,
-}: {
- folderName: string;
- project: CodemodProject;
-}) => {
- for (const [filePath, source] of Object.entries(project.files)) {
- if (typeof source !== 'string') {
- continue;
- }
-
- try {
- const ast = parseSource(source);
- let found = false;
- visit(ast, (node) => {
- if (node.type !== 'JSXElement') {
- return false;
- }
-
- const openingElement = getNode(node, 'openingElement');
- if (
- !openingElement ||
- jsxName(getNode(openingElement, 'name')) !== 'Folder'
- ) {
- return false;
- }
-
- if (
- jsxAttributeString(getJsxAttribute(openingElement, 'name')) !==
- folderName
- ) {
- return false;
- }
-
- found = true;
- return true;
- });
- if (found) {
- return relativeToRoot(filePath, project.rootDir);
- }
- } catch {
- // Ignore files that are not parseable source modules.
- }
- }
-
- return null;
-};
-
-export const getRootFileForProject = ({
- entryPoint,
- project,
-}: {
- entryPoint: string;
- project: CodemodProject;
-}): string | null => {
- let entryFile: string;
- try {
- entryFile = findProjectFile({filePath: entryPoint, project});
- } catch {
- return null;
- }
-
- try {
- const ast = parseSource(project.files[entryFile]);
- let rootComponentName: string | null = null;
- visit(ast, (node) => {
- if (node.type !== 'CallExpression') {
- return false;
- }
-
- const callee = getNode(node, 'callee');
- if (
- callee?.type !== 'Identifier' ||
- getString(callee, 'name') !== 'registerRoot'
- ) {
- return false;
- }
-
- const [argument] = getNodes(node, 'arguments');
- if (argument?.type === 'Identifier') {
- rootComponentName = getString(argument, 'name');
- }
-
- return true;
- });
- if (rootComponentName === null) {
- return null;
- }
-
- let importPath: string | null = null;
- visit(ast, (node) => {
- if (node.type !== 'ImportDeclaration') {
- return false;
- }
-
- for (const specifier of getNodes(node, 'specifiers')) {
- const local = getNode(specifier, 'local');
- if (local && getString(local, 'name') === rootComponentName) {
- importPath = getString(getNode(node, 'source'), 'value');
- return true;
- }
- }
-
- return false;
- });
- if (importPath === null) {
- // The root component is defined in the entry file itself.
- return relativeToRoot(entryFile, project.rootDir);
- }
-
- return relativeToRoot(
- resolveImportFile({fromFile: entryFile, importPath, project}),
- project.rootDir,
- );
- } catch {
- return null;
- }
-};
-
-const staticFileToken = 'remotion-file:';
-const dateToken = 'remotion-date:';
-
-type ExtractedStaticValue = {success: true; value: unknown} | {success: false};
-
-const extractSpecialDefaultPropValue = (
- node: AstNode,
-): ExtractedStaticValue | null => {
- if (node.type === 'CallExpression') {
- const callee = getNode(node, 'callee');
- const args = getNodes(node, 'arguments');
- if (
- callee?.type === 'Identifier' &&
- getString(callee, 'name') === 'staticFile' &&
- args.length === 1 &&
- args[0].type === 'StringLiteral'
- ) {
- const value = getString(args[0], 'value');
- if (value !== null) {
- return {
- success: true,
- value: `${staticFileToken}${value
- .split('/')
- .map(encodeURIComponent)
- .join('/')}`,
- };
- }
- }
-
- return {success: false};
- }
-
- if (node.type === 'NewExpression') {
- const callee = getNode(node, 'callee');
- const args = getNodes(node, 'arguments');
- if (
- callee?.type === 'Identifier' &&
- getString(callee, 'name') === 'Date' &&
- args.length === 1 &&
- args[0].type === 'StringLiteral'
- ) {
- const value = getString(args[0], 'value');
- if (value !== null) {
- return {success: true, value: `${dateToken}${value}`};
- }
- }
-
- return {success: false};
- }
-
- return null;
-};
-
-const extractStaticDefaultPropValue = (node: AstNode): ExtractedStaticValue => {
- const special = extractSpecialDefaultPropValue(node);
- if (special !== null) {
- return special;
- }
-
- switch (node.type) {
- case 'NumericLiteral':
- case 'StringLiteral':
- case 'BooleanLiteral':
- return {success: true, value: node.value};
- case 'NullLiteral':
- return {success: true, value: null};
- case 'UnaryExpression': {
- const argument = getNode(node, 'argument');
- const operator = getString(node, 'operator');
- if (
- argument?.type === 'NumericLiteral' &&
- typeof argument.value === 'number' &&
- (operator === '-' || operator === '+')
- ) {
- return {
- success: true,
- value: operator === '-' ? -argument.value : argument.value,
- };
- }
-
- return {success: false};
- }
-
- case 'TSAsExpression': {
- const expression = getNode(node, 'expression');
- return expression
- ? extractStaticDefaultPropValue(expression)
- : {success: false};
- }
-
- case 'ArrayExpression': {
- const {elements} = node;
- if (!Array.isArray(elements)) {
- return {success: false};
- }
-
- const values: unknown[] = [];
- for (const element of elements) {
- if (!isAstNode(element) || element.type === 'SpreadElement') {
- return {success: false};
- }
-
- const extracted = extractStaticDefaultPropValue(element);
- if (!extracted.success) {
- return extracted;
- }
-
- values.push(extracted.value);
- }
-
- return {success: true, value: values};
- }
-
- case 'ObjectExpression': {
- const result: Record<string, unknown> = {};
- for (const property of getNodes(node, 'properties')) {
- if (property.type !== 'ObjectProperty') {
- return {success: false};
- }
-
- const value = getNode(property, 'value');
- if (!value) {
- return {success: false};
- }
-
- const extracted = extractStaticDefaultPropValue(value);
- if (!extracted.success) {
- return extracted;
- }
-
- const key = getNode(property, 'key');
- const propertyName =
- key?.type === 'Identifier'
- ? getString(key, 'name')
- : key?.type === 'StringLiteral' || key?.type === 'NumericLiteral'
- ? String(key.value)
- : null;
- if (propertyName !== null) {
- result[propertyName] = extracted.value;
- }
- }
-
- return {success: true, value: result};
- }
-
- default:
- return {success: false};
- }
-};
-
-export const computeCanUpdateDefaultPropsFromContent = (
- content: string,
- compositionId: string,
-): CanUpdateDefaultPropsResponse => {
- try {
- const ast = parseSource(content);
- const composition = findCompositionElement({ast, compositionId});
- const defaultProps = composition
- ? getJsxAttribute(composition, 'defaultProps')
- : null;
- const value = defaultProps ? getNode(defaultProps, 'value') : null;
- const expression =
- value?.type === 'JSXExpressionContainer'
- ? getNode(value, 'expression')
- : null;
- const extracted = expression
- ? extractStaticDefaultPropValue(expression)
- : {success: false as const};
-
- if (
- !extracted.success ||
- extracted.value === null ||
- typeof extracted.value !== 'object' ||
- Array.isArray(extracted.value)
- ) {
- throw new Error(
- `Could not find or extract defaultProps for composition "${compositionId}"`,
- );
- }
-
- return {
- canUpdate: true,
- currentDefaultProps: extracted.value as Record<string, unknown>,
- };
- } catch (error) {
- return {
- canUpdate: false,
- reason: error instanceof Error ? error.message : String(error),
- };
- }
-};
-
-export const getCanUpdateDefaultPropsForProject = ({
- compositionId,
- project,
-}: {
- compositionId: string;
- project: CodemodProject;
-}): CanUpdateDefaultPropsResponse => {
- const compositionFile = getCompositionFile({compositionId, project});
- if (compositionFile === null) {
- return {canUpdate: false, reason: 'Cannot find root file in project'};
- }
-
- if (
- !compositionFile.endsWith('.tsx') &&
- !compositionFile.endsWith('.ts') &&
- !compositionFile.endsWith('.mtsx') &&
- !compositionFile.endsWith('.mts')
- ) {
- return {
- canUpdate: false,
- reason: 'Cannot update Root file if not using TypeScript',
- };
- }
-
- const filePath = findProjectFile({filePath: compositionFile, project});
- return computeCanUpdateDefaultPropsFromContent(
- project.files[filePath],
- compositionId,
- );
};
diff --git a/packages/codemods/src/insert-basic-captions.ts b/packages/codemods/src/insert-basic-captions.ts
index 61d212bd64..d7e26733b1 100644
--- a/packages/codemods/src/insert-basic-captions.ts
+++ b/packages/codemods/src/insert-basic-captions.ts
@@ -2,7 +2,7 @@ import type {JSXElement, JSXFragment} from '@babel/types';
import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
-import {findJsxElementPathForDeletion} from './delete-jsx-node';
+import {findJsxElementPathForDeletion} from './delete-jsx-node-internal';
import {
captureJsxNodePaths,
getNodePathRemappings,
diff --git a/packages/codemods/src/internals.ts b/packages/codemods/src/internals.ts
new file mode 100644
index 0000000000..7cf2e62be9
--- /dev/null
+++ b/packages/codemods/src/internals.ts
@@ -0,0 +1,1507 @@
+import {parse} from '@babel/parser';
+import type {JSXOpeningElement} from '@babel/types';
+import type {
+ CanUpdateDefaultPropsResponse,
+ CompositionComponentInfoRequest,
+ InsertJsxElementRequest,
+ SequenceNodePathRemapping,
+} from '@remotion/studio-shared';
+import * as recast from 'recast';
+import type {SequenceNodePath} from 'remotion';
+import type {CodemodProject} from './codemod-project';
+import {resolveCompositionComponentInProject} from './resolve-composition-component-location';
+import {getNodePathForRecastPath} from './sequence-props';
+import {parseAst} from './sequence-props/parse-ast';
+
+export {applyVisualControl} from './apply-visual-control';
+export {
+ deleteJsxElementAtPath,
+ deleteJsxNode,
+ deleteJsxNodes,
+ findJsxElementPathForDeletion,
+ getJsxElementTagLabel,
+} from './delete-jsx-node-internal';
+export {duplicateCompositionInSource} from './duplicate-composition';
+export {
+ duplicateJsxElementAtPath,
+ duplicateJsxNodes,
+} from './duplicate-jsx-node';
+export {
+ addEffect,
+ assertValidEffect,
+ deleteEffect,
+ deleteEffects,
+ duplicateEffect,
+ duplicateEffects,
+ ensureEffectImport,
+ enumerateEffectArrayElements,
+ findEffectCallExpression,
+ findEffectsAttr,
+ makeConfigObjectExpression,
+ pasteEffects,
+ reorderEffect,
+ updateEffectProps,
+ updateEffectPropsAst,
+ type EffectDeletionTarget,
+ type EffectArrayElement,
+ type EffectPropUpdate,
+ type EffectTarget,
+ type FormatEffectFile,
+ type PropDelta,
+ type UpdateEffectPropsResult,
+} from './effect-operations';
+export {
+ ensureRemotionImports,
+ ensureUseCurrentFrameHook,
+ findEnclosingFunctionPath,
+} from './ensure-imports-and-frame-hook';
+export {findSearchPosition} from './find-search-position';
+export {
+ generateCanvasCaptureComposition,
+ makeNewCompositionComponentSource,
+} from './generate-canvas-capture-composition';
+export {parseAndApplyCodemod} from './parse-and-apply-codemod';
+export {
+ applyCodemod,
+ type ApplyCodeModReturnType,
+ type Change,
+} from './recast-mods';
+export {reorderSequence} from './reorder-sequence';
+export {
+ insertJsxElementIntoComposition,
+ insertJsxElementIntoProjectWithNodePathRemappings,
+ makeInMemoryInsertJsxElementCodemodEnvironment,
+ resolveCompositionComponent,
+ resolveCompositionComponentWithFile,
+ type InsertJsxElementCodemodEnvironment,
+ type ResolvedCompositionComponent,
+ type ResolvedCompositionComponentWithFile,
+} from './insert-jsx-element';
+export {
+ computeSequencePropsStatusFromContent,
+ computeSequencePropsSubscriptionFromContent,
+} from './sequence-props';
+export {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';
+export {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';
+export {simpleDiff} from './simple-diff';
+export {splitJsxSequence, splitJsxSequences} from './split-jsx-sequence';
+export {splitVideoFromAudio} from './split-video-from-audio';
+export {insertBasicCaptions} from './insert-basic-captions';
+export {
+ basicCaptionsElementSource,
+ getBasicCaptionsElementFile,
+} from './basic-captions-element-source';
+export {
+ getCompositionDefaultPropsLine,
+ updateDefaultProps,
+} from './update-default-props';
+export {updateInlineCaptionPatches} from './update-inline-caption-patches';
+export {
+ type EffectKeyframeUpdate,
+ type FormatKeyframesFile,
+ type IntroducedKeyframeIdentifiers,
+ type KeyframeOperation,
+ type SequenceKeyframeUpdate,
+ updateEffectKeyframes,
+ updateEffectKeyframesAst,
+ updateSequenceKeyframes,
+ updateSequenceKeyframesAst,
+} from './update-keyframes';
+export {
+ type RemovedProp,
+ type SequencePropsNodeUpdate,
+ type SequencePropsNodeUpdateResult,
+ type SequencePropUpdate,
+ updateMultipleSequenceProps,
+ updateSequencePropsAst,
+} from './update-sequence-props';
+
+type AstNode = {
+ type: string;
+ start?: number | null;
+ end?: number | null;
+ loc?: {
+ start: {line: number; column: number};
+ end: {line: number; column: number};
+ } | null;
+ [key: string]: unknown;
+};
+
+type TextEdit = {
+ end: number;
+ start: number;
+ text: string;
+};
+
+const isAstNode = (value: unknown): value is AstNode => {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ 'type' in value &&
+ typeof value.type === 'string'
+ );
+};
+
+const getNode = (node: AstNode, key: string): AstNode | null => {
+ const value = node[key];
+ return isAstNode(value) ? value : null;
+};
+
+const getNodes = (node: AstNode, key: string): AstNode[] => {
+ const value = node[key];
+ return Array.isArray(value) ? value.filter(isAstNode) : [];
+};
+
+const getString = (node: AstNode | null, key: string): string | null => {
+ if (!node) {
+ return null;
+ }
+
+ const value = node[key];
+ return typeof value === 'string' ? value : null;
+};
+
+const getPosition = (node: AstNode, key: 'start' | 'end'): number => {
+ const value = node[key];
+ if (typeof value !== 'number') {
+ throw new Error(`Could not determine the ${key} of a source node`);
+ }
+
+ return value;
+};
+
+const visit = (
+ value: unknown,
+ visitor: (node: AstNode) => boolean | void,
+): boolean => {
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ if (visit(item, visitor)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ if (!isAstNode(value)) {
+ return false;
+ }
+
+ if (visitor(value)) {
+ return true;
+ }
+
+ for (const [key, child] of Object.entries(value)) {
+ if (
+ key === 'loc' ||
+ key === 'start' ||
+ key === 'end' ||
+ key === 'extra' ||
+ key === 'comments'
+ ) {
+ continue;
+ }
+
+ if (visit(child, visitor)) {
+ return true;
+ }
+ }
+
+ return false;
+};
+
+const parseSource = (source: string): AstNode => {
+ return parse(source, {
+ errorRecovery: false,
+ plugins: ['decorators-legacy', 'jsx', 'typescript', 'importAttributes'],
+ sourceType: 'module',
+ }) as unknown as AstNode;
+};
+
+const normalizePath = (input: string) => {
+ const hasLeadingSlash = input.startsWith('/');
+ const parts: string[] = [];
+
+ for (const part of input.replaceAll('\\', '/').split('/')) {
+ if (!part || part === '.') {
+ continue;
+ }
+
+ if (part === '..') {
+ parts.pop();
+ continue;
+ }
+
+ parts.push(part);
+ }
+
+ return `${hasLeadingSlash ? '/' : ''}${parts.join('/')}`;
+};
+
+const dirname = (filePath: string) => {
+ const normalized = normalizePath(filePath);
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash === -1 ? '' : normalized.slice(0, lastSlash);
+};
+
+const stripSourceProtocol = (filePath: string) => {
+ return filePath
+ .replace(/^webpack:\/\/\/?/, '/')
+ .replace(/^file:\/\//, '')
+ .split(/[?#]/, 1)[0];
+};
+
+export const findProjectFile = ({
+ filePath,
+ project,
+}: {
+ filePath: string;
+ project: CodemodProject;
+}) => {
+ const normalizedInput = normalizePath(stripSourceProtocol(filePath));
+ const rootDir = normalizePath(project.rootDir);
+ const candidates = [
+ normalizedInput,
+ normalizePath(normalizedInput.replace(/^\/+/, '')),
+ normalizePath(`/${normalizedInput}`),
+ normalizePath(`${rootDir}/${normalizedInput.replace(/^\//, '')}`),
+ ];
+ const normalizedFiles = new Map(
+ Object.keys(project.files).map((key) => [normalizePath(key), key]),
+ );
+
+ for (const candidate of candidates) {
+ const match = normalizedFiles.get(candidate);
+ if (match) {
+ return match;
+ }
+ }
+
+ const suffix = `/${normalizedInput.replace(/^\//, '')}`;
+ const suffixMatches = [...normalizedFiles.entries()].filter(([key]) =>
+ key.endsWith(suffix),
+ );
+ if (suffixMatches.length === 1) {
+ return suffixMatches[0][1];
+ }
+
+ throw new Error(`Could not find source file "${filePath}"`);
+};
+
+const resolveImportFile = ({
+ fromFile,
+ importPath,
+ project,
+}: {
+ fromFile: string;
+ importPath: string;
+ project: CodemodProject;
+}) => {
+ if (!importPath.startsWith('.')) {
+ throw new Error(`Cannot resolve package import "${importPath}"`);
+ }
+
+ const basePath = normalizePath(`${dirname(fromFile)}/${importPath}`);
+ const candidates = [
+ basePath,
+ ...['.tsx', '.ts', '.jsx', '.js'].map(
+ (extension) => `${basePath}${extension}`,
+ ),
+ ...['.tsx', '.ts', '.jsx', '.js'].map(
+ (extension) => `${basePath}/index${extension}`,
+ ),
+ ];
+ const normalizedFiles = new Map(
+ Object.keys(project.files).map((key) => [normalizePath(key), key]),
+ );
+
+ for (const candidate of candidates) {
+ const match = normalizedFiles.get(candidate);
+ if (match) {
+ return match;
+ }
+ }
+
+ throw new Error(`Could not find imported component file "${importPath}"`);
+};
+
+const jsxName = (name: AstNode | null): string | null => {
+ if (!name) {
+ return null;
+ }
+
+ if (name.type === 'JSXIdentifier') {
+ return getString(name, 'name');
+ }
+
+ if (name.type === 'JSXMemberExpression') {
+ const object = jsxName(getNode(name, 'object'));
+ const property = jsxName(getNode(name, 'property'));
+ return object && property ? `${object}.${property}` : null;
+ }
+
+ return null;
+};
+
+const getJsxAttribute = (openingElement: AstNode, name: string) => {
+ return (
+ getNodes(openingElement, 'attributes').find((attribute) => {
+ return (
+ attribute.type === 'JSXAttribute' &&
+ jsxName(getNode(attribute, 'name')) === name
+ );
+ }) ?? null
+ );
+};
+
+const jsxAttributeString = (attribute: AstNode | null) => {
+ const value = attribute ? getNode(attribute, 'value') : null;
+ if (!value) {
+ return null;
+ }
+
+ if (value.type === 'StringLiteral') {
+ return getString(value, 'value');
+ }
+
+ if (value.type !== 'JSXExpressionContainer') {
+ return null;
+ }
+
+ const expression = getNode(value, 'expression');
+ return expression?.type === 'StringLiteral'
+ ? getString(expression, 'value')
+ : null;
+};
+
+const findCompositionElement = ({
+ ast,
+ compositionId,
+}: {
+ ast: AstNode;
+ compositionId: string;
+}) => {
+ let result: AstNode | null = null;
+ visit(ast, (node) => {
+ if (node.type !== 'JSXOpeningElement') {
+ return false;
+ }
+
+ const name = jsxName(getNode(node, 'name'));
+ if (
+ name !== 'Composition' &&
+ name !== 'Still' &&
+ !name?.endsWith('.Composition') &&
+ !name?.endsWith('.Still')
+ ) {
+ return false;
+ }
+
+ if (jsxAttributeString(getJsxAttribute(node, 'id')) === compositionId) {
+ result = node;
+ return true;
+ }
+
+ return false;
+ });
+
+ return result;
+};
+
+const programStatements = (ast: AstNode) => {
+ const program = ast.type === 'File' ? getNode(ast, 'program') : ast;
+ if (!program || program.type !== 'Program') {
+ throw new Error('Could not parse source file');
+ }
+
+ return getNodes(program, 'body');
+};
+
+const unwrapDeclaration = (statement: AstNode) => {
+ if (
+ statement.type === 'ExportNamedDeclaration' &&
+ getNode(statement, 'declaration')
+ ) {
+ return getNode(statement, 'declaration');
+ }
+
+ return statement;
+};
+
+const findNamedDeclaration = (ast: AstNode, name: string) => {
+ for (const statement of programStatements(ast)) {
+ const declaration = unwrapDeclaration(statement);
+ if (!declaration) {
+ continue;
+ }
+
+ if (
+ (declaration.type === 'FunctionDeclaration' ||
+ declaration.type === 'ClassDeclaration') &&
+ getString(getNode(declaration, 'id'), 'name') === name
+ ) {
+ return declaration;
+ }
+
+ if (declaration.type === 'VariableDeclaration') {
+ const variable = getNodes(declaration, 'declarations').find(
+ (item) => getString(getNode(item, 'id'), 'name') === name,
+ );
+ if (variable) {
+ return variable;
+ }
+ }
+ }
+
+ return null;
+};
+
+const findDefaultDeclaration = (ast: AstNode) => {
+ for (const statement of programStatements(ast)) {
+ if (statement.type !== 'ExportDefaultDeclaration') {
+ continue;
+ }
+
+ const declaration = getNode(statement, 'declaration');
+ if (declaration?.type === 'Identifier') {
+ const name = getString(declaration, 'name');
+ return name ? findNamedDeclaration(ast, name) : null;
+ }
+
+ return declaration;
+ }
+
+ return null;
+};
+
+const unwrapExpression = (node: AstNode | null): AstNode | null => {
+ let current = node;
+ while (
+ current &&
+ (current.type === 'TSAsExpression' ||
+ current.type === 'TSSatisfiesExpression' ||
+ current.type === 'TypeCastExpression' ||
+ current.type === 'ParenthesizedExpression')
+ ) {
+ current = getNode(current, 'expression');
+ }
+
+ return current;
+};
+
+const getReturnedRoot = (declaration: AstNode) => {
+ let fn: AstNode | null = declaration;
+ if (declaration.type === 'VariableDeclarator') {
+ fn = unwrapExpression(getNode(declaration, 'init'));
+ }
+
+ if (
+ !fn ||
+ (fn.type !== 'ArrowFunctionExpression' &&
+ fn.type !== 'FunctionExpression' &&
+ fn.type !== 'FunctionDeclaration')
+ ) {
+ return null;
+ }
+
+ const body = unwrapExpression(getNode(fn, 'body'));
+ if (!body) {
+ return null;
+ }
+
+ if (body.type !== 'BlockStatement') {
+ return body;
+ }
+
+ const statements = getNodes(body, 'body');
+ const returnStatements = statements.filter(
+ (statement) => statement.type === 'ReturnStatement',
+ );
+ if (
+ returnStatements.length !== 1 ||
+ returnStatements[0] !== statements.at(-1)
+ ) {
+ return null;
+ }
+
+ return unwrapExpression(getNode(returnStatements[0], 'argument'));
+};
+
+const isCanvasRoot = (root: AstNode) => {
+ if (root.type !== 'JSXElement') {
+ return false;
+ }
+
+ const openingElement = getNode(root, 'openingElement');
+ const name = jsxName(getNode(openingElement ?? root, 'name'));
+ return (
+ name === 'ThreeCanvas' ||
+ name === 'RiveCanvas' ||
+ name === 'SkiaCanvas' ||
+ name === 'canvas'
+ );
+};
+
+const canAddToRoot = (root: AstNode | null): root is AstNode => {
+ if (!root) {
+ return false;
+ }
+
+ if (root.type === 'NullLiteral') {
+ return true;
+ }
+
+ return (
+ (root.type === 'JSXElement' || root.type === 'JSXFragment') &&
+ !isCanvasRoot(root)
+ );
+};
+
+const collectBindings = (ast: AstNode) => {
+ const bindings = new Set<string>();
+ visit(ast, (node) => {
+ if (
+ node.type === 'VariableDeclarator' ||
+ node.type === 'FunctionDeclaration' ||
+ node.type === 'ClassDeclaration' ||
+ node.type === 'ImportSpecifier' ||
+ node.type === 'ImportDefaultSpecifier' ||
+ node.type === 'ImportNamespaceSpecifier'
+ ) {
+ const identifier = node.type.startsWith('Import')
+ ? getNode(node, 'local')
+ : getNode(node, 'id');
+ const name = getString(identifier, 'name');
+ if (name) {
+ bindings.add(name);
+ }
+ }
+
+ return false;
+ });
+
+ return bindings;
+};
+
+const findImportedLocalName = ({
+ ast,
+ importedName,
+}: {
+ ast: AstNode;
+ importedName: string;
+}) => {
+ for (const statement of programStatements(ast)) {
+ if (
+ statement.type !== 'ImportDeclaration' ||
+ getString(getNode(statement, 'source'), 'value') !== 'remotion'
+ ) {
+ continue;
+ }
+
+ for (const specifier of getNodes(statement, 'specifiers')) {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ (getString(getNode(specifier, 'imported'), 'name') ??
+ getString(getNode(specifier, 'imported'), 'value')) === importedName
+ ) {
+ return getString(getNode(specifier, 'local'), 'name');
+ }
+ }
+ }
+
+ return null;
+};
+
+const chooseLocalName = ({
+ ast,
+ candidates,
+ importedName,
+}: {
+ ast: AstNode;
+ candidates: string[];
+ importedName: string;
+}) => {
+ const existing = findImportedLocalName({ast, importedName});
+ if (existing) {
+ return {addImport: false, localName: existing};
+ }
+
+ const bindings = collectBindings(ast);
+ const localName = candidates.find((candidate) => !bindings.has(candidate));
+ if (!localName) {
+ throw new Error(
+ `Cannot add <${importedName}> because all supported local names are defined`,
+ );
+ }
+
+ return {addImport: true, localName};
+};
+
+const getImportEdit = ({
+ ast,
+ imports,
+}: {
+ ast: AstNode;
+ imports: {importedName: string; localName: string}[];
+}): TextEdit | null => {
+ if (imports.length === 0) {
+ return null;
+ }
+
+ const specifiers = imports
+ .map(({importedName, localName}) =>
+ importedName === localName
+ ? importedName
+ : `${importedName} as ${localName}`,
+ )
+ .join(', ');
+ const existingImport = programStatements(ast).find(
+ (statement) =>
+ statement.type === 'ImportDeclaration' &&
+ getString(getNode(statement, 'source'), 'value') === 'remotion' &&
+ getString(statement, 'importKind') !== 'type' &&
+ !getNodes(statement, 'specifiers').some(
+ (specifier) => specifier.type === 'ImportNamespaceSpecifier',
+ ),
+ );
+ if (existingImport) {
+ const existingSpecifiers = getNodes(existingImport, 'specifiers');
+ const namedSpecifiers = existingSpecifiers.filter(
+ (specifier) => specifier.type === 'ImportSpecifier',
+ );
+ const lastNamedSpecifier = namedSpecifiers.at(-1);
+ if (lastNamedSpecifier) {
+ const end = getPosition(lastNamedSpecifier, 'end');
+ return {end, start: end, text: `, ${specifiers}`};
+ }
+
+ const defaultSpecifier = existingSpecifiers.find(
+ (specifier) => specifier.type === 'ImportDefaultSpecifier',
+ );
+ if (defaultSpecifier) {
+ const end = getPosition(defaultSpecifier, 'end');
+ return {end, start: end, text: `, {${specifiers}}`};
+ }
+ }
+
+ const firstImport = programStatements(ast).find(
+ (statement) => statement.type === 'ImportDeclaration',
+ );
+ const start = firstImport ? getPosition(firstImport, 'start') : 0;
+
+ return {
+ end: start,
+ start,
+ text: `import {${specifiers}} from 'remotion';\n`,
+ };
+};
+
+const lineIndentAt = (source: string, position: number) => {
+ const lineStart = source.lastIndexOf('\n', position - 1) + 1;
+ return source.slice(lineStart, position).match(/^\s*/)?.[0] ?? '';
+};
+
+const indentationUnit = (source: string) => {
+ if (/^\t+/m.test(source)) {
+ return '\t';
+ }
+
+ const indentation = source.match(/^([ ]+)\S/m)?.[1].length;
+ return ' '.repeat(indentation && indentation > 1 ? indentation : 2);
+};
+
+const roundCoordinate = (value: number) => {
+ const rounded = Math.round(value * 10) / 10;
+ return Object.is(rounded, -0) ? 0 : rounded;
+};
+
+const solidElement = ({
+ from,
+ height,
+ localName,
+ position,
+ sequenceLocalName,
+ width,
+}: {
+ from: number | null;
+ height: number;
+ localName: string;
+ position: {x: number; y: number} | null;
+ sequenceLocalName: string | null;
+ width: number;
+}) => {
+ const translate = position
+ ? `, translate: '${roundCoordinate(position.x)}px ${roundCoordinate(position.y)}px'`
+ : '';
+ const solid = `<${localName} width={${width}} height={${height}} color="gray" style={{position: 'absolute'${translate}}} />`;
+ if (from === null || sequenceLocalName === null) {
+ return solid;
+ }
+
+ return `<${sequenceLocalName} from={${from}} style={{position: 'absolute'${translate}}}>${solid}</${sequenceLocalName}>`;
+};
+
+const appendToJsxRoot = ({
+ element,
+ root,
+ source,
+ unit,
+}: {
+ element: string;
+ root: AstNode;
+ source: string;
+ unit: string;
+}): TextEdit => {
+ const closing =
+ root.type === 'JSXFragment'
+ ? getNode(root, 'closingFragment')
+ : getNode(root, 'closingElement');
+ if (!closing) {
+ throw new Error('Composition component root does not accept children');
+ }
+
+ const closingStart = getPosition(closing, 'start');
+ const lineStart = source.lastIndexOf('\n', closingStart - 1) + 1;
+ const beforeClosing = source.slice(lineStart, closingStart);
+ const closingIndent = beforeClosing.match(/^\s*$/)
+ ? beforeClosing
+ : lineIndentAt(source, getPosition(root, 'start'));
+
+ if (/^\s*$/.test(beforeClosing) && lineStart > 0) {
+ return {
+ start: lineStart,
+ end: closingStart,
+ text: `${closingIndent}${unit}${element}\n${closingIndent}`,
+ };
+ }
+
+ return {
+ start: closingStart,
+ end: closingStart,
+ text: `\n${closingIndent}${unit}${element}\n${closingIndent}`,
+ };
+};
+
+const replaceNullRoot = ({
+ element,
+ root,
+ source,
+ unit,
+}: {
+ element: string;
+ root: AstNode;
+ source: string;
+ unit: string;
+}): TextEdit => {
+ const indent = lineIndentAt(source, getPosition(root, 'start'));
+ return {
+ start: getPosition(root, 'start'),
+ end: getPosition(root, 'end'),
+ text: `(\n${indent}${unit}<>\n${indent}${unit}${unit}${element}\n${indent}${unit}</>\n${indent})`,
+ };
+};
+
+const replaceJsxElementRoot = ({
+ element,
+ root,
+ source,
+ unit,
+}: {
+ element: string;
+ root: AstNode;
+ source: string;
+ unit: string;
+}): TextEdit => {
+ const start = getPosition(root, 'start');
+ const indent = lineIndentAt(source, start);
+ const original = source.slice(start, getPosition(root, 'end'));
+
+ return {
+ start,
+ end: getPosition(root, 'end'),
+ text: [
+ '<>',
+ `${indent}${unit}${original}`,
+ `${indent}${unit}${element}`,
+ `${indent}</>`,
+ ].join('\n'),
+ };
+};
+
+const applyTextEdits = (source: string, edits: TextEdit[]) => {
+ const sorted = [...edits].sort((a, b) => b.start - a.start);
+ let output = source;
+ let previousStart = source.length + 1;
+
+ for (const edit of sorted) {
+ if (edit.end > previousStart) {
+ throw new Error('Overlapping source edits');
+ }
+
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
+ previousStart = edit.start;
+ }
+
+ return output;
+};
+
+export const insertSolidIntoSource = ({
+ exportName,
+ from = null,
+ height,
+ position,
+ source,
+ width,
+}: {
+ exportName: string | 'default';
+ from?: number | null;
+ height: number;
+ position: {x: number; y: number} | null;
+ source: string;
+ width: number;
+}): {output: string; line: number} => {
+ const ast = parseSource(source);
+ const declaration =
+ exportName === 'default'
+ ? findDefaultDeclaration(ast)
+ : findNamedDeclaration(ast, exportName);
+ if (!declaration) {
+ throw new Error(`Could not find composition component "${exportName}"`);
+ }
+
+ const root = getReturnedRoot(declaration);
+ if (!canAddToRoot(root)) {
+ throw new Error(
+ 'Cannot insert JSX element into this composition component',
+ );
+ }
+
+ const solidImport = chooseLocalName({
+ ast,
+ candidates: ['Solid', 'RemotionSolid'],
+ importedName: 'Solid',
+ });
+ const sequenceImport =
+ from !== null
+ ? chooseLocalName({
+ ast,
+ candidates: ['Sequence', 'RemotionSequence'],
+ importedName: 'Sequence',
+ })
+ : null;
+ const imports = [
+ ...(solidImport.addImport
+ ? [{importedName: 'Solid', localName: solidImport.localName}]
+ : []),
+ ...(sequenceImport?.addImport
+ ? [{importedName: 'Sequence', localName: sequenceImport.localName}]
+ : []),
+ ];
+ const unit = indentationUnit(source);
+ const element = solidElement({
+ from,
+ height,
+ localName: solidImport.localName,
+ position,
+ sequenceLocalName: sequenceImport?.localName ?? null,
+ width,
+ });
+ const rootEdit =
+ root.type === 'NullLiteral'
+ ? replaceNullRoot({
+ element,
+ root,
+ source,
+ unit,
+ })
+ : root.type === 'JSXElement'
+ ? replaceJsxElementRoot({
+ element,
+ root,
+ source,
+ unit,
+ })
+ : appendToJsxRoot({
+ element,
+ root,
+ source,
+ unit,
+ });
+ const importEdit = getImportEdit({ast, imports});
+ return {
+ line: root.loc?.start.line ?? 1,
+ output: applyTextEdits(source, [
+ rootEdit,
+ ...(importEdit ? [importEdit] : []),
+ ]),
+ };
+};
+
+const getNodePathRemappings = ({
+ afterSource,
+ beforeSource,
+}: {
+ afterSource: string;
+ beforeSource: string;
+}) => {
+ const astBefore = parseAst(beforeSource);
+ const astAfter = parseAst(afterSource);
+ const before: Array<{nodePath: SequenceNodePath; signature: string}> = [];
+ const after: Array<{nodePath: SequenceNodePath; signature: string}> = [];
+ recast.visit(astBefore, {
+ visitJSXOpeningElement(path) {
+ before.push({
+ nodePath: getNodePathForRecastPath(path, astBefore),
+ signature: recast.prettyPrint(path.node as JSXOpeningElement).code,
+ });
+ return this.traverse(path);
+ },
+ });
+ recast.visit(astAfter, {
+ visitJSXOpeningElement(path) {
+ after.push({
+ nodePath: getNodePathForRecastPath(path, astAfter),
+ signature: recast.prettyPrint(path.node as JSXOpeningElement).code,
+ });
+ return this.traverse(path);
+ },
+ });
+
+ let nextAfterIndex = 0;
+ const matchedAfterIndexes = new Set<number>();
+ const remappings = before.flatMap(
+ ({nodePath, signature}): SequenceNodePathRemapping[] => {
+ const matchedIndex = after.findIndex(
+ (item, index) =>
+ index >= nextAfterIndex && item.signature === signature,
+ );
+ if (matchedIndex === -1) {
+ throw new Error(
+ 'Could not map JSX node paths after inserting an element',
+ );
+ }
+
+ nextAfterIndex = matchedIndex + 1;
+ matchedAfterIndexes.add(matchedIndex);
+ const newNodePath = after[matchedIndex].nodePath;
+ if (JSON.stringify(nodePath) === JSON.stringify(newNodePath)) {
+ return [];
+ }
+
+ return [{oldNodePath: nodePath, newNodePath}];
+ },
+ );
+
+ for (let i = 0; i < after.length; i++) {
+ if (!matchedAfterIndexes.has(i)) {
+ remappings.push({oldNodePath: null, newNodePath: after[i].nodePath});
+ }
+ }
+
+ return remappings;
+};
+
+const insertSolidIntoProjectWithoutNodePathRemappings = <
+ Project extends CodemodProject,
+>({
+ project,
+ request,
+}: {
+ project: Project;
+ request: InsertJsxElementRequest;
+}): {
+ project: Project;
+ filePath: string;
+ previousSource: string;
+ nextSource: string;
+} => {
+ if (request.element.type !== 'solid') {
+ throw new Error('This codemod only supports adding <Solid>');
+ }
+
+ if (!Number.isFinite(request.element.width) || request.element.width < 1) {
+ throw new Error('width must be a positive number');
+ }
+
+ if (!Number.isFinite(request.element.height) || request.element.height < 1) {
+ throw new Error('height must be a positive number');
+ }
+
+ if (
+ request.element.position !== null &&
+ (!Number.isFinite(request.element.position.x) ||
+ !Number.isFinite(request.element.position.y))
+ ) {
+ throw new Error('Position must be finite');
+ }
+
+ if (
+ request.from !== null &&
+ (!Number.isInteger(request.from) || request.from < 0)
+ ) {
+ throw new Error('from must be a non-negative integer');
+ }
+
+ const resolved = resolveCompositionComponentInProject({
+ compositionFile: request.compositionFile,
+ compositionId: request.compositionId,
+ project,
+ });
+ const {output} = insertSolidIntoSource({
+ exportName: resolved.exportName,
+ from: request.from,
+ height: request.element.height,
+ position: request.element.position,
+ source: resolved.source,
+ width: request.element.width,
+ });
+ return {
+ filePath: resolved.filePath,
+ nextSource: output,
+ previousSource: resolved.source,
+ project: {
+ ...project,
+ files: {
+ ...project.files,
+ [resolved.filePath]: output,
+ },
+ },
+ };
+};
+
+export const insertSolidIntoProjectWithNodePathRemappings = <
+ Project extends CodemodProject,
+>({
+ project,
+ request,
+}: {
+ project: Project;
+ request: InsertJsxElementRequest;
+}): {
+ project: Project;
+ filePath: string;
+ nodePathRemappings: SequenceNodePathRemapping[];
+} => {
+ const result = insertSolidIntoProjectWithoutNodePathRemappings({
+ project,
+ request,
+ });
+
+ return {
+ filePath: result.filePath,
+ nodePathRemappings: getNodePathRemappings({
+ afterSource: result.nextSource,
+ beforeSource: result.previousSource,
+ }),
+ project: result.project,
+ };
+};
+
+export const insertSolidIntoProject = <Project extends CodemodProject>({
+ project,
+ request,
+}: {
+ project: Project;
+ request: InsertJsxElementRequest;
+}): Project => {
+ return insertSolidIntoProjectWithoutNodePathRemappings({project, request})
+ .project;
+};
+
+const relativeToRoot = (filePath: string, rootDir: string) => {
+ const normalizedFile = normalizePath(filePath);
+ const normalizedRoot = normalizePath(rootDir).replace(/\/$/, '');
+ if (normalizedFile.startsWith(`${normalizedRoot}/`)) {
+ return normalizedFile.slice(normalizedRoot.length + 1);
+ }
+
+ return normalizedFile.replace(/^\//, '');
+};
+
+export const getCompositionComponentInfo = ({
+ project,
+ request,
+}: {
+ project: CodemodProject;
+ request: CompositionComponentInfoRequest;
+}) => {
+ const resolved = resolveCompositionComponentInProject({
+ compositionFile: request.compositionFile,
+ compositionId: request.compositionId,
+ project,
+ });
+
+ return {
+ canAddSequence: resolved.canAddSequence,
+ location: resolved.location,
+ };
+};
+
+export const getCompositionFile = ({
+ compositionId,
+ project,
+}: {
+ compositionId: string;
+ project: CodemodProject;
+}) => {
+ for (const [filePath, source] of Object.entries(project.files)) {
+ if (typeof source !== 'string') {
+ continue;
+ }
+
+ try {
+ const ast = parseSource(source);
+ if (findCompositionElement({ast, compositionId})) {
+ return relativeToRoot(filePath, project.rootDir);
+ }
+ } catch {
+ // Ignore files that are not parseable source modules.
+ }
+ }
+
+ return null;
+};
+
+export const getFolderFile = ({
+ folderName,
+ project,
+}: {
+ folderName: string;
+ project: CodemodProject;
+}) => {
+ for (const [filePath, source] of Object.entries(project.files)) {
+ if (typeof source !== 'string') {
+ continue;
+ }
+
+ try {
+ const ast = parseSource(source);
+ let found = false;
+ visit(ast, (node) => {
+ if (node.type !== 'JSXElement') {
+ return false;
+ }
+
+ const openingElement = getNode(node, 'openingElement');
+ if (
+ !openingElement ||
+ jsxName(getNode(openingElement, 'name')) !== 'Folder'
+ ) {
+ return false;
+ }
+
+ if (
+ jsxAttributeString(getJsxAttribute(openingElement, 'name')) !==
+ folderName
+ ) {
+ return false;
+ }
+
+ found = true;
+ return true;
+ });
+ if (found) {
+ return relativeToRoot(filePath, project.rootDir);
+ }
+ } catch {
+ // Ignore files that are not parseable source modules.
+ }
+ }
+
+ return null;
+};
+
+export const getRootFileForProject = ({
+ entryPoint,
+ project,
+}: {
+ entryPoint: string;
+ project: CodemodProject;
+}): string | null => {
+ let entryFile: string;
+ try {
+ entryFile = findProjectFile({filePath: entryPoint, project});
+ } catch {
+ return null;
+ }
+
+ try {
+ const ast = parseSource(project.files[entryFile]);
+ let rootComponentName: string | null = null;
+ visit(ast, (node) => {
+ if (node.type !== 'CallExpression') {
+ return false;
+ }
+
+ const callee = getNode(node, 'callee');
+ if (
+ callee?.type !== 'Identifier' ||
+ getString(callee, 'name') !== 'registerRoot'
+ ) {
+ return false;
+ }
+
+ const [argument] = getNodes(node, 'arguments');
+ if (argument?.type === 'Identifier') {
+ rootComponentName = getString(argument, 'name');
+ }
+
+ return true;
+ });
+ if (rootComponentName === null) {
+ return null;
+ }
+
+ let importPath: string | null = null;
+ visit(ast, (node) => {
+ if (node.type !== 'ImportDeclaration') {
+ return false;
+ }
+
+ for (const specifier of getNodes(node, 'specifiers')) {
+ const local = getNode(specifier, 'local');
+ if (local && getString(local, 'name') === rootComponentName) {
+ importPath = getString(getNode(node, 'source'), 'value');
+ return true;
+ }
+ }
+
+ return false;
+ });
+ if (importPath === null) {
+ // The root component is defined in the entry file itself.
+ return relativeToRoot(entryFile, project.rootDir);
+ }
+
+ return relativeToRoot(
+ resolveImportFile({fromFile: entryFile, importPath, project}),
+ project.rootDir,
+ );
+ } catch {
+ return null;
+ }
+};
+
+const staticFileToken = 'remotion-file:';
+const dateToken = 'remotion-date:';
+
+type ExtractedStaticValue = {success: true; value: unknown} | {success: false};
+
+const extractSpecialDefaultPropValue = (
+ node: AstNode,
+): ExtractedStaticValue | null => {
+ if (node.type === 'CallExpression') {
+ const callee = getNode(node, 'callee');
+ const args = getNodes(node, 'arguments');
+ if (
+ callee?.type === 'Identifier' &&
+ getString(callee, 'name') === 'staticFile' &&
+ args.length === 1 &&
+ args[0].type === 'StringLiteral'
+ ) {
+ const value = getString(args[0], 'value');
+ if (value !== null) {
+ return {
+ success: true,
+ value: `${staticFileToken}${value
+ .split('/')
+ .map(encodeURIComponent)
+ .join('/')}`,
+ };
+ }
+ }
+
+ return {success: false};
+ }
+
+ if (node.type === 'NewExpression') {
+ const callee = getNode(node, 'callee');
+ const args = getNodes(node, 'arguments');
+ if (
+ callee?.type === 'Identifier' &&
+ getString(callee, 'name') === 'Date' &&
+ args.length === 1 &&
+ args[0].type === 'StringLiteral'
+ ) {
+ const value = getString(args[0], 'value');
+ if (value !== null) {
+ return {success: true, value: `${dateToken}${value}`};
+ }
+ }
+
+ return {success: false};
+ }
+
+ return null;
+};
+
+const extractStaticDefaultPropValue = (node: AstNode): ExtractedStaticValue => {
+ const special = extractSpecialDefaultPropValue(node);
+ if (special !== null) {
+ return special;
+ }
+
+ switch (node.type) {
+ case 'NumericLiteral':
+ case 'StringLiteral':
+ case 'BooleanLiteral':
+ return {success: true, value: node.value};
+ case 'NullLiteral':
+ return {success: true, value: null};
+ case 'UnaryExpression': {
+ const argument = getNode(node, 'argument');
+ const operator = getString(node, 'operator');
+ if (
+ argument?.type === 'NumericLiteral' &&
+ typeof argument.value === 'number' &&
+ (operator === '-' || operator === '+')
+ ) {
+ return {
+ success: true,
+ value: operator === '-' ? -argument.value : argument.value,
+ };
+ }
+
+ return {success: false};
+ }
+
+ case 'TSAsExpression': {
+ const expression = getNode(node, 'expression');
+ return expression
+ ? extractStaticDefaultPropValue(expression)
+ : {success: false};
+ }
+
+ case 'ArrayExpression': {
+ const {elements} = node;
+ if (!Array.isArray(elements)) {
+ return {success: false};
+ }
+
+ const values: unknown[] = [];
+ for (const element of elements) {
+ if (!isAstNode(element) || element.type === 'SpreadElement') {
+ return {success: false};
+ }
+
+ const extracted = extractStaticDefaultPropValue(element);
+ if (!extracted.success) {
+ return extracted;
+ }
+
+ values.push(extracted.value);
+ }
+
+ return {success: true, value: values};
+ }
+
+ case 'ObjectExpression': {
+ const result: Record<string, unknown> = {};
+ for (const property of getNodes(node, 'properties')) {
+ if (property.type !== 'ObjectProperty') {
+ return {success: false};
+ }
+
+ const value = getNode(property, 'value');
+ if (!value) {
+ return {success: false};
+ }
+
+ const extracted = extractStaticDefaultPropValue(value);
+ if (!extracted.success) {
+ return extracted;
+ }
+
+ const key = getNode(property, 'key');
+ const propertyName =
+ key?.type === 'Identifier'
+ ? getString(key, 'name')
+ : key?.type === 'StringLiteral' || key?.type === 'NumericLiteral'
+ ? String(key.value)
+ : null;
+ if (propertyName !== null) {
+ result[propertyName] = extracted.value;
+ }
+ }
+
+ return {success: true, value: result};
+ }
+
+ default:
+ return {success: false};
+ }
+};
+
+export const computeCanUpdateDefaultPropsFromContent = (
+ content: string,
+ compositionId: string,
+): CanUpdateDefaultPropsResponse => {
+ try {
+ const ast = parseSource(content);
+ const composition = findCompositionElement({ast, compositionId});
+ const defaultProps = composition
+ ? getJsxAttribute(composition, 'defaultProps')
+ : null;
+ const value = defaultProps ? getNode(defaultProps, 'value') : null;
+ const expression =
+ value?.type === 'JSXExpressionContainer'
+ ? getNode(value, 'expression')
+ : null;
+ const extracted = expression
+ ? extractStaticDefaultPropValue(expression)
+ : {success: false as const};
+
+ if (
+ !extracted.success ||
+ extracted.value === null ||
+ typeof extracted.value !== 'object' ||
+ Array.isArray(extracted.value)
+ ) {
+ throw new Error(
+ `Could not find or extract defaultProps for composition "${compositionId}"`,
+ );
+ }
+
+ return {
+ canUpdate: true,
+ currentDefaultProps: extracted.value as Record<string, unknown>,
+ };
+ } catch (error) {
+ return {
+ canUpdate: false,
+ reason: error instanceof Error ? error.message : String(error),
+ };
+ }
+};
+
+export const getCanUpdateDefaultPropsForProject = ({
+ compositionId,
+ project,
+}: {
+ compositionId: string;
+ project: CodemodProject;
+}): CanUpdateDefaultPropsResponse => {
+ const compositionFile = getCompositionFile({compositionId, project});
+ if (compositionFile === null) {
+ return {canUpdate: false, reason: 'Cannot find root file in project'};
+ }
+
+ if (
+ !compositionFile.endsWith('.tsx') &&
+ !compositionFile.endsWith('.ts') &&
+ !compositionFile.endsWith('.mtsx') &&
+ !compositionFile.endsWith('.mts')
+ ) {
+ return {
+ canUpdate: false,
+ reason: 'Cannot update Root file if not using TypeScript',
+ };
+ }
+
+ const filePath = findProjectFile({filePath: compositionFile, project});
+ return computeCanUpdateDefaultPropsFromContent(
+ project.files[filePath],
+ compositionId,
+ );
+};
diff --git a/packages/codemods/src/public.ts b/packages/codemods/src/public.ts
deleted file mode 100644
index 330956346d..0000000000
--- a/packages/codemods/src/public.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import type {SequenceNodePath} from 'remotion';
-import {deleteJsxNode as deleteJsxNodeFromSource} from './delete-jsx-node';
-import {
- findProjectFile,
- insertSolidIntoProjectWithNodePathRemappings,
-} from './index';
-
-export type CodemodProject = {
- files: Record<string, string>;
- rootDir: string;
-};
-
-export type CodemodFileChange = {
- filePath: string;
- previousContents: string | null;
- nextContents: string | null;
-};
-
-export type CodemodResult<Project extends CodemodProject> = {
- project: Project;
- changes: CodemodFileChange[];
-};
-
-const getCodemodResult = <Project extends CodemodProject>({
- project,
- nextProject,
-}: {
- project: Project;
- nextProject: Project;
-}): CodemodResult<Project> => {
- const filePaths = new Set([
- ...Object.keys(project.files),
- ...Object.keys(nextProject.files),
- ]);
- const changes = [...filePaths].flatMap((filePath): CodemodFileChange[] => {
- const previousContents = project.files[filePath] ?? null;
- const nextContents = nextProject.files[filePath] ?? null;
- return previousContents === nextContents
- ? []
- : [{filePath, previousContents, nextContents}];
- });
-
- return {changes, project: nextProject};
-};
-
-export type AddSolidOptions<Project extends CodemodProject> = {
- project: Project;
- compositionId: string;
- compositionFile: string;
- width: number;
- height: number;
- from?: number;
- position?: {x: number; y: number};
-};
-
-export type AddSolidResult<Project extends CodemodProject> =
- CodemodResult<Project> & {
- insertedNode: {
- filePath: string;
- nodePath: SequenceNodePath;
- };
- };
-
-export const addSolid = <Project extends CodemodProject>({
- project,
- compositionId,
- compositionFile,
- width,
- height,
- from,
- position,
-}: AddSolidOptions<Project>): AddSolidResult<Project> => {
- const insertion = insertSolidIntoProjectWithNodePathRemappings({
- project,
- request: {
- compositionFile,
- compositionId,
- element: {
- height,
- position: position ?? null,
- type: 'solid',
- width,
- },
- from: from ?? null,
- },
- });
- const insertedNodePath = insertion.nodePathRemappings.find(
- (remapping) => remapping.oldNodePath === null,
- )?.newNodePath;
- if (!insertedNodePath) {
- throw new Error('Could not determine the inserted JSX node path');
- }
-
- return {
- ...getCodemodResult({nextProject: insertion.project, project}),
- insertedNode: {
- filePath: insertion.filePath,
- nodePath: insertedNodePath,
- },
- };
-};
-
-export type DeleteJsxNodeOptions<Project extends CodemodProject> = {
- project: Project;
- filePath: string;
- nodePath: SequenceNodePath;
-};
-
-export const deleteJsxNode = async <Project extends CodemodProject>({
- project,
- filePath,
- nodePath,
-}: DeleteJsxNodeOptions<Project>): Promise<CodemodResult<Project>> => {
- const resolvedFilePath = findProjectFile({filePath, project});
- const {output} = await deleteJsxNodeFromSource({
- input: project.files[resolvedFilePath],
- nodePath,
- });
- const nextProject = {
- ...project,
- files: {
- ...project.files,
- [resolvedFilePath]: output,
- },
- };
-
- return getCodemodResult({nextProject, project});
-};
diff --git a/packages/codemods/src/recast-mods.ts b/packages/codemods/src/recast-mods.ts
index 4ce0ed8c32..040170ab1a 100644
--- a/packages/codemods/src/recast-mods.ts
+++ b/packages/codemods/src/recast-mods.ts
@@ -21,7 +21,7 @@ import type {
import type {CompositionOrFolder, RecastCodemod} from '@remotion/studio-shared';
import * as recast from 'recast';
import {applyVisualControl} from './apply-visual-control';
-import {deleteJsxElementAtPath} from './delete-jsx-node';
+import {deleteJsxElementAtPath} from './delete-jsx-node-internal';
import {parseAst} from './sequence-props/parse-ast';
import {stripParenthesizedExtra} from './strip-parenthesized-extra';
diff --git a/packages/codemods/src/reorder-sequence.ts b/packages/codemods/src/reorder-sequence.ts
index 8d96d1cc7a..298ee3a9e1 100644
--- a/packages/codemods/src/reorder-sequence.ts
+++ b/packages/codemods/src/reorder-sequence.ts
@@ -9,7 +9,7 @@ import {
findJsxElementPathForDeletion,
getJsxElementTagLabel,
getNodeSourceEdit,
-} from './delete-jsx-node';
+} from './delete-jsx-node-internal';
import {
captureJsxNodePaths,
getNodePathRemappings,
diff --git a/packages/codemods/src/split-jsx-sequence.ts b/packages/codemods/src/split-jsx-sequence.ts
index 8a4fa15fc8..fe6f6dca44 100644
--- a/packages/codemods/src/split-jsx-sequence.ts
+++ b/packages/codemods/src/split-jsx-sequence.ts
@@ -21,7 +21,7 @@ import type {SequenceNodePath} from 'remotion';
import {
findJsxElementPathForDeletion,
getJsxElementTagLabel,
-} from './delete-jsx-node';
+} from './delete-jsx-node-internal';
import {
captureJsxNodePaths,
getNodePathRemappings,
diff --git a/packages/codemods/src/split-video-from-audio.ts b/packages/codemods/src/split-video-from-audio.ts
index 7c09fe43ed..af32ec7ebb 100644
--- a/packages/codemods/src/split-video-from-audio.ts
+++ b/packages/codemods/src/split-video-from-audio.ts
@@ -14,7 +14,7 @@ import type {SequenceNodePath} from 'remotion';
import {
findJsxElementPathForDeletion,
getJsxElementTagLabel,
-} from './delete-jsx-node';
+} from './delete-jsx-node-internal';
import {
captureJsxNodePaths,
getNodePathRemappings,
diff --git a/packages/codemods/src/test/default-props.test.ts b/packages/codemods/src/test/default-props.test.ts
index 40b162639f..95e60dd6b1 100644
--- a/packages/codemods/src/test/default-props.test.ts
+++ b/packages/codemods/src/test/default-props.test.ts
@@ -1,5 +1,7 @@
import {expect, test} from 'bun:test';
-import {computeCanUpdateDefaultPropsFromContent} from '..';
+import {CodeModsInternals} from '..';
+
+const {computeCanUpdateDefaultPropsFromContent} = CodeModsInternals;
test('extracts editable default props including special values', () => {
const source = `import {Composition, staticFile} from 'remotion';
diff --git a/packages/codemods/src/test/insert-solid.test.ts b/packages/codemods/src/test/insert-solid.test.ts
index b82ad94e56..7972aef83b 100644
--- a/packages/codemods/src/test/insert-solid.test.ts
+++ b/packages/codemods/src/test/insert-solid.test.ts
@@ -1,8 +1,10 @@
import {expect, test} from 'bun:test';
-import {
+import {CodeModsInternals} from '..';
+
+const {
insertJsxElementIntoProjectWithNodePathRemappings,
insertSolidIntoSource,
-} from '..';
+} = CodeModsInternals;
test('inserts a Solid into a component source file', () => {
const result = insertSolidIntoSource({
diff --git a/packages/codemods/src/test/public-api.test.ts b/packages/codemods/src/test/public-api.test.ts
index 76ef9408c7..cf2e3a3533 100644
--- a/packages/codemods/src/test/public-api.test.ts
+++ b/packages/codemods/src/test/public-api.test.ts
@@ -1,5 +1,5 @@
import {expect, test} from 'bun:test';
-import {addSolid, deleteJsxNode} from '../public';
+import {addSolid, deleteJsxNode} from '../index';
const makeProject = () => ({
entryPoint: 'src/index.ts',
diff --git a/packages/docs/docs/codemods/add-solid.mdx b/packages/docs/docs/codemods/add-solid.mdx
index 0e32bdb327..89b55bd142 100644
--- a/packages/docs/docs/codemods/add-solid.mdx
+++ b/packages/docs/docs/codemods/add-solid.mdx
@@ -88,6 +88,7 @@ The `filePath` and `nodePath` of the inserted JSX element. Pass these values to
## See also
+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/add-solid.ts)
- [`<Solid>`](/docs/solid)
- [`deleteJsxNode()`](/docs/codemods/delete-jsx-node)
- [`@remotion/browser-bundler`](/docs/browser-bundler)
diff --git a/packages/docs/docs/codemods/delete-jsx-node.mdx b/packages/docs/docs/codemods/delete-jsx-node.mdx
index afff31f5eb..510c437773 100644
--- a/packages/docs/docs/codemods/delete-jsx-node.mdx
+++ b/packages/docs/docs/codemods/delete-jsx-node.mdx
@@ -69,6 +69,7 @@ An array describing each changed file with its `filePath`, `previousContents`, a
## See also
+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/delete-jsx-node.ts)
- [`addSolid()`](/docs/codemods/add-solid)
- [`<Sequence>`](/docs/sequence)
- [`@remotion/canvas`](/docs/canvas)
diff --git a/packages/studio-server/src/codemods/add-effect.ts b/packages/studio-server/src/codemods/add-effect.ts
index deaa9e0b20..f3bacf2ba2 100644
--- a/packages/studio-server/src/codemods/add-effect.ts
+++ b/packages/studio-server/src/codemods/add-effect.ts
@@ -1,6 +1,8 @@
-export {
+import {CodeModsInternals} from '@remotion/codemods';
+
+export const {
addEffect,
assertValidEffect,
ensureEffectImport,
makeConfigObjectExpression,
-} from '@remotion/codemods/internal';
+} = CodeModsInternals;
diff --git a/packages/studio-server/src/codemods/apply-codemod-to-file.ts b/packages/studio-server/src/codemods/apply-codemod-to-file.ts
index 40c02cec62..b8fe00438e 100644
--- a/packages/studio-server/src/codemods/apply-codemod-to-file.ts
+++ b/packages/studio-server/src/codemods/apply-codemod-to-file.ts
@@ -1,5 +1,5 @@
import {existsSync, readFileSync} from 'node:fs';
-import {parseAndApplyCodemod} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import type {
RecastCodemod,
SymbolicatedStackFrame,
@@ -7,6 +7,8 @@ import type {
import {resolveFileInsideProject} from '../helpers/resolve-file-inside-project';
import {checkIfTypeScriptFile} from '../preview-server/routes/can-update-default-props';
+const {parseAndApplyCodemod} = CodeModsInternals;
+
export const resolveFilePathFromSymbolicatedStack = (
remotionRoot: string,
stack: SymbolicatedStackFrame,
diff --git a/packages/studio-server/src/codemods/delete-effect.ts b/packages/studio-server/src/codemods/delete-effect.ts
index 7fb9f9a6de..e1e4113d9e 100644
--- a/packages/studio-server/src/codemods/delete-effect.ts
+++ b/packages/studio-server/src/codemods/delete-effect.ts
@@ -1,5 +1,5 @@
-export {
- deleteEffect,
- deleteEffects,
- type EffectDeletionTarget,
-} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
+
+export type {EffectDeletionTarget} from '@remotion/codemods';
+
+export const {deleteEffect, deleteEffects} = CodeModsInternals;
diff --git a/packages/studio-server/src/codemods/delete-jsx-node.ts b/packages/studio-server/src/codemods/delete-jsx-node.ts
index 8a2d7e3917..6204320a57 100644
--- a/packages/studio-server/src/codemods/delete-jsx-node.ts
+++ b/packages/studio-server/src/codemods/delete-jsx-node.ts
@@ -1,11 +1,13 @@
-import {
+import {CodeModsInternals} from '@remotion/codemods';
+import type {SequenceNodePath} from 'remotion';
+
+const {
deleteJsxElementAtPath,
- deleteJsxNode as deleteJsxNodeCodemod,
- deleteJsxNodes as deleteJsxNodesCodemod,
+ deleteJsxNode: deleteJsxNodeCodemod,
+ deleteJsxNodes: deleteJsxNodesCodemod,
findJsxElementPathForDeletion,
getJsxElementTagLabel,
-} from '@remotion/codemods/internal';
-import type {SequenceNodePath} from 'remotion';
+} = CodeModsInternals;
export {
deleteJsxElementAtPath,
diff --git a/packages/studio-server/src/codemods/duplicate-effect.ts b/packages/studio-server/src/codemods/duplicate-effect.ts
index 6420501d31..b2272f2319 100644
--- a/packages/studio-server/src/codemods/duplicate-effect.ts
+++ b/packages/studio-server/src/codemods/duplicate-effect.ts
@@ -1,5 +1,5 @@
-export {
- duplicateEffect,
- duplicateEffects,
- type EffectTarget as EffectDuplicationTarget,
-} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
+
+export type {EffectTarget as EffectDuplicationTarget} from '@remotion/codemods';
+
+export const {duplicateEffect, duplicateEffects} = CodeModsInternals;
diff --git a/packages/studio-server/src/codemods/insert-basic-captions.ts b/packages/studio-server/src/codemods/insert-basic-captions.ts
index a7cdc22db8..fd954768bc 100644
--- a/packages/studio-server/src/codemods/insert-basic-captions.ts
+++ b/packages/studio-server/src/codemods/insert-basic-captions.ts
@@ -1 +1,3 @@
-export {insertBasicCaptions} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
+
+export const {insertBasicCaptions} = CodeModsInternals;
diff --git a/packages/studio-server/src/codemods/paste-effects.ts b/packages/studio-server/src/codemods/paste-effects.ts
index 24ebce21b7..1ec0dbb68c 100644
--- a/packages/studio-server/src/codemods/paste-effects.ts
+++ b/packages/studio-server/src/codemods/paste-effects.ts
@@ -1,4 +1,6 @@
-import {pasteEffects as pasteEffectsCodemod} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
+
+const {pasteEffects: pasteEffectsCodemod} = CodeModsInternals;
type PasteEffectsInput = Parameters<typeof pasteEffectsCodemod>[0] & {
readonly targetFileName: string;
diff --git a/packages/studio-server/src/codemods/reorder-effect.ts b/packages/studio-server/src/codemods/reorder-effect.ts
index bd6161af3b..a13c343aa7 100644
--- a/packages/studio-server/src/codemods/reorder-effect.ts
+++ b/packages/studio-server/src/codemods/reorder-effect.ts
@@ -1 +1,3 @@
-export {reorderEffect} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
+
+export const {reorderEffect} = CodeModsInternals;
diff --git a/packages/studio-server/src/codemods/reorder-sequence.ts b/packages/studio-server/src/codemods/reorder-sequence.ts
index be73ec24cb..16ec6d64ba 100644
--- a/packages/studio-server/src/codemods/reorder-sequence.ts
+++ b/packages/studio-server/src/codemods/reorder-sequence.ts
@@ -1 +1,3 @@
-export {reorderSequence} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
+
+export const {reorderSequence} = CodeModsInternals;
diff --git a/packages/studio-server/src/codemods/split-jsx-sequence.ts b/packages/studio-server/src/codemods/split-jsx-sequence.ts
index e51ed3eef8..97ed7ce839 100644
--- a/packages/studio-server/src/codemods/split-jsx-sequence.ts
+++ b/packages/studio-server/src/codemods/split-jsx-sequence.ts
@@ -1,9 +1,11 @@
-import {
- splitJsxSequence as splitJsxSequenceCodemod,
- splitJsxSequences as splitJsxSequencesCodemod,
-} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import type {SequenceNodePath} from 'remotion';
+const {
+ splitJsxSequence: splitJsxSequenceCodemod,
+ splitJsxSequences: splitJsxSequencesCodemod,
+} = CodeModsInternals;
+
export const splitJsxSequence = ({
input,
nodePath,
diff --git a/packages/studio-server/src/codemods/split-video-from-audio.ts b/packages/studio-server/src/codemods/split-video-from-audio.ts
index 5cd6414ac0..29417dcb35 100644
--- a/packages/studio-server/src/codemods/split-video-from-audio.ts
+++ b/packages/studio-server/src/codemods/split-video-from-audio.ts
@@ -1 +1,3 @@
-export {splitVideoFromAudio} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
+
+export const {splitVideoFromAudio} = CodeModsInternals;
diff --git a/packages/studio-server/src/codemods/update-default-props.ts b/packages/studio-server/src/codemods/update-default-props.ts
index f2b4083530..acc518c2f2 100644
--- a/packages/studio-server/src/codemods/update-default-props.ts
+++ b/packages/studio-server/src/codemods/update-default-props.ts
@@ -1,4 +1,4 @@
-export {
- getCompositionDefaultPropsLine,
- updateDefaultProps,
-} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
+
+export const {getCompositionDefaultPropsLine, updateDefaultProps} =
+ CodeModsInternals;
diff --git a/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts b/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts
index 1315342621..7be5195c0d 100644
--- a/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts
+++ b/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts
@@ -1,16 +1,27 @@
import type {JSXAttribute} from '@babel/types';
-import {findEffectsAttr as findEffectsAttrCodemod} from '@remotion/codemods/internal';
-
-export {
- enumerateEffectArrayElements,
- findEffectCallExpression,
+import {
+ CodeModsInternals,
type EffectArrayElement,
type EffectPropUpdate,
type PropDelta,
type UpdateEffectPropsResult,
+} from '@remotion/codemods';
+
+export type {
+ EffectArrayElement,
+ EffectPropUpdate,
+ PropDelta,
+ UpdateEffectPropsResult,
+};
+
+export const {
+ enumerateEffectArrayElements,
+ findEffectCallExpression,
updateEffectProps,
updateEffectPropsAst,
-} from '@remotion/codemods/internal';
+} = CodeModsInternals;
+
+const {findEffectsAttr: findEffectsAttrCodemod} = CodeModsInternals;
export const findEffectsAttr = (
attrs: readonly (JSXAttribute | unknown)[],
diff --git a/packages/studio-server/src/codemods/update-inline-caption-patches.ts b/packages/studio-server/src/codemods/update-inline-caption-patches.ts
index 713af6d028..9d15be0dd3 100644
--- a/packages/studio-server/src/codemods/update-inline-caption-patches.ts
+++ b/packages/studio-server/src/codemods/update-inline-caption-patches.ts
@@ -1 +1,3 @@
-export {updateInlineCaptionPatches} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
+
+export const {updateInlineCaptionPatches} = CodeModsInternals;
diff --git a/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts b/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts
index 9bf7145233..b66343db02 100644
--- a/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts
+++ b/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts
@@ -1,5 +1,7 @@
-export {
+import {CodeModsInternals} from '@remotion/codemods';
+
+export const {
ensureRemotionImports,
ensureUseCurrentFrameHook,
findEnclosingFunctionPath,
-} from '@remotion/codemods/internal';
+} = CodeModsInternals;
diff --git a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts
index 92a0df5321..ccd5b9a273 100644
--- a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts
+++ b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts
@@ -1,16 +1,25 @@
import {
- updateEffectKeyframes as updateEffectKeyframesCodemod,
- updateSequenceKeyframes as updateSequenceKeyframesCodemod,
-} from '@remotion/codemods/internal';
-
-export {
+ CodeModsInternals,
type EffectKeyframeUpdate,
type IntroducedKeyframeIdentifiers,
type KeyframeOperation,
type SequenceKeyframeUpdate,
- updateEffectKeyframesAst,
- updateSequenceKeyframesAst,
-} from '@remotion/codemods/internal';
+} from '@remotion/codemods';
+
+export type {
+ EffectKeyframeUpdate,
+ IntroducedKeyframeIdentifiers,
+ KeyframeOperation,
+ SequenceKeyframeUpdate,
+};
+
+export const {updateEffectKeyframesAst, updateSequenceKeyframesAst} =
+ CodeModsInternals;
+
+const {
+ updateEffectKeyframes: updateEffectKeyframesCodemod,
+ updateSequenceKeyframes: updateSequenceKeyframesCodemod,
+} = CodeModsInternals;
type UpdateSequenceKeyframesInput = Omit<
Parameters<typeof updateSequenceKeyframesCodemod>[0],
diff --git a/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts b/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts
index 92f217ef3c..8041a54228 100644
--- a/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts
+++ b/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts
@@ -1,18 +1,22 @@
import type {File} from '@babel/types';
import {
+ CodeModsInternals,
type RemovedProp,
type SequencePropsNodeUpdate,
type SequencePropsNodeUpdateResult,
type SequencePropUpdate,
- updateMultipleSequenceProps as updateMultipleSequencePropsCodemod,
- updateSequencePropsAst,
-} from '@remotion/codemods/internal';
+} from '@remotion/codemods';
import type {
InteractivitySchema,
SequenceNodePath,
VideoConfigValues,
} from 'remotion';
+const {
+ updateMultipleSequenceProps: updateMultipleSequencePropsCodemod,
+ updateSequencePropsAst,
+} = CodeModsInternals;
+
export {
type RemovedProp,
type SequencePropsNodeUpdate,
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index 614f5c3469..89147ec115 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -1,13 +1,11 @@
import fs from 'node:fs';
import path from 'node:path';
import {
- insertJsxElementIntoComposition as insertJsxElementIntoCompositionCodemod,
- resolveCompositionComponent as resolveCompositionComponentCodemod,
- resolveCompositionComponentWithFile as resolveCompositionComponentWithFileCodemod,
+ CodeModsInternals,
type InsertJsxElementCodemodEnvironment,
type ResolvedCompositionComponent,
type ResolvedCompositionComponentWithFile,
-} from '@remotion/codemods/internal';
+} from '@remotion/codemods';
import type {
InsertableCompositionElement,
InsertableCompositionElementPosition,
@@ -16,6 +14,13 @@ import type {
import type {SequenceNodePath} from 'remotion';
import {svgMarkupToJsx} from './svg-to-jsx';
+const {
+ insertJsxElementIntoComposition: insertJsxElementIntoCompositionCodemod,
+ resolveCompositionComponent: resolveCompositionComponentCodemod,
+ resolveCompositionComponentWithFile:
+ resolveCompositionComponentWithFileCodemod,
+} = CodeModsInternals;
+
const makeCodemodEnvironment = (
remotionRoot: string,
sourceFileOverrides: ReadonlyMap<string, string> | null,
diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts
index 0e0e6f80c4..b594ab2168 100644
--- a/packages/studio-server/src/index.ts
+++ b/packages/studio-server/src/index.ts
@@ -1,4 +1,4 @@
-import {formatBytes} from '@remotion/studio-shared';
+import {formatBytes, type RecastCodemod} from '@remotion/studio-shared';
export {
ApiRoutes,
CopyStillToClipboardRequest,
@@ -23,7 +23,7 @@ export type {
UiOpenGlOptions,
} from '@remotion/studio-shared';
-import {parseAndApplyCodemod} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import {AnsiDiff} from './ansi-diff';
import {
addCompletedClientRender,
@@ -65,6 +65,15 @@ import {getRemotionVersion} from './preview-server/update-available';
import {remotionSkillNames} from './remotion-skill-names';
import {startStudio} from './start-studio';
+const parseAndApplyCodemod = ({
+ input,
+ codeMod,
+}: {
+ input: string;
+ codeMod: RecastCodemod;
+}): {newContents: string; changesMade: {description: string}[]} =>
+ CodeModsInternals.parseAndApplyCodemod({input, codeMod});
+
export type {
RemotionSkillsScope,
RemotionSkillsStatus,
diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
index 60c8b7ac10..a12f25f875 100644
--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts
+++ b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
@@ -1,9 +1,6 @@
import {existsSync, readFileSync} from 'node:fs';
import path from 'node:path';
-import {
- makeNewCompositionComponentSource,
- simpleDiff,
-} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import {RenderInternals} from '@remotion/renderer';
import type {
ApplyCodemodRequest,
@@ -28,6 +25,8 @@ import {
withSourceFileWriteQueue,
} from './source-file-write-queue';
+const {makeNewCompositionComponentSource, simpleDiff} = CodeModsInternals;
+
export const formatNewCompositionFile = (
codemod: Extract<ApplyCodemodRequest['codemod'], {type: 'new-composition'}>,
) => makeNewCompositionComponentSource(codemod);
diff --git a/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts
index f90128cae5..d57dea9dd8 100644
--- a/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts
+++ b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts
@@ -1,6 +1,6 @@
import {readFileSync} from 'node:fs';
import type {File} from '@babel/types';
-import {applyVisualControl} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import {RenderInternals} from '@remotion/renderer';
import type {
ApplyVisualControlRequest,
@@ -24,6 +24,8 @@ import {
withSourceFileWriteQueue,
} from './source-file-write-queue';
+const {applyVisualControl} = CodeModsInternals;
+
const getVisualControlChangeLine = (file: File, changeId: string): number => {
let line = 1;
recast.types.visit(file.program, {
diff --git a/packages/studio-server/src/preview-server/routes/can-update-default-props.ts b/packages/studio-server/src/preview-server/routes/can-update-default-props.ts
index c0c32f0f4b..0425b7cfb7 100644
--- a/packages/studio-server/src/preview-server/routes/can-update-default-props.ts
+++ b/packages/studio-server/src/preview-server/routes/can-update-default-props.ts
@@ -1,9 +1,9 @@
import {readFileSync} from 'node:fs';
-import {computeCanUpdateDefaultPropsFromContent} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import type {CanUpdateDefaultPropsResponse} from '@remotion/studio-shared';
import {getProjectInfo} from '../project-info';
-export {computeCanUpdateDefaultPropsFromContent} from '@remotion/codemods/internal';
+export const {computeCanUpdateDefaultPropsFromContent} = CodeModsInternals;
export const checkIfTypeScriptFile = (file: string) => {
if (
diff --git a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts
index 2ddf2f27a1..42dd82a300 100644
--- a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts
+++ b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts
@@ -1,5 +1,5 @@
import {readFileSync} from 'node:fs';
-import {duplicateJsxNodes} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import {RenderInternals} from '@remotion/renderer';
import type {
DuplicateJsxNodeRequest,
@@ -20,6 +20,8 @@ import {
withSourceFileWriteQueue,
} from './source-file-write-queue';
+const {duplicateJsxNodes} = CodeModsInternals;
+
export const duplicateJsxNodeHandler: ApiHandler<
DuplicateJsxNodeRequest,
DuplicateJsxNodeResponse
diff --git a/packages/studio-server/src/preview-server/routes/find-in-file.ts b/packages/studio-server/src/preview-server/routes/find-in-file.ts
index 506128cebf..c5aa9063ef 100644
--- a/packages/studio-server/src/preview-server/routes/find-in-file.ts
+++ b/packages/studio-server/src/preview-server/routes/find-in-file.ts
@@ -1,13 +1,13 @@
import fs from 'node:fs';
import path from 'node:path';
-import {findSearchPosition} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import type {
FindInFileRequest,
FindInFileResponse,
} from '@remotion/studio-shared';
import type {ApiHandler} from '../api-types';
-export {findSearchPosition} from '@remotion/codemods/internal';
+export const {findSearchPosition} = CodeModsInternals;
export const findInFileHandler: ApiHandler<
FindInFileRequest,
diff --git a/packages/studio-server/src/preview-server/routes/insert-basic-captions.ts b/packages/studio-server/src/preview-server/routes/insert-basic-captions.ts
index eacb7c4527..16ecea01cc 100644
--- a/packages/studio-server/src/preview-server/routes/insert-basic-captions.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-basic-captions.ts
@@ -1,8 +1,5 @@
import {lstatSync, readFileSync} from 'node:fs';
-import {
- basicCaptionsElementSource,
- getBasicCaptionsElementFile,
-} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import {RenderInternals} from '@remotion/renderer';
import type {
InsertBasicCaptionsRequest,
@@ -24,6 +21,9 @@ import {
withSourceFileWriteQueue,
} from './source-file-write-queue';
+const {basicCaptionsElementSource, getBasicCaptionsElementFile} =
+ CodeModsInternals;
+
export const insertBasicCaptionsHandler: ApiHandler<
InsertBasicCaptionsRequest,
InsertBasicCaptionsResponse
diff --git a/packages/studio-server/src/test/apply-codemod.test.ts b/packages/studio-server/src/test/apply-codemod.test.ts
index d3b3838750..322982c541 100644
--- a/packages/studio-server/src/test/apply-codemod.test.ts
+++ b/packages/studio-server/src/test/apply-codemod.test.ts
@@ -8,7 +8,7 @@ import {
} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'node:path';
-import {parseAndApplyCodemod} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import type {RecastCodemod} from '@remotion/studio-shared';
import {applyCodemodToFile} from '../codemods/apply-codemod-to-file';
import {
@@ -25,6 +25,8 @@ 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';
diff --git a/packages/studio-server/src/test/duplicate-jsx-node.test.ts b/packages/studio-server/src/test/duplicate-jsx-node.test.ts
index 3ceb4f9936..0c684f5364 100644
--- a/packages/studio-server/src/test/duplicate-jsx-node.test.ts
+++ b/packages/studio-server/src/test/duplicate-jsx-node.test.ts
@@ -1,7 +1,9 @@
import {expect, test} from 'bun:test';
-import {duplicateJsxNodes} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
+const {duplicateJsxNodes} = CodeModsInternals;
+
const sample = `import React from 'react';
import {AbsoluteFill} from 'remotion';
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.ts
index 01fe5233b2..f1217276b5 100644
--- a/packages/studio-server/src/test/generate-canvas-capture-composition.test.ts
+++ b/packages/studio-server/src/test/generate-canvas-capture-composition.test.ts
@@ -1,12 +1,14 @@
import {expect, test} from 'bun:test';
import {readFileSync} from 'node:fs';
import path from 'node:path';
-import {generateCanvasCaptureComposition} from '@remotion/codemods/internal';
+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(
diff --git a/packages/studio-server/src/test/insert-basic-captions.test.ts b/packages/studio-server/src/test/insert-basic-captions.test.ts
index 228e06f008..959a611fe4 100644
--- a/packages/studio-server/src/test/insert-basic-captions.test.ts
+++ b/packages/studio-server/src/test/insert-basic-captions.test.ts
@@ -8,10 +8,7 @@ import {
} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'node:path';
-import {
- basicCaptionsElementSource,
- getBasicCaptionsElementFile,
-} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import {insertBasicCaptions} from '../codemods/insert-basic-captions';
import {
createFileWatcherRegistry,
@@ -22,6 +19,9 @@ import {insertBasicCaptionsHandler} from '../preview-server/routes/insert-basic-
import {getUndoStack} from '../preview-server/undo-stack';
import {lineContainingToNodePath} from './test-utils';
+const {basicCaptionsElementSource, getBasicCaptionsElementFile} =
+ CodeModsInternals;
+
test('transcription inserts inline Basic captions beside selected Video and Audio tags', async () => {
const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-captions-'));
const entryPoint = path.join(remotionRoot, 'Root.tsx');
diff --git a/packages/studio-server/src/test/recast-mods.test.ts b/packages/studio-server/src/test/recast-mods.test.ts
index 7ac42964b1..ce182aa7e6 100644
--- a/packages/studio-server/src/test/recast-mods.test.ts
+++ b/packages/studio-server/src/test/recast-mods.test.ts
@@ -1,5 +1,7 @@
import {expect, test} from 'bun:test';
-import {parseAndApplyCodemod} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
+
+const {parseAndApplyCodemod} = CodeModsInternals;
const compositionInRoot = `import {Composition} from 'remotion';
import {NewVideo} from './NewVideo';
diff --git a/packages/studio-server/src/test/split-jsx-sequence.test.ts b/packages/studio-server/src/test/split-jsx-sequence.test.ts
index 9109ad6268..1e451ae1da 100644
--- a/packages/studio-server/src/test/split-jsx-sequence.test.ts
+++ b/packages/studio-server/src/test/split-jsx-sequence.test.ts
@@ -2,7 +2,7 @@ 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 {splitJsxSequence as splitJsxSequenceCodemod} from '@remotion/codemods/internal';
+import {CodeModsInternals} from '@remotion/codemods';
import {splitJsxSequence} from '../codemods/split-jsx-sequence';
import {
createFileWatcherRegistry,
@@ -13,6 +13,8 @@ import {splitJsxSequenceHandler} from '../preview-server/routes/split-jsx-sequen
import {getUndoStack} from '../preview-server/undo-stack';
import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
+const {splitJsxSequence: splitJsxSequenceCodemod} = CodeModsInternals;
+
const wrap = (
sequence: string,
) => `import {AbsoluteFill, Img, Interactive, Sequence, Series, Solid} from 'remotion';