Skip to content

🎥 Make videos programmatically with React

Avoid shadowed caption imports and cover binding collisions

Igor Samokhovets58982fbb4a60
diff --git a/packages/codemods/src/sequence-props/imports.ts b/packages/codemods/src/sequence-props/imports.ts
index ca37835255..d7e7778fd4 100644
--- a/packages/codemods/src/sequence-props/imports.ts
+++ b/packages/codemods/src/sequence-props/imports.ts
@@ -4,8 +4,16 @@ import type {
FunctionDeclaration,
ImportDeclaration,
ImportSpecifier,
+ Node,
VariableDeclaration,
} from '@babel/types';
+import {
+ getBindingIdentifiers,
+ isCatchClause,
+ isDeclaration,
+ isFunction,
+ isImportDeclaration,
+} from '@babel/types';
import * as recast from 'recast';
const b = recast.types.builders;
@@ -14,19 +22,7 @@ export const declarationBindsName = (
declaration: FunctionDeclaration | ClassDeclaration | VariableDeclaration,
name: string,
) => {
- if (
- declaration.type === 'FunctionDeclaration' ||
- declaration.type === 'ClassDeclaration'
- ) {
- return declaration.id?.name === name;
- }
-
- return declaration.declarations.some((variableDeclaration) => {
- return (
- variableDeclaration.id.type === 'Identifier' &&
- variableDeclaration.id.name === name
- );
- });
+ return Object.hasOwn(getBindingIdentifiers(declaration, false, true), name);
};
export const hasTopLevelBinding = ({ast, name}: {ast: File; name: string}) => {
@@ -119,6 +115,42 @@ const hasNamespaceSpecifier = (importDeclaration: ImportDeclaration) => {
);
};
+const addNamedImport = ({
+ ast,
+ importedName,
+ sourcePath,
+ localName,
+}: {
+ ast: File;
+ importedName: string;
+ sourcePath: string;
+ localName: string;
+}) => {
+ const existingImport = findImportDeclarations(ast, sourcePath).find(
+ (candidateImportDeclaration) =>
+ candidateImportDeclaration.importKind !== 'type' &&
+ !hasNamespaceSpecifier(candidateImportDeclaration),
+ );
+ const specifier = b.importSpecifier(
+ b.identifier(importedName),
+ b.identifier(localName),
+ ) as unknown as ImportSpecifier;
+
+ if (existingImport) {
+ existingImport.specifiers.push(specifier);
+ } else {
+ insertImportDeclaration(
+ ast,
+ b.importDeclaration(
+ [specifier as never],
+ b.stringLiteral(sourcePath),
+ ) as unknown as ImportDeclaration,
+ );
+ }
+
+ return localName;
+};
+
export const ensureNamedImport = ({
ast,
importedName,
@@ -149,35 +181,7 @@ export const ensureNamedImport = ({
}
}
- const existingImport = existingImports.find(
- (candidateImportDeclaration) =>
- candidateImportDeclaration.importKind !== 'type' &&
- !hasNamespaceSpecifier(candidateImportDeclaration),
- );
-
- if (existingImport) {
- const importSpecifier = b.importSpecifier(
- b.identifier(importedName),
- b.identifier(localName),
- ) as unknown as ImportSpecifier;
-
- existingImport.specifiers = [
- ...(existingImport.specifiers ?? []),
- importSpecifier,
- ];
- return localName;
- }
-
- const specifier = b.importSpecifier(
- b.identifier(importedName),
- b.identifier(localName),
- ) as unknown as ImportSpecifier;
- const importDeclaration = b.importDeclaration(
- [specifier as never],
- b.stringLiteral(sourcePath),
- ) as unknown as ImportDeclaration;
- insertImportDeclaration(ast, importDeclaration);
- return localName;
+ return addNamedImport({ast, importedName, sourcePath, localName});
};
export const ensureNamedImports = ({
@@ -281,10 +285,12 @@ const findImportedLocalName = ({
ast,
importedName,
sourcePath,
+ excludedLocalNames,
}: {
ast: File;
importedName: string;
sourcePath: string;
+ excludedLocalNames: ReadonlySet<string> | null;
}) => {
for (const declaration of getImportDeclarations({ast, sourcePath})) {
if (declaration.importKind === 'type') {
@@ -295,7 +301,8 @@ const findImportedLocalName = ({
(specifier) =>
specifier.type === 'ImportSpecifier' &&
specifier.importKind !== 'type' &&
- getImportedName(specifier) === importedName,
+ getImportedName(specifier) === importedName &&
+ !excludedLocalNames?.has(specifier.local.name),
);
if (existing) {
return existing.local?.name ?? importedName;
@@ -305,8 +312,8 @@ const findImportedLocalName = ({
return null;
};
-// Reuses an existing import of the export, otherwise imports it under the
-// preferred local name, adding a numeric suffix when that name is taken.
+// Avoid bindings throughout the file because generated JSX may be inserted
+// into any scope. Reuse imports only when their local name is not shadowed.
export const ensureOfficialNamedImport = ({
ast,
importedName,
@@ -318,18 +325,43 @@ export const ensureOfficialNamedImport = ({
sourcePath: string;
preferredLocalName: string;
}) => {
- const existing = findImportedLocalName({ast, importedName, sourcePath});
+ const boundNames = new Set<string>();
+ recast.types.visit(ast, {
+ visitNode(path) {
+ const node = path.node as Node;
+ if (
+ (isDeclaration(node) && !isImportDeclaration(node)) ||
+ isFunction(node) ||
+ isCatchClause(node)
+ ) {
+ for (const name of Object.keys(getBindingIdentifiers(node))) {
+ boundNames.add(name);
+ }
+ }
+
+ this.traverse(path);
+ },
+ });
+ const existing = findImportedLocalName({
+ ast,
+ importedName,
+ sourcePath,
+ excludedLocalNames: boundNames,
+ });
if (existing !== null) {
return existing;
}
let localName = preferredLocalName;
let suffix = 2;
- while (hasTopLevelBinding({ast, name: localName})) {
+ while (
+ boundNames.has(localName) ||
+ hasTopLevelBinding({ast, name: localName})
+ ) {
localName = `${preferredLocalName}${suffix++}`;
}
- return ensureNamedImport({ast, importedName, sourcePath, localName});
+ return addNamedImport({ast, importedName, sourcePath, localName});
};
// Serialized values are written as literal `staticFile(...)` calls, so the
@@ -340,6 +372,7 @@ export const ensureStaticFileBinding = (ast: File) => {
ast,
importedName: 'staticFile',
sourcePath: 'remotion',
+ excludedLocalNames: null,
}) === 'staticFile'
) {
return;
diff --git a/packages/codemods/src/test/insert-basic-captions.test.ts b/packages/codemods/src/test/insert-basic-captions.test.ts
index c33806fce9..ce30069ecc 100644
--- a/packages/codemods/src/test/insert-basic-captions.test.ts
+++ b/packages/codemods/src/test/insert-basic-captions.test.ts
@@ -1,7 +1,71 @@
import {expect, test} from 'bun:test';
import {insertBasicCaptions} from '../insert-basic-captions';
+import {parseAst} from '../sequence-props/parse-ast';
import {lineContainingToNodePath} from './node-path-test-utils';
+test('caption imports avoid parameters, local declarations and destructuring', () => {
+ const fixtures = [
+ {
+ declarations: '',
+ parameter: 'BasicCaptions',
+ local: '',
+ },
+ {
+ declarations: '',
+ parameter: '',
+ local: 'const BasicCaptions = () => null;',
+ },
+ {
+ declarations: 'const {BasicCaptions} = components;',
+ parameter: '',
+ local: '',
+ },
+ {
+ declarations:
+ 'const [BasicCaptions, {nested: BasicCaptions2}] = components;',
+ parameter: '',
+ local: '',
+ },
+ {
+ declarations: "import {BasicCaptions} from './basic-captions.element';",
+ parameter: 'BasicCaptions',
+ local: '',
+ },
+ ];
+ for (const element of [
+ null,
+ {componentName: 'BasicCaptions', initialProps: null},
+ ]) {
+ for (const {declarations, parameter, local} of fixtures) {
+ const input = `import {Video} from '@remotion/media';
+${declarations}
+export const Comp = (${parameter}) => {
+ ${local}
+ return <Video src="video.mp4" />;
+};`;
+ const {output} = insertBasicCaptions({
+ element,
+ input,
+ nodePath: lineContainingToNodePath(input, '<Video'),
+ captions: [],
+ durationInFrames: null,
+ premountFor: null,
+ });
+ const alias = declarations.includes('BasicCaptions2')
+ ? 'BasicCaptions3'
+ : 'BasicCaptions2';
+ expect(output).toContain(`BasicCaptions as ${alias}`);
+ expect(output).toContain(`<${alias} captions={[]}`);
+ if (!declarations.startsWith('import')) {
+ expect(output).toContain(declarations);
+ }
+
+ expect(output).toContain(`export const Comp = (${parameter}) => {`);
+ parseAst(output);
+ }
+ }
+});
+
const captions = [
{
text: 'Here',