🎥 Make videos programmatically with React
`@remotion/studio`: Resolve read-only component and sequence sources
JonnyBurgerf270760a02b4
diff --git a/bun.lock b/bun.lockindex 698658c605..6c432fe596 100644--- a/bun.lock+++ b/bun.lock@@ -1805,6 +1805,7 @@"@remotion/media-utils": "workspace:*","@remotion/player": "workspace:*","@remotion/renderer": "workspace:*",+ "@remotion/studio-codemods": "workspace:*","@remotion/studio-protocol": "workspace:*","@remotion/studio-shared": "workspace:*","@remotion/timeline-utils": "workspace:*",diff --git a/packages/bundler/src/setup-sequence-stack-traces.ts b/packages/bundler/src/setup-sequence-stack-traces.tsindex 7e7fda1fca..2418d50f23 100644--- a/packages/bundler/src/setup-sequence-stack-traces.ts+++ b/packages/bundler/src/setup-sequence-stack-traces.ts@@ -1,10 +1,9 @@import React from 'react';import JsxRuntimeDev from 'react/jsx-dev-runtime';import JsxRuntime from 'react/jsx-runtime';-import {Composition, Folder, Internals, Still} from 'remotion';+import {Internals} from 'remotion';const componentsToAddStacksTo = Internals.getComponentsToAddStacksTo();-const componentsToAddStacksToInReadOnlyStudio = [Composition, Folder, Still];const sequenceComponent = Internals.getSequenceComponent();const internalStackProp = Internals.REMOTION_INTERNAL_STACK_PROP;const studioOriginalSourcePrefix = 'studio-original://';@@ -52,10 +51,7 @@ const enableProxy = <return new Proxy(api, {apply(target, thisArg, argArray) {const component = argArray[0];- const shouldAddStack =- process.env.NODE_ENV !== 'production' ||- componentsToAddStacksToInReadOnlyStudio.includes(component);- if (shouldAddStack && componentsToAddStacksTo.includes(component)) {+ if (componentsToAddStacksTo.includes(component)) {const [first, props, ...rest] = argArray;const children = isCreateElement? rest.length === 0diff --git a/packages/bundler/src/test/setup-sequence-stack-traces.test.ts b/packages/bundler/src/test/setup-sequence-stack-traces.test.tsindex 350033e42c..6378d8dd3f 100644--- a/packages/bundler/src/test/setup-sequence-stack-traces.test.ts+++ b/packages/bundler/src/test/setup-sequence-stack-traces.test.ts@@ -44,7 +44,7 @@ test('injects a namespaced source stack without conflicting with application proexpect((renderingElement.props as {_remotionInternalStack?: string})._remotionInternalStack,- ).toBeUndefined();+ ).toContain('Error');const sourceElement = JsxRuntimeDev.jsxDEV(Composition,diff --git a/packages/it-tests/src/bundle/bundle-studio.test.ts b/packages/it-tests/src/bundle/bundle-studio.test.tsindex 0399f92111..7491219432 100644--- a/packages/it-tests/src/bundle/bundle-studio.test.ts+++ b/packages/it-tests/src/bundle/bundle-studio.test.ts@@ -68,7 +68,7 @@ test(},});await tab.goto({- url: `http://localhost:${server.port}`,+ url: `http://localhost:${server.port}/?/WidthHeight`,timeout: 10000,options: {},});@@ -111,6 +111,34 @@ test(return null;});expect(sourceLocation.toString()).toMatch(/Root\.tsx:\d+/);+ expect(sourceLocation.toString()).toMatch(/WidthHeightSequences\.tsx:\d+/);+ const sequenceSourceLocation = await tab.evaluateHandle(async () => {+ const label = document.querySelector<HTMLElement>('[title="<Sequence>"]');+ label?.parentElement?.parentElement?.dispatchEvent(+ new PointerEvent('pointerdown', {bubbles: true, button: 0}),+ );++ for (let attempt = 0; attempt < 100; attempt++) {+ const inspectorSourceLocation = document.querySelector(+ '[aria-label="Inspector source location"]',+ );+ if (+ inspectorSourceLocation?.textContent?.startsWith('<Sequence>') &&+ inspectorSourceLocation.textContent.includes(+ 'WidthHeightSequences.tsx:',+ )+ ) {+ return inspectorSourceLocation.textContent;+ }++ await new Promise((resolve) => setTimeout(resolve, 100));+ }++ return null;+ });+ expect(sequenceSourceLocation.toString()).toMatch(+ /<Sequence>WidthHeightSequences\.tsx:\d+/,+ );const fontLoaded = await tab.evaluateHandle(() => {let loaded = false;@@ -133,6 +161,7 @@ test(await Promise.all([result.dispose(),sourceLocation.dispose(),+ sequenceSourceLocation.dispose(),fontLoaded.dispose(),orphanedFontTimeouts.dispose(),]);diff --git a/packages/studio-codemods/bundle.ts b/packages/studio-codemods/bundle.tsindex c2396781ac..35f2c00014 100644--- a/packages/studio-codemods/bundle.ts+++ b/packages/studio-codemods/bundle.ts@@ -9,12 +9,18 @@ const external = ['@remotion/studio-shared', 'recast'];console.time('Generated.');const esmOutput = await build({- entrypoints: ['src/index.ts'],+ entrypoints: [+ 'src/index.ts',+ 'src/resolve-composition-component-location.ts',+ ],naming: '[name].mjs',external,});const cjsOutput = await build({- entrypoints: ['src/index.ts'],+ entrypoints: [+ 'src/index.ts',+ 'src/resolve-composition-component-location.ts',+ ],naming: '[name].cjs',format: 'cjs',external,diff --git a/packages/studio-codemods/package.json b/packages/studio-codemods/package.jsonindex fa73b22765..6b89dd6d3a 100644--- a/packages/studio-codemods/package.json+++ b/packages/studio-codemods/package.json@@ -38,6 +38,12 @@"module": "./dist/esm/index.mjs","import": "./dist/esm/index.mjs"},+ "./resolve-composition-component-location": {+ "types": "./dist/resolve-composition-component-location.d.ts",+ "require": "./dist/resolve-composition-component-location.cjs",+ "module": "./dist/esm/resolve-composition-component-location.mjs",+ "import": "./dist/esm/resolve-composition-component-location.mjs"+ },"./package.json": "./package.json"},"devDependencies": {diff --git a/packages/studio-codemods/src/resolve-composition-component-location.ts b/packages/studio-codemods/src/resolve-composition-component-location.tsnew file mode 100644index 0000000000..15ea8f5ef8--- /dev/null+++ b/packages/studio-codemods/src/resolve-composition-component-location.ts@@ -0,0 +1,491 @@+import {parse} from '@babel/parser';+import type {+ File,+ Identifier,+ JSXAttribute,+ JSXOpeningElement,+ Node,+ Statement,+ StringLiteral,+} from '@babel/types';++// Keep this entry browser-safe. The main codemod entry imports Recast, which+// depends on Node built-ins and cannot be loaded by a static Studio bundle.++export type SourceMapProject = {+ files: Record<string, string>;+ rootDir: string;+};++const parseSource = (source: string): File => {+ return parse(source, {+ errorRecovery: false,+ plugins: ['decorators-legacy', 'jsx', 'typescript', 'importAttributes'],+ sourceType: 'module',+ });+};++const isNode = (value: unknown): value is Node => {+ return (+ typeof value === 'object' &&+ value !== null &&+ 'type' in value &&+ typeof value.type === 'string'+ );+};++const visit = (value: unknown, visitor: (node: Node) => boolean): boolean => {+ if (Array.isArray(value)) {+ return value.some((item) => visit(item, visitor));+ }++ if (!isNode(value)) {+ return false;+ }++ if (visitor(value)) {+ return true;+ }++ return Object.entries(value).some(([key, child]) => {+ if (+ key === 'loc' ||+ key === 'start' ||+ key === 'end' ||+ key === 'extra' ||+ key === 'comments'+ ) {+ return false;+ }++ return visit(child, visitor);+ });+};++const normalizePath = (input: string) => {+ const hasLeadingSlash = input.startsWith('/');+ const parts: string[] = [];++ for (const part of input.replaceAll('\\', '/').split('/')) {+ if (!part || part === '.') {+ continue;+ }++ if (part === '..') {+ parts.pop();+ continue;+ }++ parts.push(part);+ }++ return `${hasLeadingSlash ? '/' : ''}${parts.join('/')}`;+};++const getProjectFile = ({+ filePath,+ project,+}: {+ filePath: string;+ project: SourceMapProject;+}) => {+ const normalizedInput = normalizePath(+ filePath+ .replace(/^webpack:\/\/\/?/, '/')+ .replace(/^file:\/\//, '')+ .split(/[?#]/, 1)[0],+ );+ const normalizedRoot = normalizePath(project.rootDir);+ const normalizedFiles = new Map(+ Object.keys(project.files).map((key) => [normalizePath(key), key]),+ );+ const candidates = [+ normalizedInput,+ normalizePath(`/${normalizedInput}`),+ normalizePath(`${normalizedRoot}/${normalizedInput.replace(/^\//, '')}`),+ ];++ for (const candidate of candidates) {+ const match = normalizedFiles.get(candidate);+ if (match) {+ return match;+ }+ }++ const suffix = `/${normalizedInput.replace(/^\//, '')}`;+ const suffixMatches = [...normalizedFiles.entries()].filter(([key]) =>+ key.endsWith(suffix),+ );+ if (suffixMatches.length === 1) {+ return suffixMatches[0][1];+ }++ throw new Error(`Could not find source file "${filePath}"`);+};++const resolveImport = ({+ fromFile,+ importPath,+ project,+}: {+ fromFile: string;+ importPath: string;+ project: SourceMapProject;+}) => {+ if (!importPath.startsWith('.')) {+ throw new Error(`Cannot resolve package import "${importPath}"`);+ }++ const normalizedFrom = normalizePath(fromFile);+ const lastSlash = normalizedFrom.lastIndexOf('/');+ const directory = lastSlash === -1 ? '' : normalizedFrom.slice(0, lastSlash);+ const basePath = normalizePath(`${directory}/${importPath}`);+ const candidates = [+ basePath,+ ...['.tsx', '.ts', '.jsx', '.js'].map(+ (extension) => `${basePath}${extension}`,+ ),+ ...['.tsx', '.ts', '.jsx', '.js'].map(+ (extension) => `${basePath}/index${extension}`,+ ),+ ];+ const normalizedFiles = new Map(+ Object.keys(project.files).map((key) => [normalizePath(key), key]),+ );++ for (const candidate of candidates) {+ const match = normalizedFiles.get(candidate);+ if (match) {+ return match;+ }+ }++ throw new Error(`Could not find imported component file "${importPath}"`);+};++const jsxName = (name: JSXOpeningElement['name']): string | null => {+ if (name.type === 'JSXIdentifier') {+ return name.name;+ }++ if (name.type === 'JSXMemberExpression') {+ const object = jsxName(name.object);+ const property = jsxName(name.property);+ return object && property ? `${object}.${property}` : null;+ }++ return null;+};++const getAttribute = (element: JSXOpeningElement, name: string) => {+ return (+ element.attributes.find(+ (attribute): attribute is JSXAttribute =>+ attribute.type === 'JSXAttribute' &&+ attribute.name.type === 'JSXIdentifier' &&+ attribute.name.name === name,+ ) ?? null+ );+};++const getStringAttribute = (attribute: JSXAttribute | 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 getIdentifierAttribute = (attribute: JSXAttribute | null) => {+ return attribute?.value?.type === 'JSXExpressionContainer' &&+ attribute.value.expression.type === 'Identifier'+ ? attribute.value.expression.name+ : null;+};++const findComposition = (file: File, compositionId: string) => {+ let result: JSXOpeningElement | null = null;+ visit(file, (node) => {+ if (node.type !== 'JSXOpeningElement') {+ return false;+ }++ const name = jsxName(node.name);+ if (+ name !== 'Composition' &&+ name !== 'Still' &&+ !name?.endsWith('.Composition') &&+ !name?.endsWith('.Still')+ ) {+ return false;+ }++ if (getStringAttribute(getAttribute(node, 'id')) === compositionId) {+ result = node;+ return true;+ }++ return false;+ });++ return result;+};++const findLazyImport = (attribute: JSXAttribute | null) => {+ let importPath: string | null = null;+ visit(attribute, (node) => {+ if (+ node.type === 'ImportExpression' &&+ node.source.type === 'StringLiteral'+ ) {+ importPath = node.source.value;+ return true;+ }++ if (+ node.type === 'CallExpression' &&+ node.callee.type === 'Import' &&+ node.arguments[0]?.type === 'StringLiteral'+ ) {+ importPath = node.arguments[0].value;+ return true;+ }++ return false;+ });++ return importPath;+};++const getDeclaration = (+ statement: Statement,+ name: string | 'default',+): Node | null => {+ if (name === 'default' && statement.type === 'ExportDefaultDeclaration') {+ return statement.declaration.type === 'Identifier'+ ? null+ : statement.declaration;+ }++ const declaration =+ statement.type === 'ExportNamedDeclaration'+ ? statement.declaration+ : statement;+ if (!declaration) {+ return null;+ }++ if (+ (declaration.type === 'FunctionDeclaration' ||+ declaration.type === 'ClassDeclaration') &&+ declaration.id?.name === name+ ) {+ return declaration;+ }++ if (declaration.type === 'VariableDeclaration') {+ return (+ declaration.declarations.find(+ (item) => item.id.type === 'Identifier' && item.id.name === name,+ ) ?? null+ );+ }++ return null;+};++const getExportedName = (name: Identifier | StringLiteral) => {+ return name.type === 'Identifier' ? name.name : name.value;+};++const resolveDeclaration = ({+ filePath,+ exportName,+ project,+ visited,+}: {+ filePath: string;+ exportName: string | 'default';+ project: SourceMapProject;+ visited: Set<string>;+}): {declaration: Node; filePath: string} => {+ const key = `${filePath}:${exportName}`;+ if (visited.has(key)) {+ throw new Error(+ `Circular component export while resolving "${exportName}"`,+ );+ }++ visited.add(key);+ const source = project.files[filePath];+ if (typeof source !== 'string') {+ throw new Error(`Could not read source file "${filePath}"`);+ }++ const file = parseSource(source);+ if (exportName === 'default') {+ const defaultExport = file.program.body.find(+ (statement) => statement.type === 'ExportDefaultDeclaration',+ );+ if (+ defaultExport?.type === 'ExportDefaultDeclaration' &&+ defaultExport.declaration.type === 'Identifier'+ ) {+ return resolveDeclaration({+ filePath,+ exportName: defaultExport.declaration.name,+ project,+ visited,+ });+ }+ }++ for (const statement of file.program.body) {+ const declaration = getDeclaration(statement, exportName);+ if (declaration) {+ return {declaration, filePath};+ }+ }++ if (exportName !== 'default') {+ for (const statement of file.program.body) {+ if (+ statement.type !== 'ExportNamedDeclaration' ||+ statement.source?.type !== 'StringLiteral'+ ) {+ continue;+ }++ for (const specifier of statement.specifiers) {+ if (+ specifier.type !== 'ExportSpecifier' ||+ getExportedName(specifier.exported) !== exportName+ ) {+ continue;+ }++ return resolveDeclaration({+ filePath: resolveImport({+ fromFile: filePath,+ importPath: statement.source.value,+ project,+ }),+ exportName: getExportedName(specifier.local),+ project,+ visited,+ });+ }+ }+ }++ throw new Error(`Could not find composition component "${exportName}"`);+};++const findImportedComponent = (file: File, localName: string) => {+ for (const statement of file.program.body) {+ if (statement.type !== 'ImportDeclaration') {+ continue;+ }++ for (const specifier of statement.specifiers) {+ if (specifier.local.name !== localName) {+ continue;+ }++ if (specifier.type === 'ImportDefaultSpecifier') {+ return {exportName: 'default' as const, path: statement.source.value};+ }++ if (specifier.type === 'ImportSpecifier') {+ return {+ exportName: getExportedName(specifier.imported),+ path: statement.source.value,+ };+ }+ }+ }++ return null;+};++export const resolveCompositionComponentLocation = ({+ compositionFile,+ compositionId,+ project,+}: {+ compositionFile: string;+ compositionId: string;+ project: SourceMapProject;+}) => {+ const registrationFile = getProjectFile({+ filePath: compositionFile,+ project,+ });+ const registrationSource = project.files[registrationFile];+ if (typeof registrationSource !== 'string') {+ throw new Error(`Could not read source file "${registrationFile}"`);+ }++ const registration = parseSource(registrationSource);+ const composition = findComposition(registration, compositionId);+ if (!composition) {+ throw new Error(`Could not find composition "${compositionId}"`);+ }++ const lazyImport = findLazyImport(getAttribute(composition, 'lazyComponent'));+ let componentFile = registrationFile;+ let exportName: string | 'default' = 'default';+ if (lazyImport) {+ componentFile = resolveImport({+ fromFile: registrationFile,+ importPath: lazyImport,+ project,+ });+ } else {+ const componentName = getIdentifierAttribute(+ getAttribute(composition, 'component'),+ );+ if (!componentName) {+ throw new Error(+ `Could not find a component prop for composition "${compositionId}"`,+ );+ }++ const imported = findImportedComponent(registration, componentName);+ if (imported) {+ componentFile = resolveImport({+ fromFile: registrationFile,+ importPath: imported.path,+ project,+ });+ exportName = imported.exportName;+ } else {+ exportName = componentName;+ }+ }++ const {declaration, filePath} = resolveDeclaration({+ filePath: componentFile,+ exportName,+ project,+ visited: new Set(),+ });+ const normalizedFile = normalizePath(filePath);+ const normalizedRoot = normalizePath(project.rootDir).replace(/\/$/, '');+ const source = normalizedFile.startsWith(`${normalizedRoot}/`)+ ? normalizedFile.slice(normalizedRoot.length + 1)+ : normalizedFile.replace(/^\//, '');++ return {+ source,+ line: declaration.loc?.start.line ?? 1,+ column: declaration.loc?.start.column ?? 0,+ };+};diff --git a/packages/studio-codemods/src/test/resolve-composition-component-location.test.ts b/packages/studio-codemods/src/test/resolve-composition-component-location.test.tsnew file mode 100644index 0000000000..fb0fc50f5a--- /dev/null+++ b/packages/studio-codemods/src/test/resolve-composition-component-location.test.ts@@ -0,0 +1,41 @@+import {expect, test} from 'bun:test';+import {resolveCompositionComponentLocation} from '../resolve-composition-component-location';++test('resolves a composition component from source map contents', () => {+ const location = resolveCompositionComponentLocation({+ compositionFile: './src/Root.tsx',+ compositionId: 'WidthHeight',+ project: {+ rootDir: '.',+ files: {+ './src/Root.tsx': [+ "import {Composition} from 'remotion';",+ "import {WidthHeightSequences} from './Sequence/WidthHeightSequences';",+ 'export const Root = () => (',+ ' <Composition',+ ' id="WidthHeight"',+ ' component={WidthHeightSequences}',+ ' durationInFrames={120}',+ ' fps={30}',+ ' width={1080}',+ ' height={1080}',+ ' />',+ ');',+ ].join('\n'),+ './src/Sequence/WidthHeightSequences.tsx': [+ "import {Sequence} from 'remotion';",+ '',+ 'export const WidthHeightSequences = () => {',+ ' return <Sequence />;',+ '};',+ ].join('\n'),+ },+ },+ });++ expect(location).toEqual({+ column: 13,+ line: 3,+ source: 'src/Sequence/WidthHeightSequences.tsx',+ });+});diff --git a/packages/studio/package.json b/packages/studio/package.jsonindex 50a7b02072..2b57a55f84 100644--- a/packages/studio/package.json+++ b/packages/studio/package.json@@ -27,6 +27,7 @@"@tanstack/react-virtual": "3.14.9","@remotion/canvas": "workspace:*","@remotion/studio-protocol": "workspace:*",+ "@remotion/studio-codemods": "workspace:*","semver": "7.5.3","remotion": "workspace:*","@remotion/captions": "workspace:*",diff --git a/packages/studio/src/components/Timeline/TimelineStack/get-stack.ts b/packages/studio/src/components/Timeline/TimelineStack/get-stack.tsindex 2923277628..1cd0e50b8d 100644--- a/packages/studio/src/components/Timeline/TimelineStack/get-stack.ts+++ b/packages/studio/src/components/Timeline/TimelineStack/get-stack.ts@@ -7,12 +7,14 @@ import {const traceMapCache: Partial<Record<string, TraceMap>> = {};const traceMapPromises: Partial<Record<string, Promise<TraceMap>>> = {};+const traceMapsByOriginalSource = new Map<string, TraceMap>();+const sourceMapFilesCache = new WeakMap<TraceMap, Record<string, string>>();const browserStudioOriginalSourcePrefix = 'browser-studio-original://';const studioOriginalSourcePrefix = 'studio-original://';-const getSourceMapCache = async (fileName: string) => {+const getSourceMapCache = (fileName: string): Promise<TraceMap> => {if (traceMapCache[fileName]) {- return traceMapCache[fileName];+ return Promise.resolve(traceMapCache[fileName]);}if (traceMapPromises[fileName]) {@@ -24,6 +26,14 @@ const getSourceMapCache = async (fileName: string) => {.then((json) => {const map = new TraceMap(json as SourceMapInput);traceMapCache[fileName] = map;+ for (let index = 0; index < map.sources.length; index++) {+ const source = map.sources[index];+ const content = map.sourcesContent?.[index];+ if (source !== null && typeof content === 'string') {+ traceMapsByOriginalSource.set(source, map);+ }+ }+return map;}).finally(() => {@@ -33,6 +43,32 @@ const getSourceMapCache = async (fileName: string) => {return traceMapPromises[fileName];};+export const getSourceMapFilesForSource = (+ source: string,+): Record<string, string> | null => {+ const map = traceMapsByOriginalSource.get(source);+ if (!map) {+ return null;+ }++ const cached = sourceMapFilesCache.get(map);+ if (cached) {+ return cached;+ }++ const files: Record<string, string> = {};+ for (let index = 0; index < map.sources.length; index++) {+ const fileName = map.sources[index];+ const content = map.sourcesContent?.[index];+ if (fileName !== null && typeof content === 'string') {+ files[fileName] = content;+ }+ }++ sourceMapFilesCache.set(map, files);+ return files;+};+export const getOriginalLocationFromStack = async (stack: string,type: 'sequence' | 'visual-control',diff --git a/packages/studio/src/helpers/open-in-editor.ts b/packages/studio/src/helpers/open-in-editor.tsindex 3e94e33f92..0b1d4f20ea 100644--- a/packages/studio/src/helpers/open-in-editor.ts+++ b/packages/studio/src/helpers/open-in-editor.ts@@ -8,6 +8,7 @@ import type {} from '@remotion/studio-shared';import {useEffect, useSyncExternalStore} from 'react';import {callApi} from '../components/call-api';+import {getSourceMapFilesForSource} from '../components/Timeline/TimelineStack/get-stack';import type {CodePosition,OriginalPosition,@@ -222,7 +223,27 @@ export const loadCompositionComponentInfo = async ({const browserStudioOperations = getBrowserStudioOperations();const body = browserStudioOperations? await browserStudioOperations.getCompositionComponentInfo(request)- : await callApi('/api/composition-component-info', request);+ : typeof window !== 'undefined' && window.remotion_isReadOnlyStudio+ ? await (async () => {+ const files = getSourceMapFilesForSource(compositionFile);+ if (files === null) {+ throw new Error(+ `Could not find source map contents for ${compositionFile}`,+ );+ }++ const {resolveCompositionComponentLocation} =+ await import('@remotion/studio-codemods/resolve-composition-component-location');+ return {+ canAddSequence: false,+ location: resolveCompositionComponentLocation({+ compositionFile,+ compositionId,+ project: {files, rootDir: '.'},+ }),+ };+ })()+ : await callApi('/api/composition-component-info', request);const result = {location: body.location,