Skip to content

🎥 Make videos programmatically with React

@remotion/studio-codemods: Remove remaining Prettier formatting

Jonny Burgerf71df77ca64c
diff --git a/bun.lock b/bun.lock
index d1ad776e5c..37551eff4d 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1898,7 +1898,6 @@
"kiwi-schema": "0.5.0",
"memfs": "3.4.3",
"open": "8.4.2",
- "prettier": "catalog:",
"recast": "0.23.21",
"remotion": "workspace:*",
"semver": "7.5.3",
@@ -1911,6 +1910,7 @@
"@typescript/native-preview": "catalog:",
"ast-types": "0.16.1",
"eslint": "catalog:",
+ "prettier": "catalog:",
"react": "catalog:",
},
},
diff --git a/packages/studio-codemods/src/apply-visual-control.ts b/packages/studio-codemods/src/apply-visual-control.ts
index 7df00a8e6d..0408bb95bb 100644
--- a/packages/studio-codemods/src/apply-visual-control.ts
+++ b/packages/studio-codemods/src/apply-visual-control.ts
@@ -1,20 +1,21 @@
-import type {
- AssignmentExpression,
- ExpressionStatement,
- File,
-} from '@babel/types';
import {
stringifyDefaultProps,
type ApplyVisualControlCodemod,
} from '@remotion/studio-shared';
import type {ExpressionKind} from 'ast-types/lib/gen/kinds';
import * as recast from 'recast';
-import type {ApplyCodeModReturnType, Change} from './recast-mods';
+import {formatSerializedValue} from './format-serialized-value';
+import {recastLocToOffset} from './recast-loc-to-offset';
import {parseAst} from './sequence-props/parse-ast';
+import {applySourceEdits, type SourceEdit} from './source-edits';
const expectString = (
- node: ExpressionKind | recast.types.namedTypes.SpreadElement,
+ node: ExpressionKind | recast.types.namedTypes.SpreadElement | undefined,
) => {
+ if (!node) {
+ throw new Error('Expected a string literal');
+ }
+
if (node.type === 'StringLiteral') {
return node.value;
}
@@ -33,14 +34,19 @@ const expectString = (
};
export const applyVisualControl = ({
- file,
+ input,
transformation,
- changesMade,
}: {
- file: File;
+ input: string;
transformation: ApplyVisualControlCodemod;
- changesMade: Change[];
-}): ApplyCodeModReturnType => {
+}): {
+ newContents: string;
+ changesMade: {description: string}[];
+} => {
+ const file = parseAst(input);
+ const changesMade: {description: string}[] = [];
+ const edits: SourceEdit[] = [];
+
recast.types.visit(file.program, {
visitCallExpression(path) {
const {node} = path;
@@ -59,40 +65,71 @@ export const applyVisualControl = ({
const firstArgument = node.arguments[0];
const str = expectString(firstArgument);
+ const matchingChanges = transformation.changes.filter(
+ (candidate) => candidate.id === str,
+ );
+ const change = matchingChanges.at(-1);
+ if (!change) {
+ return this.traverse(path);
+ }
- for (const change of transformation.changes) {
- if (change.id !== str) {
- continue;
+ const serialized = change.newValueIsUndefined
+ ? 'undefined'
+ : stringifyDefaultProps({
+ props: JSON.parse(change.newValueSerialized),
+ enumPaths: change.enumPaths,
+ });
+ if (serialized === undefined) {
+ throw new Error('Could not serialize the visual control value');
+ }
+
+ const secondArgument = node.arguments[1];
+ if (secondArgument) {
+ if (!secondArgument.loc) {
+ throw new Error('Could not locate the visual control value');
}
- let parsed: ExpressionKind;
- if (change.newValueIsUndefined) {
- parsed = (
- (
- parseAst('a = undefined').program
- .body[0] as unknown as ExpressionStatement
- ).expression as AssignmentExpression
- ).right as ExpressionKind;
- } else {
- parsed = (
- (
- parseAst(
- `a = ${stringifyDefaultProps({props: JSON.parse(change.newValueSerialized), enumPaths: change.enumPaths})}`,
- ).program.body[0] as unknown as ExpressionStatement
- ).expression as AssignmentExpression
- ).right as ExpressionKind;
+ const start = recastLocToOffset(input, secondArgument.loc.start);
+ const end = recastLocToOffset(input, secondArgument.loc.end);
+ const lineStart = input.lastIndexOf('\n', start - 1) + 1;
+ edits.push({
+ start,
+ end,
+ replacement: formatSerializedValue({
+ input,
+ linePrefix: input.slice(lineStart, start),
+ previousValue: input.slice(start, end).trim(),
+ serialized,
+ }),
+ });
+ } else {
+ if (!firstArgument.loc) {
+ throw new Error('Could not locate the visual control identifier');
}
- node.arguments[1] = parsed;
+ const offset = recastLocToOffset(input, firstArgument.loc.end);
+ const lineStart = input.lastIndexOf('\n', offset - 1) + 1;
+ edits.push({
+ start: offset,
+ end: offset,
+ replacement: `, ${formatSerializedValue({
+ input,
+ linePrefix: `${input.slice(lineStart, offset)}, `,
+ previousValue: null,
+ serialized,
+ })}`,
+ });
+ }
+ for (const matchingChange of matchingChanges) {
changesMade.push({
- description: `Applied visual control ${change.id}`,
+ description: `Applied visual control ${matchingChange.id}`,
});
}
- return this.traverse(path);
+ return false;
},
});
- return {newAst: file, changesMade};
+ return {newContents: applySourceEdits({input, edits}), changesMade};
};
diff --git a/packages/studio-codemods/src/composition-source-edits.ts b/packages/studio-codemods/src/composition-source-edits.ts
index 2c79c2d927..60076acc16 100644
--- a/packages/studio-codemods/src/composition-source-edits.ts
+++ b/packages/studio-codemods/src/composition-source-edits.ts
@@ -6,6 +6,7 @@ import {getNodeSourceEdit} from './delete-jsx-node';
import {getCompositionId} from './duplicate-composition';
import {getInsertionRootSourceEdit} from './insert-jsx-element';
import {printInsertedJsx} from './print-jsx';
+import {recastLocToOffset} from './recast-loc-to-offset';
import {applyCodemod, type Change} from './recast-mods';
import {ensureNamedImport} from './sequence-props/imports';
import {parseAst} from './sequence-props/parse-ast';
@@ -16,6 +17,7 @@ import {
getJsxStringAttributeValueSourceEdit,
type SourceEdit,
} from './source-edits';
+import {getEndOfLine, getIndentationUnit, getLineIndent} from './source-style';
export const editCompositionInSource = ({
input,
@@ -24,7 +26,13 @@ export const editCompositionInSource = ({
input: string;
codeMod: Extract<
RecastCodemod,
- {type: 'new-composition' | 'rename-composition' | 'delete-composition'}
+ {
+ type:
+ | 'new-composition'
+ | 'rename-composition'
+ | 'delete-composition'
+ | 'update-composition-metadata';
+ }
>;
}): {newContents: string; changesMade: Change[]} => {
const ast = parseAst(input);
@@ -126,12 +134,13 @@ export const editCompositionInSource = ({
recast.types.visit(ast, {
visitJSXElement(path) {
const element = path.node as unknown as JSXElement;
- if (
- getCompositionId(element) !==
- (codeMod.type === 'rename-composition'
+ const compositionId =
+ codeMod.type === 'rename-composition'
? codeMod.idToRename
- : codeMod.idToDelete)
- ) {
+ : codeMod.type === 'delete-composition'
+ ? codeMod.idToDelete
+ : codeMod.idToUpdate;
+ if (getCompositionId(element) !== compositionId) {
this.traverse(path);
return undefined;
}
@@ -144,19 +153,147 @@ export const editCompositionInSource = ({
return false;
}
- const attribute = element.openingElement.attributes.find(
+ if (codeMod.type === 'update-composition-metadata') {
+ const metadata = [
+ {name: 'fps', value: codeMod.newFps, description: 'FPS'},
+ {
+ name: 'durationInFrames',
+ value: codeMod.newDurationInFrames,
+ description: 'durationInFrames',
+ },
+ {name: 'width', value: codeMod.newWidth, description: 'width'},
+ {name: 'height', value: codeMod.newHeight, description: 'height'},
+ ] as const;
+ const existingMetadata = new Set<string>();
+
+ for (const metadataAttribute of element.openingElement.attributes) {
+ if (
+ metadataAttribute.type !== 'JSXAttribute' ||
+ metadataAttribute.name.type !== 'JSXIdentifier'
+ ) {
+ continue;
+ }
+
+ const update = metadata.find(
+ (item) => item.name === metadataAttribute.name.name,
+ );
+ if (!update || update.value === null) {
+ continue;
+ }
+
+ existingMetadata.add(update.name);
+ if (metadataAttribute.value?.loc) {
+ edits.push({
+ start: recastLocToOffset(
+ input,
+ metadataAttribute.value.loc.start,
+ ),
+ end: recastLocToOffset(input, metadataAttribute.value.loc.end),
+ replacement: `{${update.value}}`,
+ });
+ } else if (metadataAttribute.loc) {
+ const offset = recastLocToOffset(
+ input,
+ metadataAttribute.loc.end,
+ );
+ edits.push({
+ start: offset,
+ end: offset,
+ replacement: `={${update.value}}`,
+ });
+ } else {
+ throw new Error(
+ `Could not locate the "${update.name}" attribute`,
+ );
+ }
+
+ changesMade.push({
+ description: `Replaced ${update.description}`,
+ });
+ }
+
+ const missingMetadata = metadata.filter(
+ (item) => item.value !== null && !existingMetadata.has(item.name),
+ );
+ if (missingMetadata.length > 0) {
+ const {openingElement} = element;
+ if (!openingElement.loc || !openingElement.name.loc) {
+ throw new Error(
+ 'Could not locate the composition opening element',
+ );
+ }
+
+ const openingEnd = recastLocToOffset(input, openingElement.loc.end);
+ const closingStart =
+ openingEnd - (openingElement.selfClosing ? 2 : 1);
+ const lastAttribute = openingElement.attributes.findLast(
+ (candidate) => candidate.loc,
+ );
+ const anchor =
+ lastAttribute?.loc?.end ?? openingElement.name.loc.end;
+ const anchorOffset = recastLocToOffset(input, anchor);
+ const rendered = missingMetadata.map(
+ (item) => `${item.name}={${item.value}}`,
+ );
+
+ if (input.slice(anchorOffset, closingStart).includes('\n')) {
+ const closingLineStart =
+ input.lastIndexOf('\n', closingStart - 1) + 1;
+ const attributeIndent =
+ lastAttribute?.loc &&
+ lastAttribute.loc.start.line > openingElement.name.loc.end.line
+ ? getLineIndent({
+ input,
+ offset: recastLocToOffset(input, lastAttribute.loc.start),
+ })
+ : getLineIndent({
+ input,
+ offset: recastLocToOffset(
+ input,
+ openingElement.loc.start,
+ ),
+ }) + getIndentationUnit(input, null);
+ const endOfLine = getEndOfLine(input);
+ edits.push({
+ start: closingLineStart,
+ end: closingLineStart,
+ replacement:
+ rendered
+ .map(
+ (renderedAttribute) =>
+ `${attributeIndent}${renderedAttribute}`,
+ )
+ .join(endOfLine) + endOfLine,
+ });
+ } else {
+ edits.push({
+ start: anchorOffset,
+ end: anchorOffset,
+ replacement: ` ${rendered.join(' ')}`,
+ });
+ }
+
+ for (const item of missingMetadata) {
+ changesMade.push({description: `Added ${item.description}`});
+ }
+ }
+
+ return false;
+ }
+
+ const idAttribute = element.openingElement.attributes.find(
(attr) =>
attr.type === 'JSXAttribute' &&
attr.name.type === 'JSXIdentifier' &&
attr.name.name === 'id',
);
- if (attribute?.type !== 'JSXAttribute') {
+ if (idAttribute?.type !== 'JSXAttribute') {
throw new Error('Could not locate the composition id');
}
edits.push(
getJsxStringAttributeValueSourceEdit({
- attribute,
+ attribute: idAttribute,
input,
newValue: codeMod.newId,
}),
diff --git a/packages/studio-codemods/src/format-serialized-value.ts b/packages/studio-codemods/src/format-serialized-value.ts
new file mode 100644
index 0000000000..be634d3a8a
--- /dev/null
+++ b/packages/studio-codemods/src/format-serialized-value.ts
@@ -0,0 +1,135 @@
+import * as recast from 'recast';
+import {parseAst} from './sequence-props/parse-ast';
+import {
+ getSourceFormattingConfig,
+ normalizePrintedIndentation,
+} from './source-style';
+
+const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;
+
+export const formatSerializedValue = ({
+ input,
+ linePrefix,
+ previousValue,
+ serialized,
+}: {
+ input: string;
+ linePrefix: string;
+ previousValue: string | null;
+ serialized: string;
+}) => {
+ const inlineObjectSpacing = previousValue?.match(
+ /\{([\t ]*)(?=(?:["'][^"']+["']|[$A-Z_a-z][$\w]*)[\t ]*:)/,
+ )?.[1];
+ const bracketSpacing =
+ previousValue === null
+ ? null
+ : previousValue.startsWith('{ ')
+ ? true
+ : previousValue.startsWith('{') &&
+ !previousValue.startsWith('{\n') &&
+ !previousValue.startsWith('{\r\n')
+ ? false
+ : inlineObjectSpacing === undefined
+ ? null
+ : inlineObjectSpacing.length > 0;
+ const formattingConfig = getSourceFormattingConfig({
+ input,
+ prettierConfigOverride: bracketSpacing === null ? null : {bracketSpacing},
+ });
+ const valueAst = parseAst(`__value = ${serialized}`);
+ const statement = valueAst.program.body[0];
+ if (
+ statement?.type !== 'ExpressionStatement' ||
+ statement.expression.type !== 'AssignmentExpression'
+ ) {
+ throw new Error('Could not parse the serialized value');
+ }
+
+ const expression = statement.expression.right;
+ recast.types.visit(expression, {
+ visitObjectProperty(path) {
+ const {node} = path;
+ if (
+ !node.computed &&
+ node.key.type === 'StringLiteral' &&
+ identifierRegex.test(node.key.value)
+ ) {
+ node.key = recast.types.builders.identifier(node.key.value);
+ }
+
+ this.traverse(path);
+ },
+ });
+
+ const printExpression = ({
+ trailingComma,
+ wrapColumn,
+ }: {
+ trailingComma: boolean;
+ wrapColumn: number;
+ }) => {
+ const printed = recast.prettyPrint(expression, {
+ objectCurlySpacing: formattingConfig.bracketSpacing,
+ quote: formattingConfig.quote,
+ tabWidth: formattingConfig.tabWidth,
+ trailingComma,
+ useTabs: false,
+ wrapColumn,
+ }).code;
+
+ return normalizePrintedIndentation({
+ endOfLine: formattingConfig.endOfLine,
+ indentationUnit: formattingConfig.indentationUnit,
+ printed,
+ tabWidth: formattingConfig.tabWidth,
+ });
+ };
+
+ const compactLines = printExpression({
+ trailingComma: false,
+ wrapColumn: Number.POSITIVE_INFINITY,
+ })
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean);
+ const compact = compactLines.reduce((result, line) => {
+ if (result.length === 0) {
+ return line;
+ }
+
+ const omitSeparator =
+ !formattingConfig.bracketSpacing &&
+ (result.endsWith('{') || line.startsWith('}'));
+ return `${result}${omitSeparator ? '' : ' '}${line}`;
+ }, '');
+ const columnOffset = [...linePrefix].reduce(
+ (column, character) =>
+ character === '\t' ? column + formattingConfig.tabWidth : column + 1,
+ 0,
+ );
+ const compactWidth = [...compact].reduce(
+ (column, character) =>
+ character === '\t' ? column + formattingConfig.tabWidth : column + 1,
+ 0,
+ );
+ const baseIndent = linePrefix.match(/^([\t ]*)/)?.[1] ?? '';
+ const effectivePrintWidth = Math.max(
+ formattingConfig.printWidth - columnOffset,
+ 20,
+ );
+ const multiline = printExpression({
+ trailingComma: true,
+ wrapColumn: effectivePrintWidth,
+ })
+ .split(/\r?\n/)
+ .filter((line) => line.trim().length > 0)
+ .map((line, index) =>
+ index === 0 || line.length === 0 ? line : baseIndent + line,
+ )
+ .join(formattingConfig.endOfLine);
+
+ return columnOffset + compactWidth + 1 <= formattingConfig.printWidth
+ ? compact
+ : multiline;
+};
diff --git a/packages/studio-codemods/src/parse-and-apply-codemod.ts b/packages/studio-codemods/src/parse-and-apply-codemod.ts
index d44ef5d8f2..611c376e86 100644
--- a/packages/studio-codemods/src/parse-and-apply-codemod.ts
+++ b/packages/studio-codemods/src/parse-and-apply-codemod.ts
@@ -1,4 +1,5 @@
import type {RecastCodemod} from '@remotion/studio-shared';
+import {applyVisualControl} from './apply-visual-control';
import {editCompositionInSource} from './composition-source-edits';
import {duplicateCompositionInSource} from './duplicate-composition';
import {editFolderInSource} from './folder-source-edits';
@@ -13,6 +14,17 @@ export const parseAndApplyCodemod = ({
input: string;
codeMod: RecastCodemod;
}): {newContents: string; changesMade: Change[]} => {
+ if (codeMod.type === 'apply-visual-control') {
+ const result = applyVisualControl({input, transformation: codeMod});
+ if (result.changesMade.length === 0) {
+ throw new Error(
+ 'Unable to calculate the changes needed for this file. Edit the file manually.',
+ );
+ }
+
+ return result;
+ }
+
if (codeMod.type === 'duplicate-composition') {
return duplicateCompositionInSource({input, codemod: codeMod});
}
@@ -20,7 +32,8 @@ export const parseAndApplyCodemod = ({
if (
codeMod.type === 'new-composition' ||
codeMod.type === 'rename-composition' ||
- codeMod.type === 'delete-composition'
+ codeMod.type === 'delete-composition' ||
+ codeMod.type === 'update-composition-metadata'
) {
return editCompositionInSource({input, codeMod});
}
diff --git a/packages/studio-codemods/src/recast-mods.ts b/packages/studio-codemods/src/recast-mods.ts
index ffeb0a6da9..4ce0ed8c32 100644
--- a/packages/studio-codemods/src/recast-mods.ts
+++ b/packages/studio-codemods/src/recast-mods.ts
@@ -22,6 +22,7 @@ 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 {parseAst} from './sequence-props/parse-ast';
import {stripParenthesizedExtra} from './strip-parenthesized-extra';
export type Change = {
@@ -42,7 +43,14 @@ export const applyCodemod = ({
const changesMade: Change[] = [];
if (codeMod.type === 'apply-visual-control') {
- return applyVisualControl({file, transformation: codeMod, changesMade});
+ const result = applyVisualControl({
+ input: recast.print(file).code,
+ transformation: codeMod,
+ });
+ return {
+ newAst: parseAst(result.newContents),
+ changesMade: result.changesMade,
+ };
}
if (codeMod.type === 'move-composition-to-folder') {
diff --git a/packages/studio-codemods/src/test/apply-visual-control.test.ts b/packages/studio-codemods/src/test/apply-visual-control.test.ts
new file mode 100644
index 0000000000..310ef62f6e
--- /dev/null
+++ b/packages/studio-codemods/src/test/apply-visual-control.test.ts
@@ -0,0 +1,196 @@
+import {expect, test} from 'bun:test';
+import {applyVisualControl} from '../apply-visual-control';
+import {parseAndApplyCodemod} from '../parse-and-apply-codemod';
+import {parseAst} from '../sequence-props/parse-ast';
+
+test('updates visual controls without changing surrounding source', () => {
+ const input = [
+ "import {visualControl} from '@remotion/studio'",
+ '',
+ 'const untouched = { value : "keep" }',
+ "const opacity=visualControl('opacity', OPACITY)",
+ 'const mode = visualControl(`mode`, "slow")',
+ "const optional = visualControl('optional')",
+ '',
+ ].join('\r\n');
+ const {changesMade, newContents} = applyVisualControl({
+ input,
+ transformation: {
+ type: 'apply-visual-control',
+ changes: [
+ {
+ id: 'opacity',
+ newValueSerialized: '0.5',
+ newValueIsUndefined: false,
+ enumPaths: [],
+ },
+ {
+ id: 'mode',
+ newValueSerialized: '"fast"',
+ newValueIsUndefined: false,
+ enumPaths: [[]],
+ },
+ {
+ id: 'optional',
+ newValueSerialized: '',
+ newValueIsUndefined: true,
+ enumPaths: [],
+ },
+ ],
+ },
+ });
+
+ expect(changesMade).toEqual([
+ {description: 'Applied visual control opacity'},
+ {description: 'Applied visual control mode'},
+ {description: 'Applied visual control optional'},
+ ]);
+ expect(newContents).toBe(
+ input
+ .replace('OPACITY', '0.5')
+ .replace('"slow"', "'fast' as const")
+ .replace("'optional')", "'optional', undefined)"),
+ );
+ expect(() => parseAst(newContents)).not.toThrow();
+});
+
+test('formats object values using the existing source style', () => {
+ const input = `const untouched = {keep:"this spacing"}
+const settings = visualControl("settings", { old: true })
+`;
+ const {newContents} = applyVisualControl({
+ input,
+ transformation: {
+ type: 'apply-visual-control',
+ changes: [
+ {
+ id: 'settings',
+ newValueSerialized: JSON.stringify({
+ title: 'Hello',
+ 'dash-key': true,
+ }),
+ newValueIsUndefined: false,
+ enumPaths: [],
+ },
+ ],
+ },
+ });
+
+ expect(newContents).toBe(`const untouched = {keep:"this spacing"}
+const settings = visualControl("settings", { title: "Hello", "dash-key": true })
+`);
+ expect(() => parseAst(newContents)).not.toThrow();
+});
+
+test('wraps long visual-control values using CRLF and tab indentation', () => {
+ const input = [
+ 'import {visualControl} from "@remotion/studio"',
+ '',
+ 'export const value = visualControl(',
+ '\t"settings",',
+ '\t{ old: true },',
+ ')',
+ '',
+ ].join('\r\n');
+ const {newContents} = applyVisualControl({
+ input,
+ transformation: {
+ type: 'apply-visual-control',
+ changes: [
+ {
+ id: 'settings',
+ newValueSerialized: JSON.stringify({
+ title:
+ 'A long visual control title that requires wrapping across multiple lines',
+ 'dash-key': true,
+ items: [1, 2, 3],
+ }),
+ newValueIsUndefined: false,
+ enumPaths: [],
+ },
+ ],
+ },
+ });
+
+ expect(newContents).toBe(
+ [
+ 'import {visualControl} from "@remotion/studio"',
+ '',
+ 'export const value = visualControl(',
+ '\t"settings",',
+ '\t{',
+ '\t\ttitle: "A long visual control title that requires wrapping across multiple lines",',
+ '\t\t"dash-key": true,',
+ '\t\titems: [1, 2, 3],',
+ '\t},',
+ ')',
+ '',
+ ].join('\r\n'),
+ );
+ expect(() => parseAst(newContents)).not.toThrow();
+});
+
+test('an outer visual control replacement supersedes nested controls', () => {
+ const input =
+ "const value = visualControl('outer', {nested: visualControl('inner', 1)});\n";
+ const {changesMade, newContents} = applyVisualControl({
+ input,
+ transformation: {
+ type: 'apply-visual-control',
+ changes: [
+ {
+ id: 'outer',
+ newValueSerialized: '2',
+ newValueIsUndefined: false,
+ enumPaths: [],
+ },
+ {
+ id: 'inner',
+ newValueSerialized: '3',
+ newValueIsUndefined: false,
+ enumPaths: [],
+ },
+ ],
+ },
+ });
+
+ expect(changesMade).toEqual([{description: 'Applied visual control outer'}]);
+ expect(newContents).toBe("const value = visualControl('outer', 2);\n");
+});
+
+test('rejects dynamic and unmatched visual control identifiers', () => {
+ const dynamicIdentifier = `const value = visualControl(\`value-\${suffix}\`, 1);\n`;
+ expect(() =>
+ applyVisualControl({
+ input: dynamicIdentifier,
+ transformation: {
+ type: 'apply-visual-control',
+ changes: [
+ {
+ id: 'value',
+ newValueSerialized: '2',
+ newValueIsUndefined: false,
+ enumPaths: [],
+ },
+ ],
+ },
+ }),
+ ).toThrow('the string may not be dynamic');
+
+ expect(() =>
+ parseAndApplyCodemod({
+ input: "const value = visualControl('other', 1);\n",
+ codeMod: {
+ type: 'apply-visual-control',
+ changes: [
+ {
+ id: 'value',
+ newValueSerialized: '2',
+ newValueIsUndefined: false,
+ enumPaths: [],
+ },
+ ],
+ },
+ }),
+ ).toThrow('Unable to calculate the changes');
+});
diff --git a/packages/studio-codemods/src/test/composition-source-edits.test.ts b/packages/studio-codemods/src/test/composition-source-edits.test.ts
index 3fb938d2c5..3249b921e2 100644
--- a/packages/studio-codemods/src/test/composition-source-edits.test.ts
+++ b/packages/studio-codemods/src/test/composition-source-edits.test.ts
@@ -177,3 +177,121 @@ test('rename preserves expression quotes and delete replaces standalone and cond
}
}
});
+
+test('updates existing composition metadata without changing surrounding source', () => {
+ const input = [
+ 'import { Composition } from "remotion"',
+ '',
+ 'const preserve = { value : "keep" }',
+ 'export const Root = () => (',
+ ' <Composition',
+ ' id={"Original"}',
+ ' durationInFrames = { DURATION }',
+ ' fps={FPS}',
+ ' width',
+ ' height="720"',
+ ' />',
+ ')',
+ '',
+ ].join('\r\n');
+ const {changesMade, newContents} = parseAndApplyCodemod({
+ input,
+ codeMod: {
+ type: 'update-composition-metadata',
+ idToUpdate: 'Original',
+ newDurationInFrames: 240,
+ newFps: 60,
+ newWidth: 1920,
+ newHeight: 1080,
+ },
+ });
+
+ expect(changesMade).toEqual([
+ {description: 'Replaced durationInFrames'},
+ {description: 'Replaced FPS'},
+ {description: 'Replaced width'},
+ {description: 'Replaced height'},
+ ]);
+ expect(newContents).toBe(
+ input
+ .replace('{ DURATION }', '{240}')
+ .replace('{FPS}', '{60}')
+ .replace(' width\r\n', ' width={1920}\r\n')
+ .replace('height="720"', 'height={1080}'),
+ );
+ expect(() => parseAst(newContents)).not.toThrow();
+});
+
+test('adds missing composition metadata using multiline source style', () => {
+ for (const [indent, eol] of [
+ ['\t', '\n'],
+ [' ', '\n'],
+ [' ', '\r\n'],
+ ]) {
+ const input = [
+ 'export const Root = () => (',
+ `${indent}<Composition`,
+ `${indent}${indent}id="Original"`,
+ `${indent}/>`,
+ ')',
+ '',
+ ].join(eol);
+ const {changesMade, newContents} = parseAndApplyCodemod({
+ input,
+ codeMod: {
+ type: 'update-composition-metadata',
+ idToUpdate: 'Original',
+ newDurationInFrames: 90,
+ newFps: 30,
+ newWidth: 1920,
+ newHeight: 1080,
+ },
+ });
+
+ expect(changesMade).toEqual([
+ {description: 'Added FPS'},
+ {description: 'Added durationInFrames'},
+ {description: 'Added width'},
+ {description: 'Added height'},
+ ]);
+ expect(newContents).toBe(
+ input.replace(
+ `${indent}/>`,
+ [
+ `${indent}${indent}fps={30}`,
+ `${indent}${indent}durationInFrames={90}`,
+ `${indent}${indent}width={1920}`,
+ `${indent}${indent}height={1080}`,
+ `${indent}/>`,
+ ].join(eol),
+ ),
+ );
+ expect(() => parseAst(newContents)).not.toThrow();
+ }
+});
+
+test('adds missing composition metadata without reformatting an inline tag', () => {
+ const input = `const preserve = { value : "keep" };
+export const Root=()=> <Still id={'Original'} height = "720"/>;
+`;
+ const {changesMade, newContents} = parseAndApplyCodemod({
+ input,
+ codeMod: {
+ type: 'update-composition-metadata',
+ idToUpdate: 'Original',
+ newDurationInFrames: null,
+ newFps: null,
+ newWidth: 1920,
+ newHeight: 1080,
+ },
+ });
+
+ expect(changesMade).toEqual([
+ {description: 'Replaced height'},
+ {description: 'Added width'},
+ ]);
+ expect(newContents).toBe(`const preserve = { value : "keep" };
+export const Root=()=> <Still id={'Original'} height = {1080} width={1920}/>;
+`);
+ expect(() => parseAst(newContents)).not.toThrow();
+});
diff --git a/packages/studio-codemods/src/update-default-props.ts b/packages/studio-codemods/src/update-default-props.ts
index d8b85a847f..8b54f73d01 100644
--- a/packages/studio-codemods/src/update-default-props.ts
+++ b/packages/studio-codemods/src/update-default-props.ts
@@ -1,13 +1,8 @@
import {stringifyDefaultProps, type EnumPath} from '@remotion/studio-shared';
import * as recast from 'recast';
+import {formatSerializedValue} from './format-serialized-value';
import {recastLocToOffset} from './recast-loc-to-offset';
import {parseAst} from './sequence-props/parse-ast';
-import {
- getSourceFormattingConfig,
- normalizePrintedIndentation,
-} from './source-style';
-
-const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;
export const updateDefaultProps = ({
input,
@@ -151,118 +146,17 @@ export const updateDefaultProps = ({
const lineStart = input.lastIndexOf('\n', replaceStart) + 1;
const linePrefix = input.substring(lineStart, replaceStart + 1);
const previousValue = input.slice(replaceStart + 1, replaceEnd - 1).trim();
- const inlineObjectSpacing = previousValue.match(
- /\{([\t ]*)(?=(?:["'][^"']+["']|[$A-Z_a-z][$\w]*)[\t ]*:)/,
- )?.[1];
- const bracketSpacing = previousValue.startsWith('{ ')
- ? true
- : previousValue.startsWith('{') &&
- !previousValue.startsWith('{\n') &&
- !previousValue.startsWith('{\r\n')
- ? false
- : inlineObjectSpacing === undefined
- ? null
- : inlineObjectSpacing.length > 0;
- const formattingConfig = getSourceFormattingConfig({
- input,
- prettierConfigOverride: bracketSpacing === null ? null : {bracketSpacing},
- });
- const valueAst = parseAst(`__defaultProps = ${stringified}`);
- const statement = valueAst.program.body[0];
- if (
- statement?.type !== 'ExpressionStatement' ||
- statement.expression.type !== 'AssignmentExpression'
- ) {
- throw new Error('Could not parse the updated defaultProps value');
+ if (stringified === undefined) {
+ throw new Error('Could not serialize the updated defaultProps value');
}
- const expression = statement.expression.right;
- recast.types.visit(expression, {
- visitObjectProperty(path) {
- const {node} = path;
- if (
- !node.computed &&
- node.key.type === 'StringLiteral' &&
- identifierRegex.test(node.key.value)
- ) {
- node.key = recast.types.builders.identifier(node.key.value);
- }
-
- this.traverse(path);
- },
+ const formatted = formatSerializedValue({
+ input,
+ linePrefix,
+ previousValue,
+ serialized: stringified,
});
- const printExpression = ({
- trailingComma,
- wrapColumn,
- }: {
- trailingComma: boolean;
- wrapColumn: number;
- }) => {
- const printed = recast.prettyPrint(expression, {
- objectCurlySpacing: formattingConfig.bracketSpacing,
- quote: formattingConfig.quote,
- tabWidth: formattingConfig.tabWidth,
- trailingComma,
- useTabs: false,
- wrapColumn,
- }).code;
-
- return normalizePrintedIndentation({
- endOfLine: formattingConfig.endOfLine,
- indentationUnit: formattingConfig.indentationUnit,
- printed,
- tabWidth: formattingConfig.tabWidth,
- });
- };
-
- const compactLines = printExpression({
- trailingComma: false,
- wrapColumn: Number.POSITIVE_INFINITY,
- })
- .split(/\r?\n/)
- .map((line) => line.trim())
- .filter(Boolean);
- const compact = compactLines.reduce((result, line) => {
- if (result.length === 0) {
- return line;
- }
-
- const omitSeparator =
- !formattingConfig.bracketSpacing &&
- (result.endsWith('{') || line.startsWith('}'));
- return `${result}${omitSeparator ? '' : ' '}${line}`;
- }, '');
- const columnOffset = [...linePrefix].reduce(
- (column, character) =>
- character === '\t' ? column + formattingConfig.tabWidth : column + 1,
- 0,
- );
- const compactWidth = [...compact].reduce(
- (column, character) =>
- character === '\t' ? column + formattingConfig.tabWidth : column + 1,
- 0,
- );
- const baseIndent = linePrefix.match(/^([\t ]*)/)?.[1] ?? '';
- const effectivePrintWidth = Math.max(
- formattingConfig.printWidth - columnOffset,
- 20,
- );
- const multiline = printExpression({
- trailingComma: true,
- wrapColumn: effectivePrintWidth,
- })
- .split(/\r?\n/)
- .filter((line) => line.trim().length > 0)
- .map((line, index) =>
- index === 0 || line.length === 0 ? line : baseIndent + line,
- )
- .join(formattingConfig.endOfLine);
- const formatted =
- columnOffset + compactWidth + 1 <= formattingConfig.printWidth
- ? compact
- : multiline;
-
// Replace the JSX expression container in the original input
const output =
input.substring(0, replaceStart) +
diff --git a/packages/studio-server/package.json b/packages/studio-server/package.json
index 54ed345090..e070ef376a 100644
--- a/packages/studio-server/package.json
+++ b/packages/studio-server/package.json
@@ -31,7 +31,6 @@
"kiwi-schema": "0.5.0",
"semver": "7.5.3",
"zod": "catalog:",
- "prettier": "catalog:",
"remotion": "workspace:*",
"recast": "0.23.21",
"@remotion/bundler": "workspace:*",
@@ -47,6 +46,7 @@
"@types/semver": "7.5.3",
"@remotion/eslint-config-internal": "workspace:*",
"eslint": "catalog:",
+ "prettier": "catalog:",
"@types/node": "catalog:",
"@typescript/native-preview": "catalog:"
},
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 6d3339d92e..8363441b73 100644
--- a/packages/studio-server/src/codemods/apply-codemod-to-file.ts
+++ b/packages/studio-server/src/codemods/apply-codemod-to-file.ts
@@ -1,11 +1,11 @@
import {existsSync, readFileSync} from 'node:fs';
+import {parseAndApplyCodemod} from '@remotion/studio-codemods';
import type {
RecastCodemod,
SymbolicatedStackFrame,
} from '@remotion/studio-shared';
import {resolveFileInsideProject} from '../helpers/resolve-file-inside-project';
import {checkIfTypeScriptFile} from '../preview-server/routes/can-update-default-props';
-import {formatOutput, parseAndApplyCodemod} from './duplicate-composition';
export const resolveFilePathFromSymbolicatedStack = (
remotionRoot: string,
@@ -30,7 +30,7 @@ export const resolveFilePathFromSymbolicatedStack = (
return absolutePath;
};
-export const applyCodemodToFile = async ({
+export const applyCodemodToFile = ({
filePath,
codeMod,
}: {
@@ -45,20 +45,5 @@ export const applyCodemodToFile = async ({
input,
});
- if (
- codeMod.type === 'new-composition' ||
- codeMod.type === 'duplicate-composition' ||
- codeMod.type === 'rename-composition' ||
- codeMod.type === 'delete-composition' ||
- codeMod.type === 'move-composition-to-folder' ||
- codeMod.type === 'move-composition-or-folder' ||
- codeMod.type === 'rename-folder' ||
- codeMod.type === 'new-folder' ||
- codeMod.type === 'delete-folder'
- ) {
- return newContents;
- }
-
- const formatted = await formatOutput(newContents);
- return formatted;
+ return Promise.resolve(newContents);
};
diff --git a/packages/studio-server/src/codemods/duplicate-composition.ts b/packages/studio-server/src/codemods/duplicate-composition.ts
deleted file mode 100644
index 981ca04883..0000000000
--- a/packages/studio-server/src/codemods/duplicate-composition.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-export {parseAndApplyCodemod} from '@remotion/studio-codemods';
-
-const getPrettier = async () => {
- try {
- return await import('prettier');
- } catch {
- throw new Error('Prettier cannot be found in the current project.');
- }
-};
-
-export const formatOutput = async (tsContent: string) => {
- const prettier = await getPrettier();
-
- const {format, resolveConfig, resolveConfigFile} = prettier;
-
- const configFilePath = await resolveConfigFile();
- if (!configFilePath) {
- throw new Error(
- 'The Prettier config file was not found. For this feature, the "prettier" package must be installed and a .prettierrc file must exist.',
- );
- }
-
- const prettierConfig = await resolveConfig(configFilePath);
- if (!prettierConfig) {
- throw new Error(
- `The Prettier config at ${configFilePath} could not be read`,
- );
- }
-
- const newContents = await format(tsContent, {
- ...prettierConfig,
- filepath: 'test.tsx',
- });
-
- return newContents;
-};
diff --git a/packages/studio-server/src/codemods/format-file-content.ts b/packages/studio-server/src/codemods/format-file-content.ts
deleted file mode 100644
index 2d2174df67..0000000000
--- a/packages/studio-server/src/codemods/format-file-content.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-// eslint-disable-next-line @typescript-eslint/consistent-type-imports
-type PrettierType = typeof import('prettier');
-
-export const formatFileContent = async ({
- input,
- prettierConfigOverride,
-}: {
- input: string;
- prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{output: string; formatted: boolean}> => {
- let prettier: PrettierType | null = null;
-
- try {
- prettier = await import('prettier');
- } catch {
- return {
- output: input,
- formatted: false,
- };
- }
-
- const {format, resolveConfig, resolveConfigFile} = prettier as PrettierType;
-
- let prettierConfig: Record<string, unknown> | null;
-
- if (prettierConfigOverride !== undefined && prettierConfigOverride !== null) {
- prettierConfig = prettierConfigOverride;
- } else {
- const configFilePath = await resolveConfigFile();
- if (!configFilePath) {
- return {
- output: input,
- formatted: false,
- };
- }
-
- prettierConfig = await resolveConfig(configFilePath);
- }
-
- if (!prettierConfig) {
- return {
- output: input,
- formatted: false,
- };
- }
-
- const prettified = await format(input, {
- ...prettierConfig,
- filepath: 'test.tsx',
- plugins: [],
- endOfLine: 'lf',
- });
-
- return {
- output: prettified,
- formatted: true,
- };
-};
diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts
index 6bcf05a551..3c9d750fed 100644
--- a/packages/studio-server/src/index.ts
+++ b/packages/studio-server/src/index.ts
@@ -23,6 +23,7 @@ export type {
UiOpenGlOptions,
} from '@remotion/studio-shared';
+import {parseAndApplyCodemod} from '@remotion/studio-codemods';
import {AnsiDiff} from './ansi-diff';
import {
addCompletedClientRender,
@@ -30,10 +31,6 @@ import {
removeCompletedClientRender,
} from './client-render-queue';
import {applyCodemodToFile} from './codemods/apply-codemod-to-file';
-import {
- formatOutput,
- parseAndApplyCodemod,
-} from './codemods/duplicate-composition';
import {updateDefaultProps} from './codemods/update-default-props';
import {
detectOutdatedRemotionSkills,
@@ -98,7 +95,6 @@ export const StudioServerInternals = {
formatBytes,
parseAndApplyCodemod,
applyCodemodToFile,
- formatOutput,
updateDefaultProps,
getInstalledDependencies,
getInstalledDependenciesWithVersions,
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 7f8168205a..c95e2ef099 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,13 +1,13 @@
import {readFileSync} from 'node:fs';
import type {File} from '@babel/types';
import {RenderInternals} from '@remotion/renderer';
-import {applyCodemod} from '@remotion/studio-codemods';
+import {applyVisualControl} from '@remotion/studio-codemods';
import type {
ApplyVisualControlRequest,
ApplyVisualControlResponse,
} from '@remotion/studio-shared';
import * as recast from 'recast';
-import {parseAst, serializeAst} from '../../codemods/parse-ast';
+import {parseAst} from '../../codemods/parse-ast';
import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
import type {ApiHandler} from '../api-types';
@@ -19,7 +19,6 @@ import {
suppressUndoStackInvalidation,
} from '../undo-stack';
import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';
-import {warnAboutPrettierOnce} from './log-updates/log-update';
import {
getCodemodTimingPrefix,
withSourceFileWriteQueue,
@@ -52,7 +51,7 @@ export const applyVisualControlHandler: ApiHandler<
ApplyVisualControlRequest,
ApplyVisualControlResponse
> = ({input: {fileName, changes}, remotionRoot, logLevel}) => {
- return withSourceFileWriteQueue(async () => {
+ return withSourceFileWriteQueue(() => {
RenderInternals.Log.trace(
{indent: false, logLevel},
`[apply-visual-control] Received request for ${fileName} with ${changes.length} changes`,
@@ -68,9 +67,9 @@ export const applyVisualControlHandler: ApiHandler<
const logLine =
changes.length > 0 ? getVisualControlChangeLine(ast, changes[0].id) : 1;
- const {newAst, changesMade} = applyCodemod({
- file: ast,
- codeMod: {
+ const {newContents: output, changesMade} = applyVisualControl({
+ input: fileContents,
+ transformation: {
type: 'apply-visual-control',
changes,
},
@@ -80,31 +79,6 @@ export const applyVisualControlHandler: ApiHandler<
throw new Error('No changes were made to the file');
}
- let output = serializeAst(newAst);
- let formatted = false;
-
- // eslint-disable-next-line @typescript-eslint/consistent-type-imports
- type PrettierType = typeof import('prettier');
- try {
- const prettier: PrettierType = await import('prettier');
- const {format, resolveConfig, resolveConfigFile} = prettier;
- const configFilePath = await resolveConfigFile();
- if (configFilePath) {
- const prettierConfig = await resolveConfig(configFilePath);
- if (prettierConfig) {
- output = await format(output, {
- ...prettierConfig,
- filepath: 'test.tsx',
- plugins: [],
- endOfLine: 'auto',
- });
- formatted = true;
- }
- }
- } catch {
- // Prettier not available, use unformatted output
- }
-
pushToUndoStack({
filePath: absolutePath,
oldContents: fileContents,
@@ -151,14 +125,9 @@ export const applyVisualControlHandler: ApiHandler<
{indent: false, logLevel},
`${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(`${locationLabel}`)} Applied visual control changes`,
);
- if (!formatted) {
- warnAboutPrettierOnce(logLevel);
- }
printUndoHint(logLevel);
- return {
- success: true,
- };
+ return Promise.resolve({success: true});
});
};
diff --git a/packages/studio-server/src/test/apply-codemod.test.ts b/packages/studio-server/src/test/apply-codemod.test.ts
index eec51bd87f..dcff46162c 100644
--- a/packages/studio-server/src/test/apply-codemod.test.ts
+++ b/packages/studio-server/src/test/apply-codemod.test.ts
@@ -8,9 +8,9 @@ import {
} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'node:path';
+import {parseAndApplyCodemod} from '@remotion/studio-codemods';
import type {RecastCodemod} from '@remotion/studio-shared';
import {applyCodemodToFile} from '../codemods/apply-codemod-to-file';
-import {parseAndApplyCodemod} from '../codemods/duplicate-composition';
import {
createFileWatcherRegistry,
setFileWatcherRegistry,
@@ -20,6 +20,7 @@ import {
applyCodemodHandler,
getCodemodLogMessage,
} from '../preview-server/routes/apply-codemod';
+import {applyVisualControlHandler} from '../preview-server/routes/apply-visual-control-change';
import {redoHandler} from '../preview-server/routes/redo';
import {undoHandler} from '../preview-server/routes/undo';
import {getRedoStack, getUndoStack} from '../preview-server/undo-stack';
@@ -213,6 +214,116 @@ export const Root = () => <Folder name="Before" />;
}
});
+test('metadata codemods do not run Prettier after applying source edits', async () => {
+ const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
+ const filePath = path.join(remotionRoot, 'Root.tsx');
+ const input = `const untouched = { value : "keep" };
+export const Root=()=> <Composition id='Comp' width = { WIDTH }/>;
+`;
+
+ try {
+ writeFileSync(filePath, input);
+ const output = await applyCodemodToFile({
+ filePath,
+ codeMod: {
+ type: 'update-composition-metadata',
+ idToUpdate: 'Comp',
+ newDurationInFrames: 90,
+ newFps: null,
+ newHeight: 1080,
+ newWidth: 1920,
+ },
+ });
+
+ expect(output).toBe(`const untouched = { value : "keep" };
+export const Root=()=> <Composition id='Comp' width = {1920} durationInFrames={90} height={1080}/>;
+`);
+ } finally {
+ rmSync(remotionRoot, {recursive: true, force: true});
+ }
+});
+
+test('visual-control codemods do not run Prettier after applying source edits', async () => {
+ const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
+ const filePath = path.join(remotionRoot, 'Root.tsx');
+ const input = `const untouched = { value : "keep" };
+export const Root=()=> visualControl('opacity', OPACITY);
+`;
+
+ try {
+ writeFileSync(filePath, input);
+ const output = await applyCodemodToFile({
+ filePath,
+ codeMod: {
+ type: 'apply-visual-control',
+ changes: [
+ {
+ id: 'opacity',
+ newValueSerialized: '0.5',
+ newValueIsUndefined: false,
+ enumPaths: [],
+ },
+ ],
+ },
+ });
+
+ expect(output).toBe(input.replace('OPACITY', '0.5'));
+ } finally {
+ rmSync(remotionRoot, {recursive: true, force: true});
+ }
+});
+
+test('visual-control handler preserves source formatting', async () => {
+ const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
+ const cleanupFileWatcher = setFileWatcherRegistry(
+ createFileWatcherRegistry(),
+ );
+ const cleanupLiveEvents = setLiveEventsListener({
+ sendEventToClient: () => undefined,
+ sendEventToClientId: () => true,
+ router: () => Promise.resolve(),
+ closeConnections: () => Promise.resolve(),
+ addNewClientListener: () => () => undefined,
+ });
+ const filePath = path.join(remotionRoot, 'Root.tsx');
+ const input = `const untouched = { value : "keep" };
+export const Root=()=> visualControl('opacity', OPACITY);
+`;
+
+ try {
+ clearUndoRedoStacks();
+ writeFileSync(filePath, input);
+ const response = await applyVisualControlHandler(
+ getHandlerOptions({
+ input: {
+ fileName: 'Root.tsx',
+ changes: [
+ {
+ id: 'opacity',
+ newValueSerialized: '0.5',
+ newValueIsUndefined: false,
+ enumPaths: [],
+ },
+ ],
+ },
+ entryPoint: filePath,
+ remotionRoot,
+ }),
+ );
+
+ expect(response.success).toBe(true);
+ expect(readFileSync(filePath, 'utf-8')).toBe(
+ input.replace('OPACITY', '0.5'),
+ );
+ expect(getUndoStack()).toHaveLength(1);
+ } finally {
+ clearUndoRedoStacks();
+ cleanupLiveEvents();
+ cleanupFileWatcher();
+ rmSync(remotionRoot, {recursive: true, force: true});
+ }
+});
+
test('formats precise log messages for all codemods', () => {
const testCases: {codemod: RecastCodemod; expected: string}[] = [
{
diff --git a/packages/studio-server/src/test/recast-mods.test.ts b/packages/studio-server/src/test/recast-mods.test.ts
index 0b84deed06..1c06859c8d 100644
--- a/packages/studio-server/src/test/recast-mods.test.ts
+++ b/packages/studio-server/src/test/recast-mods.test.ts
@@ -1,5 +1,5 @@
import {expect, test} from 'bun:test';
-import {parseAndApplyCodemod} from '../codemods/duplicate-composition';
+import {parseAndApplyCodemod} from '@remotion/studio-codemods';
const compositionInRoot = `import {Composition} from 'remotion';
import {NewVideo} from './NewVideo';
diff --git a/packages/studio-server/src/test/test-utils.ts b/packages/studio-server/src/test/test-utils.ts
index 81d01cdbea..52cc8138ce 100644
--- a/packages/studio-server/src/test/test-utils.ts
+++ b/packages/studio-server/src/test/test-utils.ts
@@ -1,16 +1,26 @@
import type {Expression} from '@babel/types';
+import {format, resolveConfig, resolveConfigFile} from 'prettier';
import type {SequenceNodePath} from 'remotion';
-import {formatFileContent} from '../codemods/format-file-content';
import {parseAst} from '../codemods/parse-ast';
import {lineColumnToNodePath as _lineColumnToNodePath} from '../preview-server/routes/can-update-sequence-props';
export const prettify = async (input: string): Promise<string> => {
- const {output, formatted} = await formatFileContent({input});
- if (!formatted) {
- throw new Error('prettier could not format input');
+ const configFilePath = await resolveConfigFile();
+ if (!configFilePath) {
+ throw new Error('Prettier config could not be found');
}
- return output;
+ const prettierConfig = await resolveConfig(configFilePath);
+ if (!prettierConfig) {
+ throw new Error(`Prettier config at ${configFilePath} could not be read`);
+ }
+
+ return format(input, {
+ ...prettierConfig,
+ filepath: 'test.tsx',
+ plugins: [],
+ endOfLine: 'lf',
+ });
};
export const parseExpression = (code: string): Expression => {
diff --git a/packages/template-recorder/scripts/server/register-composition.ts b/packages/template-recorder/scripts/server/register-composition.ts
index 233824f1ca..5ed45f0a37 100644
--- a/packages/template-recorder/scripts/server/register-composition.ts
+++ b/packages/template-recorder/scripts/server/register-composition.ts
@@ -75,11 +75,7 @@ export const registerComposition = async ({
enumPaths: [],
});
- const formatted = await StudioServerInternals.formatOutput(
- withDefaultScene,
- );
-
- writeFileSync(rootPath, formatted, 'utf-8');
+ writeFileSync(rootPath, withDefaultScene, 'utf-8');
return {registered: true};
} catch (err) {
return {