🎥 Make videos programmatically with React
Address review: escape namespaced string props, alias staticFile imports, detect in-scope canvas wrappers
JonnyBurgerb69affaf6381
diff --git a/packages/codemods/src/build-jsx-element.ts b/packages/codemods/src/build-jsx-element.tsindex b829993e25..2f2129c637 100644--- a/packages/codemods/src/build-jsx-element.ts+++ b/packages/codemods/src/build-jsx-element.ts@@ -4,8 +4,7 @@ import * as recast from 'recast';import {NoReactInternals} from 'remotion/no-react';import type {CodemodElement} from './codemod-element';import type {CodemodValue} from './codemod-value';-import {ensureOfficialNamedImport} from './insert-jsx-element';-import {ensureNamedImports} from './sequence-props/imports';+import {ensureOfficialNamedImport} from './sequence-props/imports';import {parseValueExpression} from './update-nested-prop';const b = recast.types.builders;@@ -86,17 +85,33 @@ export const buildJsxElement = ({return b.jsxAttribute(buildAttributeName(name), b.stringLiteral(value));}+ const expression = parseValueExpression(value);if (containsFileToken(value)) {- ensureNamedImports({+ // The serializer writes `staticFile(...)`; point the calls at the+ // import's local name if that name is taken in this file.+ const staticFileLocalName = ensureOfficialNamedImport({ast,- importedNames: new Set(['staticFile']),+ importedName: 'staticFile',sourcePath: 'remotion',+ preferredLocalName: 'staticFile',});+ if (staticFileLocalName !== 'staticFile') {+ recast.types.visit(expression, {+ visitCallExpression(path) {+ const {callee} = path.node;+ if (callee.type === 'Identifier' && callee.name === 'staticFile') {+ callee.name = staticFileLocalName;+ }++ this.traverse(path);+ },+ });+ }}return b.jsxAttribute(buildAttributeName(name),- b.jsxExpressionContainer(parseValueExpression(value)),+ b.jsxExpressionContainer(expression),);});const children = element.children.map(diff --git a/packages/codemods/src/insert-jsx-element.ts b/packages/codemods/src/insert-jsx-element.tsindex 10d8335949..d0e16dce36 100644--- a/packages/codemods/src/insert-jsx-element.ts+++ b/packages/codemods/src/insert-jsx-element.ts@@ -1,10 +1,8 @@import type {- ClassDeclaration,ExportAllDeclaration,ExportNamedDeclaration,ExportSpecifier,File,- FunctionDeclaration,ImportDeclaration,ImportDefaultSpecifier,JSXAttribute,@@ -13,7 +11,6 @@ import type {JSXSpreadAttribute,NullLiteral,ObjectProperty,- VariableDeclaration,} from '@babel/types';import type {InsertJsxElementRequest,@@ -32,8 +29,12 @@ import {import {indentInsertedJsx, printInsertedJsx} from './print-jsx';import {recastLocToOffset} from './recast-loc-to-offset';import {+ declarationBindsName,ensureNamedImport,+ ensureStaticFileBinding,+ getImportDeclarations,getImportedName,+ hasTopLevelBinding,insertImportDeclaration,} from './sequence-props/imports';import {parseAst, parseAstForReadOnly} from './sequence-props/parse-ast';@@ -1139,53 +1140,6 @@ const addElementToNullComponentReturn = ({return returnStatement.loc?.start.line ?? 1;};-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- );- });-};--const hasTopLevelBinding = ({ast, name}: {ast: File; name: string}) => {- return ast.program.body.some((node) => {- if (- node.type === 'FunctionDeclaration' ||- node.type === 'ClassDeclaration' ||- node.type === 'VariableDeclaration'- ) {- return declarationBindsName(node, name);- }-- if (- node.type === 'ExportNamedDeclaration' &&- node.declaration &&- (node.declaration.type === 'FunctionDeclaration' ||- node.declaration.type === 'ClassDeclaration' ||- node.declaration.type === 'VariableDeclaration')- ) {- return declarationBindsName(node.declaration, name);- }-- if (node.type !== 'ImportDeclaration') {- return false;- }-- return node.specifiers?.some((specifier) => specifier.local?.name === name);- });-};-const getAvailableSequenceLocalName = (ast: File) => {const candidates = ['Sequence', 'RemotionSequence'];const available = candidates.find((candidate) => {@@ -1248,68 +1202,6 @@ const ensureInteractiveImport = (ast: File) => {});};-const getImportDeclarations = ({- ast,- sourcePath,-}: {- ast: File;- sourcePath: string;-}) => {- return ast.program.body.filter(- (node): node is ImportDeclaration =>- node.type === 'ImportDeclaration' &&- node.source.type === 'StringLiteral' &&- node.source.value === sourcePath,- );-};--// Reuses an existing import of the export, otherwise imports it under the-// preferred local name, adding a numeric suffix when that name is taken.-export const ensureOfficialNamedImport = ({- ast,- importedName,- sourcePath,- preferredLocalName,-}: {- ast: File;- importedName: string;- sourcePath: string;- preferredLocalName: string;-}) => {- for (const declaration of getImportDeclarations({ast, sourcePath})) {- if (declaration.importKind === 'type') {- continue;- }-- const existing = declaration.specifiers.find(- (specifier) =>- specifier.type === 'ImportSpecifier' &&- specifier.importKind !== 'type' &&- getImportedName(specifier) === importedName,- );- if (existing) {- return existing.local?.name ?? importedName;- }- }-- let localName = preferredLocalName;- let suffix = 2;- while (hasTopLevelBinding({ast, name: localName})) {- localName = `${preferredLocalName}${suffix++}`;- }-- return ensureNamedImport({ast, importedName, sourcePath, localName});-};--const ensureStaticFileImport = (ast: File) => {- return ensureOfficialNamedImport({- ast,- importedName: 'staticFile',- sourcePath: 'remotion',- preferredLocalName: 'staticFile',- });-};-const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;const toPascalCaseIdentifier = (value: string) => {@@ -2225,7 +2117,7 @@ const createInsertableJsxElement = ({element.serializedResolvedPropsWithCustomSchema,);if (containsFileToken(props)) {- ensureStaticFileImport(ast);+ ensureStaticFileBinding(ast);}return createCompositionComponentElement({localName, props});diff --git a/packages/codemods/src/print-jsx.ts b/packages/codemods/src/print-jsx.tsindex 5fe5f84df5..c8f011b644 100644--- a/packages/codemods/src/print-jsx.ts+++ b/packages/codemods/src/print-jsx.ts@@ -241,12 +241,13 @@ export const printInsertedJsx = ({.join(endOfLine);}+ // String attributes need JSX entity escaping, which the generic+ // printer does not apply. This covers `xlink:href` style names too.if (attribute.type === 'JSXAttribute' &&- attribute.name.type === 'JSXIdentifier' &&attribute.value?.type === 'StringLiteral') {- return `${attribute.name.name}="${escapeJsxStringAttribute(attribute.value.value)}"`;+ return `${printNode(attribute.name, printWidth)}="${escapeJsxStringAttribute(attribute.value.value)}"`;}const printed = normalizeIndentation(diff --git a/packages/codemods/src/sequence-props/imports.ts b/packages/codemods/src/sequence-props/imports.tsindex a539646ea9..ca37835255 100644--- a/packages/codemods/src/sequence-props/imports.ts+++ b/packages/codemods/src/sequence-props/imports.ts@@ -1,8 +1,62 @@-import type {File, ImportDeclaration, ImportSpecifier} from '@babel/types';+import type {+ ClassDeclaration,+ File,+ FunctionDeclaration,+ ImportDeclaration,+ ImportSpecifier,+ VariableDeclaration,+} from '@babel/types';import * as recast from 'recast';const b = recast.types.builders;+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+ );+ });+};++export const hasTopLevelBinding = ({ast, name}: {ast: File; name: string}) => {+ return ast.program.body.some((node) => {+ if (+ node.type === 'FunctionDeclaration' ||+ node.type === 'ClassDeclaration' ||+ node.type === 'VariableDeclaration'+ ) {+ return declarationBindsName(node, name);+ }++ if (+ node.type === 'ExportNamedDeclaration' &&+ node.declaration &&+ (node.declaration.type === 'FunctionDeclaration' ||+ node.declaration.type === 'ClassDeclaration' ||+ node.declaration.type === 'VariableDeclaration')+ ) {+ return declarationBindsName(node.declaration, name);+ }++ if (node.type !== 'ImportDeclaration') {+ return false;+ }++ return node.specifiers?.some((specifier) => specifier.local?.name === name);+ });+};+export const getImportedName = (specifier: ImportSpecifier) => {if (specifier.imported.type === 'Identifier') {return specifier.imported.name;@@ -207,3 +261,99 @@ export const ensureNamedImports = ({) as unknown as ImportDeclaration;insertImportDeclaration(ast, importDeclaration);};++export const getImportDeclarations = ({+ ast,+ sourcePath,+}: {+ ast: File;+ sourcePath: string;+}) => {+ return ast.program.body.filter(+ (node): node is ImportDeclaration =>+ node.type === 'ImportDeclaration' &&+ node.source.type === 'StringLiteral' &&+ node.source.value === sourcePath,+ );+};++const findImportedLocalName = ({+ ast,+ importedName,+ sourcePath,+}: {+ ast: File;+ importedName: string;+ sourcePath: string;+}) => {+ for (const declaration of getImportDeclarations({ast, sourcePath})) {+ if (declaration.importKind === 'type') {+ continue;+ }++ const existing = declaration.specifiers.find(+ (specifier) =>+ specifier.type === 'ImportSpecifier' &&+ specifier.importKind !== 'type' &&+ getImportedName(specifier) === importedName,+ );+ if (existing) {+ return existing.local?.name ?? importedName;+ }+ }++ 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.+export const ensureOfficialNamedImport = ({+ ast,+ importedName,+ sourcePath,+ preferredLocalName,+}: {+ ast: File;+ importedName: string;+ sourcePath: string;+ preferredLocalName: string;+}) => {+ const existing = findImportedLocalName({ast, importedName, sourcePath});+ if (existing !== null) {+ return existing;+ }++ let localName = preferredLocalName;+ let suffix = 2;+ while (hasTopLevelBinding({ast, name: localName})) {+ localName = `${preferredLocalName}${suffix++}`;+ }++ return ensureNamedImport({ast, importedName, sourcePath, localName});+};++// Serialized values are written as literal `staticFile(...)` calls, so the+// binding must be named exactly `staticFile`.+export const ensureStaticFileBinding = (ast: File) => {+ if (+ findImportedLocalName({+ ast,+ importedName: 'staticFile',+ sourcePath: 'remotion',+ }) === 'staticFile'+ ) {+ return;+ }++ if (hasTopLevelBinding({ast, name: 'staticFile'})) {+ throw new Error(+ 'Cannot write staticFile() because "staticFile" is already bound to something else in this file',+ );+ }++ ensureNamedImports({+ ast,+ importedNames: new Set(['staticFile']),+ sourcePath: 'remotion',+ });+};diff --git a/packages/codemods/src/test/public-editing.test.ts b/packages/codemods/src/test/public-editing.test.tsindex 8e18c14ede..13e5a23524 100644--- a/packages/codemods/src/test/public-editing.test.ts+++ b/packages/codemods/src/test/public-editing.test.ts@@ -685,6 +685,47 @@ test('addElement returns remappings usable by public discovery and targets nodeswrapper: createElement({component: 'div', children: ['x']}),}),).toThrow('cannot have children');+ // Canvas wrappers are validated even when they reuse an existing import.+ expect(() =>+ wrapJsxNode({+ project: afterBefore,+ node: div,+ wrapper: createElement({+ component: 'HtmlInCanvas',+ props: {width: 0, height: 0},+ }),+ }),+ ).toThrow('positive integer dimensions');+ const conflicting = {+ rootDir: '/',+ files: {+ 'svg.tsx': `import {staticFile} from './util';\nexport const Icon = () => <svg />;\n`,+ },+ };+ const escaped = addElement({+ project: conflicting,+ element: createElement({+ component: 'use',+ props: {'xlink:href': 'a"b&<c>', href: staticFileValue('x.png')},+ }),+ target: {+ type: 'inside',+ node: getJsxNodes({project: conflicting, filePath: 'svg.tsx'})[0],+ },+ });+ expect(getChangedContents(escaped, 'svg.tsx')).toContain(+ `<use xlink:href="a"b&amp;<c>" href={staticFile2('x.png')} />`,+ );+ expect(getChangedContents(escaped, 'svg.tsx')).toContain(+ "import {staticFile as staticFile2} from 'remotion';",+ );+ expect(() =>+ updateJsxNodeProps({+ project: conflicting,+ node: getJsxNodes({project: conflicting, filePath: 'svg.tsx'})[0],+ props: {href: staticFileValue('x.png')},+ }),+ ).toThrow('already bound');expect(() =>createElement({component: 'div', importPath: 'remotion'}),).toThrow('uppercase');diff --git a/packages/codemods/src/update-sequence-props.ts b/packages/codemods/src/update-sequence-props.tsindex 4192197a95..c4dc253626 100644--- a/packages/codemods/src/update-sequence-props.ts+++ b/packages/codemods/src/update-sequence-props.ts@@ -52,7 +52,7 @@ import {getCssShorthandsForUpdates,type CssShorthandProperty,} from './sequence-props/css-shorthand-properties';-import {ensureNamedImports} from './sequence-props/imports';+import {ensureStaticFileBinding} from './sequence-props/imports';import {parseAst, serializeAst} from './sequence-props/parse-ast';import {parseVideoConfigNumericExpression,@@ -106,11 +106,7 @@ const ensureImportsForUpdates = ({JSON.stringify(value) !== JSON.stringify(defaultValue)),)) {- ensureNamedImports({- ast,- importedNames: new Set(['staticFile']),- sourcePath: 'remotion',- });+ ensureStaticFileBinding(ast);}};diff --git a/packages/codemods/src/wrap-jsx-node.ts b/packages/codemods/src/wrap-jsx-node.tsindex e7553b1ae3..d81fb481db 100644--- a/packages/codemods/src/wrap-jsx-node.ts+++ b/packages/codemods/src/wrap-jsx-node.ts@@ -29,17 +29,21 @@ export type WrapJsxNodeOptions<Project extends CodemodProject> = {wrapper: CodemodElement;};+// Recognizes canvas wrappers whether they are imported by the wrapper or+// already in scope in the file (no importPath).const getHtmlInCanvasWrapperName = (wrapper: CodemodElement) => {+ const exportName = wrapper.importName ?? wrapper.component;if (- wrapper.importPath === 'remotion' &&- wrapper.component === 'HtmlInCanvas'+ exportName === 'HtmlInCanvas' &&+ (wrapper.importPath === null || wrapper.importPath === 'remotion')) {return 'HtmlInCanvas';}if (- wrapper.importPath === '@remotion/motion-blur' &&- wrapper.component === 'HtmlInCanvasMotionBlur'+ exportName === 'HtmlInCanvasMotionBlur' &&+ (wrapper.importPath === null ||+ wrapper.importPath === '@remotion/motion-blur')) {return 'HtmlInCanvasMotionBlur';}diff --git a/packages/docs/docs/codemods/wrap-jsx-node.mdx b/packages/docs/docs/codemods/wrap-jsx-node.mdxindex 625445599f..80a7d24076 100644--- a/packages/docs/docs/codemods/wrap-jsx-node.mdx+++ b/packages/docs/docs/codemods/wrap-jsx-node.mdx@@ -49,7 +49,7 @@ The reference of the JSX element to wrap. See [node references](/docs/codemods#n### wrapper-The wrapper element, created with [`createElement()`](/docs/codemods/create-element). It must not have children. Wrapping in [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) requires positive integer `width` and `height` props and is rejected inside or around another `<HtmlInCanvas>`.+The wrapper element, created with [`createElement()`](/docs/codemods/create-element). It must not have children. Wrapping in [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) or [`<HtmlInCanvasMotionBlur>`](/docs/motion-blur/html-in-canvas-motion-blur) requires positive integer `width` and `height` props and is rejected inside or around another canvas wrapper, whether the wrapper is imported by the element or already in scope.## Return value