🎥 Make videos programmatically with React
remotion.dev/experimental_new: Support dragging in elements (#10524)
Jonny Burgerc05c3141a519
diff --git a/bun.lock b/bun.lockindex 9e611c06a4..a7a94d8188 100644--- a/bun.lock+++ b/bun.lock@@ -139,9 +139,11 @@"version": "4.0.513","dependencies": {"@remotion/studio-codemods": "workspace:*",+ "@remotion/studio-protocol": "workspace:*","@remotion/studio-shared": "workspace:*","@rspack/browser": "2.1.1","fflate": "0.8.2",+ "prettier": "catalog:","react-refresh": "0.18.0","remotion": "workspace:*",},diff --git a/packages/browser-studio/e2e/app.tsx b/packages/browser-studio/e2e/app.tsxindex d0bab2e983..16cf8d4563 100644--- a/packages/browser-studio/e2e/app.tsx+++ b/packages/browser-studio/e2e/app.tsx@@ -1,10 +1,21 @@import {BrowserStudio,createBlankTemplateProject,+ type VirtualProject,} from '@remotion/browser-studio';import {createRoot} from 'react-dom/client';+import {VERSION} from 'remotion/version';const project = createBlankTemplateProject();+(+ window as typeof window & {+ __browserStudioProject: VirtualProject;+ __browserStudioRemotionVersion: string;+ }+).__browserStudioProject = project;+(+ window as typeof window & {__browserStudioRemotionVersion: string}+).__browserStudioRemotionVersion = VERSION;project.files['/project/src/index.ts'] =`import {fade} from '@remotion/transitions/fade';import {registerRoot} from 'remotion';@@ -24,6 +35,11 @@ createRoot(root).render(iframeSrc="/frame.html"project={project}readOnly={false}+ onProjectChange={(nextProject) => {+ (+ window as typeof window & {__browserStudioProject: VirtualProject}+ ).__browserStudioProject = nextProject;+ }}workspacePackageBaseUrl={new URL('/__remotion_browser_studio_workspace__/', window.location.href).hrefdiff --git a/packages/browser-studio/e2e/browser-studio.test.ts b/packages/browser-studio/e2e/browser-studio.test.tsindex 117d1be9a2..4fd05e5003 100644--- a/packages/browser-studio/e2e/browser-studio.test.ts+++ b/packages/browser-studio/e2e/browser-studio.test.ts@@ -78,6 +78,164 @@ test('loads the Browser Studio canvas and enables Visual Mode', async ({expect(updateAvailableRequests).toEqual([]);});+test('drops and imports an Element payload with the deployment Remotion version', async ({+ page,+}) => {+ await page.goto('/');+ const studio = page.frameLocator('iframe');+ await expect(studio.getByTitle('/project').getByText('MyComp')).toBeVisible();+ await studio.locator('[data-compname="MyComp"]').click();+ const canvas = studio.locator('.remotion-studio-composition-container');+ await expect(canvas).toBeVisible();+ const box = await canvas.boundingBox();+ if (box === null) {+ throw new Error('Browser Studio canvas has no bounding box');+ }++ const dataTransfer = await canvas.evaluateHandle(() => new DataTransfer());+ await dataTransfer.evaluate((transfer) => {+ const payload = JSON.stringify({+ type: 'remotion-element',+ version: 1,+ element: {+ dependencies: [{name: '@remotion/shapes', version: null}],+ dimensions: {width: 320, height: 180},+ displayName: 'Browser Element',+ durationInFrames: 60,+ installationMode: 'wrapped',+ slug: 'browser-element',+ sourceCode: `import {Rect} from '@remotion/shapes';++export const BrowserElement = () => <Rect width={320} height={180} fill="red" />;+`,+ },+ });+ transfer.effectAllowed = 'copy';+ transfer.setData(+ 'application/vnd.remotion.drag+json;v=1;type=element;width=320;height=180;duration=60',+ payload,+ );+ transfer.setData('text/plain', payload);+ });+ const coordinates = {+ clientX: box.x + box.width / 2,+ clientY: box.y + box.height / 2,+ dataTransfer,+ };+ await canvas.dispatchEvent('dragover', coordinates);+ await canvas.dispatchEvent('drop', coordinates);++ await expect(+ studio.getByText('Install Element', {exact: true}),+ ).toBeVisible();+ await expect(+ studio.getByText('Unverified drag-and-drop payload'),+ ).toBeVisible();+ await expect(+ studio.getByText(+ 'Dependencies are resolved in the browser; package lifecycle scripts do not run.',+ ),+ ).toHaveCount(0);+ await studio.getByRole('button', {name: /^Install/}).click();++ await expect+ .poll(() =>+ page.evaluate(() => {+ const browserWindow = window as typeof window & {+ __browserStudioProject: {files: Record<string, string>};+ __browserStudioRemotionVersion: string;+ };+ const packageJson = JSON.parse(+ browserWindow.__browserStudioProject.files['/project/package.json'],+ ) as {dependencies: Record<string, string>};+ return {+ composition:+ browserWindow.__browserStudioProject.files[+ '/project/src/Composition.tsx'+ ],+ element:+ browserWindow.__browserStudioProject.files[+ '/project/src/browser-element.element.tsx'+ ],+ installedVersion: packageJson.dependencies['@remotion/shapes'],+ remotionVersion: browserWindow.__browserStudioRemotionVersion,+ };+ }),+ )+ .toMatchObject({+ composition: expect.stringContaining('<BrowserElement />'),+ element: expect.stringContaining('export const BrowserElement'),+ installedVersion: expect.any(String),+ });+ const versions = await page.evaluate(() => {+ const browserWindow = window as typeof window & {+ __browserStudioProject: {files: Record<string, string>};+ __browserStudioRemotionVersion: string;+ };+ const packageJson = JSON.parse(+ browserWindow.__browserStudioProject.files['/project/package.json'],+ ) as {dependencies: Record<string, string>};+ return {+ installed: packageJson.dependencies['@remotion/shapes'],+ remotion: browserWindow.__browserStudioRemotionVersion,+ };+ });+ expect(versions.installed).toBe(versions.remotion);+ await expect(studio.getByText('Browser Element')).toBeVisible();+});++test('reports inline SVG imports as unsupported without changing the project', async ({+ page,+}) => {+ await page.goto('/');+ const studio = page.frameLocator('iframe');+ await expect(studio.getByTitle('/project').getByText('MyComp')).toBeVisible();+ await studio.locator('[data-compname="MyComp"]').click();+ const canvas = studio.locator('.remotion-studio-composition-container');+ await expect(canvas).toBeVisible();+ const compositionBefore = await page.evaluate(() => {+ const browserWindow = window as typeof window & {+ __browserStudioProject: {files: Record<string, string>};+ };+ return browserWindow.__browserStudioProject.files[+ '/project/src/Composition.tsx'+ ];+ });++ const dataTransfer = await canvas.evaluateHandle(() => {+ const transfer = new DataTransfer();+ transfer.items.add(+ new File(+ ['<svg viewBox="0 0 10 10"><circle r="4" /></svg>'],+ 'shape.svg',+ {+ type: 'image/svg+xml',+ },+ ),+ );+ return transfer;+ });+ await canvas.dispatchEvent('dragover', {dataTransfer});+ await canvas.dispatchEvent('drop', {dataTransfer});+ await studio.getByRole('button', {name: /Import as inline/}).click();++ await expect(+ studio.getByText(+ 'Importing SVG markup is not supported in Browser Studio',+ {exact: true},+ ),+ ).toBeVisible();+ const compositionAfter = await page.evaluate(() => {+ const browserWindow = window as typeof window & {+ __browserStudioProject: {files: Record<string, string>};+ };+ return browserWindow.__browserStudioProject.files[+ '/project/src/Composition.tsx'+ ];+ });+ expect(compositionAfter).toBe(compositionBefore);+});+test('clears hover backgrounds even if pointer leave events are lost', async ({page,}) => {diff --git a/packages/browser-studio/package.json b/packages/browser-studio/package.jsonindex 392bf9bfdb..35da54f78a 100644--- a/packages/browser-studio/package.json+++ b/packages/browser-studio/package.json@@ -28,9 +28,11 @@},"dependencies": {"@remotion/studio-codemods": "workspace:*",+ "@remotion/studio-protocol": "workspace:*","@remotion/studio-shared": "workspace:*","@rspack/browser": "2.1.1","fflate": "0.8.2",+ "prettier": "catalog:","react-refresh": "0.18.0","remotion": "workspace:*"},diff --git a/packages/browser-studio/src/BrowserStudio.tsx b/packages/browser-studio/src/BrowserStudio.tsxindex 531dcc6c14..fd68d422b6 100644--- a/packages/browser-studio/src/BrowserStudio.tsx+++ b/packages/browser-studio/src/BrowserStudio.tsx@@ -13,6 +13,7 @@ import {import {browserStudioDependencyVersions} from './dependency-versions';import {Spinner} from './Spinner';import type {+ BrowserStudioDependencyResolution,BrowserStudioProps,BrowserStudioWorkerCompileRequest,BrowserStudioWorkerCompileResponse,@@ -139,6 +140,8 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({const [state, setState] = useState<CompileState>(makeInitialState);const [iframeHtml, setIframeHtml] = useState<string | null>(null);const [iframeLoaded, setIframeLoaded] = useState(false);+ const [installedDependencyResolutions, setInstalledDependencyResolutions] =+ useState<Record<string, BrowserStudioDependencyResolution>>({});const iframeRef = useRef<HTMLIFrameElement | null>(null);const lastWrittenDocumentRef = useRef<Document | null>(null);const lastWrittenHtmlRef = useRef<string | null>(null);@@ -147,6 +150,8 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({const bundleUrlRef = useRef<string | null>(null);const onCompileStateChangeRef = useRef(onCompileStateChange);onCompileStateChangeRef.current = onCompileStateChange;+ const dependencyResolverRef = useRef(dependencyResolver);+ dependencyResolverRef.current = dependencyResolver;const publicFileManager = useMemo(() =>createBrowserStudioPublicFileManager({@@ -200,6 +205,58 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({},[],);+ const resolveElementDependencies = useCallback(+ (dependencies: readonly {name: string; version: string | null}[]) => {+ const remotionVersion = browserStudioDependencyVersions.remotion;+ if (!remotionVersion) {+ throw new Error('Browser Studio Remotion version is unavailable');+ }++ const versions: Record<string, string> = {};+ const resolutions: Record<string, BrowserStudioDependencyResolution> = {};+ for (const dependency of dependencies) {+ const requestedVersion = dependency.name.startsWith('@remotion/')+ ? remotionVersion+ : dependency.version;+ const customResolution = dependencyResolverRef.current?.({+ name: dependency.name,+ version: requestedVersion,+ });+ const customVersion =+ typeof customResolution === 'string' &&+ !customResolution.startsWith('http')+ ? customResolution+ : typeof customResolution === 'object'+ ? (customResolution?.version ?? null)+ : null;+ const version = dependency.name.startsWith('@remotion/')+ ? remotionVersion+ : (customVersion ?? requestedVersion);+ if (version === null) {+ throw new Error(`Could not resolve ${dependency.name}`);+ }++ versions[dependency.name] = version;+ resolutions[dependency.name] = dependency.name.startsWith('@remotion/')+ ? typeof customResolution === 'string' &&+ customResolution.startsWith('http')+ ? customResolution+ : typeof customResolution === 'object' && customResolution?.url+ ? {url: customResolution.url}+ : version+ : (customResolution ?? version);+ }++ setInstalledDependencyResolutions((current) => {+ const next = {...current, ...resolutions};+ return JSON.stringify(current) === JSON.stringify(next)+ ? current+ : next;+ });+ return Promise.resolve(versions);+ },+ [],+ );const browserStudioOperations = useMemo(() =>@@ -208,8 +265,9 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({getStaticFiles: publicFileManager.getStaticFiles,getProject: () => activeProjectRef.current,onProjectChange: updateProject,+ resolveDependencies: resolveElementDependencies,}),- [publicFileManager, updateProject],+ [publicFileManager, resolveElementDependencies, updateProject],);const previousIncomingProject = useRef(project);const incomingProjectAcknowledgesEdit =@@ -358,22 +416,25 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({const request: BrowserStudioWorkerCompileRequest = {type: 'init',- dependencyResolutions: Object.fromEntries(- Object.entries(browserStudioDependencyVersions).map(- ([name, version]) => {- const customResolution = dependencyResolver?.({name, version});- if (customResolution) {- return [name, customResolution];- }-- if (name === '@remotion/studio') {- return [name, {url: localStudioPreviewEntry}];- }-- return [name, null];- },+ dependencyResolutions: {+ ...Object.fromEntries(+ Object.entries(browserStudioDependencyVersions).map(+ ([name, version]) => {+ const customResolution = dependencyResolver?.({name, version});+ if (customResolution) {+ return [name, customResolution];+ }++ if (name === '@remotion/studio') {+ return [name, {url: localStudioPreviewEntry}];+ }++ return [name, null];+ },+ ),),- ),+ ...installedDependencyResolutions,+ },project: activeProjectRef.current,workspacePackageBaseUrl: workspacePackageBaseUrl ?? null,};@@ -390,6 +451,7 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({browserStudioOperations,dependencyResolver,hmrAssetManager,+ installedDependencyResolutions,publicFileManager,readOnly,workspacePackageBaseUrl,diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex e8978e58a1..578e26d531 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -5,23 +5,51 @@ import {getCanUpdateDefaultPropsForProject,getCompositionComponentInfo,getCompositionFile,- insertSolidIntoProjectWithNodePathRemappings,+ insertJsxElementIntoProjectWithNodePathRemappings,JsxElementIdentityMismatchError,JsxElementNotFoundAtLocationError,+ makeInMemoryInsertJsxElementCodemodEnvironment,+ resolveCompositionComponentWithFile,} from '@remotion/studio-codemods';-import type {- BrowserStudioOperations,- EventSourceEvent,- InsertJsxElementResponse,- SubscribeToSequencePropsRequest,- SubscribeToSequencePropsResponse,- UnsubscribeFromSequencePropsRequest,+import {StudioProtocolInternals} from '@remotion/studio-protocol';+import {+ getRequiredPackageForInsertableElement,+ type BrowserStudioOperations,+ type ElementInstallExpectedFileState,+ type EventSourceEvent,+ type InsertElementResponse,+ type SubscribeToSequencePropsRequest,+ type SubscribeToSequencePropsResponse,+ type UnsubscribeFromSequencePropsRequest,} from '@remotion/studio-shared';+import * as prettierPluginEstree from 'prettier/plugins/estree';+import * as prettierPluginTypescript from 'prettier/plugins/typescript';+import {format} from 'prettier/standalone';import {createBrowserStudioProjectController} from './browser-studio-project-controller';import {makeBrowserStudioProjectArchive} from './download-project';import {saveSequencePropsInProject} from './save-sequence-props';import type {VirtualProject} from './types';+/*+ * SVG conversion uses SVGR in desktop Studio. SVGR depends on Node APIs, so+ * Browser Studio deliberately reports the unsupported operation instead.+ */+const svgMarkupToJsx = (): Promise<never> =>+ Promise.reject(+ new Error('Importing SVG markup is not supported in Browser Studio'),+ );++const formatCodemodFile = async ({contents}: {contents: string}) => ({+ formatted: true,+ output: await format(contents, {+ bracketSpacing: false,+ parser: 'typescript',+ plugins: [prettierPluginTypescript, prettierPluginEstree],+ singleQuote: true,+ useTabs: true,+ }),+});+export {insertSolidIntoProject,insertSolidIntoProjectWithNodePathRemappings,@@ -44,6 +72,10 @@ type SequencePropsSubscription = {effectChain: string;};+type ResolveElementDependencies = (+ dependencies: readonly {name: string; version: string | null}[],+) => Promise<Record<string, string>>;+const getEffectChain = (result: SuccessfulSequencePropsSubscription) =>result.status.effects.map((effect) => (effect.canUpdate ? effect.callee : false))@@ -66,11 +98,142 @@ const makeSequencePropsSubscriptionKey = ({effectKeys,});+const normalizeElementSource = (source: string) =>+ source.replace(/\r\n/g, '\n').trim();++const getElementSourceHash = async (source: string) => {+ const hash = await crypto.subtle.digest(+ 'SHA-256',+ new TextEncoder().encode(source),+ );+ return Array.from(new Uint8Array(hash), (byte) =>+ byte.toString(16).padStart(2, '0'),+ ).join('');+};++const dirname = (filePath: string) => {+ const slash = filePath.replaceAll('\\', '/').lastIndexOf('/');+ return slash === -1 ? '' : filePath.slice(0, slash);+};++const relativeToRoot = (filePath: string, rootDir: string) => {+ const root = rootDir.replace(/\/$/, '');+ return filePath.startsWith(`${root}/`)+ ? filePath.slice(root.length + 1)+ : filePath.replace(/^\//, '');+};++const getElementInstallPlanForProject = async ({+ compositionFile,+ compositionId,+ element,+ project,+}: Parameters<BrowserStudioOperations['prepareElementInstall']>[0] & {+ project: VirtualProject;+}) => {+ const componentName =+ StudioProtocolInternals.getElementComponentNameFromSourceCode(+ element.sourceCode,+ );+ const elementFileName = StudioProtocolInternals.makeElementFileNameFromSlug(+ element.slug,+ );+ if (componentName === null || elementFileName === null) {+ throw new Error('Invalid Element source');+ }++ const target = await resolveCompositionComponentWithFile({+ compositionFile,+ compositionId,+ environment: makeInMemoryInsertJsxElementCodemodEnvironment({+ formatFile: formatCodemodFile,+ project,+ svgMarkupToJsx,+ }),+ });+ const elementFilePath = `${dirname(target.fileName)}/${elementFileName}`;+ if (elementFilePath === target.fileName) {+ throw new Error('Element source file conflicts with the composition file');+ }++ const existingSource = project.files[elementFilePath] ?? null;+ const expectedFileState: ElementInstallExpectedFileState =+ existingSource === null+ ? {exists: false}+ : {+ exists: true,+ sourceHash: await getElementSourceHash(existingSource),+ };++ return {+ componentName,+ elementFilePath,+ existingSource,+ expectedFileState,+ filePath: relativeToRoot(elementFilePath, project.rootDir),+ importPath: `./${elementFileName.replace(/\.tsx$/, '')}`,+ };+};++const expectedFileStateMatches = ({+ actual,+ expected,+}: {+ actual: ElementInstallExpectedFileState;+ expected: ElementInstallExpectedFileState;+}) => {+ if (actual.exists !== expected.exists) {+ return false;+ }++ return (+ !actual.exists ||+ (expected.exists && actual.sourceHash === expected.sourceHash)+ );+};++const addDependenciesToProject = ({+ dependencies,+ project,+}: {+ dependencies: Record<string, string>;+ project: VirtualProject;+}): VirtualProject => {+ if (Object.keys(dependencies).length === 0) {+ return project;+ }++ const root = project.rootDir.replace(/\/$/, '');+ const packageJsonPath =+ Object.keys(project.files).find(+ (file) => file.replaceAll('\\', '/') === `${root}/package.json`,+ ) ?? `${root}/package.json`;+ const existing = project.files[packageJsonPath];+ const parsed = existing+ ? (JSON.parse(existing) as Record<string, unknown>)+ : {name: 'remotion-browser-studio-project', private: true};+ const currentDependencies =+ typeof parsed.dependencies === 'object' && parsed.dependencies !== null+ ? (parsed.dependencies as Record<string, string>)+ : {};+ parsed.dependencies = {...currentDependencies, ...dependencies};+ const indentation = existing?.match(/\n([ \t]+)"/)?.[1] ?? ' ';++ return {+ ...project,+ files: {+ ...project.files,+ [packageJsonPath]: `${JSON.stringify(parsed, null, indentation)}\n`,+ },+ };+};+export const createBrowserStudioOperations = ({dependencyVersions,getStaticFiles,getProject,onProjectChange,+ resolveDependencies,}: {dependencyVersions: Record<string, string>;getStaticFiles: Parameters<@@ -78,6 +241,7 @@ export const createBrowserStudioOperations = ({>[0]['getStaticFiles'];getProject: () => VirtualProject;onProjectChange: (project: VirtualProject) => void;+ resolveDependencies: ResolveElementDependencies | null;}): BrowserStudioOperationsController => {const defaultPropsSubscriptions = new Map<string, Set<string>>();const lastDefaultPropsResults = new Map<string, string>();@@ -197,6 +361,96 @@ export const createBrowserStudioOperations = ({}};+ const resolveElementDependencies = async (+ dependencies: readonly {name: string; version: string | null}[],+ ) => {+ const resolved =+ resolveDependencies !== null+ ? await resolveDependencies(dependencies)+ : {};+ const remotionVersion = dependencyVersions.remotion;++ for (const dependency of dependencies) {+ if (dependency.name.startsWith('@remotion/')) {+ if (!remotionVersion) {+ throw new Error(+ `Cannot resolve ${dependency.name} because the Browser Studio Remotion version is unavailable`,+ );+ }++ resolved[dependency.name] = remotionVersion;+ continue;+ }++ if (dependency.version === null) {+ throw new Error(`Could not resolve ${dependency.name}`);+ }++ resolved[dependency.name] ??= dependency.version;+ }++ return resolved;+ };++ const insertJsxElement: BrowserStudioOperations['insertJsxElement'] = async (+ request,+ ) => {+ try {+ const requiredPackage = getRequiredPackageForInsertableElement(+ request.element,+ );+ const installedDependencies =+ requiredPackage === null+ ? {}+ : await resolveElementDependencies([+ {name: requiredPackage, version: null},+ ]);+ const project = addDependenciesToProject({+ dependencies: installedDependencies,+ project: getProject(),+ });+ const result = await insertJsxElementIntoProjectWithNodePathRemappings({+ formatFile: formatCodemodFile,+ project,+ request,+ svgMarkupToJsx,+ wrapInSequence: null,+ });+ const nodePathMutation = controller.applyMutation({+ fileName: result.filePath,+ mutate: () => result.project,+ nodePathMutationFiles: [+ {+ absolutePath: result.filePath,+ remappings: result.nodePathRemappings,+ restoredNodePaths: [],+ },+ ],+ });+ if (nodePathMutation === null) {+ throw new Error('Could not insert JSX element');+ }++ return {+ success: true,+ insertedNodePath:+ result.insertedNodePath === null+ ? null+ : {+ absolutePath: result.filePath,+ nodePath: result.insertedNodePath,+ },+ nodePathMutation,+ };+ } catch (error) {+ return {+ success: false,+ reason: error instanceof Error ? error.message : String(error),+ stack: error instanceof Error && error.stack ? error.stack : '',+ };+ }+ };+return {deleteStaticFile: controller.deleteStaticFile,downloadProject: () =>@@ -215,38 +469,161 @@ export const createBrowserStudioOperations = ({Promise.resolve(getCompositionComponentInfo({project: getProject(), request}),),- insertSolid: (request) => {+ insertElement: async (request) => {try {- const result = insertSolidIntoProjectWithNodePathRemappings({- project: getProject(),- request,+ const project = getProject();+ const plan = await getElementInstallPlanForProject({+ compositionFile: request.compositionFile,+ compositionId: request.compositionId,+ element: request.element,+ project,+ });+ if (+ request.expectedFileState !== null &&+ !expectedFileStateMatches({+ actual: plan.expectedFileState,+ expected: request.expectedFileState,+ })+ ) {+ if (plan.existingSource !== null) {+ return {+ success: false,+ type: 'file-conflict',+ conflict: {+ existingSource: plan.existingSource,+ filePath: plan.filePath,+ incomingSource: request.element.sourceCode,+ },+ };+ }++ throw new Error('Element source changed during installation');+ }++ const sourcesDiffer =+ plan.existingSource !== null &&+ normalizeElementSource(plan.existingSource) !==+ normalizeElementSource(request.element.sourceCode);+ if (+ sourcesDiffer &&+ !request.overwriteExisting &&+ plan.existingSource !== null+ ) {+ return {+ success: false,+ type: 'file-conflict',+ conflict: {+ existingSource: plan.existingSource,+ filePath: plan.filePath,+ incomingSource: request.element.sourceCode,+ },+ };+ }++ const installedDependencies = await resolveElementDependencies(+ request.element.dependencies,+ );+ const installationMode = request.element.installationMode ?? 'wrapped';+ const componentOwnsSequence =+ installationMode === 'component-owned-sequence';+ const durationInFrames = request.element.durationInFrames ?? null;+ const insertion =+ await insertJsxElementIntoProjectWithNodePathRemappings({+ formatFile: formatCodemodFile,+ project,+ request: {+ compositionFile: request.compositionFile,+ compositionId: request.compositionId,+ element: {+ componentName: plan.componentName,+ importName: plan.componentName,+ importPath: plan.importPath,+ position: componentOwnsSequence ? request.position : null,+ props: componentOwnsSequence+ ? [+ ...(durationInFrames === null+ ? []+ : [+ {+ name: 'durationInFrames',+ value: durationInFrames,+ },+ ]),+ {name: 'name', value: request.element.displayName},+ ]+ : [],+ type: 'component',+ },+ from: componentOwnsSequence ? request.from : null,+ },+ svgMarkupToJsx,+ wrapInSequence: componentOwnsSequence+ ? null+ : {+ dimensions: request.element.dimensions,+ durationInFrames,+ from: request.from,+ name: request.element.displayName,+ position: request.position,+ },+ });+ const projectWithElement = {+ ...insertion.project,+ files: {+ ...insertion.project.files,+ [plan.elementFilePath]: request.element.sourceCode,+ },+ };+ const nextProject = addDependenciesToProject({+ dependencies: installedDependencies,+ project: projectWithElement,});const nodePathMutation = controller.applyMutation({- fileName: result.filePath,- mutate: () => result.project,+ fileName: insertion.filePath,+ mutate: () => nextProject,nodePathMutationFiles: [{- absolutePath: result.filePath,- remappings: result.nodePathRemappings,+ absolutePath: insertion.filePath,+ remappings: insertion.nodePathRemappings,restoredNodePaths: [],},],});if (nodePathMutation === null) {- throw new Error('Could not insert <Solid>');+ throw new Error('Could not insert Element');}- return Promise.resolve({- success: true,- insertedNodePath: null,- nodePathMutation,+ return {success: true, nodePathMutation};+ } catch (error) {+ return {+ success: false,+ type: 'error',+ reason: error instanceof Error ? error.message : String(error),+ stack: error instanceof Error ? (error.stack ?? '') : '',+ } satisfies InsertElementResponse;+ }+ },+ insertJsxElement,+ insertSolid: insertJsxElement,+ prepareElementInstall: async (request) => {+ try {+ const plan = await getElementInstallPlanForProject({+ ...request,+ project: getProject(),});+ return {+ success: true,+ plan: {+ expectedFileState: plan.expectedFileState,+ filePath: plan.filePath,+ },+ };} catch (error) {- return Promise.resolve({+ return {success: false,reason: error instanceof Error ? error.message : String(error),stack: error instanceof Error ? (error.stack ?? '') : '',- } satisfies InsertJsxElementResponse);+ };}},redo: controller.redo,diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 5e0fb77384..7b2b23eaf9 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -109,6 +109,7 @@ export const MyComponent = () => <AbsoluteFill>Existing</AbsoluteFill>;onProjectChange: (nextProject) => {currentProject = nextProject;},+ resolveDependencies: null,});expect(operations.getCompositionFile('MyComp')).toBe('src/index.tsx');expect(operations.getCompositionFile('Unknown')).toBeNull();@@ -140,7 +141,10 @@ export const MyComponent = () => <AbsoluteFill>Existing</AbsoluteFill>;});expect(result.success).toBe(true);expect(currentProject.files['/project/src/MyComponent.tsx']).toContain(- '<Solid width={1280}',+ '<Solid',+ );+ expect(currentProject.files['/project/src/MyComponent.tsx']).toContain(+ 'width={1280}',);});@@ -208,6 +212,7 @@ export const Root = () => <Composition id="MyComp" component={Component} duratioonProjectChange: (nextProject) => {currentProject = nextProject;},+ resolveDependencies: null,});const events: EventSourceEvent[] = [];operations.subscribeToEvent((event) => events.push(event));@@ -287,6 +292,7 @@ test('reports invalid timeline Solid input without changing the project', asynconProjectChange: (nextProject) => {currentProject = nextProject;},+ resolveDependencies: null,});const result = await operations.insertSolid({@@ -327,6 +333,7 @@ registerRoot(Root);`,onProjectChange: (nextProject) => {currentProject = nextProject;},+ resolveDependencies: null,});const events: EventSourceEvent[] = [];operations.subscribeToEvent((event) => events.push(event));@@ -404,6 +411,7 @@ export const Root = () => <Composition id="MyComp" component={Component} duratioonProjectChange: (nextProject) => {currentProject = nextProject;},+ resolveDependencies: null,});const events: EventSourceEvent[] = [];operations.subscribeToEvent((event) => events.push(event));diff --git a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts b/packages/browser-studio/src/test/browser-studio-project-operations.test.tsindex 6463f6404a..bfee487a53 100644--- a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts@@ -1,4 +1,5 @@import {expect, test} from 'bun:test';+import type {ElementDragData} from '@remotion/studio-protocol';import type {EventSourceEvent} from '@remotion/studio-shared';import {createBrowserStudioOperations} from '../browser-studio-operations';import {@@ -27,6 +28,7 @@ test('mutates virtual files, emits events, and preserves undo and redo history',onProjectChange: (nextProject) => {project = nextProject;},+ resolveDependencies: null,});const events: EventSourceEvent[] = [];const contentsAtMutation: string[] = [];@@ -74,8 +76,9 @@ test('mutates virtual files, emits events, and preserves undo and redo history',expect(contentsAtMutation).toEqual([initialProject.files['/project/src/Composition.tsx'],]);+ expect(project.files['/project/src/Composition.tsx']).toContain('<Solid');expect(project.files['/project/src/Composition.tsx']).toContain(- '<Solid width={1280}',+ 'width={1280}',);const {redo, undo} = operations;@@ -100,8 +103,9 @@ test('mutates virtual files, emits events, and preserves undo and redo history',expect(redoResult.nodePathMutation.files).toEqual(insertResult.nodePathMutation.files,);+ expect(project.files['/project/src/Composition.tsx']).toContain('<Solid');expect(project.files['/project/src/Composition.tsx']).toContain(- '<Solid width={1280}',+ 'width={1280}',);const {writeStaticFile} = operations;@@ -157,7 +161,7 @@ test('mutates virtual files, emits events, and preserves undo and redo history',await operations.getFileSource('webpack://remotion/./src/Composition.tsx?source',),- ).toContain('<Solid width={1280}');+ ).toContain('<Solid');const eventCount = events.length;unsubscribe();@@ -167,6 +171,172 @@ test('mutates virtual files, emits events, and preserves undo and redo history',expect(revokedUrls).toContain('blob:virtual-2');});+test('imports an Element with pinned Remotion dependencies as one undoable mutation', async () => {+ const initialProject = createBlankTemplateProject();+ let project = initialProject;+ const resolvedDependencyNames: string[][] = [];+ const operations = createBrowserStudioOperations({+ dependencyVersions: {remotion: '4.0.999'},+ getStaticFiles: null,+ getProject: () => project,+ onProjectChange: (nextProject) => {+ project = nextProject;+ },+ resolveDependencies: (dependencies) => {+ resolvedDependencyNames.push(+ dependencies.map((dependency) => dependency.name),+ );+ return Promise.resolve({+ '@remotion/shapes': '0.0.1',+ zod: '4.1.5',+ });+ },+ });+ const element = {+ dependencies: [+ {name: '@remotion/shapes', version: null},+ {name: 'zod', version: '4.1.5'},+ ],+ dimensions: {width: 640, height: 180},+ displayName: 'Lower Third',+ durationInFrames: 90,+ installationMode: 'wrapped' as const,+ slug: 'titles/lower-third',+ sourceCode: `import {Rect} from '@remotion/shapes';++export const LowerThird = () => <Rect width={640} height={180} />;+`,+ } satisfies ElementDragData['element'];+ const preflight = await operations.prepareElementInstall({+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ element,+ });+ if (!preflight.success) {+ throw new Error(preflight.reason);+ }++ expect(preflight.plan).toEqual({+ expectedFileState: {exists: false},+ filePath: 'src/lower-third.element.tsx',+ });+ const inserted = await operations.insertElement({+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ element,+ expectedFileState: preflight.plan.expectedFileState,+ from: 12,+ overwriteExisting: false,+ position: {x: 24, y: 48},+ });+ if (!inserted.success) {+ throw new Error(+ inserted.type === 'error' ? inserted.reason : 'Unexpected file conflict',+ );+ }++ expect(resolvedDependencyNames).toEqual([['@remotion/shapes', 'zod']]);+ expect(project.files['/project/src/lower-third.element.tsx']).toBe(+ element.sourceCode,+ );+ expect(project.files['/project/src/Composition.tsx']).toContain(+ "import {LowerThird} from './lower-third.element';",+ );+ expect(project.files['/project/src/Composition.tsx']).toContain('<Sequence');+ expect(project.files['/project/src/Composition.tsx']).toContain('from={12}');+ expect(project.files['/project/src/Composition.tsx']).toContain(+ 'name="Lower Third"',+ );+ expect(project.files['/project/src/Composition.tsx']).toContain(+ "translate: '24px 48px'",+ );+ const packageJson = JSON.parse(project.files['/project/package.json']) as {+ dependencies: Record<string, string>;+ };+ expect(packageJson.dependencies['@remotion/shapes']).toBe('4.0.999');+ expect(packageJson.dependencies.zod).toBe('4.1.5');++ expect((await operations.undo()).success).toBe(true);+ expect(project.files['/project/src/Composition.tsx']).toBe(+ initialProject.files['/project/src/Composition.tsx'],+ );+ expect(project.files['/project/src/lower-third.element.tsx']).toBeUndefined();+ expect(project.files['/project/package.json']).toBe(+ initialProject.files['/project/package.json'],+ );+ expect((await operations.redo()).success).toBe(true);+ expect(project.files['/project/src/lower-third.element.tsx']).toBe(+ element.sourceCode,+ );+});++test('inserts generic elements with pinned Remotion dependencies', async () => {+ let project = createBlankTemplateProject();+ const operations = createBrowserStudioOperations({+ dependencyVersions: {remotion: '4.0.999'},+ getStaticFiles: null,+ getProject: () => project,+ onProjectChange: (nextProject) => {+ project = nextProject;+ },+ resolveDependencies: null,+ });+ const result = await operations.insertJsxElement({+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ element: {+ assetType: 'video',+ dimensions: {height: 1080, width: 1920},+ durationInFrames: 90,+ position: null,+ src: 'clip.mp4',+ srcType: 'static',+ type: 'asset',+ },+ from: 12,+ });+ if (!result.success) {+ throw new Error(result.reason);+ }++ expect(project.files['/project/src/Composition.tsx']).toContain(+ "from '@remotion/media'",+ );+ expect(project.files['/project/src/Composition.tsx']).toContain('<Video');+ const packageJson = JSON.parse(project.files['/project/package.json']) as {+ dependencies: Record<string, string>;+ };+ expect(packageJson.dependencies['@remotion/media']).toBe('4.0.999');+});++test('rejects inline SVG importing in Browser Studio', async () => {+ const project = createBlankTemplateProject();+ const operations = createBrowserStudioOperations({+ dependencyVersions: {},+ getStaticFiles: null,+ getProject: () => project,+ onProjectChange: () => {+ throw new Error('SVG insertion must not mutate the project');+ },+ resolveDependencies: null,+ });+ const result = await operations.insertJsxElement({+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ element: {+ markup: '<svg viewBox="0 0 10 10" />',+ position: null,+ type: 'svg',+ },+ from: null,+ });++ expect(result).toMatchObject({+ reason: 'Importing SVG markup is not supported in Browser Studio',+ success: false,+ });+});+test('replays an HMR event emitted before the Studio subscribes', () => {const project = createBlankTemplateProject();const operations = createBrowserStudioOperations({@@ -174,6 +344,7 @@ test('replays an HMR event emitted before the Studio subscribes', () => {getStaticFiles: null,getProject: () => project,onProjectChange: () => undefined,+ resolveDependencies: null,});const hmrEvent = {type: 'hmr',@@ -207,6 +378,7 @@ test('rejects unsafe public paths and conflicting renames', async () => {onProjectChange: (nextProject) => {project = nextProject;},+ resolveDependencies: null,});const {renameStaticFile, writeStaticFile} = operations;diff --git a/packages/browser-studio/src/test/download-project.test.ts b/packages/browser-studio/src/test/download-project.test.tsindex 011dfd5f87..8879d86c3f 100644--- a/packages/browser-studio/src/test/download-project.test.ts+++ b/packages/browser-studio/src/test/download-project.test.ts@@ -25,6 +25,7 @@ test('downloads the current Browser Studio project as a runnable archive', asynconProjectChange: (nextProject) => {project = nextProject;},+ resolveDependencies: null,});const insertResult = await operations.insertSolid({@@ -49,9 +50,8 @@ test('downloads the current Browser Studio project as a runnable archive', async>;expect(archive.fileName).toBe('remotion-project.zip');- expect(strFromU8(files['src/Composition.tsx'])).toContain(- '<Solid width={1280}',- );+ expect(strFromU8(files['src/Composition.tsx'])).toContain('<Solid');+ expect(strFromU8(files['src/Composition.tsx'])).toContain('width={1280}');expect(strFromU8(files['tsconfig.json'])).toBe(project.files['/project/tsconfig.json'],);diff --git a/packages/studio-codemods/src/get-node-path-remappings.ts b/packages/studio-codemods/src/get-node-path-remappings.tsnew file mode 100644index 0000000000..d9010fee47--- /dev/null+++ b/packages/studio-codemods/src/get-node-path-remappings.ts@@ -0,0 +1,79 @@+import type {File, JSXOpeningElement} from '@babel/types';+import type {SequenceNodePathRemapping} from '@remotion/studio-shared';+import * as recast from 'recast';+import type {SequenceNodePath} from 'remotion';+import {getNodePathForRecastPath} from './sequence-props';+import {parseAst} from './sequence-props/parse-ast';++export type CapturedJsxNodePath = {+ node: JSXOpeningElement;+ nodePath: SequenceNodePath;+};++export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {+ const captured: CapturedJsxNodePath[] = [];+ recast.visit(ast, {+ visitJSXOpeningElement(path) {+ captured.push({+ node: path.node as JSXOpeningElement,+ nodePath: getNodePathForRecastPath(path, ast),+ });+ return this.traverse(path);+ },+ });++ return captured;+};++export const getNodePathRemappings = ({+ ast,+ captured,+ output,+}: {+ ast: File;+ captured: CapturedJsxNodePath[];+ output: string;+}): {+ nodePathRemappings: SequenceNodePathRemapping[];+ finalNodePathByNode: Map<JSXOpeningElement, SequenceNodePath>;+} => {+ const nodesAfterMutation: JSXOpeningElement[] = [];+ recast.visit(ast, {+ visitJSXOpeningElement(path) {+ nodesAfterMutation.push(path.node as JSXOpeningElement);+ return this.traverse(path);+ },+ });++ const finalAst = parseAst(output);+ const finalNodePaths: SequenceNodePath[] = [];+ recast.visit(finalAst, {+ visitJSXOpeningElement(path) {+ finalNodePaths.push(getNodePathForRecastPath(path, finalAst));+ return this.traverse(path);+ },+ });++ if (nodesAfterMutation.length !== finalNodePaths.length) {+ throw new Error('Could not map JSX node paths after modifying JSX nodes');+ }++ const finalNodePathByNode = new Map<JSXOpeningElement, SequenceNodePath>();+ for (let i = 0; i < nodesAfterMutation.length; i++) {+ finalNodePathByNode.set(nodesAfterMutation[i], finalNodePaths[i]);+ }++ const nodePathRemappings = captured.flatMap(({node, nodePath}) => {+ const newNodePath = finalNodePathByNode.get(node) ?? null;+ if (+ newNodePath !== null &&+ JSON.stringify(nodePath) === JSON.stringify(newNodePath)+ ) {+ return [];+ }++ return [{oldNodePath: nodePath, newNodePath}];+ });++ return {finalNodePathByNode, nodePathRemappings};+};diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.tsindex a53dfa3a95..016caef068 100644--- a/packages/studio-codemods/src/index.ts+++ b/packages/studio-codemods/src/index.ts@@ -12,6 +12,16 @@ import {getNodePathForRecastPath} from './sequence-props';import {parseAst} from './sequence-props/parse-ast';export {findSearchPosition} from './find-search-position';+export {+ insertJsxElementIntoComposition,+ insertJsxElementIntoProjectWithNodePathRemappings,+ makeInMemoryInsertJsxElementCodemodEnvironment,+ resolveCompositionComponent,+ resolveCompositionComponentWithFile,+ type InsertJsxElementCodemodEnvironment,+ type ResolvedCompositionComponent,+ type ResolvedCompositionComponentWithFile,+} from './insert-jsx-element';export {computeSequencePropsStatusFromContent,computeSequencePropsSubscriptionFromContent,@@ -1144,6 +1154,60 @@ export const insertSolidIntoSource = ({};};+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.print(path.node as JSXOpeningElement).code,+ });+ return this.traverse(path);+ },+ });+ recast.visit(astAfter, {+ visitJSXOpeningElement(path) {+ after.push({+ nodePath: getNodePathForRecastPath(path, astAfter),+ signature: recast.print(path.node as JSXOpeningElement).code,+ });+ return this.traverse(path);+ },+ });++ let nextAfterIndex = 0;+ return 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;+ const newNodePath = after[matchedIndex].nodePath;+ if (JSON.stringify(nodePath) === JSON.stringify(newNodePath)) {+ return [];+ }++ return [{oldNodePath: nodePath, newNodePath}];+ },+ );+};+export const insertSolidIntoProjectWithNodePathRemappings = <Project extends CodemodProject,>({@@ -1197,56 +1261,11 @@ export const insertSolidIntoProjectWithNodePathRemappings = <source: resolved.source,width: request.element.width,});- const astBefore = parseAst(resolved.source);- const astAfter = parseAst(output);- 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.print(path.node as JSXOpeningElement).code,- });- return this.traverse(path);- },- });- recast.visit(astAfter, {- visitJSXOpeningElement(path) {- after.push({- nodePath: getNodePathForRecastPath(path, astAfter),- signature: recast.print(path.node as JSXOpeningElement).code,- });- return this.traverse(path);- },+ const nodePathRemappings = getNodePathRemappings({+ afterSource: output,+ beforeSource: resolved.source,});- let nextAfterIndex = 0;- const nodePathRemappings = 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 <Solid>');- }-- nextAfterIndex = matchedIndex + 1;- const newNodePath = after[matchedIndex].nodePath;- if (JSON.stringify(nodePath) === JSON.stringify(newNodePath)) {- return [];- }-- return [{oldNodePath: nodePath, newNodePath}];- },- );-return {filePath: resolved.filePath,nodePathRemappings,diff --git a/packages/studio-codemods/src/insert-jsx-element.ts b/packages/studio-codemods/src/insert-jsx-element.tsnew file mode 100644index 0000000000..376d5560e1--- /dev/null+++ b/packages/studio-codemods/src/insert-jsx-element.ts@@ -0,0 +1,2631 @@+import type {+ ClassDeclaration,+ ExportAllDeclaration,+ ExportNamedDeclaration,+ ExportSpecifier,+ File,+ FunctionDeclaration,+ ImportDeclaration,+ ImportDefaultSpecifier,+ ImportSpecifier,+ JSXAttribute,+ JSXElement,+ JSXOpeningElement,+ JSXSpreadAttribute,+ ObjectProperty,+ VariableDeclaration,+} from '@babel/types';+import {+ isUrl,+ type InsertJsxElementRequest,+ type InsertableCompositionElement,+ type InsertableCompositionElementPosition,+ type SequenceNodePathRemapping,+} from '@remotion/studio-shared';+import type {namedTypes} from 'ast-types';+import * as recast from 'recast';+import type {SequenceNodePath} from 'remotion';+import {NoReactInternals} from 'remotion/no-react';+import {+ captureJsxNodePaths,+ getNodePathRemappings,+} from './get-node-path-remappings';+import {+ ensureNamedImport,+ getImportedName,+ insertImportDeclaration,+} from './sequence-props/imports';+import {+ parseAst,+ parseAstForReadOnly,+ serializeAst,+} from './sequence-props/parse-ast';+import {stripParenthesizedExtra} from './strip-parenthesized-extra';+import {parseValueExpression} from './update-nested-prop';++type ComponentProp = Extract<+ InsertableCompositionElement,+ {type: 'component'}+>['props'][number];++export type InsertJsxElementCodemodEnvironment = {+ rootDir: string;+ dirname: (fileName: string) => string;+ extname: (fileName: string) => string;+ fileExists: (fileName: string) => boolean;+ formatFile: (input: {+ contents: string;+ prettierConfigOverride: Record<string, unknown> | null;+ }) => Promise<{output: string; formatted: boolean}>;+ isAbsolute: (fileName: string) => boolean;+ join: (...parts: string[]) => string;+ pathSeparator: string;+ readFile: (fileName: string) => Promise<string>;+ relative: (from: string, to: string) => string;+ resolve: (...parts: string[]) => string;+ svgMarkupToJsx: (markup: string) => Promise<namedTypes.JSXElement>;+};++const normalizeVirtualPath = (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 resolveVirtualPath = (...parts: string[]) => {+ let resolved = '';+ for (const part of parts) {+ if (part.startsWith('/')) {+ resolved = part;+ } else {+ resolved = `${resolved}/${part}`;+ }+ }++ return normalizeVirtualPath(resolved);+};++const virtualDirname = (fileName: string) => {+ const normalized = normalizeVirtualPath(fileName);+ const lastSlash = normalized.lastIndexOf('/');+ return lastSlash <= 0+ ? normalized.startsWith('/')+ ? '/'+ : ''+ : normalized.slice(0, lastSlash);+};++const relativeVirtualPath = (from: string, to: string) => {+ const fromParts = normalizeVirtualPath(from).split('/').filter(Boolean);+ const toParts = normalizeVirtualPath(to).split('/').filter(Boolean);+ let sharedParts = 0;+ while (+ sharedParts < fromParts.length &&+ sharedParts < toParts.length &&+ fromParts[sharedParts] === toParts[sharedParts]+ ) {+ sharedParts++;+ }++ return [+ ...fromParts.slice(sharedParts).map(() => '..'),+ ...toParts.slice(sharedParts),+ ].join('/');+};++export const makeInMemoryInsertJsxElementCodemodEnvironment = ({+ formatFile,+ project,+ svgMarkupToJsx,+}: {+ formatFile: InsertJsxElementCodemodEnvironment['formatFile'];+ project: {files: Record<string, string>; rootDir: string};+ svgMarkupToJsx: InsertJsxElementCodemodEnvironment['svgMarkupToJsx'];+}): InsertJsxElementCodemodEnvironment => {+ const filesByNormalizedPath = new Map(+ Object.entries(project.files).map(([fileName, contents]) => [+ normalizeVirtualPath(fileName),+ contents,+ ]),+ );++ return {+ dirname: virtualDirname,+ extname: (fileName) => {+ const name = fileName.slice(fileName.lastIndexOf('/') + 1);+ const dot = name.lastIndexOf('.');+ return dot === -1 ? '' : name.slice(dot);+ },+ fileExists: (fileName) =>+ filesByNormalizedPath.has(normalizeVirtualPath(fileName)),+ formatFile,+ isAbsolute: (fileName) => fileName.startsWith('/'),+ join: (...parts) => resolveVirtualPath(...parts),+ pathSeparator: '/',+ readFile: (fileName) => {+ const contents = filesByNormalizedPath.get(+ normalizeVirtualPath(fileName),+ );+ if (contents === undefined) {+ throw new Error(`Could not read source file "${fileName}"`);+ }++ return Promise.resolve(contents);+ },+ relative: relativeVirtualPath,+ resolve: resolveVirtualPath,+ rootDir: normalizeVirtualPath(project.rootDir),+ svgMarkupToJsx,+ };+};++type SourceLocation = {+ line: number;+ column: number;+};++type NodeWithLocation = {+ loc?: {+ start: {+ line: number;+ column: number;+ };+ } | null;+};++export type ResolvedCompositionComponent = {+ source: string;+ line: number;+ column: number;+ canAddSequence: boolean;+};++export type ResolvedCompositionComponentWithFile =+ ResolvedCompositionComponent & {+ fileName: string;+ exportName: string | 'default';+ };++type ImportTarget = {+ importPath: string;+ exportName: string | 'default';+};++type ReExportTarget = {+ importPath: string;+ exportName: string | 'default';+};++const allowedFileExtensions = new Set(['.tsx', '.ts', '.jsx', '.js']);+const extensionsToProbe = ['.tsx', '.ts', '.jsx', '.js'];++const isInRemotionRoot = ({+ environment,+ fileName,+}: {+ environment: InsertJsxElementCodemodEnvironment;+ fileName: string;+}) => {+ const relativePath = environment.relative(environment.rootDir, fileName);+ return (+ !relativePath.startsWith('..') && !environment.isAbsolute(relativePath)+ );+};++const readSourceFile = ({+ environment,+ fileName,+}: {+ environment: InsertJsxElementCodemodEnvironment;+ fileName: string;+}) => {+ const resolved = environment.resolve(environment.rootDir, fileName);+ if (!isInRemotionRoot({environment, fileName: resolved})) {+ throw new Error(`Not allowed to open ${fileName}`);+ }++ if (!allowedFileExtensions.has(environment.extname(resolved))) {+ throw new Error(`Not allowed to open ${fileName}`);+ }++ return environment.readFile(resolved);+};++const getAttributeName = (attribute: JSXAttribute) => {+ if (attribute.name.type !== 'JSXIdentifier') {+ return null;+ }++ return attribute.name.name;+};++const findAttribute = (element: JSXElement, name: string) => {+ return element.openingElement.attributes.find((attribute) => {+ if (attribute.type !== 'JSXAttribute') {+ return false;+ }++ return getAttributeName(attribute) === name;+ }) as JSXAttribute | undefined;+};++const getStringAttributeValue = (element: JSXElement, name: string) => {+ const attribute = findAttribute(element, name);+ if (!attribute?.value) {+ return null;+ }++ if (attribute.value.type === 'StringLiteral') {+ return attribute.value.value;+ }++ if (+ attribute.value.type === 'JSXExpressionContainer' &&+ attribute.value.expression.type === 'StringLiteral'+ ) {+ return attribute.value.expression.value;+ }++ return null;+};++const findCompositionElement = ({+ ast,+ compositionId,+}: {+ ast: File;+ compositionId: string;+}) => {+ let found: JSXElement | null = null;++ recast.types.visit(ast, {+ visitJSXElement(astPath) {+ if (found) {+ return false;+ }++ const node = astPath.node as JSXElement;+ const openingName = node.openingElement.name;+ if (+ openingName.type === 'JSXIdentifier' &&+ (openingName.name === 'Composition' || openingName.name === 'Still') &&+ getStringAttributeValue(node, 'id') === compositionId+ ) {+ found = node;+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ });++ return found;+};++const getComponentIdentifier = (element: JSXElement) => {+ const attribute = findAttribute(element, 'component');+ if (+ !attribute?.value ||+ attribute.value.type !== 'JSXExpressionContainer' ||+ attribute.value.expression.type !== 'Identifier'+ ) {+ return null;+ }++ return attribute.value.expression.name;+};++const isRecord = (value: unknown): value is Record<string, unknown> => {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+};++const findDynamicImportPath = (value: unknown): string | null => {+ if (!isRecord(value)) {+ return null;+ }++ if (+ value.type === 'CallExpression' &&+ isRecord(value.callee) &&+ value.callee.type === 'Import' &&+ Array.isArray(value.arguments) &&+ isRecord(value.arguments[0]) &&+ value.arguments[0].type === 'StringLiteral' &&+ typeof value.arguments[0].value === 'string'+ ) {+ return value.arguments[0].value;+ }++ for (const [key, child] of Object.entries(value)) {+ if (+ key === 'loc' ||+ key === 'start' ||+ key === 'end' ||+ key === 'comments' ||+ key === 'leadingComments' ||+ key === 'trailingComments' ||+ key === 'innerComments' ||+ key === 'extra' ||+ key === 'original'+ ) {+ continue;+ }++ if (Array.isArray(child)) {+ for (const item of child) {+ const nestedResult = findDynamicImportPath(item);+ if (nestedResult) {+ return nestedResult;+ }+ }++ continue;+ }++ const childResult = findDynamicImportPath(child);+ if (childResult) {+ return childResult;+ }+ }++ return null;+};++const getLazyImportPath = (element: JSXElement) => {+ const attribute = findAttribute(element, 'lazyComponent');+ if (!attribute?.value || attribute.value.type !== 'JSXExpressionContainer') {+ return null;+ }++ return findDynamicImportPath(attribute.value.expression);+};++const findImportTarget = ({+ ast,+ componentName,+}: {+ ast: File;+ componentName: string;+}): ImportTarget | null => {+ let found: ImportTarget | null = null;++ recast.types.visit(ast, {+ visitImportDeclaration(astPath) {+ if (found) {+ return false;+ }++ const node = astPath.node as ImportDeclaration;+ if (typeof node.source.value !== 'string') {+ return false;+ }++ const matchingSpecifier = node.specifiers?.find((specifier) => {+ return specifier.local?.name === componentName;+ });+ if (!matchingSpecifier) {+ return false;+ }++ if (matchingSpecifier.type === 'ImportDefaultSpecifier') {+ found = {+ importPath: node.source.value,+ exportName: 'default',+ };+ return false;+ }++ if (+ matchingSpecifier.type === 'ImportSpecifier' &&+ matchingSpecifier.imported.type === 'Identifier'+ ) {+ found = {+ importPath: node.source.value,+ exportName: matchingSpecifier.imported.name,+ };+ return false;+ }++ if (+ matchingSpecifier.type === 'ImportSpecifier' &&+ matchingSpecifier.imported.type === 'StringLiteral'+ ) {+ found = {+ importPath: node.source.value,+ exportName: matchingSpecifier.imported.value,+ };+ return false;+ }++ return false;+ },+ });++ return found;+};++const getExportedName = (exported: unknown) => {+ if (!exported) {+ return null;+ }++ if (!isRecord(exported)) {+ return null;+ }++ if (exported.type === 'Identifier' && typeof exported.name === 'string') {+ return exported.name;+ }++ if (exported.type === 'StringLiteral' && typeof exported.value === 'string') {+ return exported.value;+ }++ return null;+};++const getSpecifierLocalName = (specifier: ExportSpecifier) => {+ if (specifier.local.type === 'Identifier') {+ return specifier.local.name;+ }++ return null;+};++const findReExportTargets = ({+ ast,+ exportName,+}: {+ ast: File;+ exportName: string | 'default';+}) => {+ const targets: ReExportTarget[] = [];++ recast.types.visit(ast, {+ visitExportNamedDeclaration(astPath) {+ const node = astPath.node as ExportNamedDeclaration;++ for (const specifier of node.specifiers) {+ if (specifier.type !== 'ExportSpecifier') {+ continue;+ }++ const exportedName = getExportedName(specifier.exported);+ if (exportedName !== exportName) {+ continue;+ }++ const localName = getSpecifierLocalName(specifier);+ if (!localName) {+ continue;+ }++ // Support barrel files that import a component and export it in a+ // separate declaration. See https://github.com/remotion-dev/remotion/issues/9172.+ if (typeof node.source?.value !== 'string') {+ const importTarget = findImportTarget({+ ast,+ componentName: localName,+ });+ if (importTarget) {+ targets.push(importTarget);+ }++ continue;+ }++ targets.push({+ importPath: node.source.value,+ exportName: localName === 'default' ? 'default' : localName,+ });+ }++ return false;+ },+ visitExportAllDeclaration(astPath) {+ const node = astPath.node as ExportAllDeclaration;+ if (typeof node.source.value !== 'string') {+ return false;+ }++ targets.push({+ importPath: node.source.value,+ exportName,+ });++ return false;+ },+ });++ return targets;+};++const resolveImportPath = ({+ environment,+ importPath,+ fromFile,+}: {+ environment: InsertJsxElementCodemodEnvironment;+ importPath: string;+ fromFile: string;+}) => {+ if (!importPath.startsWith('.')) {+ throw new Error(`Cannot resolve non-relative import ${importPath}`);+ }++ const basePath = environment.resolve(+ environment.dirname(fromFile),+ importPath,+ );+ const candidates = environment.extname(basePath)+ ? [basePath]+ : [+ ...extensionsToProbe.map((extension) => `${basePath}${extension}`),+ ...extensionsToProbe.map((extension) =>+ environment.join(basePath, `index${extension}`),+ ),+ ];++ const existingFile = candidates.find(environment.fileExists);+ if (!existingFile) {+ throw new Error(`Could not find imported component file ${importPath}`);+ }++ return existingFile;+};++const locationFromNode = (node: NodeWithLocation): SourceLocation | null => {+ if (!node.loc) {+ return null;+ }++ return {+ line: node.loc.start.line,+ column: node.loc.start.column,+ };+};++const findLocalSymbolLocation = ({+ ast,+ name,+}: {+ ast: File;+ name: string;+}): SourceLocation | null => {+ let location: SourceLocation | null = null;++ // Recast can omit the declaration location for exported functions and+ // classes, including components resolved through barrel files. The identifier+ // keeps its location. See https://github.com/remotion-dev/remotion/issues/9172.+ recast.types.visit(ast, {+ visitVariableDeclarator(astPath) {+ if (location) {+ return false;+ }++ const {node} = astPath;+ if (node.id.type === 'Identifier' && node.id.name === name) {+ location = locationFromNode(node.id);+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ visitFunctionDeclaration(astPath) {+ if (location) {+ return false;+ }++ const {node} = astPath;+ if (node.id?.name === name) {+ location = locationFromNode(node.id);+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ visitClassDeclaration(astPath) {+ if (location) {+ return false;+ }++ const {node} = astPath;+ if (node.id?.name === name) {+ location = locationFromNode(node.id);+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ });++ return location;+};++const findDefaultExportLocation = (ast: File): SourceLocation | null => {+ let location: SourceLocation | null = null;+ let exportedIdentifier: string | null = null;++ recast.types.visit(ast, {+ visitExportDefaultDeclaration(astPath) {+ if (location || exportedIdentifier) {+ return false;+ }++ const {node} = astPath;+ if (node.declaration.type === 'Identifier') {+ exportedIdentifier = node.declaration.name;+ return false;+ }++ location = locationFromNode(node.declaration) ?? locationFromNode(node);+ return false;+ },+ });++ if (exportedIdentifier) {+ return findLocalSymbolLocation({ast, name: exportedIdentifier});+ }++ return location;+};++type LocalComponentDeclaration =+ | namedTypes.VariableDeclarator+ | namedTypes.FunctionDeclaration+ | namedTypes.ClassDeclaration;++type FunctionLikeNode =+ | namedTypes.ArrowFunctionExpression+ | namedTypes.FunctionExpression+ | namedTypes.FunctionDeclaration;++type DefaultExportDeclaration =+ namedTypes.ExportDefaultDeclaration['declaration'];++const findLocalComponentDeclaration = ({+ ast,+ name,+}: {+ ast: File;+ name: string;+}): LocalComponentDeclaration | null => {+ let declaration: LocalComponentDeclaration | null = null;++ recast.types.visit(ast, {+ visitVariableDeclarator(astPath) {+ if (declaration) {+ return false;+ }++ const {node} = astPath;+ if (node.id.type === 'Identifier' && node.id.name === name) {+ declaration = node;+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ visitFunctionDeclaration(astPath) {+ if (declaration) {+ return false;+ }++ const {node} = astPath;+ if (node.id?.name === name) {+ declaration = node;+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ visitClassDeclaration(astPath) {+ if (declaration) {+ return false;+ }++ const {node} = astPath;+ if (node.id?.name === name) {+ declaration = node;+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ });++ return declaration;+};++const getTopLevelReturnStatement = (+ statements: namedTypes.Statement[],+): namedTypes.ReturnStatement | null => {+ const returnStatements: namedTypes.ReturnStatement[] = [];+ for (const statement of statements) {+ if (recast.types.namedTypes.ReturnStatement.check(statement)) {+ returnStatements.push(statement);+ }+ }++ if (returnStatements.length !== 1) {+ return null;+ }++ const singleReturn = returnStatements[0];+ const finalStatement = statements.at(-1);+ if (singleReturn !== finalStatement) {+ return null;+ }++ return singleReturn;+};++const getReturnedJsxFromFunction = (+ fn: FunctionLikeNode,+): namedTypes.JSXElement | namedTypes.JSXFragment | null => {+ if (fn.type === 'ArrowFunctionExpression') {+ if (fn.body.type === 'JSXElement' || fn.body.type === 'JSXFragment') {+ return fn.body;+ }++ if (fn.body.type !== 'BlockStatement') {+ return null;+ }++ const arrowReturnStatement = getTopLevelReturnStatement(fn.body.body);+ if (!arrowReturnStatement?.argument) {+ return null;+ }++ return arrowReturnStatement.argument.type === 'JSXElement' ||+ arrowReturnStatement.argument.type === 'JSXFragment'+ ? arrowReturnStatement.argument+ : null;+ }++ if (fn.body.type !== 'BlockStatement') {+ return null;+ }++ const returnStatement = getTopLevelReturnStatement(fn.body.body);+ if (!returnStatement?.argument) {+ return null;+ }++ return returnStatement.argument.type === 'JSXElement' ||+ returnStatement.argument.type === 'JSXFragment'+ ? returnStatement.argument+ : null;+};++const findRenderMethod = (+ declaration: namedTypes.ClassDeclaration,+): namedTypes.ClassMethod | null => {+ const renderMethod = declaration.body.body.find((member) => {+ return (+ member.type === 'ClassMethod' &&+ member.kind === 'method' &&+ member.key.type === 'Identifier' &&+ member.key.name === 'render'+ );+ });++ return renderMethod?.type === 'ClassMethod' ? renderMethod : null;+};++const getComponentRootNode = (+ declaration: LocalComponentDeclaration | DefaultExportDeclaration,+): namedTypes.JSXElement | namedTypes.JSXFragment | null => {+ if (declaration.type === 'VariableDeclarator') {+ if (+ !declaration.init ||+ (declaration.init.type !== 'ArrowFunctionExpression' &&+ declaration.init.type !== 'FunctionExpression')+ ) {+ return null;+ }++ return getReturnedJsxFromFunction(declaration.init);+ }++ if (+ declaration.type === 'ArrowFunctionExpression' ||+ declaration.type === 'FunctionExpression' ||+ declaration.type === 'FunctionDeclaration'+ ) {+ return getReturnedJsxFromFunction(declaration);+ }++ if (declaration.type !== 'ClassDeclaration') {+ return null;+ }++ const renderMethod = findRenderMethod(declaration);+ if (!renderMethod) {+ return null;+ }++ const returnStatement = getTopLevelReturnStatement(renderMethod.body.body);+ if (!returnStatement?.argument) {+ return null;+ }++ return returnStatement.argument.type === 'JSXElement' ||+ returnStatement.argument.type === 'JSXFragment'+ ? returnStatement.argument+ : null;+};++const createSequenceElement = (): namedTypes.JSXElement => {+ return recast.types.builders.jsxElement(+ recast.types.builders.jsxOpeningElement(+ recast.types.builders.jsxIdentifier('Sequence'),+ [],+ ),+ recast.types.builders.jsxClosingElement(+ recast.types.builders.jsxIdentifier('Sequence'),+ ),+ [],+ );+};++const createSequenceWithChild = ({+ child,+ sequenceLocalName,+}: {+ child: namedTypes.JSXElement;+ sequenceLocalName: string;+}): namedTypes.JSXElement => {+ return recast.types.builders.jsxElement(+ recast.types.builders.jsxOpeningElement(+ recast.types.builders.jsxIdentifier(sequenceLocalName),+ [],+ ),+ recast.types.builders.jsxClosingElement(+ recast.types.builders.jsxIdentifier(sequenceLocalName),+ ),+ [child],+ );+};++const createNumberAttribute = (+ name: string,+ value: number,+): namedTypes.JSXAttribute => {+ return recast.types.builders.jsxAttribute(+ recast.types.builders.jsxIdentifier(name),+ recast.types.builders.jsxExpressionContainer(+ recast.types.builders.numericLiteral(value),+ ),+ );+};++const createStringAttribute = (+ name: string,+ value: string,+): namedTypes.JSXAttribute => {+ return recast.types.builders.jsxAttribute(+ recast.types.builders.jsxIdentifier(name),+ recast.types.builders.stringLiteral(value),+ );+};++const createBooleanAttribute = (+ name: string,+ value: boolean,+): namedTypes.JSXAttribute => {+ return recast.types.builders.jsxAttribute(+ recast.types.builders.jsxIdentifier(name),+ recast.types.builders.jsxExpressionContainer(+ recast.types.builders.booleanLiteral(value),+ ),+ );+};++const translateDecimalPlaces = 1;++const roundTranslateCoordinate = (value: number): number => {+ const factor = 10 ** translateDecimalPlaces;+ const rounded = Math.round(value * factor) / factor;+ return Object.is(rounded, -0) ? 0 : rounded;+};++const formatTranslateValue = ({x, y}: InsertableCompositionElementPosition) =>+ `${roundTranslateCoordinate(x)}px ${roundTranslateCoordinate(y)}px`;++const createStyleAttribute = (+ properties: namedTypes.ObjectProperty[],+): namedTypes.JSXAttribute => {+ return recast.types.builders.jsxAttribute(+ recast.types.builders.jsxIdentifier('style'),+ recast.types.builders.jsxExpressionContainer(+ recast.types.builders.objectExpression(properties),+ ),+ );+};++const getPositionStyleProperties = (+ position: InsertableCompositionElementPosition | null,+): namedTypes.ObjectProperty[] => {+ const properties = [+ recast.types.builders.objectProperty(+ recast.types.builders.identifier('position'),+ recast.types.builders.stringLiteral('absolute'),+ ),+ ];++ if (position) {+ properties.push(+ recast.types.builders.objectProperty(+ recast.types.builders.identifier('translate'),+ recast.types.builders.stringLiteral(formatTranslateValue(position)),+ ),+ );+ }++ return properties;+};++const createPositionAbsoluteStyleAttribute = (+ position: InsertableCompositionElementPosition | null,+): namedTypes.JSXAttribute => {+ return createStyleAttribute(getPositionStyleProperties(position));+};++const createAssetStyleAttribute = ({+ dimensions,+ position,+}: {+ dimensions: {width: number; height: number} | null;+ position: InsertableCompositionElementPosition | null;+}): namedTypes.JSXAttribute => {+ return createStyleAttribute([+ ...getPositionStyleProperties(position),+ ...(dimensions+ ? [+ recast.types.builders.objectProperty(+ recast.types.builders.identifier('width'),+ recast.types.builders.numericLiteral(dimensions.width),+ ),+ recast.types.builders.objectProperty(+ recast.types.builders.identifier('height'),+ recast.types.builders.numericLiteral(dimensions.height),+ ),+ ]+ : []),+ ]);+};++const createStaticFileSrcAttribute = ({+ staticFileLocalName,+ src,+}: {+ staticFileLocalName: string;+ src: string;+}): namedTypes.JSXAttribute => {+ return recast.types.builders.jsxAttribute(+ recast.types.builders.jsxIdentifier('src'),+ recast.types.builders.jsxExpressionContainer(+ recast.types.builders.callExpression(+ recast.types.builders.identifier(staticFileLocalName),+ [recast.types.builders.stringLiteral(src)],+ ),+ ),+ );+};++const createComponentProp = ({+ name,+ value,+}: ComponentProp): namedTypes.JSXAttribute => {+ if (typeof value === 'number') {+ return createNumberAttribute(name, value);+ }++ if (typeof value === 'boolean') {+ return createBooleanAttribute(name, value);+ }++ return createStringAttribute(name, value);+};++const createStringSrcAttribute = (src: string): namedTypes.JSXAttribute => {+ return recast.types.builders.jsxAttribute(+ recast.types.builders.jsxIdentifier('src'),+ recast.types.builders.stringLiteral(src),+ );+};++const createSolidElement = ({+ localName,+ width,+ height,+ position,+}: {+ localName: string;+ width: number;+ height: number;+ position: InsertableCompositionElementPosition | null;+}): namedTypes.JSXElement => {+ return recast.types.builders.jsxElement(+ recast.types.builders.jsxOpeningElement(+ recast.types.builders.jsxIdentifier(localName),+ [+ createNumberAttribute('width', width),+ createNumberAttribute('height', height),+ createStringAttribute('color', 'gray'),+ createPositionAbsoluteStyleAttribute(position),+ ],+ true,+ ),+ null,+ [],+ );+};++const createComponentElement = ({+ addPositionStyle,+ from,+ localName,+ props,+ position,+}: {+ addPositionStyle: boolean;+ from: number | null;+ localName: string;+ props: ComponentProp[];+ position: InsertableCompositionElementPosition | null;+}): namedTypes.JSXElement => {+ return recast.types.builders.jsxElement(+ recast.types.builders.jsxOpeningElement(+ recast.types.builders.jsxIdentifier(localName),+ [+ ...props.map(createComponentProp),+ ...(from === null ? [] : [createNumberAttribute('from', from)]),+ ...(addPositionStyle+ ? [createPositionAbsoluteStyleAttribute(position)]+ : []),+ ],+ true,+ ),+ null,+ [],+ );+};++const createSequenceWrappedElement = ({+ child,+ dimensions,+ durationInFrames,+ from,+ name,+ position,+ sequenceLocalName,+}: {+ child: namedTypes.JSXElement;+ dimensions: {width: number; height: number} | null;+ durationInFrames: number | null;+ from: number | null;+ name: string | null;+ position: InsertableCompositionElementPosition | null;+ sequenceLocalName: string;+}): namedTypes.JSXElement => {+ return recast.types.builders.jsxElement(+ recast.types.builders.jsxOpeningElement(+ recast.types.builders.jsxIdentifier(sequenceLocalName),+ [+ ...(from === null ? [] : [createNumberAttribute('from', from)]),+ ...(name === null ? [] : [createStringAttribute('name', name)]),+ ...(dimensions !== null+ ? [+ createNumberAttribute('width', dimensions.width),+ createNumberAttribute('height', dimensions.height),+ ]+ : []),+ ...(durationInFrames === null+ ? []+ : [createNumberAttribute('durationInFrames', durationInFrames)]),+ createPositionAbsoluteStyleAttribute(position),+ ],+ false,+ ),+ recast.types.builders.jsxClosingElement(+ recast.types.builders.jsxIdentifier(sequenceLocalName),+ ),+ [child],+ );+};++const createAssetElement = ({+ addPositionStyle,+ durationInFrames,+ from,+ localName,+ staticFileLocalName,+ src,+ dimensions,+ position,+}: {+ addPositionStyle: boolean;+ durationInFrames: number | null;+ from: number | null;+ localName: string;+ staticFileLocalName: string | null;+ src: string;+ dimensions: {width: number; height: number} | null;+ position: InsertableCompositionElementPosition | null;+}): namedTypes.JSXElement => {+ return recast.types.builders.jsxElement(+ recast.types.builders.jsxOpeningElement(+ recast.types.builders.jsxIdentifier(localName),+ [+ staticFileLocalName === null+ ? createStringSrcAttribute(src)+ : createStaticFileSrcAttribute({staticFileLocalName, src}),+ ...(durationInFrames === null+ ? []+ : [createNumberAttribute('durationInFrames', durationInFrames)]),+ ...(from === null ? [] : [createNumberAttribute('from', from)]),+ ...(addPositionStyle+ ? [createAssetStyleAttribute({dimensions, position})]+ : []),+ ],+ true,+ ),+ null,+ [],+ );+};++const createSvgElement = async ({+ environment,+ from,+ interactiveLocalName,+ markup,+ position,+}: {+ environment: InsertJsxElementCodemodEnvironment;+ from: number | null;+ interactiveLocalName: string;+ markup: string;+ position: InsertableCompositionElementPosition | null;+}): Promise<namedTypes.JSXElement> => {+ const svgElement = await environment.svgMarkupToJsx(markup);+ const attributes = svgElement.openingElement.attributes ?? [];+ svgElement.openingElement.attributes = attributes;+ if (from !== null) {+ attributes.push(createNumberAttribute('from', from));+ }++ const styleAttribute = attributes.find(+ (attribute) =>+ attribute.type === 'JSXAttribute' &&+ attribute.name.type === 'JSXIdentifier' &&+ attribute.name.name === 'style',+ );+ const positionProperties = getPositionStyleProperties(position);++ if (styleAttribute === undefined) {+ attributes.push(createStyleAttribute(positionProperties));+ } else if (+ styleAttribute.type === 'JSXAttribute' &&+ styleAttribute.value?.type === 'JSXExpressionContainer' &&+ styleAttribute.value.expression.type === 'ObjectExpression'+ ) {+ styleAttribute.value.expression.properties.push(...positionProperties);+ } else {+ throw new Error('Could not convert the root SVG style to JSX');+ }++ const interactiveSvgName = () =>+ recast.types.builders.jsxMemberExpression(+ recast.types.builders.jsxIdentifier(interactiveLocalName),+ recast.types.builders.jsxIdentifier('Svg'),+ );+ svgElement.openingElement.name = interactiveSvgName();+ if (+ svgElement.closingElement !== null &&+ svgElement.closingElement !== undefined+ ) {+ svgElement.closingElement.name = interactiveSvgName();+ }++ return svgElement;+};++const createFragmentWithElement = (element: namedTypes.JSXElement) => {+ return recast.types.builders.jsxFragment(+ recast.types.builders.jsxOpeningFragment(),+ recast.types.builders.jsxClosingFragment(),+ [element],+ );+};++const replaceNullReturnInFunctionLike = ({+ fn,+ element,+}: {+ fn: FunctionLikeNode;+ element: namedTypes.JSXElement;+}): number | null => {+ if (fn.type === 'ArrowFunctionExpression' && fn.body.type === 'NullLiteral') {+ fn.body = createFragmentWithElement(element);+ return fn.loc?.start.line ?? 1;+ }++ if (fn.body.type !== 'BlockStatement') {+ return null;+ }++ const returnStatement = getTopLevelReturnStatement(fn.body.body);+ if (+ !returnStatement?.argument ||+ returnStatement.argument.type !== 'NullLiteral'+ ) {+ return null;+ }++ returnStatement.argument = createFragmentWithElement(element);+ return returnStatement.loc?.start.line ?? 1;+};++const addElementToNullComponentReturn = ({+ declaration,+ element,+}: {+ declaration: LocalComponentDeclaration | DefaultExportDeclaration;+ element: namedTypes.JSXElement;+}): number | null => {+ if (declaration.type === 'VariableDeclarator') {+ if (+ !declaration.init ||+ (declaration.init.type !== 'ArrowFunctionExpression' &&+ declaration.init.type !== 'FunctionExpression')+ ) {+ return null;+ }++ return replaceNullReturnInFunctionLike({fn: declaration.init, element});+ }++ if (+ declaration.type === 'ArrowFunctionExpression' ||+ declaration.type === 'FunctionExpression' ||+ declaration.type === 'FunctionDeclaration'+ ) {+ return replaceNullReturnInFunctionLike({fn: declaration, element});+ }++ if (declaration.type !== 'ClassDeclaration') {+ return null;+ }++ const renderMethod = findRenderMethod(declaration);+ if (!renderMethod) {+ return null;+ }++ const returnStatement = getTopLevelReturnStatement(renderMethod.body.body);+ if (+ !returnStatement?.argument ||+ returnStatement.argument.type !== 'NullLiteral'+ ) {+ return null;+ }++ returnStatement.argument = createFragmentWithElement(element);+ 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 getAvailableSolidLocalName = (ast: File) => {+ const candidates = ['Solid', 'RemotionSolid'];+ const available = candidates.find((candidate) => {+ return !hasTopLevelBinding({ast, name: candidate});+ });++ if (!available) {+ throw new Error('Cannot add <Solid> because Solid is already defined');+ }++ return available;+};++const ensureSolidImport = (ast: File) => {+ return ensureNamedImport({+ ast,+ importedName: 'Solid',+ sourcePath: 'remotion',+ localName: getAvailableSolidLocalName(ast),+ });+};++const getAvailableSequenceLocalName = (ast: File) => {+ const candidates = ['Sequence', 'RemotionSequence'];+ const available = candidates.find((candidate) => {+ return !hasTopLevelBinding({ast, name: candidate});+ });++ if (!available) {+ throw new Error(+ 'Cannot add <Sequence> because Sequence is already defined',+ );+ }++ return available;+};++const ensureSequenceImport = (ast: File) => {+ return ensureNamedImport({+ ast,+ importedName: 'Sequence',+ sourcePath: 'remotion',+ localName: getAvailableSequenceLocalName(ast),+ });+};++const ensureInteractiveImport = (ast: File) => {+ for (const statement of ast.program.body) {+ if (+ statement.type !== 'ImportDeclaration' ||+ statement.source.type !== 'StringLiteral' ||+ statement.source.value !== 'remotion'+ ) {+ continue;+ }++ for (const specifier of statement.specifiers ?? []) {+ if (+ specifier.type === 'ImportSpecifier' &&+ getImportedName(specifier) === 'Interactive'+ ) {+ return specifier.local?.name ?? 'Interactive';+ }+ }+ }++ const candidates = ['Interactive', 'RemotionInteractive'];+ const localName = candidates.find((candidate) => {+ return !hasTopLevelBinding({ast, name: candidate});+ });+ if (localName === undefined) {+ throw new Error(+ 'Cannot add <Interactive.Svg> because Interactive is already defined',+ );+ }++ return ensureNamedImport({+ ast,+ importedName: 'Interactive',+ sourcePath: 'remotion',+ localName,+ });+};++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 importDeclarationHasNamespaceSpecifier = (+ importDeclaration: ImportDeclaration,+) => {+ return importDeclaration.specifiers?.some(+ (specifier) => specifier.type === 'ImportNamespaceSpecifier',+ );+};++const hasOfficialLocalImport = ({+ ast,+ importedName,+ sourcePath,+}: {+ ast: File;+ importedName: string;+ sourcePath: string;+}) => {+ return getImportDeclarations({ast, sourcePath}).some((importDeclaration) => {+ return importDeclaration.specifiers?.some((specifier) => {+ return (+ specifier.type === 'ImportSpecifier' &&+ getImportedName(specifier) === importedName &&+ (specifier.local?.name ?? importedName) === importedName+ );+ });+ });+};++const addOfficialNamedImport = ({+ ast,+ importedName,+ sourcePath,+}: {+ ast: File;+ importedName: string;+ sourcePath: string;+}) => {+ const existingImport = getImportDeclarations({ast, sourcePath}).find(+ (candidate) => !importDeclarationHasNamespaceSpecifier(candidate),+ );+ const importSpecifier = recast.types.builders.importSpecifier(+ recast.types.builders.identifier(importedName),+ ) as unknown as ImportSpecifier;++ if (existingImport) {+ existingImport.specifiers = [+ ...(existingImport.specifiers ?? []),+ importSpecifier,+ ];+ return;+ }++ const importDeclaration = recast.types.builders.importDeclaration(+ [importSpecifier as never],+ recast.types.builders.stringLiteral(sourcePath),+ ) as unknown as ImportDeclaration;+ insertImportDeclaration(ast, importDeclaration);+};++const ensureOfficialNamedImport = ({+ ast,+ importedName,+ sourcePath,+ label,+}: {+ ast: File;+ importedName: string;+ sourcePath: string;+ label: string;+}) => {+ if (hasOfficialLocalImport({ast, importedName, sourcePath})) {+ return importedName;+ }++ if (hasTopLevelBinding({ast, name: importedName})) {+ throw new Error(+ `Cannot add ${label} because ${importedName} is already defined`,+ );+ }++ addOfficialNamedImport({ast, importedName, sourcePath});+ return importedName;+};++const ensureStaticFileImport = (ast: File) => {+ return ensureOfficialNamedImport({+ ast,+ importedName: 'staticFile',+ sourcePath: 'remotion',+ label: 'staticFile()',+ });+};++const ensureCanvasImageImport = (ast: File) => {+ return ensureOfficialNamedImport({+ ast,+ importedName: 'CanvasImage',+ sourcePath: 'remotion',+ label: '<CanvasImage>',+ });+};++const ensureAnimatedImageImport = (ast: File) => {+ return ensureOfficialNamedImport({+ ast,+ importedName: 'AnimatedImage',+ sourcePath: 'remotion',+ label: '<AnimatedImage>',+ });+};++const ensureVideoImport = (ast: File) => {+ return ensureOfficialNamedImport({+ ast,+ importedName: 'Video',+ sourcePath: '@remotion/media',+ label: '<Video>',+ });+};++const ensureAudioImport = (ast: File) => {+ return ensureOfficialNamedImport({+ ast,+ importedName: 'Audio',+ sourcePath: '@remotion/media',+ label: '<Audio>',+ });+};++const ensureGifImport = (ast: File) => {+ return ensureOfficialNamedImport({+ ast,+ importedName: 'Gif',+ sourcePath: '@remotion/gif',+ label: '<Gif>',+ });+};++const hasComponentLocalImport = ({+ ast,+ importName,+ importPath,+}: {+ ast: File;+ importName: string;+ importPath: string;+}) => {+ for (const importDeclaration of getImportDeclarations({+ ast,+ sourcePath: importPath,+ })) {+ if (importDeclaration.importKind === 'type') {+ continue;+ }++ for (const specifier of importDeclaration.specifiers ?? []) {+ if (+ specifier.type === 'ImportSpecifier' &&+ specifier.importKind !== 'type' &&+ getImportedName(specifier) === importName+ ) {+ return specifier.local?.name ?? importName;+ }+ }+ }++ return null;+};++const ensureComponentImport = ({+ ast,+ componentName,+ importName,+ importPath,+}: {+ ast: File;+ componentName: string;+ importName: string;+ importPath: string;+}) => {+ const existingLocalName = hasComponentLocalImport({+ ast,+ importName,+ importPath,+ });++ if (existingLocalName) {+ return existingLocalName;+ }++ if (hasTopLevelBinding({ast, name: componentName})) {+ throw new Error(+ `Cannot add <${componentName}> because ${componentName} is already defined`,+ );+ }++ return ensureNamedImport({+ ast,+ importedName: importName,+ sourcePath: importPath,+ localName: componentName,+ });+};++const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;++const toPascalCaseIdentifier = (value: string) => {+ const words = value.match(/[a-zA-Z0-9]+/g) ?? [];+ const candidate = words+ .map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`)+ .join('');++ if (!candidate) {+ return 'CompositionComponent';+ }++ if (/^[0-9]/.test(candidate)) {+ return `Composition${candidate}`;+ }++ return identifierRegex.test(candidate) ? candidate : 'CompositionComponent';+};++const getAvailableLocalName = ({+ ast,+ baseName,+}: {+ ast: File;+ baseName: string;+}) => {+ if (!hasTopLevelBinding({ast, name: baseName})) {+ return baseName;+ }++ const suffixed = `${baseName}Composition`;+ if (!hasTopLevelBinding({ast, name: suffixed})) {+ return suffixed;+ }++ for (let i = 2; i < 100; i++) {+ const candidate = `${suffixed}${i}`;+ if (!hasTopLevelBinding({ast, name: candidate})) {+ return candidate;+ }+ }++ throw new Error(`Cannot find a local name for ${baseName}`);+};++const getImportPathBetweenFiles = ({+ environment,+ fromFile,+ toFile,+}: {+ environment: InsertJsxElementCodemodEnvironment;+ fromFile: string;+ toFile: string;+}) => {+ let relativeImport = environment+ .relative(environment.dirname(fromFile), toFile)+ .replaceAll(environment.pathSeparator, '/')+ .replace(/\.(tsx|ts|jsx|js)$/, '');++ if (!relativeImport.startsWith('.')) {+ relativeImport = `./${relativeImport}`;+ }++ return relativeImport;+};++const ensureDefaultImport = ({+ ast,+ localName,+ sourcePath,+}: {+ ast: File;+ localName: string;+ sourcePath: string;+}) => {+ for (const declaration of getImportDeclarations({ast, sourcePath})) {+ const defaultSpecifier = declaration.specifiers?.find(+ (specifier) => specifier.type === 'ImportDefaultSpecifier',+ );+ if (defaultSpecifier?.local?.name) {+ return defaultSpecifier.local.name;+ }+ }++ const importSpecifier = recast.types.builders.importDefaultSpecifier(+ recast.types.builders.identifier(localName),+ ) as unknown as ImportDefaultSpecifier;+ const existingImport = getImportDeclarations({ast, sourcePath}).find(+ (declaration) => {+ return !declaration.specifiers?.some(+ (specifier) => specifier.type === 'ImportNamespaceSpecifier',+ );+ },+ );++ if (existingImport) {+ existingImport.specifiers = [+ importSpecifier,+ ...(existingImport.specifiers ?? []),+ ];+ return localName;+ }++ const importDeclaration = recast.types.builders.importDeclaration(+ [importSpecifier as never],+ recast.types.builders.stringLiteral(sourcePath),+ ) as unknown as ImportDeclaration;+ insertImportDeclaration(ast, importDeclaration);+ return localName;+};++const parseSerializedCompositionProps = (+ serializedResolvedPropsWithCustomSchema: string,+) => {+ const parsed: unknown = JSON.parse(serializedResolvedPropsWithCustomSchema);+ if (!isRecord(parsed)) {+ throw new Error('Resolved composition props must be an object');+ }++ return parsed;+};++const containsFileToken = (value: unknown): boolean => {+ if (typeof value === 'string') {+ return value.startsWith(NoReactInternals.FILE_TOKEN);+ }++ if (Array.isArray(value)) {+ return value.some(containsFileToken);+ }++ if (isRecord(value)) {+ return Object.values(value).some(containsFileToken);+ }++ return false;+};++const createExpressionAttribute = (+ name: string,+ value: unknown,+): namedTypes.JSXAttribute => {+ return recast.types.builders.jsxAttribute(+ recast.types.builders.jsxIdentifier(name),+ recast.types.builders.jsxExpressionContainer(+ parseValueExpression(value) as never,+ ),+ ) as unknown as namedTypes.JSXAttribute;+};++const createCompositionPropAttribute = ({+ name,+ value,+}: {+ name: string;+ value: unknown;+}): namedTypes.JSXAttribute => {+ if (+ typeof value === 'string' &&+ !value.startsWith(NoReactInternals.FILE_TOKEN) &&+ !value.startsWith(NoReactInternals.DATE_TOKEN)+ ) {+ return createStringAttribute(name, value) as namedTypes.JSXAttribute;+ }++ return createExpressionAttribute(name, value);+};++const createCompositionObjectProperty = ({+ name,+ value,+}: {+ name: string;+ value: unknown;+}): ObjectProperty => {+ return recast.types.builders.objectProperty(+ identifierRegex.test(name)+ ? recast.types.builders.identifier(name)+ : recast.types.builders.stringLiteral(name),+ parseValueExpression(value) as never,+ ) as unknown as ObjectProperty;+};++const createCompositionComponentElement = ({+ localName,+ props,+}: {+ localName: string;+ props: Record<string, unknown>;+}) => {+ const directAttributes: namedTypes.JSXAttribute[] = [];+ const spreadProperties: ObjectProperty[] = [];++ for (const [name, value] of Object.entries(props)) {+ if (identifierRegex.test(name)) {+ directAttributes.push(createCompositionPropAttribute({name, value}));+ } else {+ spreadProperties.push(createCompositionObjectProperty({name, value}));+ }+ }++ const attributes: (JSXAttribute | JSXSpreadAttribute)[] = [+ ...(directAttributes as unknown as JSXAttribute[]),+ ...(spreadProperties.length === 0+ ? []+ : [+ recast.types.builders.jsxSpreadAttribute(+ recast.types.builders.objectExpression(+ spreadProperties as never,+ ) as never,+ ) as unknown as JSXSpreadAttribute,+ ]),+ ];++ return recast.types.builders.jsxElement(+ recast.types.builders.jsxOpeningElement(+ recast.types.builders.jsxIdentifier(localName),+ attributes as never,+ true,+ ),+ null,+ [],+ );+};++const getDefaultExportDeclaration = (+ ast: File,+): LocalComponentDeclaration | DefaultExportDeclaration | null => {+ let declaration: DefaultExportDeclaration | null = null;+ let identifierName: string | null = null;++ recast.types.visit(ast, {+ visitExportDefaultDeclaration(astPath) {+ if (declaration || identifierName) {+ return false;+ }++ const {node} = astPath;+ if (node.declaration.type === 'Identifier') {+ identifierName = node.declaration.name;+ return false;+ }++ declaration = node.declaration;+ return false;+ },+ });++ if (identifierName) {+ return findLocalComponentDeclaration({ast, name: identifierName});+ }++ return declaration;+};++const getDeclarationByExportName = ({+ ast,+ exportName,+}: {+ ast: File;+ exportName: string | 'default';+}): LocalComponentDeclaration | DefaultExportDeclaration | null => {+ if (exportName === 'default') {+ return getDefaultExportDeclaration(ast);+ }++ return findLocalComponentDeclaration({ast, name: exportName});+};++const addElementToComponentRoot = ({+ ast,+ exportName,+ element,+}: {+ ast: File;+ exportName: string | 'default';+ element: namedTypes.JSXElement;+}) => {+ const declaration = getDeclarationByExportName({ast, exportName});+ if (!declaration) {+ throw new Error('Could not find composition component declaration');+ }++ const rootNode = getComponentRootNode(declaration);+ if (!rootNode) {+ const insertedAt = addElementToNullComponentReturn({declaration, element});+ if (insertedAt !== null) {+ return insertedAt;+ }++ throw new Error('Composition component does not return JSX');+ }++ const CANVAS_ROOT_ELEMENTS = [+ 'ThreeCanvas',+ 'RiveCanvas',+ 'SkiaCanvas',+ 'canvas',+ ];++ if (+ rootNode.type === 'JSXElement' &&+ rootNode.openingElement.name.type === 'JSXIdentifier' &&+ CANVAS_ROOT_ELEMENTS.includes(rootNode.openingElement.name.name)+ ) {+ throw new Error(+ `Cannot insert a JSX element into a composition whose root element is <${rootNode.openingElement.name.name}>`,+ );+ }++ if (rootNode.type === 'JSXElement') {+ const existingRoot = rootNode.openingElement.selfClosing+ ? createSequenceWithChild({+ child: stripParenthesizedExtra(rootNode),+ sequenceLocalName: ensureSequenceImport(ast),+ })+ : stripParenthesizedExtra(rootNode);+ const fragment = recast.types.builders.jsxFragment(+ recast.types.builders.jsxOpeningFragment(),+ recast.types.builders.jsxClosingFragment(),+ [existingRoot, element],+ );+ let replaced = false;+ recast.types.visit(ast, {+ visitJSXElement(astPath) {+ if (astPath.node === rootNode) {+ astPath.replace(fragment);+ replaced = true;+ return false;+ }++ this.traverse(astPath);+ },+ });++ if (!replaced) {+ throw new Error('Could not replace composition component root');+ }++ return rootNode.loc?.start.line ?? 1;+ }++ if (!rootNode.children) {+ throw new Error('Composition component root does not accept children');+ }++ rootNode.children.push(element);+ return rootNode.loc?.start.line ?? 1;+};++const canAddSequenceToComponent = ({+ ast,+ exportName,+}: {+ ast: File;+ exportName: string | 'default';+}): boolean => {+ try {+ addElementToComponentRoot({+ ast,+ exportName,+ element: createSequenceElement(),+ });+ recast.print(ast);+ return true;+ } catch {+ return false;+ }+};++const getComponentLocationInFile = async ({+ environment,+ fileName,+ exportName,+ ast: providedAst,+}: {+ environment: InsertJsxElementCodemodEnvironment;+ fileName: string;+ exportName: string | 'default';+ ast?: File;+}): Promise<ResolvedCompositionComponentWithFile> => {+ const ast =+ providedAst ?? parseAst(await readSourceFile({environment, fileName}));+ const location =+ exportName === 'default'+ ? findDefaultExportLocation(ast)+ : findLocalSymbolLocation({ast, name: exportName});+ const canAddSequence = canAddSequenceToComponent({+ ast,+ exportName,+ });++ return {+ source: environment.relative(environment.rootDir, fileName),+ fileName,+ exportName,+ line: location?.line ?? 1,+ column: location?.column ?? 0,+ canAddSequence,+ };+};++const getComponentLocationRecursively = async ({+ environment,+ fileName,+ exportName,+ visited,+}: {+ environment: InsertJsxElementCodemodEnvironment;+ fileName: string;+ exportName: string | 'default';+ visited: Set<string>;+}): Promise<ResolvedCompositionComponentWithFile> => {+ const key = `${fileName}:${exportName}`;+ if (visited.has(key)) {+ throw new Error(+ `Could not resolve component export "${exportName}" in ${environment.relative(environment.rootDir, fileName)}`,+ );+ }++ visited.add(key);+ try {+ const input = await readSourceFile({environment, fileName});+ const ast = parseAst(input);+ const localDeclaration = getDeclarationByExportName({+ ast,+ exportName,+ });+ if (localDeclaration) {+ return await getComponentLocationInFile({+ environment,+ fileName,+ exportName,+ ast,+ });+ }++ const reExportTargets = findReExportTargets({+ ast,+ exportName,+ });+ for (const target of reExportTargets) {+ try {+ const resolvedImportPath = resolveImportPath({+ environment,+ importPath: target.importPath,+ fromFile: fileName,+ });++ return await getComponentLocationRecursively({+ environment,+ fileName: resolvedImportPath,+ exportName: target.exportName,+ visited,+ });+ } catch {+ continue;+ }+ }++ if (reExportTargets.length > 0) {+ throw new Error(+ `Could not resolve component export "${exportName}" in ${environment.relative(environment.rootDir, fileName)}`,+ );+ }++ return await getComponentLocationInFile({+ environment,+ fileName,+ exportName,+ ast,+ });+ } finally {+ visited.delete(key);+ }+};++export async function resolveCompositionComponentWithFile({+ environment,+ compositionFile,+ compositionId,+}: {+ environment: InsertJsxElementCodemodEnvironment;+ compositionFile: string;+ compositionId: string;+}): Promise<ResolvedCompositionComponentWithFile> {+ const compositionFileName = environment.resolve(+ environment.rootDir,+ compositionFile,+ );+ const input = await readSourceFile({+ environment,+ fileName: compositionFileName,+ });+ const ast = parseAstForReadOnly(input);+ const compositionElement = findCompositionElement({ast, compositionId});+ if (!compositionElement) {+ throw new Error(`Could not find composition "${compositionId}"`);+ }++ const lazyImportPath = getLazyImportPath(compositionElement);+ if (lazyImportPath) {+ const lazyComponentFile = resolveImportPath({+ environment,+ importPath: lazyImportPath,+ fromFile: compositionFileName,+ });+ return getComponentLocationRecursively({+ environment,+ fileName: lazyComponentFile,+ exportName: 'default',+ visited: new Set(),+ });+ }++ const componentName = getComponentIdentifier(compositionElement);+ if (!componentName) {+ throw new Error(+ `Could not find a component prop for composition "${compositionId}"`,+ );+ }++ const importTarget = findImportTarget({ast, componentName});+ if (!importTarget) {+ return getComponentLocationInFile({+ environment,+ fileName: compositionFileName,+ exportName: componentName,+ });+ }++ const importedComponentFile = resolveImportPath({+ environment,+ importPath: importTarget.importPath,+ fromFile: compositionFileName,+ });++ return getComponentLocationRecursively({+ environment,+ fileName: importedComponentFile,+ exportName: importTarget.exportName,+ visited: new Set(),+ });+}++export const resolveCompositionComponent = async ({+ environment,+ compositionFile,+ compositionId,+}: {+ environment: InsertJsxElementCodemodEnvironment;+ compositionFile: string;+ compositionId: string;+}): Promise<ResolvedCompositionComponent> => {+ const {source, line, column, canAddSequence} =+ await resolveCompositionComponentWithFile({+ environment,+ compositionFile,+ compositionId,+ });++ return {+ source,+ line,+ column,+ canAddSequence,+ };+};++const ensureCompositionComponentImport = async ({+ ast,+ compositionFile,+ compositionId,+ destinationFileName,+ environment,+}: {+ ast: File;+ compositionFile: string;+ compositionId: string;+ destinationFileName: string;+ environment: InsertJsxElementCodemodEnvironment;+}) => {+ const sourceLocation = await resolveCompositionComponentWithFile({+ environment,+ compositionFile,+ compositionId,+ });++ if (sourceLocation.fileName === destinationFileName) {+ if (sourceLocation.exportName === 'default') {+ throw new Error(+ 'Cannot insert a composition whose component is a default export in the same file',+ );+ }++ if (!hasTopLevelBinding({ast, name: sourceLocation.exportName})) {+ throw new Error(+ `Cannot find component "${sourceLocation.exportName}" in this file`,+ );+ }++ return sourceLocation.exportName;+ }++ const sourcePath = getImportPathBetweenFiles({+ environment,+ fromFile: destinationFileName,+ toFile: sourceLocation.fileName,+ });++ if (sourceLocation.exportName === 'default') {+ return ensureDefaultImport({+ ast,+ localName: getAvailableLocalName({+ ast,+ baseName: toPascalCaseIdentifier(compositionId),+ }),+ sourcePath,+ });+ }++ return ensureNamedImport({+ ast,+ importedName: sourceLocation.exportName,+ sourcePath,+ localName: getAvailableLocalName({+ ast,+ baseName: sourceLocation.exportName,+ }),+ });+};++const createInsertableJsxElement = ({+ addPositionStyleToComponent,+ ast,+ destinationFileName,+ element,+ environment,+ from,+}: {+ addPositionStyleToComponent: boolean;+ ast: File;+ destinationFileName: string;+ element: InsertableCompositionElement;+ environment: InsertJsxElementCodemodEnvironment;+ from: number | null;+}): Promise<namedTypes.JSXElement> | namedTypes.JSXElement => {+ if (element.type === 'solid') {+ const solidLocalName = ensureSolidImport(ast);++ return createSolidElement({+ localName: solidLocalName,+ width: element.width,+ height: element.height,+ position: element.position,+ });+ }++ if (element.type === 'component') {+ const componentLocalName = ensureComponentImport({+ ast,+ componentName: element.componentName,+ importName: element.importName,+ importPath: element.importPath,+ });++ return createComponentElement({+ addPositionStyle: addPositionStyleToComponent,+ from,+ localName: componentLocalName,+ props: element.props,+ position: element.position,+ });+ }++ if (element.type === 'svg') {+ return createSvgElement({+ environment,+ from,+ interactiveLocalName: ensureInteractiveImport(ast),+ markup: element.markup,+ position: element.position,+ });+ }++ if (element.type === 'composition') {+ return Promise.resolve(+ ensureCompositionComponentImport({+ ast,+ compositionFile: element.compositionFile,+ compositionId: element.compositionId,+ destinationFileName,+ environment,+ }),+ ).then((localName) => {+ const props = parseSerializedCompositionProps(+ element.serializedResolvedPropsWithCustomSchema,+ );+ if (containsFileToken(props)) {+ ensureStaticFileImport(ast);+ }++ return createCompositionComponentElement({localName, props});+ });+ }++ if (element.type === 'asset') {+ if (element.srcType === 'remote' && !isUrl(element.src)) {+ throw new Error('Remote asset source must be a URL');+ }++ const staticFileLocalName =+ element.srcType === 'remote' ? null : ensureStaticFileImport(ast);+ let localName: string;+ if (element.assetType === 'image') {+ localName = ensureCanvasImageImport(ast);+ } else if (element.assetType === 'video') {+ localName = ensureVideoImport(ast);+ } else if (element.assetType === 'gif') {+ localName = ensureGifImport(ast);+ } else if (element.assetType === 'animated-image') {+ localName = ensureAnimatedImageImport(ast);+ } else if (element.assetType === 'audio') {+ localName = ensureAudioImport(ast);+ } else {+ throw new Error('Unsupported asset type');+ }++ return createAssetElement({+ addPositionStyle:+ addPositionStyleToComponent && element.assetType !== 'audio',+ durationInFrames:+ element.assetType === 'image' ? null : element.durationInFrames,+ from,+ localName,+ staticFileLocalName,+ src: element.src,+ dimensions:+ element.assetType === 'image' && from !== null+ ? null+ : element.dimensions,+ position: element.position,+ });+ }++ throw new Error('Unsupported element type');+};++export const insertJsxElementIntoComposition = async ({+ compositionFile,+ compositionId,+ element,+ environment,+ from,+ prettierConfigOverride,+ wrapInSequence,+}: {+ compositionFile: string;+ compositionId: string;+ element: InsertableCompositionElement;+ environment: InsertJsxElementCodemodEnvironment;+ from: number | null;+ prettierConfigOverride: Record<string, unknown> | null;+ wrapInSequence: {+ dimensions: {width: number; height: number} | null;+ durationInFrames: number | null;+ from: number | null;+ name: string | null;+ position: InsertableCompositionElementPosition | null;+ } | null;+}): Promise<{+ fileName: string;+ source: string;+ oldContents: string;+ output: string;+ formatted: boolean;+ logLine: number;+ nodePathRemappings: SequenceNodePathRemapping[];+ insertedNodePath: SequenceNodePath | null;+}> => {+ if (+ from !== null &&+ (!Number.isInteger(from) || !Number.isFinite(from) || from < 0)+ ) {+ throw new Error('from must be a non-negative integer');+ }++ if (+ element.position !== null &&+ (!Number.isFinite(element.position.x) ||+ !Number.isFinite(element.position.y))+ ) {+ throw new Error('Position must be finite');+ }++ const location = await resolveCompositionComponentWithFile({+ environment,+ compositionFile,+ compositionId,+ });+ if (!location.canAddSequence) {+ throw new Error(+ 'Cannot insert JSX element into this composition component',+ );+ }++ const input = await readSourceFile({+ environment,+ fileName: location.fileName,+ });+ const ast = parseAst(input);+ const capturedNodePaths = captureJsxNodePaths(ast);+ if (+ element.type === 'composition' &&+ element.compositionId === compositionId+ ) {+ throw new Error('Cannot insert a composition into itself');+ }++ const sequenceWrapper =+ element.type === 'composition'+ ? {+ dimensions: {width: element.width, height: element.height},+ durationInFrames: element.durationInFrames,+ name: element.compositionId,+ position: element.position,+ from,+ }+ : from === null ||+ element.type === 'asset' ||+ element.type === 'svg' ||+ element.type === 'component'+ ? wrapInSequence+ : {+ dimensions: null,+ durationInFrames: null,+ name: null,+ position: element.position,+ from,+ };+ const elementToInsert = await createInsertableJsxElement({+ addPositionStyleToComponent: sequenceWrapper === null,+ ast,+ destinationFileName: location.fileName,+ element,+ environment,+ from,+ });+ const finalElementToInsert = sequenceWrapper+ ? createSequenceWrappedElement({+ child: elementToInsert,+ dimensions: sequenceWrapper.dimensions,+ durationInFrames: sequenceWrapper.durationInFrames ?? null,+ from: sequenceWrapper.from,+ name: sequenceWrapper.name,+ position: sequenceWrapper.position,+ sequenceLocalName: ensureSequenceImport(ast),+ })+ : elementToInsert;+ const logLine = addElementToComponentRoot({+ ast,+ exportName: location.exportName,+ element: finalElementToInsert,+ });+ const finalFile = serializeAst(ast);++ const {output, formatted} = await environment.formatFile({+ contents: finalFile,+ prettierConfigOverride,+ });+ const {finalNodePathByNode, nodePathRemappings} = getNodePathRemappings({+ ast,+ captured: capturedNodePaths,+ output,+ });+ const insertedNodePath =+ finalNodePathByNode.get(+ finalElementToInsert.openingElement as JSXOpeningElement,+ ) ?? null;++ return {+ fileName: location.fileName,+ source: location.source,+ oldContents: input,+ output,+ formatted,+ insertedNodePath,+ logLine,+ nodePathRemappings,+ };+};++export const insertJsxElementIntoProjectWithNodePathRemappings = async <+ Project extends {files: Record<string, string>; rootDir: string},+>({+ project,+ request,+ formatFile,+ svgMarkupToJsx,+ wrapInSequence,+}: {+ project: Project;+ request: InsertJsxElementRequest;+ formatFile: InsertJsxElementCodemodEnvironment['formatFile'];+ svgMarkupToJsx: InsertJsxElementCodemodEnvironment['svgMarkupToJsx'];+ wrapInSequence: {+ dimensions: {width: number; height: number} | null;+ durationInFrames: number | null;+ from: number | null;+ name: string | null;+ position: InsertableCompositionElementPosition | null;+ } | null;+}): Promise<{+ filePath: string;+ insertedNodePath: SequenceNodePath | null;+ nodePathRemappings: SequenceNodePathRemapping[];+ project: Project;+}> => {+ const result = await insertJsxElementIntoComposition({+ compositionFile: request.compositionFile,+ compositionId: request.compositionId,+ element: request.element,+ environment: makeInMemoryInsertJsxElementCodemodEnvironment({+ formatFile,+ project,+ svgMarkupToJsx,+ }),+ from: request.from,+ prettierConfigOverride: null,+ wrapInSequence,+ });++ return {+ filePath: result.fileName,+ insertedNodePath: result.insertedNodePath,+ nodePathRemappings: result.nodePathRemappings,+ project: {+ ...project,+ files: {...project.files, [result.fileName]: result.output},+ },+ };+};diff --git a/packages/studio-codemods/src/sequence-props/imports.ts b/packages/studio-codemods/src/sequence-props/imports.tsindex 86d1c09f0b..4293791044 100644--- a/packages/studio-codemods/src/sequence-props/imports.ts+++ b/packages/studio-codemods/src/sequence-props/imports.ts@@ -79,9 +79,14 @@ export const ensureNamedImport = ({const existingImports = findImportDeclarations(ast, sourcePath);for (const existingImportDeclaration of existingImports) {+ if (existingImportDeclaration.importKind === 'type') {+ continue;+ }+const matchingSpecifier = existingImportDeclaration.specifiers?.find((importSpecifierCandidate) =>importSpecifierCandidate.type === 'ImportSpecifier' &&+ importSpecifierCandidate.importKind !== 'type' &&getImportedName(importSpecifierCandidate) === importedName,);@@ -92,6 +97,7 @@ export const ensureNamedImport = ({const existingImport = existingImports.find((candidateImportDeclaration) =>+ candidateImportDeclaration.importKind !== 'type' &&!hasNamespaceSpecifier(candidateImportDeclaration),);@@ -137,9 +143,16 @@ export const ensureNamedImports = ({const existingNames = new Set<string>();for (const existingImportDeclaration of existingImports) {+ if (existingImportDeclaration.importKind === 'type') {+ continue;+ }+for (const importSpecifierCandidate of existingImportDeclaration.specifiers ??[]) {- if (importSpecifierCandidate.type !== 'ImportSpecifier') {+ if (+ importSpecifierCandidate.type !== 'ImportSpecifier' ||+ importSpecifierCandidate.importKind === 'type'+ ) {continue;}@@ -153,6 +166,7 @@ export const ensureNamedImports = ({const existingImport = existingImports.find((candidateImportDeclaration) =>+ candidateImportDeclaration.importKind !== 'type' &&!hasNamespaceSpecifier(candidateImportDeclaration),);diff --git a/packages/studio-codemods/src/sequence-props/parse-ast.ts b/packages/studio-codemods/src/sequence-props/parse-ast.tsindex eeb71e4efa..11cb97fca2 100644--- a/packages/studio-codemods/src/sequence-props/parse-ast.ts+++ b/packages/studio-codemods/src/sequence-props/parse-ast.ts@@ -11,6 +11,10 @@ export const parseAst = (input: string) => {}) as File;};+export const parseAstForReadOnly = (input: string) => {+ return tsParser.parse(input) as File;+};+export const serializeAst = (ast: File) => {const raw = recast.print(ast, {parser: tsParser,diff --git a/packages/studio-codemods/src/strip-parenthesized-extra.ts b/packages/studio-codemods/src/strip-parenthesized-extra.tsnew file mode 100644index 0000000000..1b6f458986--- /dev/null+++ b/packages/studio-codemods/src/strip-parenthesized-extra.ts@@ -0,0 +1,20 @@+// When a node was originally parenthesized (e.g. the `<JSX/>` inside+// `return (<JSX/>)`), Babel records `extra.parenthesized` on it. If we move+// such a node into a new JSX parent without clearing that hint, recast prints+// stray `(` / `)` characters around it as JSX text.+export const stripParenthesizedExtra = <T extends object>(node: T): T => {+ const {extra} = node as {extra?: unknown};+ if (!extra) {+ return node;+ }++ const {+ parenthesized: _p,+ parenStart: _ps,+ ...rest+ } = extra as {+ parenthesized?: boolean;+ parenStart?: number;+ };+ return {...node, extra: rest};+};diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.tsindex 5a7fe6b417..b5f37c56a0 100644--- a/packages/studio-server/src/helpers/resolve-composition-component.ts+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts@@ -1,2092 +1,62 @@import fs from 'node:fs';import path from 'node:path';-import type {- ClassDeclaration,- ExportAllDeclaration,- ExportNamedDeclaration,- ExportSpecifier,- File,- FunctionDeclaration,- ImportDeclaration,- ImportDefaultSpecifier,- ImportSpecifier,- JSXAttribute,- JSXElement,- JSXOpeningElement,- JSXSpreadAttribute,- ObjectProperty,- VariableDeclaration,-} from '@babel/types';-import type {ComponentProp} from '@remotion/studio-protocol';import {- isUrl,- type InsertableCompositionElement,- type InsertableCompositionElementPosition,- type SequenceNodePathRemapping,+ insertJsxElementIntoComposition as insertJsxElementIntoCompositionCodemod,+ resolveCompositionComponent as resolveCompositionComponentCodemod,+ resolveCompositionComponentWithFile as resolveCompositionComponentWithFileCodemod,+ type InsertJsxElementCodemodEnvironment,+ type ResolvedCompositionComponent,+ type ResolvedCompositionComponentWithFile,+} from '@remotion/studio-codemods';+import type {+ InsertableCompositionElement,+ InsertableCompositionElementPosition,+ SequenceNodePathRemapping,} from '@remotion/studio-shared';-import type {namedTypes} from 'ast-types';-import * as recast from 'recast';import type {SequenceNodePath} from 'remotion';-import {NoReactInternals} from 'remotion/no-react';import {formatFileContent} from '../codemods/format-file-content';-import {- captureJsxNodePaths,- getNodePathRemappings,-} from '../codemods/get-node-path-remappings';-import {- parseAst,- parseAstForReadOnly,- serializeAst,-} from '../codemods/parse-ast';-import {stripParenthesizedExtra} from '../codemods/strip-parenthesized-extra';-import {parseValueExpression} from '../codemods/update-nested-prop';-import {- ensureNamedImport,- getImportedName,- insertImportDeclaration,-} from './imports';import {svgMarkupToJsx} from './svg-to-jsx';-type SourceLocation = {- line: number;- column: number;-};--type NodeWithLocation = {- loc?: {- start: {- line: number;- column: number;- };- } | null;-};--export type ResolvedCompositionComponent = {- source: string;- line: number;- column: number;- canAddSequence: boolean;-};--export type ResolvedCompositionComponentWithFile =- ResolvedCompositionComponent & {- fileName: string;- exportName: string | 'default';- };--type ImportTarget = {- importPath: string;- exportName: string | 'default';-};--type ReExportTarget = {- importPath: string;- exportName: string | 'default';-};--const allowedFileExtensions = new Set(['.tsx', '.ts', '.jsx', '.js']);-const extensionsToProbe = ['.tsx', '.ts', '.jsx', '.js'];--const isInRemotionRoot = ({+const makeCodemodEnvironment = (+ remotionRoot: string,+): InsertJsxElementCodemodEnvironment => ({+ dirname: path.dirname,+ extname: path.extname,+ fileExists: (fileName) =>+ fs.existsSync(fileName) && fs.statSync(fileName).isFile(),+ formatFile: ({contents, prettierConfigOverride}) =>+ formatFileContent({input: contents, prettierConfigOverride}),+ isAbsolute: path.isAbsolute,+ join: path.join,+ pathSeparator: path.sep,+ readFile: (fileName) => fs.promises.readFile(fileName, 'utf-8'),+ relative: path.relative,+ resolve: path.resolve,+ rootDir: remotionRoot,+ svgMarkupToJsx,+});++export type {+ ResolvedCompositionComponent,+ ResolvedCompositionComponentWithFile,+};++export const resolveCompositionComponentWithFile = ({remotionRoot,- fileName,-}: {- remotionRoot: string;- fileName: string;-}) => {- const relativePath = path.relative(remotionRoot, fileName);- return !relativePath.startsWith('..') && !path.isAbsolute(relativePath);-};--const readSourceFile = ({- remotionRoot,- fileName,-}: {- remotionRoot: string;- fileName: string;-}) => {- const resolved = path.resolve(remotionRoot, fileName);- if (!isInRemotionRoot({remotionRoot, fileName: resolved})) {- throw new Error(`Not allowed to open ${fileName}`);- }-- if (!allowedFileExtensions.has(path.extname(resolved))) {- throw new Error(`Not allowed to open ${fileName}`);- }-- return fs.promises.readFile(resolved, 'utf-8');-};--const getAttributeName = (attribute: JSXAttribute) => {- if (attribute.name.type !== 'JSXIdentifier') {- return null;- }-- return attribute.name.name;-};--const findAttribute = (element: JSXElement, name: string) => {- return element.openingElement.attributes.find((attribute) => {- if (attribute.type !== 'JSXAttribute') {- return false;- }-- return getAttributeName(attribute) === name;- }) as JSXAttribute | undefined;-};--const getStringAttributeValue = (element: JSXElement, name: string) => {- const attribute = findAttribute(element, name);- if (!attribute?.value) {- return null;- }-- if (attribute.value.type === 'StringLiteral') {- return attribute.value.value;- }-- if (- attribute.value.type === 'JSXExpressionContainer' &&- attribute.value.expression.type === 'StringLiteral'- ) {- return attribute.value.expression.value;- }-- return null;-};--const findCompositionElement = ({- ast,- compositionId,-}: {- ast: File;- compositionId: string;-}) => {- let found: JSXElement | null = null;-- recast.types.visit(ast, {- visitJSXElement(astPath) {- if (found) {- return false;- }-- const node = astPath.node as JSXElement;- const openingName = node.openingElement.name;- if (- openingName.type === 'JSXIdentifier' &&- (openingName.name === 'Composition' || openingName.name === 'Still') &&- getStringAttributeValue(node, 'id') === compositionId- ) {- found = node;- return false;- }-- this.traverse(astPath);- return undefined;- },- });-- return found;-};--const getComponentIdentifier = (element: JSXElement) => {- const attribute = findAttribute(element, 'component');- if (- !attribute?.value ||- attribute.value.type !== 'JSXExpressionContainer' ||- attribute.value.expression.type !== 'Identifier'- ) {- return null;- }-- return attribute.value.expression.name;-};--const isRecord = (value: unknown): value is Record<string, unknown> => {- return typeof value === 'object' && value !== null && !Array.isArray(value);-};--const findDynamicImportPath = (value: unknown): string | null => {- if (!isRecord(value)) {- return null;- }-- if (- value.type === 'CallExpression' &&- isRecord(value.callee) &&- value.callee.type === 'Import' &&- Array.isArray(value.arguments) &&- isRecord(value.arguments[0]) &&- value.arguments[0].type === 'StringLiteral' &&- typeof value.arguments[0].value === 'string'- ) {- return value.arguments[0].value;- }-- for (const [key, child] of Object.entries(value)) {- if (- key === 'loc' ||- key === 'start' ||- key === 'end' ||- key === 'comments' ||- key === 'leadingComments' ||- key === 'trailingComments' ||- key === 'innerComments' ||- key === 'extra' ||- key === 'original'- ) {- continue;- }-- if (Array.isArray(child)) {- for (const item of child) {- const nestedResult = findDynamicImportPath(item);- if (nestedResult) {- return nestedResult;- }- }-- continue;- }-- const childResult = findDynamicImportPath(child);- if (childResult) {- return childResult;- }- }-- return null;-};--const getLazyImportPath = (element: JSXElement) => {- const attribute = findAttribute(element, 'lazyComponent');- if (!attribute?.value || attribute.value.type !== 'JSXExpressionContainer') {- return null;- }-- return findDynamicImportPath(attribute.value.expression);-};--const findImportTarget = ({- ast,- componentName,-}: {- ast: File;- componentName: string;-}): ImportTarget | null => {- let found: ImportTarget | null = null;-- recast.types.visit(ast, {- visitImportDeclaration(astPath) {- if (found) {- return false;- }-- const node = astPath.node as ImportDeclaration;- if (typeof node.source.value !== 'string') {- return false;- }-- const matchingSpecifier = node.specifiers?.find((specifier) => {- return specifier.local?.name === componentName;- });- if (!matchingSpecifier) {- return false;- }-- if (matchingSpecifier.type === 'ImportDefaultSpecifier') {- found = {- importPath: node.source.value,- exportName: 'default',- };- return false;- }-- if (- matchingSpecifier.type === 'ImportSpecifier' &&- matchingSpecifier.imported.type === 'Identifier'- ) {- found = {- importPath: node.source.value,- exportName: matchingSpecifier.imported.name,- };- return false;- }-- if (- matchingSpecifier.type === 'ImportSpecifier' &&- matchingSpecifier.imported.type === 'StringLiteral'- ) {- found = {- importPath: node.source.value,- exportName: matchingSpecifier.imported.value,- };- return false;- }-- return false;- },- });-- return found;-};--const getExportedName = (exported: unknown) => {- if (!exported) {- return null;- }-- if (!isRecord(exported)) {- return null;- }-- if (exported.type === 'Identifier' && typeof exported.name === 'string') {- return exported.name;- }-- if (exported.type === 'StringLiteral' && typeof exported.value === 'string') {- return exported.value;- }-- return null;-};--const getSpecifierLocalName = (specifier: ExportSpecifier) => {- if (specifier.local.type === 'Identifier') {- return specifier.local.name;- }-- return null;-};--const findReExportTargets = ({- ast,- exportName,-}: {- ast: File;- exportName: string | 'default';-}) => {- const targets: ReExportTarget[] = [];-- recast.types.visit(ast, {- visitExportNamedDeclaration(astPath) {- const node = astPath.node as ExportNamedDeclaration;-- for (const specifier of node.specifiers) {- if (specifier.type !== 'ExportSpecifier') {- continue;- }-- const exportedName = getExportedName(specifier.exported);- if (exportedName !== exportName) {- continue;- }-- const localName = getSpecifierLocalName(specifier);- if (!localName) {- continue;- }-- // Support barrel files that import a component and export it in a- // separate declaration. See https://github.com/remotion-dev/remotion/issues/9172.- if (typeof node.source?.value !== 'string') {- const importTarget = findImportTarget({- ast,- componentName: localName,- });- if (importTarget) {- targets.push(importTarget);- }-- continue;- }-- targets.push({- importPath: node.source.value,- exportName: localName === 'default' ? 'default' : localName,- });- }-- return false;- },- visitExportAllDeclaration(astPath) {- const node = astPath.node as ExportAllDeclaration;- if (typeof node.source.value !== 'string') {- return false;- }-- targets.push({- importPath: node.source.value,- exportName,- });-- return false;- },- });-- return targets;-};--const resolveImportPath = ({- importPath,- fromFile,-}: {- importPath: string;- fromFile: string;-}) => {- if (!importPath.startsWith('.')) {- throw new Error(`Cannot resolve non-relative import ${importPath}`);- }-- const basePath = path.resolve(path.dirname(fromFile), importPath);- const candidates = path.extname(basePath)- ? [basePath]- : [- ...extensionsToProbe.map((extension) => `${basePath}${extension}`),- ...extensionsToProbe.map((extension) =>- path.join(basePath, `index${extension}`),- ),- ];-- const existingFile = candidates.find((candidate) => {- return fs.existsSync(candidate) && fs.statSync(candidate).isFile();- });- if (!existingFile) {- throw new Error(`Could not find imported component file ${importPath}`);- }-- return existingFile;-};--const locationFromNode = (node: NodeWithLocation): SourceLocation | null => {- if (!node.loc) {- return null;- }-- return {- line: node.loc.start.line,- column: node.loc.start.column,- };-};--const findLocalSymbolLocation = ({- ast,- name,-}: {- ast: File;- name: string;-}): SourceLocation | null => {- let location: SourceLocation | null = null;-- // Recast can omit the declaration location for exported functions and- // classes, including components resolved through barrel files. The identifier- // keeps its location. See https://github.com/remotion-dev/remotion/issues/9172.- recast.types.visit(ast, {- visitVariableDeclarator(astPath) {- if (location) {- return false;- }-- const {node} = astPath;- if (node.id.type === 'Identifier' && node.id.name === name) {- location = locationFromNode(node.id);- return false;- }-- this.traverse(astPath);- return undefined;- },- visitFunctionDeclaration(astPath) {- if (location) {- return false;- }-- const {node} = astPath;- if (node.id?.name === name) {- location = locationFromNode(node.id);- return false;- }-- this.traverse(astPath);- return undefined;- },- visitClassDeclaration(astPath) {- if (location) {- return false;- }-- const {node} = astPath;- if (node.id?.name === name) {- location = locationFromNode(node.id);- return false;- }-- this.traverse(astPath);- return undefined;- },- });-- return location;-};--const findDefaultExportLocation = (ast: File): SourceLocation | null => {- let location: SourceLocation | null = null;- let exportedIdentifier: string | null = null;-- recast.types.visit(ast, {- visitExportDefaultDeclaration(astPath) {- if (location || exportedIdentifier) {- return false;- }-- const {node} = astPath;- if (node.declaration.type === 'Identifier') {- exportedIdentifier = node.declaration.name;- return false;- }-- location = locationFromNode(node.declaration) ?? locationFromNode(node);- return false;- },- });-- if (exportedIdentifier) {- return findLocalSymbolLocation({ast, name: exportedIdentifier});- }-- return location;-};--type LocalComponentDeclaration =- | namedTypes.VariableDeclarator- | namedTypes.FunctionDeclaration- | namedTypes.ClassDeclaration;--type FunctionLikeNode =- | namedTypes.ArrowFunctionExpression- | namedTypes.FunctionExpression- | namedTypes.FunctionDeclaration;--type DefaultExportDeclaration =- namedTypes.ExportDefaultDeclaration['declaration'];--const findLocalComponentDeclaration = ({- ast,- name,-}: {- ast: File;- name: string;-}): LocalComponentDeclaration | null => {- let declaration: LocalComponentDeclaration | null = null;-- recast.types.visit(ast, {- visitVariableDeclarator(astPath) {- if (declaration) {- return false;- }-- const {node} = astPath;- if (node.id.type === 'Identifier' && node.id.name === name) {- declaration = node;- return false;- }-- this.traverse(astPath);- return undefined;- },- visitFunctionDeclaration(astPath) {- if (declaration) {- return false;- }-- const {node} = astPath;- if (node.id?.name === name) {- declaration = node;- return false;- }-- this.traverse(astPath);- return undefined;- },- visitClassDeclaration(astPath) {- if (declaration) {- return false;- }-- const {node} = astPath;- if (node.id?.name === name) {- declaration = node;- return false;- }-- this.traverse(astPath);- return undefined;- },- });-- return declaration;-};--const getTopLevelReturnStatement = (- statements: namedTypes.Statement[],-): namedTypes.ReturnStatement | null => {- const returnStatements: namedTypes.ReturnStatement[] = [];- for (const statement of statements) {- if (recast.types.namedTypes.ReturnStatement.check(statement)) {- returnStatements.push(statement);- }- }-- if (returnStatements.length !== 1) {- return null;- }-- const singleReturn = returnStatements[0];- const finalStatement = statements.at(-1);- if (singleReturn !== finalStatement) {- return null;- }-- return singleReturn;-};--const getReturnedJsxFromFunction = (- fn: FunctionLikeNode,-): namedTypes.JSXElement | namedTypes.JSXFragment | null => {- if (fn.type === 'ArrowFunctionExpression') {- if (fn.body.type === 'JSXElement' || fn.body.type === 'JSXFragment') {- return fn.body;- }-- if (fn.body.type !== 'BlockStatement') {- return null;- }-- const arrowReturnStatement = getTopLevelReturnStatement(fn.body.body);- if (!arrowReturnStatement?.argument) {- return null;- }-- return arrowReturnStatement.argument.type === 'JSXElement' ||- arrowReturnStatement.argument.type === 'JSXFragment'- ? arrowReturnStatement.argument- : null;- }-- if (fn.body.type !== 'BlockStatement') {- return null;- }-- const returnStatement = getTopLevelReturnStatement(fn.body.body);- if (!returnStatement?.argument) {- return null;- }-- return returnStatement.argument.type === 'JSXElement' ||- returnStatement.argument.type === 'JSXFragment'- ? returnStatement.argument- : null;-};--const findRenderMethod = (- declaration: namedTypes.ClassDeclaration,-): namedTypes.ClassMethod | null => {- const renderMethod = declaration.body.body.find((member) => {- return (- member.type === 'ClassMethod' &&- member.kind === 'method' &&- member.key.type === 'Identifier' &&- member.key.name === 'render'- );- });-- return renderMethod?.type === 'ClassMethod' ? renderMethod : null;-};--const getComponentRootNode = (- declaration: LocalComponentDeclaration | DefaultExportDeclaration,-): namedTypes.JSXElement | namedTypes.JSXFragment | null => {- if (declaration.type === 'VariableDeclarator') {- if (- !declaration.init ||- (declaration.init.type !== 'ArrowFunctionExpression' &&- declaration.init.type !== 'FunctionExpression')- ) {- return null;- }-- return getReturnedJsxFromFunction(declaration.init);- }-- if (- declaration.type === 'ArrowFunctionExpression' ||- declaration.type === 'FunctionExpression' ||- declaration.type === 'FunctionDeclaration'- ) {- return getReturnedJsxFromFunction(declaration);- }-- if (declaration.type !== 'ClassDeclaration') {- return null;- }-- const renderMethod = findRenderMethod(declaration);- if (!renderMethod) {- return null;- }-- const returnStatement = getTopLevelReturnStatement(renderMethod.body.body);- if (!returnStatement?.argument) {- return null;- }-- return returnStatement.argument.type === 'JSXElement' ||- returnStatement.argument.type === 'JSXFragment'- ? returnStatement.argument- : null;-};--const createSequenceElement = (): namedTypes.JSXElement => {- return recast.types.builders.jsxElement(- recast.types.builders.jsxOpeningElement(- recast.types.builders.jsxIdentifier('Sequence'),- [],- ),- recast.types.builders.jsxClosingElement(- recast.types.builders.jsxIdentifier('Sequence'),- ),- [],- );-};--const createSequenceWithChild = ({- child,- sequenceLocalName,-}: {- child: namedTypes.JSXElement;- sequenceLocalName: string;-}): namedTypes.JSXElement => {- return recast.types.builders.jsxElement(- recast.types.builders.jsxOpeningElement(- recast.types.builders.jsxIdentifier(sequenceLocalName),- [],- ),- recast.types.builders.jsxClosingElement(- recast.types.builders.jsxIdentifier(sequenceLocalName),- ),- [child],- );-};--const createNumberAttribute = (- name: string,- value: number,-): namedTypes.JSXAttribute => {- return recast.types.builders.jsxAttribute(- recast.types.builders.jsxIdentifier(name),- recast.types.builders.jsxExpressionContainer(- recast.types.builders.numericLiteral(value),- ),- );-};--const createStringAttribute = (- name: string,- value: string,-): namedTypes.JSXAttribute => {- return recast.types.builders.jsxAttribute(- recast.types.builders.jsxIdentifier(name),- recast.types.builders.stringLiteral(value),- );-};--const createBooleanAttribute = (- name: string,- value: boolean,-): namedTypes.JSXAttribute => {- return recast.types.builders.jsxAttribute(- recast.types.builders.jsxIdentifier(name),- recast.types.builders.jsxExpressionContainer(- recast.types.builders.booleanLiteral(value),- ),- );-};--const translateDecimalPlaces = 1;--const roundTranslateCoordinate = (value: number): number => {- const factor = 10 ** translateDecimalPlaces;- const rounded = Math.round(value * factor) / factor;- return Object.is(rounded, -0) ? 0 : rounded;-};--const formatTranslateValue = ({x, y}: InsertableCompositionElementPosition) =>- `${roundTranslateCoordinate(x)}px ${roundTranslateCoordinate(y)}px`;--const createStyleAttribute = (- properties: namedTypes.ObjectProperty[],-): namedTypes.JSXAttribute => {- return recast.types.builders.jsxAttribute(- recast.types.builders.jsxIdentifier('style'),- recast.types.builders.jsxExpressionContainer(- recast.types.builders.objectExpression(properties),- ),- );-};--const getPositionStyleProperties = (- position: InsertableCompositionElementPosition | null,-): namedTypes.ObjectProperty[] => {- const properties = [- recast.types.builders.objectProperty(- recast.types.builders.identifier('position'),- recast.types.builders.stringLiteral('absolute'),- ),- ];-- if (position) {- properties.push(- recast.types.builders.objectProperty(- recast.types.builders.identifier('translate'),- recast.types.builders.stringLiteral(formatTranslateValue(position)),- ),- );- }-- return properties;-};--const createPositionAbsoluteStyleAttribute = (- position: InsertableCompositionElementPosition | null,-): namedTypes.JSXAttribute => {- return createStyleAttribute(getPositionStyleProperties(position));-};--const createAssetStyleAttribute = ({- dimensions,- position,-}: {- dimensions: {width: number; height: number} | null;- position: InsertableCompositionElementPosition | null;-}): namedTypes.JSXAttribute => {- return createStyleAttribute([- ...getPositionStyleProperties(position),- ...(dimensions- ? [- recast.types.builders.objectProperty(- recast.types.builders.identifier('width'),- recast.types.builders.numericLiteral(dimensions.width),- ),- recast.types.builders.objectProperty(- recast.types.builders.identifier('height'),- recast.types.builders.numericLiteral(dimensions.height),- ),- ]- : []),- ]);-};--const createStaticFileSrcAttribute = ({- staticFileLocalName,- src,-}: {- staticFileLocalName: string;- src: string;-}): namedTypes.JSXAttribute => {- return recast.types.builders.jsxAttribute(- recast.types.builders.jsxIdentifier('src'),- recast.types.builders.jsxExpressionContainer(- recast.types.builders.callExpression(- recast.types.builders.identifier(staticFileLocalName),- [recast.types.builders.stringLiteral(src)],- ),- ),- );-};--const createComponentProp = ({- name,- value,-}: ComponentProp): namedTypes.JSXAttribute => {- if (typeof value === 'number') {- return createNumberAttribute(name, value);- }-- if (typeof value === 'boolean') {- return createBooleanAttribute(name, value);- }-- return createStringAttribute(name, value);-};--const createStringSrcAttribute = (src: string): namedTypes.JSXAttribute => {- return recast.types.builders.jsxAttribute(- recast.types.builders.jsxIdentifier('src'),- recast.types.builders.stringLiteral(src),- );-};--const createSolidElement = ({- localName,- width,- height,- position,-}: {- localName: string;- width: number;- height: number;- position: InsertableCompositionElementPosition | null;-}): namedTypes.JSXElement => {- return recast.types.builders.jsxElement(- recast.types.builders.jsxOpeningElement(- recast.types.builders.jsxIdentifier(localName),- [- createNumberAttribute('width', width),- createNumberAttribute('height', height),- createStringAttribute('color', 'gray'),- createPositionAbsoluteStyleAttribute(position),- ],- true,- ),- null,- [],- );-};--const createComponentElement = ({- addPositionStyle,- from,- localName,- props,- position,-}: {- addPositionStyle: boolean;- from: number | null;- localName: string;- props: ComponentProp[];- position: InsertableCompositionElementPosition | null;-}): namedTypes.JSXElement => {- return recast.types.builders.jsxElement(- recast.types.builders.jsxOpeningElement(- recast.types.builders.jsxIdentifier(localName),- [- ...props.map(createComponentProp),- ...(from === null ? [] : [createNumberAttribute('from', from)]),- ...(addPositionStyle- ? [createPositionAbsoluteStyleAttribute(position)]- : []),- ],- true,- ),- null,- [],- );-};--const createSequenceWrappedElement = ({- child,- dimensions,- durationInFrames,- from,- name,- position,- sequenceLocalName,-}: {- child: namedTypes.JSXElement;- dimensions: {width: number; height: number} | null;- durationInFrames: number | null;- from: number | null;- name: string | null;- position: InsertableCompositionElementPosition | null;- sequenceLocalName: string;-}): namedTypes.JSXElement => {- return recast.types.builders.jsxElement(- recast.types.builders.jsxOpeningElement(- recast.types.builders.jsxIdentifier(sequenceLocalName),- [- ...(from === null ? [] : [createNumberAttribute('from', from)]),- ...(name === null ? [] : [createStringAttribute('name', name)]),- ...(dimensions !== null- ? [- createNumberAttribute('width', dimensions.width),- createNumberAttribute('height', dimensions.height),- ]- : []),- ...(durationInFrames === null- ? []- : [createNumberAttribute('durationInFrames', durationInFrames)]),- createPositionAbsoluteStyleAttribute(position),- ],- false,- ),- recast.types.builders.jsxClosingElement(- recast.types.builders.jsxIdentifier(sequenceLocalName),- ),- [child],- );-};--const createAssetElement = ({- addPositionStyle,- durationInFrames,- from,- localName,- staticFileLocalName,- src,- dimensions,- position,-}: {- addPositionStyle: boolean;- durationInFrames: number | null;- from: number | null;- localName: string;- staticFileLocalName: string | null;- src: string;- dimensions: {width: number; height: number} | null;- position: InsertableCompositionElementPosition | null;-}): namedTypes.JSXElement => {- return recast.types.builders.jsxElement(- recast.types.builders.jsxOpeningElement(- recast.types.builders.jsxIdentifier(localName),- [- staticFileLocalName === null- ? createStringSrcAttribute(src)- : createStaticFileSrcAttribute({staticFileLocalName, src}),- ...(durationInFrames === null- ? []- : [createNumberAttribute('durationInFrames', durationInFrames)]),- ...(from === null ? [] : [createNumberAttribute('from', from)]),- ...(addPositionStyle- ? [createAssetStyleAttribute({dimensions, position})]- : []),- ],- true,- ),- null,- [],- );-};--const createSvgElement = async ({- from,- interactiveLocalName,- markup,- position,-}: {- from: number | null;- interactiveLocalName: string;- markup: string;- position: InsertableCompositionElementPosition | null;-}): Promise<namedTypes.JSXElement> => {- const svgElement = await svgMarkupToJsx(markup);- const attributes = svgElement.openingElement.attributes ?? [];- svgElement.openingElement.attributes = attributes;- if (from !== null) {- attributes.push(createNumberAttribute('from', from));- }-- const styleAttribute = attributes.find(- (attribute) =>- attribute.type === 'JSXAttribute' &&- attribute.name.type === 'JSXIdentifier' &&- attribute.name.name === 'style',- );- const positionProperties = getPositionStyleProperties(position);-- if (styleAttribute === undefined) {- attributes.push(createStyleAttribute(positionProperties));- } else if (- styleAttribute.type === 'JSXAttribute' &&- styleAttribute.value?.type === 'JSXExpressionContainer' &&- styleAttribute.value.expression.type === 'ObjectExpression'- ) {- styleAttribute.value.expression.properties.push(...positionProperties);- } else {- throw new Error('Could not convert the root SVG style to JSX');- }-- const interactiveSvgName = () =>- recast.types.builders.jsxMemberExpression(- recast.types.builders.jsxIdentifier(interactiveLocalName),- recast.types.builders.jsxIdentifier('Svg'),- );- svgElement.openingElement.name = interactiveSvgName();- if (- svgElement.closingElement !== null &&- svgElement.closingElement !== undefined- ) {- svgElement.closingElement.name = interactiveSvgName();- }-- return svgElement;-};--const createFragmentWithElement = (element: namedTypes.JSXElement) => {- return recast.types.builders.jsxFragment(- recast.types.builders.jsxOpeningFragment(),- recast.types.builders.jsxClosingFragment(),- [element],- );-};--const replaceNullReturnInFunctionLike = ({- fn,- element,-}: {- fn: FunctionLikeNode;- element: namedTypes.JSXElement;-}): number | null => {- if (fn.type === 'ArrowFunctionExpression' && fn.body.type === 'NullLiteral') {- fn.body = createFragmentWithElement(element);- return fn.loc?.start.line ?? 1;- }-- if (fn.body.type !== 'BlockStatement') {- return null;- }-- const returnStatement = getTopLevelReturnStatement(fn.body.body);- if (- !returnStatement?.argument ||- returnStatement.argument.type !== 'NullLiteral'- ) {- return null;- }-- returnStatement.argument = createFragmentWithElement(element);- return returnStatement.loc?.start.line ?? 1;-};--const addElementToNullComponentReturn = ({- declaration,- element,-}: {- declaration: LocalComponentDeclaration | DefaultExportDeclaration;- element: namedTypes.JSXElement;-}): number | null => {- if (declaration.type === 'VariableDeclarator') {- if (- !declaration.init ||- (declaration.init.type !== 'ArrowFunctionExpression' &&- declaration.init.type !== 'FunctionExpression')- ) {- return null;- }-- return replaceNullReturnInFunctionLike({fn: declaration.init, element});- }-- if (- declaration.type === 'ArrowFunctionExpression' ||- declaration.type === 'FunctionExpression' ||- declaration.type === 'FunctionDeclaration'- ) {- return replaceNullReturnInFunctionLike({fn: declaration, element});- }-- if (declaration.type !== 'ClassDeclaration') {- return null;- }-- const renderMethod = findRenderMethod(declaration);- if (!renderMethod) {- return null;- }-- const returnStatement = getTopLevelReturnStatement(renderMethod.body.body);- if (- !returnStatement?.argument ||- returnStatement.argument.type !== 'NullLiteral'- ) {- return null;- }-- returnStatement.argument = createFragmentWithElement(element);- 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 getAvailableSolidLocalName = (ast: File) => {- const candidates = ['Solid', 'RemotionSolid'];- const available = candidates.find((candidate) => {- return !hasTopLevelBinding({ast, name: candidate});- });-- if (!available) {- throw new Error('Cannot add <Solid> because Solid is already defined');- }-- return available;-};--const ensureSolidImport = (ast: File) => {- return ensureNamedImport({- ast,- importedName: 'Solid',- sourcePath: 'remotion',- localName: getAvailableSolidLocalName(ast),- });-};--const getAvailableSequenceLocalName = (ast: File) => {- const candidates = ['Sequence', 'RemotionSequence'];- const available = candidates.find((candidate) => {- return !hasTopLevelBinding({ast, name: candidate});- });-- if (!available) {- throw new Error(- 'Cannot add <Sequence> because Sequence is already defined',- );- }-- return available;-};--const ensureSequenceImport = (ast: File) => {- return ensureNamedImport({- ast,- importedName: 'Sequence',- sourcePath: 'remotion',- localName: getAvailableSequenceLocalName(ast),- });-};--const ensureInteractiveImport = (ast: File) => {- for (const statement of ast.program.body) {- if (- statement.type !== 'ImportDeclaration' ||- statement.source.type !== 'StringLiteral' ||- statement.source.value !== 'remotion'- ) {- continue;- }-- for (const specifier of statement.specifiers ?? []) {- if (- specifier.type === 'ImportSpecifier' &&- getImportedName(specifier) === 'Interactive'- ) {- return specifier.local?.name ?? 'Interactive';- }- }- }-- const candidates = ['Interactive', 'RemotionInteractive'];- const localName = candidates.find((candidate) => {- return !hasTopLevelBinding({ast, name: candidate});- });- if (localName === undefined) {- throw new Error(- 'Cannot add <Interactive.Svg> because Interactive is already defined',- );- }-- return ensureNamedImport({- ast,- importedName: 'Interactive',- sourcePath: 'remotion',- localName,- });-};--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 importDeclarationHasNamespaceSpecifier = (- importDeclaration: ImportDeclaration,-) => {- return importDeclaration.specifiers?.some(- (specifier) => specifier.type === 'ImportNamespaceSpecifier',- );-};--const hasOfficialLocalImport = ({- ast,- importedName,- sourcePath,-}: {- ast: File;- importedName: string;- sourcePath: string;-}) => {- return getImportDeclarations({ast, sourcePath}).some((importDeclaration) => {- return importDeclaration.specifiers?.some((specifier) => {- return (- specifier.type === 'ImportSpecifier' &&- getImportedName(specifier) === importedName &&- (specifier.local?.name ?? importedName) === importedName- );- });- });-};--const addOfficialNamedImport = ({- ast,- importedName,- sourcePath,-}: {- ast: File;- importedName: string;- sourcePath: string;-}) => {- const existingImport = getImportDeclarations({ast, sourcePath}).find(- (candidate) => !importDeclarationHasNamespaceSpecifier(candidate),- );- const importSpecifier = recast.types.builders.importSpecifier(- recast.types.builders.identifier(importedName),- ) as unknown as ImportSpecifier;-- if (existingImport) {- existingImport.specifiers = [- ...(existingImport.specifiers ?? []),- importSpecifier,- ];- return;- }-- const importDeclaration = recast.types.builders.importDeclaration(- [importSpecifier as never],- recast.types.builders.stringLiteral(sourcePath),- ) as unknown as ImportDeclaration;- insertImportDeclaration(ast, importDeclaration);-};--const ensureOfficialNamedImport = ({- ast,- importedName,- sourcePath,- label,-}: {- ast: File;- importedName: string;- sourcePath: string;- label: string;-}) => {- if (hasOfficialLocalImport({ast, importedName, sourcePath})) {- return importedName;- }-- if (hasTopLevelBinding({ast, name: importedName})) {- throw new Error(- `Cannot add ${label} because ${importedName} is already defined`,- );- }-- addOfficialNamedImport({ast, importedName, sourcePath});- return importedName;-};--const ensureStaticFileImport = (ast: File) => {- return ensureOfficialNamedImport({- ast,- importedName: 'staticFile',- sourcePath: 'remotion',- label: 'staticFile()',- });-};--const ensureCanvasImageImport = (ast: File) => {- return ensureOfficialNamedImport({- ast,- importedName: 'CanvasImage',- sourcePath: 'remotion',- label: '<CanvasImage>',- });-};--const ensureAnimatedImageImport = (ast: File) => {- return ensureOfficialNamedImport({- ast,- importedName: 'AnimatedImage',- sourcePath: 'remotion',- label: '<AnimatedImage>',- });-};--const ensureVideoImport = (ast: File) => {- return ensureOfficialNamedImport({- ast,- importedName: 'Video',- sourcePath: '@remotion/media',- label: '<Video>',- });-};--const ensureAudioImport = (ast: File) => {- return ensureOfficialNamedImport({- ast,- importedName: 'Audio',- sourcePath: '@remotion/media',- label: '<Audio>',- });-};--const ensureGifImport = (ast: File) => {- return ensureOfficialNamedImport({- ast,- importedName: 'Gif',- sourcePath: '@remotion/gif',- label: '<Gif>',- });-};--const hasComponentLocalImport = ({- ast,- importName,- importPath,-}: {- ast: File;- importName: string;- importPath: string;-}) => {- for (const importDeclaration of getImportDeclarations({- ast,- sourcePath: importPath,- })) {- for (const specifier of importDeclaration.specifiers ?? []) {- if (- specifier.type === 'ImportSpecifier' &&- getImportedName(specifier) === importName- ) {- return specifier.local?.name ?? importName;- }- }- }-- return null;-};--const ensureComponentImport = ({- ast,- componentName,- importName,- importPath,-}: {- ast: File;- componentName: string;- importName: string;- importPath: string;-}) => {- const existingLocalName = hasComponentLocalImport({- ast,- importName,- importPath,- });-- if (existingLocalName) {- return existingLocalName;- }-- if (hasTopLevelBinding({ast, name: componentName})) {- throw new Error(- `Cannot add <${componentName}> because ${componentName} is already defined`,- );- }-- return ensureNamedImport({- ast,- importedName: importName,- sourcePath: importPath,- localName: componentName,- });-};--const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;--const toPascalCaseIdentifier = (value: string) => {- const words = value.match(/[a-zA-Z0-9]+/g) ?? [];- const candidate = words- .map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`)- .join('');-- if (!candidate) {- return 'CompositionComponent';- }-- if (/^[0-9]/.test(candidate)) {- return `Composition${candidate}`;- }-- return identifierRegex.test(candidate) ? candidate : 'CompositionComponent';-};--const getAvailableLocalName = ({- ast,- baseName,-}: {- ast: File;- baseName: string;-}) => {- if (!hasTopLevelBinding({ast, name: baseName})) {- return baseName;- }-- const suffixed = `${baseName}Composition`;- if (!hasTopLevelBinding({ast, name: suffixed})) {- return suffixed;- }-- for (let i = 2; i < 100; i++) {- const candidate = `${suffixed}${i}`;- if (!hasTopLevelBinding({ast, name: candidate})) {- return candidate;- }- }-- throw new Error(`Cannot find a local name for ${baseName}`);-};--const getImportPathBetweenFiles = ({- fromFile,- toFile,-}: {- fromFile: string;- toFile: string;-}) => {- let relativeImport = path- .relative(path.dirname(fromFile), toFile)- .replaceAll(path.sep, '/')- .replace(/\.(tsx|ts|jsx|js)$/, '');-- if (!relativeImport.startsWith('.')) {- relativeImport = `./${relativeImport}`;- }-- return relativeImport;-};--const ensureDefaultImport = ({- ast,- localName,- sourcePath,-}: {- ast: File;- localName: string;- sourcePath: string;-}) => {- for (const declaration of getImportDeclarations({ast, sourcePath})) {- const defaultSpecifier = declaration.specifiers?.find(- (specifier) => specifier.type === 'ImportDefaultSpecifier',- );- if (defaultSpecifier?.local?.name) {- return defaultSpecifier.local.name;- }- }-- const importSpecifier = recast.types.builders.importDefaultSpecifier(- recast.types.builders.identifier(localName),- ) as unknown as ImportDefaultSpecifier;- const existingImport = getImportDeclarations({ast, sourcePath}).find(- (declaration) => {- return !declaration.specifiers?.some(- (specifier) => specifier.type === 'ImportNamespaceSpecifier',- );- },- );-- if (existingImport) {- existingImport.specifiers = [- importSpecifier,- ...(existingImport.specifiers ?? []),- ];- return localName;- }-- const importDeclaration = recast.types.builders.importDeclaration(- [importSpecifier as never],- recast.types.builders.stringLiteral(sourcePath),- ) as unknown as ImportDeclaration;- insertImportDeclaration(ast, importDeclaration);- return localName;-};--const ensureCompositionComponentImport = async ({- ast,compositionFile,compositionId,- destinationFileName,- remotionRoot,}: {- ast: File;+ remotionRoot: string;compositionFile: string;compositionId: string;- destinationFileName: string;- remotionRoot: string;-}) => {- const sourceLocation = await resolveCompositionComponentWithFile({- remotionRoot,+}): Promise<ResolvedCompositionComponentWithFile> =>+ resolveCompositionComponentWithFileCodemod({compositionFile,compositionId,+ environment: makeCodemodEnvironment(remotionRoot),});- if (sourceLocation.fileName === destinationFileName) {- if (sourceLocation.exportName === 'default') {- throw new Error(- 'Cannot insert a composition whose component is a default export in the same file',- );- }-- if (!hasTopLevelBinding({ast, name: sourceLocation.exportName})) {- throw new Error(- `Cannot find component "${sourceLocation.exportName}" in this file`,- );- }-- return sourceLocation.exportName;- }-- const sourcePath = getImportPathBetweenFiles({- fromFile: destinationFileName,- toFile: sourceLocation.fileName,- });-- if (sourceLocation.exportName === 'default') {- return ensureDefaultImport({- ast,- localName: getAvailableLocalName({- ast,- baseName: toPascalCaseIdentifier(compositionId),- }),- sourcePath,- });- }-- return ensureNamedImport({- ast,- importedName: sourceLocation.exportName,- sourcePath,- localName: getAvailableLocalName({- ast,- baseName: sourceLocation.exportName,- }),- });-};--const parseSerializedCompositionProps = (- serializedResolvedPropsWithCustomSchema: string,-) => {- const parsed: unknown = JSON.parse(serializedResolvedPropsWithCustomSchema);- if (!isRecord(parsed)) {- throw new Error('Resolved composition props must be an object');- }-- return parsed;-};--const containsFileToken = (value: unknown): boolean => {- if (typeof value === 'string') {- return value.startsWith(NoReactInternals.FILE_TOKEN);- }-- if (Array.isArray(value)) {- return value.some(containsFileToken);- }-- if (isRecord(value)) {- return Object.values(value).some(containsFileToken);- }-- return false;-};--const createExpressionAttribute = (- name: string,- value: unknown,-): namedTypes.JSXAttribute => {- return recast.types.builders.jsxAttribute(- recast.types.builders.jsxIdentifier(name),- recast.types.builders.jsxExpressionContainer(- parseValueExpression(value) as never,- ),- ) as unknown as namedTypes.JSXAttribute;-};--const createCompositionPropAttribute = ({- name,- value,-}: {- name: string;- value: unknown;-}): namedTypes.JSXAttribute => {- if (- typeof value === 'string' &&- !value.startsWith(NoReactInternals.FILE_TOKEN) &&- !value.startsWith(NoReactInternals.DATE_TOKEN)- ) {- return createStringAttribute(name, value) as namedTypes.JSXAttribute;- }-- return createExpressionAttribute(name, value);-};--const createCompositionObjectProperty = ({- name,- value,-}: {- name: string;- value: unknown;-}): ObjectProperty => {- return recast.types.builders.objectProperty(- identifierRegex.test(name)- ? recast.types.builders.identifier(name)- : recast.types.builders.stringLiteral(name),- parseValueExpression(value) as never,- ) as unknown as ObjectProperty;-};--const createCompositionComponentElement = ({- localName,- props,-}: {- localName: string;- props: Record<string, unknown>;-}) => {- const directAttributes: namedTypes.JSXAttribute[] = [];- const spreadProperties: ObjectProperty[] = [];-- for (const [name, value] of Object.entries(props)) {- if (identifierRegex.test(name)) {- directAttributes.push(createCompositionPropAttribute({name, value}));- } else {- spreadProperties.push(createCompositionObjectProperty({name, value}));- }- }-- const attributes: (JSXAttribute | JSXSpreadAttribute)[] = [- ...(directAttributes as unknown as JSXAttribute[]),- ...(spreadProperties.length === 0- ? []- : [- recast.types.builders.jsxSpreadAttribute(- recast.types.builders.objectExpression(- spreadProperties as never,- ) as never,- ) as unknown as JSXSpreadAttribute,- ]),- ];-- return recast.types.builders.jsxElement(- recast.types.builders.jsxOpeningElement(- recast.types.builders.jsxIdentifier(localName),- attributes as never,- true,- ),- null,- [],- );-};--const addElementToComponentRoot = ({- ast,- exportName,- element,-}: {- ast: File;- exportName: string | 'default';- element: namedTypes.JSXElement;-}) => {- const declaration = getDeclarationByExportName({ast, exportName});- if (!declaration) {- throw new Error('Could not find composition component declaration');- }-- const rootNode = getComponentRootNode(declaration);- if (!rootNode) {- const insertedAt = addElementToNullComponentReturn({declaration, element});- if (insertedAt !== null) {- return insertedAt;- }-- throw new Error('Composition component does not return JSX');- }-- const CANVAS_ROOT_ELEMENTS = [- 'ThreeCanvas',- 'RiveCanvas',- 'SkiaCanvas',- 'canvas',- ];-- if (- rootNode.type === 'JSXElement' &&- rootNode.openingElement.name.type === 'JSXIdentifier' &&- CANVAS_ROOT_ELEMENTS.includes(rootNode.openingElement.name.name)- ) {- throw new Error(- `Cannot insert a JSX element into a composition whose root element is <${rootNode.openingElement.name.name}>`,- );- }-- if (rootNode.type === 'JSXElement') {- const existingRoot = rootNode.openingElement.selfClosing- ? createSequenceWithChild({- child: stripParenthesizedExtra(rootNode),- sequenceLocalName: ensureSequenceImport(ast),- })- : stripParenthesizedExtra(rootNode);- const fragment = recast.types.builders.jsxFragment(- recast.types.builders.jsxOpeningFragment(),- recast.types.builders.jsxClosingFragment(),- [existingRoot, element],- );- let replaced = false;- recast.types.visit(ast, {- visitJSXElement(astPath) {- if (astPath.node === rootNode) {- astPath.replace(fragment);- replaced = true;- return false;- }-- this.traverse(astPath);- },- });-- if (!replaced) {- throw new Error('Could not replace composition component root');- }-- return rootNode.loc?.start.line ?? 1;- }-- if (!rootNode.children) {- throw new Error('Composition component root does not accept children');- }-- rootNode.children.push(element);- return rootNode.loc?.start.line ?? 1;-};--const getDefaultExportDeclaration = (- ast: File,-): LocalComponentDeclaration | DefaultExportDeclaration | null => {- let declaration: DefaultExportDeclaration | null = null;- let identifierName: string | null = null;-- recast.types.visit(ast, {- visitExportDefaultDeclaration(astPath) {- if (declaration || identifierName) {- return false;- }-- const {node} = astPath;- if (node.declaration.type === 'Identifier') {- identifierName = node.declaration.name;- return false;- }-- declaration = node.declaration;- return false;- },- });-- if (identifierName) {- return findLocalComponentDeclaration({ast, name: identifierName});- }-- return declaration;-};--const getDeclarationByExportName = ({- ast,- exportName,-}: {- ast: File;- exportName: string | 'default';-}): LocalComponentDeclaration | DefaultExportDeclaration | null => {- if (exportName === 'default') {- return getDefaultExportDeclaration(ast);- }-- return findLocalComponentDeclaration({ast, name: exportName});-};--const canAddSequenceToComponent = ({- ast,- exportName,-}: {- ast: File;- exportName: string | 'default';-}): boolean => {- try {- addElementToComponentRoot({- ast,- exportName,- element: createSequenceElement(),- });- recast.print(ast);- return true;- } catch {- return false;- }-};--const getComponentLocationInFile = async ({- remotionRoot,- fileName,- exportName,- ast: providedAst,-}: {- remotionRoot: string;- fileName: string;- exportName: string | 'default';- ast?: File;-}): Promise<ResolvedCompositionComponentWithFile> => {- const ast =- providedAst ?? parseAst(await readSourceFile({remotionRoot, fileName}));- const location =- exportName === 'default'- ? findDefaultExportLocation(ast)- : findLocalSymbolLocation({ast, name: exportName});- const canAddSequence = canAddSequenceToComponent({- ast,- exportName,- });-- return {- source: path.relative(remotionRoot, fileName),- fileName,- exportName,- line: location?.line ?? 1,- column: location?.column ?? 0,- canAddSequence,- };-};--const getComponentLocationRecursively = async ({- remotionRoot,- fileName,- exportName,- visited,-}: {- remotionRoot: string;- fileName: string;- exportName: string | 'default';- visited: Set<string>;-}): Promise<ResolvedCompositionComponentWithFile> => {- const key = `${fileName}:${exportName}`;- if (visited.has(key)) {- throw new Error(- `Could not resolve component export "${exportName}" in ${path.relative(remotionRoot, fileName)}`,- );- }-- visited.add(key);- try {- const input = await readSourceFile({remotionRoot, fileName});- const ast = parseAst(input);- const localDeclaration = getDeclarationByExportName({- ast,- exportName,- });- if (localDeclaration) {- return await getComponentLocationInFile({- remotionRoot,- fileName,- exportName,- ast,- });- }-- const reExportTargets = findReExportTargets({- ast,- exportName,- });- for (const target of reExportTargets) {- try {- const resolvedImportPath = resolveImportPath({- importPath: target.importPath,- fromFile: fileName,- });-- return await getComponentLocationRecursively({- remotionRoot,- fileName: resolvedImportPath,- exportName: target.exportName,- visited,- });- } catch {- continue;- }- }-- if (reExportTargets.length > 0) {- throw new Error(- `Could not resolve component export "${exportName}" in ${path.relative(remotionRoot, fileName)}`,- );- }-- return await getComponentLocationInFile({- remotionRoot,- fileName,- exportName,- ast,- });- } finally {- visited.delete(key);- }-};--export const resolveCompositionComponentWithFile = async ({+export const resolveCompositionComponent = ({remotionRoot,compositionFile,compositionId,@@ -2094,201 +64,14 @@ export const resolveCompositionComponentWithFile = async ({remotionRoot: string;compositionFile: string;compositionId: string;-}): Promise<ResolvedCompositionComponentWithFile> => {- const compositionFileName = path.resolve(remotionRoot, compositionFile);- const input = await readSourceFile({- remotionRoot,- fileName: compositionFileName,- });- const ast = parseAstForReadOnly(input);- const compositionElement = findCompositionElement({ast, compositionId});- if (!compositionElement) {- throw new Error(`Could not find composition "${compositionId}"`);- }-- const lazyImportPath = getLazyImportPath(compositionElement);- if (lazyImportPath) {- const lazyComponentFile = resolveImportPath({- importPath: lazyImportPath,- fromFile: compositionFileName,- });- return getComponentLocationRecursively({- remotionRoot,- fileName: lazyComponentFile,- exportName: 'default',- visited: new Set(),- });- }-- const componentName = getComponentIdentifier(compositionElement);- if (!componentName) {- throw new Error(- `Could not find a component prop for composition "${compositionId}"`,- );- }-- const importTarget = findImportTarget({ast, componentName});- if (!importTarget) {- return getComponentLocationInFile({- remotionRoot,- fileName: compositionFileName,- exportName: componentName,- });- }-- const importedComponentFile = resolveImportPath({- importPath: importTarget.importPath,- fromFile: compositionFileName,- });-- return getComponentLocationRecursively({- remotionRoot,- fileName: importedComponentFile,- exportName: importTarget.exportName,- visited: new Set(),+}): Promise<ResolvedCompositionComponent> =>+ resolveCompositionComponentCodemod({+ compositionFile,+ compositionId,+ environment: makeCodemodEnvironment(remotionRoot),});-};-export const resolveCompositionComponent = async ({- remotionRoot,- compositionFile,- compositionId,-}: {- remotionRoot: string;- compositionFile: string;- compositionId: string;-}): Promise<ResolvedCompositionComponent> => {- const {source, line, column, canAddSequence} =- await resolveCompositionComponentWithFile({- remotionRoot,- compositionFile,- compositionId,- });-- return {- source,- line,- column,- canAddSequence,- };-};--const createInsertableJsxElement = ({- addPositionStyleToComponent,- ast,- destinationFileName,- element,- from,- remotionRoot,-}: {- addPositionStyleToComponent: boolean;- ast: File;- destinationFileName: string;- element: InsertableCompositionElement;- from: number | null;- remotionRoot: string;-}): Promise<namedTypes.JSXElement> | namedTypes.JSXElement => {- if (element.type === 'solid') {- const solidLocalName = ensureSolidImport(ast);-- return createSolidElement({- localName: solidLocalName,- width: element.width,- height: element.height,- position: element.position,- });- }-- if (element.type === 'component') {- const componentLocalName = ensureComponentImport({- ast,- componentName: element.componentName,- importName: element.importName,- importPath: element.importPath,- });-- return createComponentElement({- addPositionStyle: addPositionStyleToComponent,- from,- localName: componentLocalName,- props: element.props,- position: element.position,- });- }-- if (element.type === 'svg') {- return createSvgElement({- from,- interactiveLocalName: ensureInteractiveImport(ast),- markup: element.markup,- position: element.position,- });- }-- if (element.type === 'composition') {- return Promise.resolve(- ensureCompositionComponentImport({- ast,- compositionFile: element.compositionFile,- compositionId: element.compositionId,- destinationFileName,- remotionRoot,- }),- ).then((localName) => {- const props = parseSerializedCompositionProps(- element.serializedResolvedPropsWithCustomSchema,- );- if (containsFileToken(props)) {- ensureStaticFileImport(ast);- }-- return createCompositionComponentElement({localName, props});- });- }-- if (element.type === 'asset') {- if (element.srcType === 'remote' && !isUrl(element.src)) {- throw new Error('Remote asset source must be a URL');- }-- const staticFileLocalName =- element.srcType === 'remote' ? null : ensureStaticFileImport(ast);- let localName: string;- if (element.assetType === 'image') {- localName = ensureCanvasImageImport(ast);- } else if (element.assetType === 'video') {- localName = ensureVideoImport(ast);- } else if (element.assetType === 'gif') {- localName = ensureGifImport(ast);- } else if (element.assetType === 'animated-image') {- localName = ensureAnimatedImageImport(ast);- } else if (element.assetType === 'audio') {- localName = ensureAudioImport(ast);- } else {- throw new Error('Unsupported asset type');- }-- return createAssetElement({- addPositionStyle:- addPositionStyleToComponent && element.assetType !== 'audio',- durationInFrames:- element.assetType === 'image' ? null : element.durationInFrames,- from,- localName,- staticFileLocalName,- src: element.src,- dimensions:- element.assetType === 'image' && from !== null- ? null- : element.dimensions,- position: element.position,- });- }-- throw new Error('Unsupported element type');-};--export const insertJsxElementIntoComposition = async ({+export const insertJsxElementIntoComposition = ({remotionRoot,compositionFile,compositionId,@@ -2319,100 +102,22 @@ export const insertJsxElementIntoComposition = async ({logLine: number;nodePathRemappings: SequenceNodePathRemapping[];insertedNodePath: SequenceNodePath | null;-}> => {- const location = await resolveCompositionComponentWithFile({- remotionRoot,+}> =>+ insertJsxElementIntoCompositionCodemod({compositionFile,compositionId,- });- if (!location.canAddSequence) {- throw new Error(- 'Cannot insert JSX element into this composition component',- );- }-- const input = await readSourceFile({- remotionRoot,- fileName: location.fileName,- });- const ast = parseAst(input);- const capturedNodePaths = captureJsxNodePaths(ast);- if (- element.type === 'composition' &&- element.compositionId === compositionId- ) {- throw new Error('Cannot insert a composition into itself');- }-- const sequenceWrapper =- element.type === 'composition'- ? {- dimensions: {width: element.width, height: element.height},- durationInFrames: element.durationInFrames,- name: element.compositionId,- position: element.position,- from,- }- : from === null ||- element.type === 'asset' ||- element.type === 'svg' ||- element.type === 'component'- ? wrapInSequence- : {- dimensions: null,- durationInFrames: null,- name: null,- position: element.position,- from,- };- const elementToInsert = await createInsertableJsxElement({- addPositionStyleToComponent: sequenceWrapper === null,- ast,- destinationFileName: location.fileName,element,+ environment: makeCodemodEnvironment(remotionRoot),from,- remotionRoot,- });- const finalElementToInsert = sequenceWrapper- ? createSequenceWrappedElement({- child: elementToInsert,- dimensions: sequenceWrapper.dimensions,- durationInFrames: sequenceWrapper.durationInFrames ?? null,- from: sequenceWrapper.from,- name: sequenceWrapper.name,- position: sequenceWrapper.position,- sequenceLocalName: ensureSequenceImport(ast),- })- : elementToInsert;- const logLine = addElementToComponentRoot({- ast,- exportName: location.exportName,- element: finalElementToInsert,- });- const finalFile = serializeAst(ast);-- const {output, formatted} = await formatFileContent({- input: finalFile,prettierConfigOverride,+ wrapInSequence:+ wrapInSequence === null+ ? null+ : {+ dimensions: wrapInSequence.dimensions,+ durationInFrames: wrapInSequence.durationInFrames ?? null,+ from: wrapInSequence.from,+ name: wrapInSequence.name,+ position: wrapInSequence.position,+ },});- const {finalNodePathByNode, nodePathRemappings} = getNodePathRemappings({- ast,- captured: capturedNodePaths,- output,- });- const insertedNodePath =- finalNodePathByNode.get(- finalElementToInsert.openingElement as JSXOpeningElement,- ) ?? null;-- return {- fileName: location.fileName,- source: location.source,- oldContents: input,- output,- formatted,- insertedNodePath,- logLine,- nodePathRemappings,- };-};diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.tsindex adc8bc17ec..d84a52d62c 100644--- a/packages/studio-server/src/test/resolve-composition-component.test.ts+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts@@ -1672,6 +1672,95 @@ test('inserts a component into the resolved composition component', async () =>}});+test('rejects type-only component imports instead of using them as values', async () => {+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));+ try {+ await fs.writeFile(+ path.join(tempDir, 'Root.tsx'),+ [+ "import {Composition} from 'remotion';",+ "import {MyComp} from './MyComp';",+ 'export const RemotionRoot = () => {',+ '\treturn <Composition id="test" component={MyComp} />;',+ '};',+ '',+ ].join('\n'),+ );++ for (const typeOnlyImport of [+ "import type {LowerThird} from './lower-third.element';",+ "import {type LowerThird} from './lower-third.element';",+ ]) {+ await fs.writeFile(+ path.join(tempDir, 'MyComp.tsx'),+ [+ typeOnlyImport,+ "import {AbsoluteFill} from 'remotion';",+ '',+ 'export const MyComp: React.FC = () => {',+ '\treturn <AbsoluteFill>hello</AbsoluteFill>;',+ '};',+ '',+ ].join('\n'),+ );++ await expect(+ insertJsxElementIntoComposition({+ remotionRoot: tempDir,+ compositionFile: 'Root.tsx',+ compositionId: 'test',+ element: {+ type: 'component',+ componentName: 'LowerThird',+ importName: 'LowerThird',+ importPath: './lower-third.element',+ props: [],+ position: null,+ },+ from: null,+ prettierConfigOverride: {singleQuote: true, useTabs: true},+ }),+ ).rejects.toThrow(+ 'Cannot add <LowerThird> because LowerThird is already defined',+ );+ }++ await fs.writeFile(+ path.join(tempDir, 'MyComp.tsx'),+ [+ "import type {LowerThird as LowerThirdProps} from './lower-third.element';",+ "import {AbsoluteFill} from 'remotion';",+ '',+ 'export const MyComp: React.FC = () => {',+ '\treturn <AbsoluteFill>hello</AbsoluteFill>;',+ '};',+ '',+ ].join('\n'),+ );+ const result = await insertJsxElementIntoComposition({+ remotionRoot: tempDir,+ compositionFile: 'Root.tsx',+ compositionId: 'test',+ element: {+ type: 'component',+ componentName: 'LowerThird',+ importName: 'LowerThird',+ importPath: './lower-third.element',+ props: [],+ position: null,+ },+ from: null,+ prettierConfigOverride: {singleQuote: true, useTabs: true},+ });+ expect(result.output).toContain(+ "import { LowerThird } from './lower-third.element';",+ );+ expect(result.output).toContain('<LowerThird');+ } finally {+ await fs.rm(tempDir, {recursive: true, force: true});+ }+});+test('wraps a component in a dimensionless Sequence', async () => {const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));try {diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.tsindex 79f033ba54..0db89cb185 100644--- a/packages/studio-shared/src/browser-studio-operations.ts+++ b/packages/studio-shared/src/browser-studio-operations.ts@@ -7,6 +7,10 @@ import type {FindInFileResponse,InsertJsxElementRequest,InsertJsxElementResponse,+ InsertElementRequest,+ InsertElementResponse,+ PrepareElementInstallRequest,+ PrepareElementInstallResponse,RedoResponse,RenameStaticFileRequest,RenameStaticFileResponse,@@ -44,6 +48,15 @@ export type BrowserStudioOperations = {insertSolid: (request: InsertJsxElementRequest,) => Promise<InsertJsxElementResponse>;+ insertElement: (+ request: InsertElementRequest,+ ) => Promise<InsertElementResponse>;+ insertJsxElement: (+ request: InsertJsxElementRequest,+ ) => Promise<InsertJsxElementResponse>;+ prepareElementInstall: (+ request: PrepareElementInstallRequest,+ ) => Promise<PrepareElementInstallResponse>;redo: () => Promise<RedoResponse>;renameStaticFile: (request: RenameStaticFileRequest,diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsxindex a72834b875..3149771a36 100644--- a/packages/studio/src/components/Canvas.tsx+++ b/packages/studio/src/components/Canvas.tsx@@ -12,6 +12,7 @@ import React, {import type {CanvasContent} from 'remotion';import {Internals, watchStaticFile, type PreviewSize} from 'remotion';import {getStaticFiles} from '../api/get-static-files';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../helpers/client-id';import {getClipboardFigmaHtml} from '../helpers/clipboard-figma';import {getClipboardImageFiles} from '../helpers/clipboard-images';@@ -60,6 +61,7 @@ import EditorGuides from './EditorGuides';import {EditorRulers} from './EditorRuler';import {useIsRulerVisible} from './EditorRuler/use-is-ruler-visible';import {getEffectDragData} from './effect-drag-and-drop';+import {prepareElementInstall} from './element-install-api';import {subscribeToElementInstallRequests} from './element-install-request';import {ElementInstallConfirmation} from './ElementInstallConfirmation';import {handleDrop} from './handle-drop';@@ -857,7 +859,7 @@ export const Canvas: React.FC<{const handleInstallRequest = async () => {setInstallingElementName(activeElementInstallRequest.element.displayName);- const preflight = await callApi('/api/prepare-element-install', {+ const preflight = await prepareElementInstall({compositionFile: activeElementInstallRequest.compositionFile,compositionId: activeElementInstallRequest.compositionId,element: activeElementInstallRequest.element,@@ -916,6 +918,9 @@ export const Canvas: React.FC<{dependenciesToReview={dependenciesToReview}missingPackages={missingPackages}sourceCode={activeElementInstallRequest.element.sourceCode}+ usesBrowserDependencyResolution={+ getBrowserStudioOperations() !== null+ }/>),confirmLabel: 'Install',diff --git a/packages/studio/src/components/ElementInstallConfirmation.tsx b/packages/studio/src/components/ElementInstallConfirmation.tsxindex 04daf9068c..2959364ee6 100644--- a/packages/studio/src/components/ElementInstallConfirmation.tsx+++ b/packages/studio/src/components/ElementInstallConfirmation.tsx@@ -210,6 +210,7 @@ export const ElementInstallConfirmation: React.FC<{readonly dependenciesToReview: string[];readonly missingPackages: string[];readonly sourceCode: string;+ readonly usesBrowserDependencyResolution: boolean;}> = ({displayName,sourceLabel,@@ -220,6 +221,7 @@ export const ElementInstallConfirmation: React.FC<{dependenciesToReview,missingPackages,sourceCode,+ usesBrowserDependencyResolution,}) => {return (<div style={container}>@@ -293,9 +295,10 @@ export const ElementInstallConfirmation: React.FC<{<div style={warningStyle}><WarningTriangle style={warningIconStyle} /><p style={warningDescriptionStyle}>- This adds executable source code to your project. Package lifecycle- scripts may also run during installation, with access to your files- and the network.+ This adds executable source code to your project.+ {usesBrowserDependencyResolution+ ? null+ : ' Package lifecycle scripts may also run during installation, with access to your files and the network.'}</p></div>diff --git a/packages/studio/src/components/element-install-api.ts b/packages/studio/src/components/element-install-api.tsnew file mode 100644index 0000000000..ad249750f3--- /dev/null+++ b/packages/studio/src/components/element-install-api.ts@@ -0,0 +1,26 @@+import type {+ InsertElementRequest,+ InsertElementResponse,+ PrepareElementInstallRequest,+ PrepareElementInstallResponse,+} from '@remotion/studio-shared';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';+import {callApi} from './call-api';++export const prepareElementInstall = (+ request: PrepareElementInstallRequest,+): Promise<PrepareElementInstallResponse> => {+ const browserStudioOperations = getBrowserStudioOperations();+ return browserStudioOperations+ ? browserStudioOperations.prepareElementInstall(request)+ : callApi('/api/prepare-element-install', request);+};++export const installElement = (+ request: InsertElementRequest,+): Promise<InsertElementResponse> => {+ const browserStudioOperations = getBrowserStudioOperations();+ return browserStudioOperations+ ? browserStudioOperations.insertElement(request)+ : callApi('/api/insert-element', request);+};diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.tsindex 4402c608b6..7bf0764d22 100644--- a/packages/studio/src/components/import-assets.ts+++ b/packages/studio/src/components/import-assets.ts@@ -18,12 +18,14 @@ import {Internals, staticFile} from 'remotion';import {NoReactInternals} from 'remotion/no-react';import {getStaticFiles} from '../api/get-static-files';import {writeStaticFile} from '../api/write-static-file';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';import {formatFigmaClipboardErrorNotification} from '../helpers/clipboard-figma';import {requestInsertedElementSelection} from '../helpers/inserted-element-selection';import {installRequiredPackages} from '../helpers/install-required-package';import type {Dimensions} from '../helpers/is-current-selected-still';import {getMediaMetadata} from '../helpers/use-media-metadata';import {callApi} from './call-api';+import {installElement} from './element-install-api';import {showNotification} from './Notifications/NotificationCenter';export type InsertElementDropPosition = {@@ -719,16 +721,17 @@ const insertCompositionElement = async ({from: number | null;}) => {const requiredPackage = getRequiredPackageForInsertableElement(element);- await installRequiredPackages(- requiredPackage ? [{name: requiredPackage, version: null}] : [],- );-- const result = await callApi('/api/insert-jsx-element', {- compositionFile,- compositionId,- element,- from,- });+ const browserStudioOperations = getBrowserStudioOperations();+ if (browserStudioOperations === null) {+ await installRequiredPackages(+ requiredPackage ? [{name: requiredPackage, version: null}] : [],+ );+ }++ const request = {compositionFile, compositionId, element, from};+ const result = browserStudioOperations+ ? await browserStudioOperations.insertJsxElement(request)+ : await callApi('/api/insert-jsx-element', request);if (!result.success) {showNotification(result.reason, 4000);@@ -1405,9 +1408,11 @@ export const insertElement = async ({overwriteExisting: boolean;}) => {try {- await installRequiredPackages(element.dependencies);+ if (getBrowserStudioOperations() === null) {+ await installRequiredPackages(element.dependencies);+ }- const response = await callApi('/api/insert-element', {+ const response = await installElement({compositionFile,compositionId,element,diff --git a/packages/studio/src/test/make-browser-studio-operations.ts b/packages/studio/src/test/make-browser-studio-operations.tsindex 9883de6000..66c2d1b5f5 100644--- a/packages/studio/src/test/make-browser-studio-operations.ts+++ b/packages/studio/src/test/make-browser-studio-operations.ts@@ -15,7 +15,10 @@ export const makeBrowserStudioOperations = (unusedOperation('getCompositionComponentInfo'),getCompositionFile: () => unusedOperation('getCompositionFile'),getFileSource: () => unusedOperation('getFileSource'),+ insertElement: () => unusedOperation('insertElement'),+ insertJsxElement: () => unusedOperation('insertJsxElement'),insertSolid: () => unusedOperation('insertSolid'),+ prepareElementInstall: () => unusedOperation('prepareElementInstall'),redo: () => unusedOperation('redo'),renameStaticFile: () => unusedOperation('renameStaticFile'),saveSequenceProps: () => unusedOperation('saveSequenceProps'),