Skip to content

πŸŽ₯ Make videos programmatically with React

6.7 KB
Raw Blame
import fs from 'fs';
import assert from 'node:assert';
import {expect, test} from '@playwright/test';
import {
	getAllSchemaKeys,
	type SubscribeToSequencePropsRequest,
} from '@remotion/studio-shared';
import {NoReactInternals} from 'remotion/no-react';
import {apiCall} from './api-call.mts';
import {newVideoFile} from './constants.mts';
import {startStudio, stopStudio} from './studio-server.mts';

const subscribeToSequenceProps = async (
	request: SubscribeToSequencePropsRequest,
) => {
	const response = await apiCall('/api/subscribe-to-sequence-props', {
		requests: [request],
	});
	assert(response.success);
	const subscription = response.data.results[0];
	assert(subscription);
	return subscription;
};

test.describe('node-path cache for stale source maps', () => {
	let originalContent: string;

	test.beforeEach(async () => {
		originalContent = fs.readFileSync(newVideoFile, 'utf-8');
		await startStudio();
	});

	test.afterEach(async () => {
		fs.writeFileSync(newVideoFile, originalContent);
		await stopStudio();
	});

	// Regression test for the following scenario:
	//
	// 1. NewVideo.tsx has <Video> on line 22:
	//
	//      export const Component = () => {
	//        return <Video src={src} />;      // line 22
	//      };
	//
	// 2. The studio updates a prop via the API (suppressing the webpack rebuild).
	//    Prettier then wraps the return in parentheses, shifting <Video> to line 23:
	//
	//      export const Component = () => {
	//        return (
	//          <Video src={src} style={{}} />  // now line 23
	//        );
	//      };
	//
	// 3. On reload, the stale source map still resolves to line 22, but the tag
	//    is now on line 23. Without the node-path cache, subscribe-to-sequence-props
	//    would fail because lineColumnToNodePath(ast, 22) finds nothing.
	//
	// The cache stores (fileName, line, column) β†’ AST nodePath on first successful
	// resolution. When the same stale coordinates are sent again, the cached
	// nodePath is reused (and verified against the current AST).

	test('subscribe-to-sequence-props recovers from stale line numbers and node paths', async () => {
		const content = fs.readFileSync(newVideoFile, 'utf-8');
		const lines = content.split('\n');
		const videoLineIndex = lines.findIndex((l) => l.includes('<Video'));
		expect(videoLineIndex).toBeGreaterThan(-1);
		const videoLine = videoLineIndex + 1; // 1-indexed

		// 1. Initial subscription β†’ resolves line to AST nodePath and caches it
		const result1 = await subscribeToSequenceProps({
			fileName: 'src/NewVideo.tsx',
			line: videoLine,
			column: 0,
			nodePath: null,
			componentIdentity: 'dev.remotion.media.Video',
			effects: [],
			assetKeys: [],
			keys: getAllSchemaKeys(NoReactInternals.sequenceSchema),
			clientId: 'e2e-cache-test-1',
		});
		expect(result1.success).toBe(true);
		assert(result1.success);
		expect(result1.status.canUpdate).toBe(true);
		assert(result1.status.canUpdate);
		expect(result1.nodePath).toBeTruthy();

		// 2. Simulate prettier wrapping the return in parentheses,
		//    shifting <Video> down by one line.
		const editedContent = content.replace(
			'return <Video src={src} debugOverlay />;',
			'return (\n\t\t<Video src={src} debugOverlay />\n\t);',
		);
		expect(editedContent).not.toBe(content);
		fs.writeFileSync(newVideoFile, editedContent);

		// Verify the tag actually moved
		const editedLines = editedContent.split('\n');
		const newVideoLineIndex = editedLines.findIndex((l) =>
			l.includes('<Video'),
		);
		expect(newVideoLineIndex + 1).toBe(videoLine + 1);

		// 3. Subscribe again with the ORIGINAL (stale) line number.
		//    Without the cache, this would fail because the tag is no longer on this line.
		//    With the cache, the previously resolved nodePath is reused.
		const result2 = await subscribeToSequenceProps({
			fileName: 'src/NewVideo.tsx',
			line: videoLine, // stale line number
			column: 0,
			nodePath: null,
			componentIdentity: 'dev.remotion.media.Video',
			keys: getAllSchemaKeys(NoReactInternals.sequenceSchema),
			assetKeys: [],
			effects: [],
			clientId: 'e2e-cache-test-2',
		});
		expect(result2.success).toBe(true);
		assert(result2.success);
		expect(result2.status.canUpdate).toBe(true);
		assert(result2.status.canUpdate);
		expect(result2.nodePath).toBeTruthy();

		// The nodePath should be the same β€” both refer to the same <Video> element
		expect(result2.nodePath).toEqual(result1.nodePath);

		fs.writeFileSync(newVideoFile, originalContent);

		const identityContent = fs.readFileSync(newVideoFile, 'utf-8');
		const identityLines = identityContent.split('\n');
		const identityVideoLineIndex = identityLines.findIndex((l) =>
			l.includes('<Video'),
		);
		expect(identityVideoLineIndex).toBeGreaterThan(-1);
		const identityVideoLine = identityVideoLineIndex + 1;

		const identityResult = await subscribeToSequenceProps({
			fileName: 'src/NewVideo.tsx',
			line: identityVideoLine,
			column: 0,
			nodePath: null,
			componentIdentity: 'dev.remotion.media.Video',
			keys: ['debugOverlay'],
			assetKeys: [],
			effects: [],
			clientId: 'e2e-identity-mismatch-1',
		});
		expect(identityResult.success).toBe(true);
		assert(identityResult.success);
		expect(identityResult.status.canUpdate).toBe(true);
		assert(identityResult.status.canUpdate);
		expect(identityResult.status.props.debugOverlay).toEqual({
			status: 'static',
			codeValue: true,
			keyframeDisplayOffsetAdjustment: null,
		});

		const staleNodePath = identityResult.nodePath.nodePath;
		const wrappedInSequence = identityContent.replace(
			'return <Video src={src} debugOverlay />;',
			'return (\n\t\t<Sequence>\n\t\t\t<Video src={src} debugOverlay />\n\t\t</Sequence>\n\t);',
		);
		expect(wrappedInSequence).not.toBe(identityContent);
		fs.writeFileSync(newVideoFile, wrappedInSequence);

		const wrappedLines = wrappedInSequence.split('\n');
		const wrappedVideoLineIndex = wrappedLines.findIndex((l) =>
			l.includes('<Video'),
		);
		expect(wrappedVideoLineIndex).toBeGreaterThan(-1);
		const wrappedVideoLine = wrappedVideoLineIndex + 1;
		expect(wrappedVideoLine).not.toBe(identityVideoLine);

		const reconnectResult = await subscribeToSequenceProps({
			fileName: 'src/NewVideo.tsx',
			line: wrappedVideoLine,
			column: 0,
			nodePath: staleNodePath,
			componentIdentity: 'dev.remotion.media.Video',
			keys: ['debugOverlay'],
			assetKeys: [],
			effects: [],
			clientId: 'e2e-identity-mismatch-2',
		});
		expect(reconnectResult.success).toBe(true);
		assert(reconnectResult.success);
		expect(reconnectResult.status.canUpdate).toBe(true);
		assert(reconnectResult.status.canUpdate);
		expect(reconnectResult.status.props.debugOverlay).toEqual({
			status: 'static',
			codeValue: true,
			keyframeDisplayOffsetAdjustment: null,
		});
		expect(reconnectResult.nodePath.nodePath).not.toEqual(staleNodePath);
	});
});