Skip to content

πŸŽ₯ Make videos programmatically with React

`docs`: Declare and display Element dependencies (#10022)

Igor Samokhovets5dcb054a7c46
diff --git a/packages/docs/plugins/element-source-utils.js b/packages/docs/plugins/element-source-utils.js
index f837e8e4a0..782f968033 100644
--- a/packages/docs/plugins/element-source-utils.js
+++ b/packages/docs/plugins/element-source-utils.js
@@ -4,6 +4,10 @@ import {parse} from '@babel/parser';
const getPackageName = (importPath) => {
if (
+ importPath === 'react' ||
+ importPath.startsWith('react/') ||
+ importPath === 'react-dom' ||
+ importPath.startsWith('react-dom/') ||
importPath === 'remotion' ||
importPath.startsWith('.') ||
importPath.startsWith('/') ||
diff --git a/packages/docs/plugins/remark-element-source.js b/packages/docs/plugins/remark-element-source.js
index 63ce88a163..ebc9c1715a 100644
--- a/packages/docs/plugins/remark-element-source.js
+++ b/packages/docs/plugins/remark-element-source.js
@@ -1,7 +1,4 @@
-import {
- getRemotionElementDependencies,
- getRemotionElementSource,
-} from './element-source-utils.js';
+import {getRemotionElementSource} from './element-source-utils.js';
const getAttributeValue = (node, name) => {
const attribute = node.attributes?.find((attr) => attr.name === name);
@@ -42,51 +39,17 @@ const sourceCodeAttribute = (sourceCode) => {
};
};
-const dependenciesAttribute = (dependencies) => {
- const value = JSON.stringify(dependencies);
-
- return {
- type: 'mdxJsxAttribute',
- name: 'dependencies',
- value: {
- type: 'mdxJsxAttributeValueExpression',
- value,
- data: {
- estree: {
- type: 'Program',
- body: [
- {
- type: 'ExpressionStatement',
- expression: {
- type: 'ArrayExpression',
- elements: dependencies.map((dependency) => ({
- type: 'Literal',
- value: dependency,
- raw: JSON.stringify(dependency),
- })),
- },
- },
- ],
- sourceType: 'module',
- },
- },
- },
- };
-};
-
-const setElementPageSource = ({dependencies, node, sourceCode}) => {
+const setElementPageSource = ({node, sourceCode}) => {
const attributesWithoutSourceFile = (node.attributes ?? []).filter(
(attribute) => attribute.name !== 'sourceFile',
);
const attributesWithoutGeneratedValues = attributesWithoutSourceFile.filter(
- (attribute) =>
- attribute.name !== 'sourceCode' && attribute.name !== 'dependencies',
+ (attribute) => attribute.name !== 'sourceCode',
);
node.attributes = [
...attributesWithoutGeneratedValues,
sourceCodeAttribute(sourceCode),
- dependenciesAttribute(dependencies),
];
};
@@ -102,8 +65,7 @@ const getSourceCodeNode = ({node, sourceFilePath}) => {
}
const sourceCode = getRemotionElementSource({file, sourceFilePath});
- const dependencies = getRemotionElementDependencies(sourceCode);
- setElementPageSource({dependencies, node, sourceCode});
+ setElementPageSource({node, sourceCode});
return {
type: 'code',
diff --git a/packages/docs/src/components/Elements/ElementPage.module.css b/packages/docs/src/components/Elements/ElementPage.module.css
index 5faeb6fb50..9d93a65436 100644
--- a/packages/docs/src/components/Elements/ElementPage.module.css
+++ b/packages/docs/src/components/Elements/ElementPage.module.css
@@ -152,6 +152,16 @@
font-weight: 600;
}
+.dependencyList {
+ margin: 0;
+ padding-left: 18px;
+ text-align: left;
+}
+
+.dependencyList li + li {
+ margin-top: 4px;
+}
+
.contributors {
display: flex;
align-items: center;
diff --git a/packages/docs/src/components/Elements/ElementPage.tsx b/packages/docs/src/components/Elements/ElementPage.tsx
index 9883dd69cd..6845939e4f 100644
--- a/packages/docs/src/components/Elements/ElementPage.tsx
+++ b/packages/docs/src/components/Elements/ElementPage.tsx
@@ -26,7 +26,6 @@ import styles from './ElementPage.module.css';
type ElementPageProps = {
readonly children?: ReactNode;
readonly definition: ElementDefinition;
- readonly dependencies: string[];
readonly sourceCode?: string;
};
@@ -39,7 +38,6 @@ type InstallStatus =
export const ElementPage: React.FC<ElementPageProps> = ({
children,
definition,
- dependencies,
sourceCode,
}) => {
const {
@@ -74,7 +72,7 @@ export const ElementPage: React.FC<ElementPageProps> = ({
: null;
return createElementPayload({
- dependencies,
+ dependencies: definition.dependencies,
dimensions,
displayName,
durationInFrames,
@@ -82,7 +80,7 @@ export const ElementPage: React.FC<ElementPageProps> = ({
sourceCode,
});
}, [
- dependencies,
+ definition.dependencies,
displayName,
durationInFrames,
elementHeight,
@@ -243,6 +241,24 @@ export const ElementPage: React.FC<ElementPageProps> = ({
{`${durationInFrames} frames (${durationInFrames / fps}s)`}
</dd>
</div>
+ <div>
+ <dt>Dependencies</dt>
+ <dd>
+ {definition.dependencies.length === 0 ? (
+ 'None'
+ ) : (
+ <ul className={styles.dependencyList}>
+ {definition.dependencies.map((dependency) => (
+ <li key={dependency.name}>
+ {dependency.version === null
+ ? dependency.name
+ : `${dependency.name}@${dependency.version}`}
+ </li>
+ ))}
+ </ul>
+ )}
+ </dd>
+ </div>
</dl>
</div>
diff --git a/packages/docs/src/components/Elements/element-definitions.ts b/packages/docs/src/components/Elements/element-definitions.ts
index 9fbc728fe2..59e1652eb9 100644
--- a/packages/docs/src/components/Elements/element-definitions.ts
+++ b/packages/docs/src/components/Elements/element-definitions.ts
@@ -1,3 +1,4 @@
+import type {ElementDependency} from '@remotion/studio-protocol';
import type {ComponentType} from 'react';
import {LiquidContours} from '../../../elements/backgrounds/liquid-contours/liquid-contours';
import {NotebookPaper} from '../../../elements/backgrounds/notebook-paper/notebook-paper';
@@ -25,6 +26,7 @@ export type ElementDefinition = {
readonly category: string;
readonly component: ComponentType<Record<string, never>>;
readonly contributors: readonly Contributor[];
+ readonly dependencies: readonly ElementDependency[];
readonly description: string;
readonly displayName: string;
readonly durationInFrames: number;
@@ -46,6 +48,7 @@ export const elementDefinitions = {
contributors: [],
description:
'A flowing two-color background made from animated liquid contour bands.',
+ dependencies: [{name: '@remotion/effects', version: null}],
displayName: 'Liquid Contours',
durationInFrames: 240,
elementHeight: null,
@@ -68,6 +71,7 @@ export const elementDefinitions = {
component: NotebookPaper,
contributors: [],
description: 'A white paper background with subtle blue gridlines.',
+ dependencies: [{name: '@remotion/effects', version: null}],
displayName: 'Notebook Paper',
durationInFrames: 120,
elementHeight: null,
@@ -91,6 +95,7 @@ export const elementDefinitions = {
contributors: [],
description:
'A white paper texture background with a slowly changing posterized seed.',
+ dependencies: [{name: '@remotion/effects', version: null}],
displayName: 'Paper Texture',
durationInFrames: 120,
elementHeight: null,
@@ -113,6 +118,7 @@ export const elementDefinitions = {
component: RotatingStarburst,
contributors: [],
description: 'A solid background with a slowly rotating starburst effect.',
+ dependencies: [{name: '@remotion/effects', version: null}],
displayName: 'Rotating Starburst',
durationInFrames: 240,
elementHeight: null,
@@ -135,6 +141,7 @@ export const elementDefinitions = {
component: LocationLowerThird,
contributors: [],
description: 'An animated lower third for an event location and venue.',
+ dependencies: [],
displayName: 'Location Lower Third',
durationInFrames: 120,
elementHeight: 138,
@@ -158,6 +165,7 @@ export const elementDefinitions = {
contributors: [],
description:
'A clean animated lower third for introducing a speaker, guest, or host.',
+ dependencies: [{name: '@remotion/google-fonts', version: null}],
displayName: 'Name Lower Third',
durationInFrames: 120,
elementHeight: 138,
@@ -181,6 +189,7 @@ export const elementDefinitions = {
contributors: [],
description:
'A bold bar chart card with three directly labeled data points.',
+ dependencies: [{name: '@remotion/google-fonts', version: null}],
displayName: 'Horizontal Bar Chart',
durationInFrames: 120,
elementHeight: 864,
@@ -209,6 +218,7 @@ export const elementDefinitions = {
],
description:
'A simple animated counter that smoothly counts from a start value to an end value.',
+ dependencies: [{name: '@remotion/google-fonts', version: null}],
displayName: 'Number Counter',
durationInFrames: 120,
elementHeight: 200,
@@ -232,6 +242,7 @@ export const elementDefinitions = {
contributors: [],
description:
'An animated product card with a bold title, catalog image, pricing, and discount.',
+ dependencies: [{name: '@remotion/google-fonts', version: null}],
displayName: 'Product Offer',
durationInFrames: 150,
elementHeight: 900,
@@ -255,6 +266,10 @@ export const elementDefinitions = {
contributors: [],
description:
'An animated hand-drawn circle with posterized drawing progress and shape changes.',
+ dependencies: [
+ {name: '@remotion/google-fonts', version: null},
+ {name: '@remotion/rough-notation', version: null},
+ ],
displayName: 'Circle Marker',
durationInFrames: 120,
elementHeight: 220,
@@ -278,6 +293,10 @@ export const elementDefinitions = {
contributors: [],
description:
'An animated hand-drawn cross for removing a word or phrase with emphasis.',
+ dependencies: [
+ {name: '@remotion/google-fonts', version: null},
+ {name: '@remotion/rough-notation', version: null},
+ ],
displayName: 'Crossed Off',
durationInFrames: 120,
elementHeight: 220,
@@ -299,6 +318,7 @@ export const elementDefinitions = {
contributors: [],
description:
'A framed news article with camera movement, blur, and animated passage highlights.',
+ dependencies: [{name: '@remotion/rough-notation', version: null}],
displayName: 'News Article Headline Highlight',
durationInFrames: 150,
elementHeight: null,
@@ -322,6 +342,10 @@ export const elementDefinitions = {
contributors: [],
description:
'An animated hand-drawn line for striking through a word or phrase.',
+ dependencies: [
+ {name: '@remotion/google-fonts', version: null},
+ {name: '@remotion/rough-notation', version: null},
+ ],
displayName: 'Strike Through',
durationInFrames: 120,
elementHeight: 220,
@@ -345,6 +369,10 @@ export const elementDefinitions = {
contributors: [],
description:
'A hand-drawn animated text marker for calling attention to one phrase.',
+ dependencies: [
+ {name: '@remotion/google-fonts', version: null},
+ {name: '@remotion/rough-notation', version: null},
+ ],
displayName: 'Text Marker',
durationInFrames: 120,
elementHeight: 220,
@@ -366,6 +394,11 @@ export const elementDefinitions = {
contributors: [{username: 'JonnyBurger', contribution: null}],
description:
'Previously a paid template on remotion.pro, Timed Captions is now free for everyone.',
+ dependencies: [
+ {name: '@remotion/captions', version: null},
+ {name: '@remotion/google-fonts', version: null},
+ {name: '@remotion/layout-utils', version: null},
+ ],
displayName: 'Timed Captions',
durationInFrames: 210,
elementHeight: 180,
diff --git a/packages/docs/src/test/elements.test.ts b/packages/docs/src/test/elements.test.ts
index 804c71618b..343e33d5c2 100644
--- a/packages/docs/src/test/elements.test.ts
+++ b/packages/docs/src/test/elements.test.ts
@@ -107,20 +107,18 @@ describe('Elements must follow the colocated single-file format', () => {
expect(
elementPage.attributes.some((attr) => attr.name === 'sourceCode'),
).toBe(true);
- const dependencies = elementPage.attributes.find(
- (attribute) => attribute.name === 'dependencies',
- );
- expect(dependencies?.value.value).toBe(
- JSON.stringify(
- getRemotionElementDependencies(readFileSync(element.tsxPath, 'utf8')),
+ expect(
+ elementPage.attributes.some(
+ (attribute) => attribute.name === 'dependencies',
),
- );
+ ).toBe(false);
});
test('extracts dependencies using the TypeScript parser', () => {
expect(
getRemotionElementDependencies(`
import type {FC} from 'react';
+ import {createRoot} from 'react-dom/client';
import {loadFont} from '@remotion/google-fonts/Inter';
import {AbsoluteFill} from 'remotion';
// import value from 'comment-dependency';
@@ -131,12 +129,7 @@ describe('Elements must follow the colocated single-file format', () => {
export const Element: FC = () => <AbsoluteFill />;
`),
- ).toEqual([
- 'react',
- '@remotion/google-fonts',
- 'actual-reexport',
- 'actual-dynamic',
- ]);
+ ).toEqual(['@remotion/google-fonts', 'actual-reexport', 'actual-dynamic']);
});
for (const element of allElements) {
@@ -315,6 +308,25 @@ describe('Element preview definitions', () => {
}
});
+ test('declares every external source dependency centrally', () => {
+ for (const element of productionElements) {
+ const definition = elementDefinitionList.find(
+ (entry) => entry.slug === element.name,
+ );
+ if (!definition) {
+ throw new Error(`Missing definition for ${element.name}`);
+ }
+
+ expect(
+ definition.dependencies.map((dependency) => dependency.name).sort(),
+ ).toEqual(
+ getRemotionElementDependencies(
+ readFileSync(element.tsxPath, 'utf8'),
+ ).sort(),
+ );
+ }
+ });
+
test('contains valid render metadata', () => {
for (const definition of elementDefinitionList) {
expect(Number.isInteger(definition.width)).toBe(true);
diff --git a/packages/studio-protocol/src/element-drag-data.ts b/packages/studio-protocol/src/element-drag-data.ts
index 99b6892465..0b9dabf467 100644
--- a/packages/studio-protocol/src/element-drag-data.ts
+++ b/packages/studio-protocol/src/element-drag-data.ts
@@ -4,11 +4,16 @@ import {
} from './component-drag-data';
import {isRecord, isValidPackageName} from './validation';
+export type ElementDependency = {
+ readonly name: string;
+ readonly version: string | null;
+};
+
export type ElementDragData = {
type: 'remotion-element';
version: 1;
element: {
- dependencies: string[];
+ dependencies: ElementDependency[];
/** Absent in legacy v1 drag payloads. */
durationInFrames?: number;
slug: string;
@@ -45,15 +50,9 @@ const isSlug = (value: unknown): value is string => {
};
export const makeElementFileNameFromSlug = (slug: string) => {
- if (!isSlug(slug)) {
- return null;
- }
-
+ if (!isSlug(slug)) return null;
const lastSegment = slug.split('/').at(-1);
- if (!lastSegment) {
- return null;
- }
-
+ if (!lastSegment) return null;
const fileName = `${lastSegment}.element.tsx`;
return isLowercaseElementFileName(fileName) ? fileName : null;
};
@@ -65,16 +64,30 @@ export const getElementComponentNameFromSourceCode = (sourceCode: string) => {
),
).map((match) => match[1]);
const uniqueComponentNames = Array.from(new Set(componentNames));
-
- if (uniqueComponentNames.length !== 1) {
- return null;
- }
-
+ if (uniqueComponentNames.length !== 1) return null;
return isComponentIdentifier(uniqueComponentNames[0])
? uniqueComponentNames[0]
: null;
};
+const packagesProvidedByRemotionProjects = new Set([
+ 'react',
+ 'react-dom',
+ 'remotion',
+]);
+
+const isExactVersion = (value: unknown): value is string =>
+ typeof value === 'string' &&
+ /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(value);
+
+export const isElementDependency = (
+ value: unknown,
+): value is ElementDependency =>
+ isRecord(value) &&
+ typeof value.name === 'string' &&
+ isValidPackageName(value.name) &&
+ (value.version === null || isExactVersion(value.version));
+
export const makeElementDragData = ({
dependencies,
dimensions,
@@ -82,32 +95,43 @@ export const makeElementDragData = ({
durationInFrames,
slug,
sourceCode,
-}: ElementDragData['element']): ElementDragData => {
- return {
- type: 'remotion-element',
- version: 1,
- element: {
- dependencies: Array.from(new Set(dependencies)),
- ...(durationInFrames === undefined ? {} : {durationInFrames}),
- slug,
- displayName,
- sourceCode,
- dimensions,
- },
- };
-};
+}: Omit<ElementDragData['element'], 'dependencies'> & {
+ dependencies: (ElementDependency | string)[];
+}): ElementDragData => ({
+ type: 'remotion-element',
+ version: 1,
+ element: {
+ dependencies: Array.from(
+ new Map(
+ dependencies
+ .map((dependency) =>
+ typeof dependency === 'string'
+ ? {name: dependency, version: null}
+ : dependency,
+ )
+ .filter(
+ (dependency) =>
+ !packagesProvidedByRemotionProjects.has(dependency.name),
+ )
+ .map((dependency) => [dependency.name, dependency] as const),
+ ).values(),
+ ),
+ dimensions,
+ displayName,
+ ...(durationInFrames === undefined ? {} : {durationInFrames}),
+ slug,
+ sourceCode,
+ },
+});
-const isDimensions = (value: unknown): value is ComponentDimensions => {
- return (
- isRecord(value) &&
- typeof value.width === 'number' &&
- Number.isFinite(value.width) &&
- value.width > 0 &&
- typeof value.height === 'number' &&
- Number.isFinite(value.height) &&
- value.height > 0
- );
-};
+const isDimensions = (value: unknown): value is ComponentDimensions =>
+ isRecord(value) &&
+ typeof value.width === 'number' &&
+ Number.isFinite(value.width) &&
+ value.width > 0 &&
+ typeof value.height === 'number' &&
+ Number.isFinite(value.height) &&
+ value.height > 0;
const isDuration = (value: unknown): value is number =>
typeof value === 'number' &&
@@ -123,10 +147,8 @@ export const parseElementDragData = (value: string): ElementDragData | null => {
parsed.type !== 'remotion-element' ||
parsed.version !== 1 ||
!isRecord(parsed.element)
- ) {
+ )
return null;
- }
-
const {
dependencies,
dimensions,
@@ -135,6 +157,16 @@ export const parseElementDragData = (value: string): ElementDragData | null => {
slug,
sourceCode,
} = parsed.element;
+ const normalizedDependencies =
+ dependencies === undefined
+ ? []
+ : Array.isArray(dependencies) && dependencies.length <= 100
+ ? dependencies.map((dependency) =>
+ typeof dependency === 'string'
+ ? {name: dependency, version: null}
+ : dependency,
+ )
+ : null;
if (
!isSlug(slug) ||
typeof displayName !== 'string' ||
@@ -145,28 +177,21 @@ export const parseElementDragData = (value: string): ElementDragData | null => {
sourceCode.length >= 200000 ||
getElementComponentNameFromSourceCode(sourceCode) === null ||
makeElementFileNameFromSlug(slug) === null ||
+ normalizedDependencies === null ||
+ !normalizedDependencies.every(isElementDependency) ||
(durationInFrames !== undefined && !isDuration(durationInFrames)) ||
- (dependencies !== undefined &&
- (!Array.isArray(dependencies) ||
- dependencies.length > 100 ||
- !dependencies.every(
- (dependency) =>
- typeof dependency === 'string' && isValidPackageName(dependency),
- ))) ||
(dimensions !== undefined &&
dimensions !== null &&
!isDimensions(dimensions))
- ) {
+ )
return null;
- }
-
return makeElementDragData({
- dependencies: dependencies ?? [],
+ dependencies: normalizedDependencies,
+ dimensions: dimensions ?? null,
+ displayName,
durationInFrames,
slug,
- displayName,
sourceCode,
- dimensions: dimensions ?? null,
});
} catch {
return null;
diff --git a/packages/studio-protocol/src/element-payload.ts b/packages/studio-protocol/src/element-payload.ts
index dc3b19f856..ee007ae81f 100644
--- a/packages/studio-protocol/src/element-payload.ts
+++ b/packages/studio-protocol/src/element-payload.ts
@@ -1,10 +1,12 @@
import type {ComponentDimensions} from './component-drag-data';
import {makeDragData} from './drag-data';
-import type {makeElementDragData} from './element-drag-data';
import {
getElementComponentNameFromSourceCode,
+ isElementDependency,
makeElementFileNameFromSlug,
parseElementDragData,
+ type ElementDependency,
+ type ElementDragData,
} from './element-drag-data';
import {isRecord, isValidPackageName} from './validation';
@@ -16,12 +18,12 @@ export type CreateElementPayloadInput = {
readonly displayName: string;
readonly slug: string;
readonly sourceCode: string;
- readonly dependencies: readonly string[];
+ readonly dependencies: readonly (ElementDependency | string)[];
readonly dimensions: ComponentDimensions | null;
readonly durationInFrames: number;
};
-export type StudioElementPayload = ReturnType<typeof makeElementDragData> & {
+export type StudioElementPayload = ElementDragData & {
readonly durationInFrames: number;
};
@@ -38,79 +40,71 @@ const assertCreateElementPayloadInput = (
throw new TypeError('displayName must be a non-empty string');
}
- if (input.displayName.length >= 120) {
+ if (input.displayName.length >= 120)
throw new TypeError('displayName must be shorter than 120 characters');
- }
-
- if (makeElementFileNameFromSlug(input.slug) === null) {
+ if (makeElementFileNameFromSlug(input.slug) === null)
throw new TypeError('slug must be a safe lowercase Element slug');
- }
-
if (
typeof input.sourceCode !== 'string' ||
input.sourceCode.trim().length === 0
- ) {
+ )
throw new TypeError('sourceCode must be a non-empty string');
- }
-
- if (input.sourceCode.length >= MAX_SOURCE_CODE_SIZE) {
+ if (input.sourceCode.length >= MAX_SOURCE_CODE_SIZE)
throw new TypeError(
`sourceCode must be shorter than ${MAX_SOURCE_CODE_SIZE} characters`,
);
- }
-
- if (getElementComponentNameFromSourceCode(input.sourceCode) === null) {
+ if (getElementComponentNameFromSourceCode(input.sourceCode) === null)
throw new TypeError(
'sourceCode must contain exactly one exported named React component',
);
- }
-
- if (!Array.isArray(input.dependencies)) {
+ if (!Array.isArray(input.dependencies))
throw new TypeError('dependencies must be an array');
- }
-
- if (input.dependencies.length > MAX_DEPENDENCIES) {
+ if (input.dependencies.length > MAX_DEPENDENCIES)
throw new TypeError(
`dependencies must contain at most ${MAX_DEPENDENCIES} packages`,
);
- }
-
for (const dependency of input.dependencies) {
- if (typeof dependency !== 'string' || !isValidPackageName(dependency)) {
+ if (
+ (typeof dependency === 'string' && !isValidPackageName(dependency)) ||
+ (typeof dependency !== 'string' && !isElementDependency(dependency))
+ ) {
throw new TypeError(
- `Invalid dependency package name: ${String(dependency)}`,
+ `Invalid Element dependency: ${JSON.stringify(dependency)}`,
);
}
}
- if (!isDuration(input.durationInFrames)) {
+ if (!isDuration(input.durationInFrames))
throw new TypeError(
'durationInFrames must be an integer between 1 and 100000000',
);
- }
};
export const createElementPayload = (
input: CreateElementPayloadInput,
): StudioElementPayload => {
assertCreateElementPayloadInput(input);
-
const constructed = makeDragData({
type: 'element',
- ...input,
- dependencies: input.dependencies.slice(),
+ dependencies: input.dependencies.map((dependency) =>
+ typeof dependency === 'string'
+ ? {name: dependency, version: null}
+ : dependency,
+ ),
+ dimensions: input.dimensions,
+ displayName: input.displayName,
+ durationInFrames: input.durationInFrames,
+ slug: input.slug,
+ sourceCode: input.sourceCode,
});
const payload: StudioElementPayload = {
...constructed.data,
durationInFrames: input.durationInFrames,
};
-
- if (JSON.stringify(payload).length > MAX_PAYLOAD_SIZE) {
+ if (JSON.stringify(payload).length > MAX_PAYLOAD_SIZE)
throw new TypeError(
`The Element payload must be smaller than ${MAX_PAYLOAD_SIZE} characters`,
);
- }
-
return payload;
};
@@ -123,35 +117,20 @@ export const parseStudioElementPayload = (
value.version !== 1 ||
!isDuration(value.durationInFrames) ||
!isRecord(value.element)
- ) {
+ )
return null;
- }
-
- const parsed = parseElementDragData(
+ const element = parseElementDragData(
JSON.stringify({
type: value.type,
version: value.version,
element: value.element,
}),
);
- if (parsed === null) {
- return null;
- }
-
- try {
- makeDragData({
- type: 'element',
- ...parsed.element,
- durationInFrames: value.durationInFrames,
- });
- } catch {
- return null;
- }
-
+ if (element === null) return null;
const payload: StudioElementPayload = {
- ...parsed,
+ ...element,
element: {
- ...parsed.element,
+ ...element.element,
durationInFrames: value.durationInFrames,
},
durationInFrames: value.durationInFrames,
diff --git a/packages/studio-protocol/src/index.ts b/packages/studio-protocol/src/index.ts
index c10c3db649..f06ec056e9 100644
--- a/packages/studio-protocol/src/index.ts
+++ b/packages/studio-protocol/src/index.ts
@@ -44,7 +44,7 @@ export type {
SfxDragPreviewMetadata,
} from './drag-preview-metadata';
export type {EffectDragData} from './effect-drag-data';
-export type {ElementDragData} from './element-drag-data';
+export type {ElementDependency, ElementDragData} from './element-drag-data';
export type {SfxDragData} from './sfx-drag-data';
export {setStudioDragData} from './drag-transport';
export {
diff --git a/packages/studio-protocol/src/test/drag-data.test.ts b/packages/studio-protocol/src/test/drag-data.test.ts
index 0587fbef03..961c20f48c 100644
--- a/packages/studio-protocol/src/test/drag-data.test.ts
+++ b/packages/studio-protocol/src/test/drag-data.test.ts
@@ -39,7 +39,7 @@ const inputs: MakeDragDataInput[] = [
},
{
type: 'element',
- dependencies: ['@remotion/google-fonts'],
+ dependencies: [{name: '@remotion/google-fonts', version: null}],
slug: 'overlays/lower-third',
displayName: 'Lower Third',
sourceCode: 'export const LowerThird = () => null;',
diff --git a/packages/studio-protocol/src/test/element-payload.test.ts b/packages/studio-protocol/src/test/element-payload.test.ts
index d3b97f22bb..3123dc70f5 100644
--- a/packages/studio-protocol/src/test/element-payload.test.ts
+++ b/packages/studio-protocol/src/test/element-payload.test.ts
@@ -4,7 +4,13 @@ import {setStudioDragData} from '../drag-transport';
import {createElementPayload} from '../element-payload';
const validInput = {
- dependencies: ['remotion', 'remotion'],
+ dependencies: [
+ 'react',
+ 'react-dom',
+ 'remotion',
+ '@remotion/google-fonts',
+ '@remotion/google-fonts',
+ ],
dimensions: {width: 800, height: 200},
displayName: 'Lower Third',
durationInFrames: 90,
@@ -19,7 +25,7 @@ test('creates one canonical Element payload for HTTP and drag transports', () =>
version: 1,
durationInFrames: 90,
element: {
- dependencies: ['remotion'],
+ dependencies: [{name: '@remotion/google-fonts', version: null}],
dimensions: {width: 800, height: 200},
displayName: 'Lower Third',
durationInFrames: 90,
@@ -69,7 +75,7 @@ test('rejects invalid Element authoring input with actionable errors', () => {
},
{
input: {...validInput, dependencies: ['FS']},
- message: 'Invalid dependency package name: FS',
+ message: 'Invalid Element dependency: "FS"',
},
{
input: {...validInput, dimensions: {width: 0, height: 200}},
diff --git a/packages/studio-server/src/preview-server/routes/install-dependency.ts b/packages/studio-server/src/preview-server/routes/install-dependency.ts
index d04b543d7d..010db32617 100644
--- a/packages/studio-server/src/preview-server/routes/install-dependency.ts
+++ b/packages/studio-server/src/preview-server/routes/install-dependency.ts
@@ -1,5 +1,6 @@
import {spawn} from 'node:child_process';
import {RenderInternals} from '@remotion/renderer';
+import type {ElementDependency} from '@remotion/studio-protocol';
import {
extraPackages,
isValidPackageName,
@@ -17,27 +18,43 @@ const getExtraPackageVersion = (packageName: string): string | null => {
return pkg ? pkg.version : null;
};
-export const getPackageInstallSpec = (packageName: string): string => {
- const extraVersion = getExtraPackageVersion(packageName);
- if (extraVersion) {
- return `${packageName}@${extraVersion}`;
- }
-
- if (packageName === 'remotion' || packageName.startsWith('@remotion/')) {
- return `${packageName}@${VERSION}`;
- }
-
- return packageName;
+export const getPackageInstallSpec = (
+ dependency: ElementDependency | string,
+): string => {
+ const {name, version} =
+ typeof dependency === 'string'
+ ? {name: dependency, version: null}
+ : dependency;
+ const extraVersion = getExtraPackageVersion(name);
+ if (extraVersion) return `${name}@${extraVersion}`;
+ if (name === 'remotion' || name.startsWith('@remotion/'))
+ return `${name}@${VERSION}`;
+ return version === null ? name : `${name}@${version}`;
};
export const handleInstallPackage: ApiHandler<
InstallPackageRequest,
InstallPackageResponse
-> = async ({logLevel, remotionRoot, input: {packageNames}}) => {
- for (const packageName of packageNames) {
- if (!isValidPackageName(packageName)) {
+> = async ({logLevel, remotionRoot, input: {dependencies}}) => {
+ for (const dependency of dependencies) {
+ if (!isValidPackageName(dependency.name)) {
+ return Promise.reject(
+ new Error(
+ `Package name ${JSON.stringify(dependency.name)} is invalid.`,
+ ),
+ );
+ }
+
+ if (
+ dependency.version !== null &&
+ !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(
+ dependency.version,
+ )
+ ) {
return Promise.reject(
- new Error(`Package name ${JSON.stringify(packageName)} is invalid.`),
+ new Error(
+ `Package version ${JSON.stringify(dependency.version)} is invalid.`,
+ ),
);
}
}
@@ -50,28 +67,21 @@ export const handleInstallPackage: ApiHandler<
});
if (manager === 'unknown') {
throw new Error(
- `No lockfile was found in your project (one of ${lockFilePaths
- .map((p) => p.path)
- .join(', ')}). Install dependencies using your favorite manager!`,
+ `No lockfile was found in your project (one of ${lockFilePaths.map((p) => p.path).join(', ')}). Install dependencies using your favorite manager!`,
);
}
- // Remotion packages must match the Studio version and catalogued extra
- // packages use their supported version. Other packages resolve normally.
- const packagesWithVersions = packageNames.map(getPackageInstallSpec);
-
+ const packagesWithVersions = dependencies.map(getPackageInstallSpec);
const command = getInstallCommand({
manager: manager.manager,
packages: packagesWithVersions,
version: '',
additionalArgs: [],
});
-
RenderInternals.Log.info(
{indent: false, logLevel},
RenderInternals.chalk.gray(`╭─ ${manager.manager} ${command.join(' ')}`),
);
-
const time = Date.now();
try {
await new Promise<void>((resolve, reject) => {
@@ -80,42 +90,38 @@ export const handleInstallPackage: ApiHandler<
command,
getPackageManagerSpawnOptions(),
);
- cmd.on('error', (err) => {
- reject(err);
- });
- cmd.stdout.on('data', (d: Buffer) => {
- const splitted = d.toString().trim().split('\n');
- splitted.forEach((line) => {
- RenderInternals.Log.info({indent: true, logLevel}, line);
- });
- });
- cmd.stdout.on('end', () => {
- resolve();
- });
- cmd.on('close', (code, signal) => {
- if (code === 0) {
- resolve();
- } else {
- reject(
- new Error(`Command exited with code ${code} and signal ${signal}`),
- );
- }
- });
+ cmd.on('error', reject);
+ cmd.stdout.on('data', (d: Buffer) =>
+ d
+ .toString()
+ .trim()
+ .split('\n')
+ .forEach((line) =>
+ RenderInternals.Log.info({indent: true, logLevel}, line),
+ ),
+ );
+ cmd.stdout.on('end', resolve);
+ cmd.on('close', (code, signal) =>
+ code === 0
+ ? resolve()
+ : reject(
+ new Error(
+ `Command exited with code ${code} and signal ${signal}`,
+ ),
+ ),
+ );
});
- const timeEnd = Date.now();
-
RenderInternals.Log.info(
{indent: false, logLevel},
RenderInternals.chalk.gray('╰─ '),
- `Done in ${timeEnd - time}ms`,
+ `Done in ${Date.now() - time}ms`,
);
- return Promise.resolve({});
+ return {};
} catch (err) {
- const timeEnd = Date.now();
RenderInternals.Log.info(
{indent: false, logLevel},
RenderInternals.chalk.gray('╰─ '),
- RenderInternals.chalk.red(`Errored in ${timeEnd - time}ms`),
+ RenderInternals.chalk.red(`Errored in ${Date.now() - time}ms`),
);
return Promise.reject(err);
}
diff --git a/packages/studio-server/src/test/install-dependency.test.ts b/packages/studio-server/src/test/install-dependency.test.ts
index c58c858a7a..98fd8ac5c0 100644
--- a/packages/studio-server/src/test/install-dependency.test.ts
+++ b/packages/studio-server/src/test/install-dependency.test.ts
@@ -17,3 +17,12 @@ test('lets the package manager resolve other packages', () => {
expect(getPackageInstallSpec('lodash')).toBe('lodash');
expect(getPackageInstallSpec('@acme/video')).toBe('@acme/video');
});
+
+test('uses exact declared versions for non-Remotion dependencies', () => {
+ expect(getPackageInstallSpec({name: 'lodash', version: '4.17.21'})).toBe(
+ );
+ expect(
+ getPackageInstallSpec({name: '@remotion/effects', version: '1.0.0'}),
+ ).toBe(`@remotion/effects@${VERSION}`);
+});
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index b08791338a..45ab5c8552 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -11,7 +11,11 @@ import type {
X264Preset,
} from '@remotion/renderer';
import type {HardwareAccelerationOption} from '@remotion/renderer/client';
-import type {ComponentProp, ElementDragData} from '@remotion/studio-protocol';
+import type {
+ ComponentProp,
+ ElementDependency,
+ ElementDragData,
+} from '@remotion/studio-protocol';
import type {
_InternalTypes,
CannotUpdateSequenceReason,
@@ -1009,7 +1013,7 @@ export type UpdateDefaultEditorResponse =
};
export type InstallPackageRequest = {
- packageNames: string[];
+ dependencies: ElementDependency[];
};
export type InstallPackageResponse = {};
diff --git a/packages/studio-shared/src/test/element-drag-data.test.ts b/packages/studio-shared/src/test/element-drag-data.test.ts
index b63ccf7d4d..b8e623c794 100644
--- a/packages/studio-shared/src/test/element-drag-data.test.ts
+++ b/packages/studio-shared/src/test/element-drag-data.test.ts
@@ -2,7 +2,7 @@ import {expect, test} from 'bun:test';
import {StudioProtocolInternals} from '@remotion/studio-protocol';
const validElement = {
- dependencies: ['@remotion/google-fonts'],
+ dependencies: [{name: '@remotion/google-fonts', version: null}],
slug: 'overlays/lower-third',
displayName: 'Lower Third',
sourceCode: 'export const LowerThird = () => null;',
@@ -12,7 +12,7 @@ const makeElementDragData = (
element:
| typeof validElement
| {
- dependencies: string[];
+ dependencies: {name: string; version: null}[];
slug: string;
displayName: string;
sourceCode: string;
@@ -23,7 +23,7 @@ const makeElementDragData = (
type: 'element',
...element,
durationInFrames: 120,
- }).data;
+ } as never).data;
const parseElementDragData = (payload: string) => {
let dimensions: (typeof validElement)['dimensions'] | null = null;
try {
@@ -45,7 +45,7 @@ const parseElementDragData = (payload: string) => {
...validElement,
dimensions,
durationInFrames: 120,
- });
+ } as never);
const parsed = StudioProtocolInternals.parseDragData({mimeType, payload});
return parsed?.type === 'element' ? parsed.data : null;
};
diff --git a/packages/studio/src/api/install-package.ts b/packages/studio/src/api/install-package.ts
index d24322d62c..bb38874fc7 100644
--- a/packages/studio/src/api/install-package.ts
+++ b/packages/studio/src/api/install-package.ts
@@ -1,9 +1,10 @@
+import type {ElementDependency} from '@remotion/studio-protocol';
import type {InstallPackageResponse} from '@remotion/studio-shared';
import {getRemotionEnvironment} from 'remotion';
import {callApi} from '../components/call-api';
export const installPackages = (
- packageNames: string[],
+ dependencies: (ElementDependency | string)[],
): Promise<InstallPackageResponse> => {
if (!getRemotionEnvironment().isStudio) {
throw new Error('installPackages() is only available in the Studio');
@@ -13,5 +14,11 @@ export const installPackages = (
throw new Error('installPackages() is not available in Read-Only Studio');
}
- return callApi('/api/install-package', {packageNames});
+ return callApi('/api/install-package', {
+ dependencies: dependencies.map((dependency) =>
+ typeof dependency === 'string'
+ ? {name: dependency, version: null}
+ : dependency,
+ ),
+ });
};
diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsx
index 1334c5ae32..395f9ba35a 100644
--- a/packages/studio/src/components/Canvas.tsx
+++ b/packages/studio/src/components/Canvas.tsx
@@ -872,17 +872,28 @@ export const Canvas: React.FC<{
}
const declaredDependencies = Array.from(
- new Set(activeElementInstallRequest.element.dependencies),
+ new Map(
+ activeElementInstallRequest.element.dependencies.map((dependency) => [
+ dependency.name,
+ dependency,
+ ]),
+ ).values(),
);
- const missingPackages = getMissingPackages(declaredDependencies);
- const ignoredDependencies = declaredDependencies.filter(
- (packageName) =>
- elementInstallDependencyIgnoreList.includes(packageName) &&
- !missingPackages.includes(packageName),
+ const missingPackages = getMissingPackages(declaredDependencies).map(
+ (dependency) => dependency.name,
);
- const dependenciesToReview = declaredDependencies.filter(
- (packageName) => !ignoredDependencies.includes(packageName),
+ const ignoredDependencies = declaredDependencies.filter(
+ (dependency) =>
+ elementInstallDependencyIgnoreList.includes(dependency.name) &&
+ !missingPackages.includes(dependency.name),
);
+ const dependenciesToReview = declaredDependencies
+ .filter((dependency) => !ignoredDependencies.includes(dependency))
+ .map((dependency) =>
+ dependency.version === null
+ ? dependency.name
+ : `${dependency.name}@${dependency.version}`,
+ );
const sourceLabel =
activeElementInstallRequest.source.type === 'studio-protocol'
? activeElementInstallRequest.source.origin
diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.ts
index 2f1fc32582..86fefb0416 100644
--- a/packages/studio/src/components/import-assets.ts
+++ b/packages/studio/src/components/import-assets.ts
@@ -693,7 +693,9 @@ const insertCompositionElement = async ({
from: number | null;
}) => {
const requiredPackage = getRequiredPackageForInsertableElement(element);
- await installRequiredPackages(requiredPackage ? [requiredPackage] : []);
+ await installRequiredPackages(
+ requiredPackage ? [{name: requiredPackage, version: null}] : [],
+ );
const result = await callApi('/api/insert-jsx-element', {
compositionFile,
diff --git a/packages/studio/src/helpers/install-required-package.ts b/packages/studio/src/helpers/install-required-package.ts
index eadf6da6ab..35ee33f5d8 100644
--- a/packages/studio/src/helpers/install-required-package.ts
+++ b/packages/studio/src/helpers/install-required-package.ts
@@ -1,41 +1,56 @@
+import type {ElementDependency} from '@remotion/studio-protocol';
import {installPackages} from '../api/install-package';
import {showNotification} from '../components/Notifications/NotificationCenter';
let installQueue: Promise<void> = Promise.resolve();
-export const getMissingPackages = (packageNames: string[]) => {
- const uniquePackageNames = Array.from(new Set(packageNames));
- const installedPackages = window.remotion_installedPackages ?? [];
+const uniqueDependencies = (
+ dependencies: (ElementDependency | string)[],
+): ElementDependency[] =>
+ Array.from(
+ new Map(
+ dependencies.map((dependency) => {
+ const normalized =
+ typeof dependency === 'string'
+ ? {name: dependency, version: null}
+ : dependency;
+ return [normalized.name, normalized] as const;
+ }),
+ ).values(),
+ );
- return uniquePackageNames.filter(
- (packageName) => !installedPackages.includes(packageName),
+export const getMissingPackages = (
+ dependencies: (ElementDependency | string)[],
+) => {
+ const installedPackages = window.remotion_installedPackages ?? [];
+ return uniqueDependencies(dependencies).filter(
+ (dependency) =>
+ dependency.version !== null ||
+ !installedPackages.includes(dependency.name),
);
};
-const addInstalledPackages = (packageNames: string[]) => {
+const addInstalledPackages = (dependencies: (ElementDependency | string)[]) => {
const installedPackages = window.remotion_installedPackages ?? [];
window.remotion_installedPackages = Array.from(
- new Set([...installedPackages, ...packageNames]),
+ new Set([
+ ...installedPackages,
+ ...uniqueDependencies(dependencies).map((dependency) => dependency.name),
+ ]),
);
};
-const formatPackageList = (packageNames: string[]) => {
- if (packageNames.length === 1) {
- return packageNames[0];
- }
-
- return `${packageNames.length} packages`;
-};
+const formatPackageList = (dependencies: ElementDependency[]) =>
+ dependencies.length === 1
+ ? dependencies[0]!.name
+ : `${dependencies.length} packages`;
export const installRequiredPackages = async (
- packageNames: string[],
+ dependencies: (ElementDependency | string)[],
): Promise<void> => {
const runInstall = async () => {
- const missingPackages = getMissingPackages(packageNames);
- if (missingPackages.length === 0) {
- return;
- }
-
+ const missingPackages = getMissingPackages(dependencies);
+ if (missingPackages.length === 0) return;
showNotification(
`Installing ${formatPackageList(missingPackages)}...`,
3000,