🎥 Make videos programmatically with React
`@remotion/studio-protocol`: Add Element catalogs to Studio
Igor Samokhovets30e4a9dd27a4
diff --git a/packages/docs/docs/studio-protocol/add-element-library-to-studio.mdx b/packages/docs/docs/studio-protocol/add-element-library-to-studio.mdxnew file mode 100644index 0000000000..5269f1aca2--- /dev/null+++ b/packages/docs/docs/studio-protocol/add-element-library-to-studio.mdx@@ -0,0 +1,99 @@+---+image: /generated/articles-docs-studio-protocol-add-element-library-to-studio.png+title: 'addElementLibraryToStudio()'+crumb: '@remotion/studio-protocol'+---++# addElementLibraryToStudio()<AvailableFrom v="4.0.518" />++Requests that an Element catalog is added to a recently focused Remotion Studio project.++## Example++```ts twoslash title="add-catalog.ts"+import {addElementLibraryToStudio} from '@remotion/studio-protocol';++const result = await addElementLibraryToStudio({+ url: 'https://example.com/elements',+ displayName: 'Acme Elements',+});++if (!result.success) {+ console.error(result.code, result.message);+} else {+ console.log(result.status); // "awaiting-confirmation"+}+```++Local Studio ports are probed and the most recently focused compatible writable Studio is selected. Studio shows a confirmation before changing the project.++## Arguments++### url++An absolute HTTP or HTTPS URL for the Element catalog. The URL is normalized before it is stored.++### displayName?++The label shown in Browse Elements. If omitted, Studio derives a label from the URL.++## Return value++Returns a promise with a discriminated union.++### success++Indicates whether the request reached the selected Studio tab.++### status++On success, the value is `"awaiting-confirmation"`. This means Studio received the request, not that the config was changed. The user can still decline it.++### target++On success, contains the project name, Studio origin, and Studio version.++### code++On failure, one of:++- `invalid-url`+- `invalid-display-name`+- `unsupported-origin`+- `no-compatible-studio`+- `studio-upgrade-required`+- `no-configurable-target`+- `unsupported-protocol`+- `invalid-response`+- `target-expired`+- `no-config-file`+- `request-rejected`+- `request-timed-out`+- `network-error`++### message++A human-readable failure message. Use `code` for application logic.++## Persistence++After confirmation, Studio adds an object-form [`Config.addElementLibrary()`](/docs/config#addelementlibrary) call to the loaded `remotion.config.ts`. Existing config source and catalog entries are preserved.++Catalogs are identified by their normalized URL. Requesting an already configured URL does not add another call or replace its display name.++A project without a loaded `remotion.config.ts` returns `no-config-file`.++## Supported origins++The function supports HTTPS websites. HTTP is supported only on `localhost` and `127.0.0.1` for local development. The catalog itself must use HTTP or HTTPS.++The confirmation shows the requesting website, catalog URL, and display name. The catalog is not added or loaded before confirmation. Adding a catalog does not install Element source code or dependencies; each Element installation keeps its own confirmation.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering={false} player={false} studio={false} hideServers />++## See also++- [Studio Protocol security](/docs/studio-protocol/security)+- [`Config.addElementLibrary()`](/docs/config#addelementlibrary)diff --git a/packages/docs/docs/studio-protocol/index.mdx b/packages/docs/docs/studio-protocol/index.mdxindex a7752da190..c36722595c 100644--- a/packages/docs/docs/studio-protocol/index.mdx+++ b/packages/docs/docs/studio-protocol/index.mdx@@ -30,6 +30,12 @@ Offer both delivery methods when possible. They use the same Element payload but| [Drag-and-drop](/docs/studio-protocol/set-studio-drag-data) | The user chooses the exact Studio tab, timeline position, and canvas position. | Drag data has no reliable website provenance, so Studio labels the source as [unverified](/docs/studio-protocol/security#confirmation-boundary). || [Installation request](/docs/studio-protocol/install-in-studio) | The requesting website is shown in Studio. On macOS, Studio attempts to bring the target tab to the foreground. | Local Studio ports are probed and the most recently focused compatible Studio is selected automatically. |+### Adding Element catalogs++A website can use [`addElementLibraryToStudio()`](/docs/studio-protocol/add-element-library-to-studio) to request that its catalog is persisted in a Remotion project's config. Studio shows the requesting origin and catalog URL before changing `remotion.config.ts`.++Adding a catalog does not install Element source code or dependencies. Each Element installation keeps its own confirmation.+## APIsimport {TableOfContents} from './table-of-contents';diff --git a/packages/docs/docs/studio-protocol/security.mdx b/packages/docs/docs/studio-protocol/security.mdxindex fa033349e0..f3f817331e 100644--- a/packages/docs/docs/studio-protocol/security.mdx+++ b/packages/docs/docs/studio-protocol/security.mdx@@ -7,11 +7,11 @@ crumb: '@remotion/studio-protocol'# Studio Protocol security-An Element contains executable React source code and may declare npm dependencies. Studio requires confirmation before applying an Element delivered through drag-and-drop or an installation request.+An Element contains executable React source code and may declare npm dependencies. Studio requires confirmation before applying an Element delivered through drag-and-drop or an installation request. It also requires confirmation before adding an external Element catalog to a project.## Allowed origins-Any HTTPS website can request an Element installation confirmation. HTTP is supported only for local development pages on `localhost` or `127.0.0.1`.+Any HTTPS website can request an Element installation or catalog confirmation. HTTP is supported only for local development pages on `localhost` or `127.0.0.1`.Studio reflects only the requesting allowed origin in CORS. It does not use wildcard CORS or cross-origin credentials.@@ -23,11 +23,15 @@ Before confirming, Studio shows the target composition and destination file, souDeclining the confirmation does not write source files or install packages.+A catalog request made with [`addElementLibraryToStudio()`](/docs/studio-protocol/add-element-library-to-studio) shows the requesting origin, exact catalog URL, and requested display name. The catalog is not loaded before confirmation. Confirming persists a [`Config.addElementLibrary()`](/docs/config#addelementlibrary) call in `remotion.config.ts`; it does not install Element source code or dependencies. Individual Element installations still require confirmation.++Declining or closing the catalog confirmation does not change the config.+## Target information-Discovery exposes limited metadata needed to present the destination: project name, composition ID, Studio version, focus time, and a short-lived target token. It does not expose project source code or filesystem contents.+Discovery exposes limited metadata needed to present the destination: project name, composition ID when applicable, Studio version, focus time, and a short-lived target token. It does not expose project source code, config contents, or filesystem paths.-Target tokens are opaque, single-use, short-lived, and bound to the requesting origin, selected Studio tab, and composition.+Target tokens are opaque, single-use, short-lived, and bound to the requesting origin, selected Studio tab, and operation. Element installation tokens are also bound to the composition.## See alsodiff --git a/packages/docs/docs/studio-protocol/table-of-contents.tsx b/packages/docs/docs/studio-protocol/table-of-contents.tsxindex d9e60ef5c3..55158dc7dd 100644--- a/packages/docs/docs/studio-protocol/table-of-contents.tsx+++ b/packages/docs/docs/studio-protocol/table-of-contents.tsx@@ -17,6 +17,10 @@ export const TableOfContents: React.FC = () => {<strong>installInStudio()</strong><div>Request installation into the active Studio</div></TOCItem>+ <TOCItem link="/docs/studio-protocol/add-element-library-to-studio">+ <strong>addElementLibraryToStudio()</strong>+ <div>Add an Element catalog to a Studio project</div>+ </TOCItem></Grid>);};diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 99b5c30d52..fb94afed00 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -825,6 +825,7 @@ const sidebars: SidebarsConfig = {'studio-protocol/create-element-payload','studio-protocol/set-studio-drag-data','studio-protocol/install-in-studio',+ 'studio-protocol/add-element-library-to-studio','studio-protocol/security',],},diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex fafe845400..482398e662 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -6994,6 +6994,15 @@ export const articles = [noAi: false,slug: 'studio-into-app',},+ {+ id: 'studio-protocol/add-element-library-to-studio',+ title: 'addElementLibraryToStudio()',+ relativePath: 'docs/studio-protocol/add-element-library-to-studio.mdx',+ compId: 'articles-docs-studio-protocol-add-element-library-to-studio',+ crumb: '@remotion/studio-protocol',+ noAi: false,+ slug: 'studio-protocol/add-element-library-to-studio',+ },{id: 'studio-protocol/component-library-integration',title: 'Integrating a component library with Studio',diff --git a/packages/docs/static/generated/articles-docs-studio-protocol-add-element-library-to-studio.png b/packages/docs/static/generated/articles-docs-studio-protocol-add-element-library-to-studio.pngnew file mode 100644index 0000000000..6a25d1d58bBinary files /dev/null and b/packages/docs/static/generated/articles-docs-studio-protocol-add-element-library-to-studio.png differdiff --git a/packages/example/e2e/studio-protocol.test.mts b/packages/example/e2e/studio-protocol.test.mtsindex c6dc6f2ba2..459938e9d5 100644--- a/packages/example/e2e/studio-protocol.test.mts+++ b/packages/example/e2e/studio-protocol.test.mts@@ -46,7 +46,7 @@ const waitForFile = async (file: string) => {test('installs an Element from a website into a clean Studio project', async ({browser,}) => {- test.setTimeout(120_000);+ test.setTimeout(180_000);const dirname = path.dirname(fileURLToPath(import.meta.url));const packagesDirectory = path.resolve(dirname, '..', '..');const repositoryRoot = path.resolve(packagesDirectory, '..');@@ -81,6 +81,7 @@ export const MyComponent = () => {const externalLibraryUrl = 'https://external-elements.example.com/library';const reloadedExternalLibraryUrl ='https://second-elements.example.com/components';+ const protocolLibraryUrl = 'https://protocol-catalog.example.com/library';const configFile = path.join(temporaryProject, 'remotion.config.ts');fs.appendFileSync(configFile,@@ -135,10 +136,11 @@ export const MyComponent = () => {response.writeHead(200, {'Content-Type': 'text/html'});response.end(`<!doctype html><button id="install">Install in Studio</button>+ <button id="add-library">Add catalog to Studio</button><button id="license">Configure license in Studio</button><p id="status"></p><script type="module">- import {createElementPayload, installInStudio, StudioProtocolInternals} from '/protocol.js';+ import {addElementLibraryToStudio, createElementPayload, installInStudio, StudioProtocolInternals} from '/protocol.js';const payload = createElementPayload({displayName: 'Protocol Element',slug: 'protocol-element',@@ -152,6 +154,14 @@ export const MyComponent = () => {const result = await installInStudio({payload});document.querySelector('#status').textContent = JSON.stringify(result);};+ document.querySelector('#add-library').onclick = async () => {+ document.querySelector('#status').textContent = '';+ const result = await addElementLibraryToStudio({+ url: '${protocolLibraryUrl}',+ displayName: 'Protocol Catalog',+ });+ document.querySelector('#status').textContent = JSON.stringify(result);+ };document.querySelector('#license').onclick = async () => {document.querySelector('#status').textContent = '';const result = await StudioProtocolInternals.setLicenseKeyInStudio({@@ -213,6 +223,7 @@ export const MyComponent = () => {target: {compositionId: 'MyComp'},},{type: 'set-license-key'},+ {type: 'add-element-library'},],});@@ -313,6 +324,79 @@ export const MyComponent = () => {await studioPage.mouse.click(500, 300);const senderPage = await context.newPage();await senderPage.goto(senderUrl);+ const configBeforeCatalogConfirmation = fs.readFileSync(configFile, 'utf8');+ await senderPage+ .getByRole('button', {name: 'Add catalog to Studio'})+ .click();+ await senderPage.waitForFunction(+ () => document.querySelector('#status')?.textContent !== '',+ );+ expect(await senderPage.locator('#status').textContent()).toContain(+ 'awaiting-confirmation',+ );++ await studioPage.bringToFront();+ const addCatalogDialog = studioPage.getByRole('dialog');+ await expect(+ addCatalogDialog.getByText('Add Element catalog', {exact: true}),+ ).toBeVisible();+ await expect(+ addCatalogDialog.getByText(senderUrl, {exact: true}),+ ).toBeVisible();+ await expect(+ addCatalogDialog.getByText(protocolLibraryUrl, {exact: true}),+ ).toBeVisible();+ await expect(+ addCatalogDialog.getByText('Display name: Protocol Catalog', {+ exact: true,+ }),+ ).toBeVisible();+ await expect(decoyStudioPage.getByText('Add Element catalog')).toHaveCount(+ 0,+ );+ expect(fs.readFileSync(configFile, 'utf8')).toBe(+ configBeforeCatalogConfirmation,+ );+ await addCatalogDialog.getByRole('button', {name: /^Add catalog/}).click();+ await expect+ .poll(() => fs.readFileSync(configFile, 'utf8'), {timeout: 30_000})+ .toContain(protocolLibraryUrl);++ await browseElements.click();+ await expect(+ studioPage.getByRole('button', {+ name: 'Protocol Catalog',+ exact: true,+ }),+ ).toBeVisible({timeout: 30_000});+ await studioPage.keyboard.press('Escape');++ await studioPage.bringToFront();+ await studioPage.mouse.click(500, 300);+ await senderPage.bringToFront();+ await senderPage+ .getByRole('button', {name: 'Add catalog to Studio'})+ .click();+ await senderPage.waitForFunction(+ () => document.querySelector('#status')?.textContent !== '',+ );+ await studioPage.bringToFront();+ await studioPage+ .getByRole('dialog')+ .getByRole('button', {name: /^Add catalog/})+ .click();+ await expect+ .poll(+ () =>+ fs.readFileSync(configFile, 'utf8').split(protocolLibraryUrl).length -+ 1,+ {timeout: 30_000},+ )+ .toBe(1);++ await studioPage.bringToFront();+ await studioPage.mouse.click(500, 300);+ await senderPage.bringToFront();await senderPage.getByRole('button', {name: 'Configure license in Studio'}).click();diff --git a/packages/studio-protocol/src/add-element-library-to-studio.ts b/packages/studio-protocol/src/add-element-library-to-studio.tsnew file mode 100644index 0000000000..81527fabf5--- /dev/null+++ b/packages/studio-protocol/src/add-element-library-to-studio.ts@@ -0,0 +1,287 @@+import {isAllowedStudioProtocolPageOrigin} from './install-in-studio';+import type {StudioProtocolFetcher} from './studio-discovery';+import {+ discoverStudios,+ fetchWithTimeout,+ focusedStudioMaxAge,+ getAddElementLibraryCapability,+ hasLegacyStudio,+ isAbortError,+ studioProtocolProbePorts,+} from './studio-discovery';+import {isRecord} from './validation';++export type AddElementLibraryToStudioInput = {+ readonly url: string;+ readonly displayName?: string;+};++export type AddElementLibraryToStudioErrorCode =+ | 'invalid-url'+ | 'invalid-display-name'+ | 'unsupported-origin'+ | 'no-compatible-studio'+ | 'studio-upgrade-required'+ | 'no-configurable-target'+ | 'unsupported-protocol'+ | 'invalid-response'+ | 'target-expired'+ | 'no-config-file'+ | 'request-rejected'+ | 'request-timed-out'+ | 'network-error';++export type AddElementLibraryToStudioResult =+ | {+ readonly success: true;+ readonly status: 'awaiting-confirmation';+ readonly target: {+ readonly projectName: string | null;+ readonly studioOrigin: string;+ readonly studioVersion: string;+ };+ }+ | {+ readonly success: false;+ readonly code: AddElementLibraryToStudioErrorCode;+ readonly message: string;+ };++export type AddElementLibraryToStudioDependencies = {+ readonly fetchFn: StudioProtocolFetcher;+ readonly now: () => number;+ readonly pageOrigin: string | null;+ readonly ports: readonly number[];+};++export type StudioProtocolAddElementLibraryRequest = {+ readonly operation: 'add-element-library';+ readonly protocol: 'remotion-studio-protocol';+ readonly protocolVersion: 1;+ readonly targetId: string;+ readonly url: string;+ readonly displayName: string | null;+};++const failure = (+ code: AddElementLibraryToStudioErrorCode,+ message: string,+): AddElementLibraryToStudioResult => ({success: false, code, message});++export const addElementLibraryToStudioWithDependencies = async (+ {+ displayName,+ url,+ }: {+ readonly displayName: string | null;+ readonly url: string;+ },+ dependencies: AddElementLibraryToStudioDependencies,+): Promise<AddElementLibraryToStudioResult> => {+ if (!isAllowedStudioProtocolPageOrigin(dependencies.pageOrigin)) {+ return failure(+ 'unsupported-origin',+ 'Adding an Element catalog is only supported on HTTPS websites and local development origins.',+ );+ }++ if (typeof url !== 'string') {+ return failure('invalid-url', 'The Element catalog URL must be a string.');+ }++ let normalizedUrl: string;+ try {+ const parsedUrl = new URL(url);+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {+ return failure(+ 'invalid-url',+ 'The Element catalog URL must use HTTP or HTTPS.',+ );+ }++ normalizedUrl = parsedUrl.href;+ } catch {+ return failure(+ 'invalid-url',+ 'The Element catalog URL must be an absolute HTTP or HTTPS URL.',+ );+ }++ if (displayName !== null && typeof displayName !== 'string') {+ return failure(+ 'invalid-display-name',+ 'The Element catalog display name must be a string.',+ );+ }++ const normalizedDisplayName = displayName?.trim() ?? null;+ if (normalizedDisplayName === '') {+ return failure(+ 'invalid-display-name',+ 'The Element catalog display name must not be empty.',+ );+ }++ const discovery = await discoverStudios(dependencies);+ if (discovery.studios.length === 0) {+ if (discovery.foundUnsupportedProtocol) {+ return failure(+ 'unsupported-protocol',+ 'The running Remotion Studio uses an unsupported Studio Protocol version.',+ );+ }++ if (await hasLegacyStudio(dependencies)) {+ return failure(+ 'studio-upgrade-required',+ 'This Remotion Studio cannot add an Element catalog through Studio Protocol. Upgrade Remotion to 4.0.518 or newer.',+ );+ }++ if (discovery.foundInvalidResponse) {+ return failure(+ 'invalid-response',+ 'Remotion Studio returned an invalid Studio Protocol response.',+ );+ }++ return failure(+ 'no-compatible-studio',+ 'Start Remotion Studio, focus it, and try again.',+ );+ }++ const supportedStudios = discovery.studios.flatMap((studio) => {+ const capability = getAddElementLibraryCapability(studio.descriptor);+ return capability === null ? [] : [{...studio, capability}];+ });+ if (supportedStudios.length === 0) {+ return failure(+ 'studio-upgrade-required',+ 'This Remotion Studio cannot add an Element catalog through Studio Protocol. Upgrade Remotion to 4.0.518 or newer.',+ );+ }++ const now = dependencies.now();+ const configurable = supportedStudios+ .filter(({capability}) => {+ const {target} = capability;+ return (+ target !== null &&+ target.expiresAt > now &&+ now - target.lastFocusedAt < focusedStudioMaxAge+ );+ })+ .sort((a, b) => {+ const focusDifference =+ b.capability.target!.lastFocusedAt - a.capability.target!.lastFocusedAt;+ return focusDifference === 0+ ? b.discoveredAt - a.discoveredAt+ : focusDifference;+ });+ const selected = configurable[0];+ const selectedTarget = selected?.capability.target;+ if (!selected || selectedTarget === null || selectedTarget === undefined) {+ return failure(+ 'no-configurable-target',+ 'Focus a writable Remotion Studio tab, then try again.',+ );+ }++ let response: Response;+ try {+ const requestBody = {+ operation: 'add-element-library',+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ targetId: selectedTarget.id,+ url: normalizedUrl,+ displayName: normalizedDisplayName,+ } satisfies StudioProtocolAddElementLibraryRequest;+ response = await fetchWithTimeout({+ fetchFn: dependencies.fetchFn,+ url: `${selected.origin}/api/studio-protocol/element-library`,+ options: {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify(requestBody),+ },+ });+ } catch (error) {+ const timedOut = isAbortError(error);+ return failure(+ timedOut ? 'request-timed-out' : 'network-error',+ timedOut+ ? 'The request to Remotion Studio timed out.'+ : 'Could not connect to Remotion Studio.',+ );+ }++ let result: unknown;+ try {+ result = await response.json();+ } catch {+ return failure(+ 'invalid-response',+ 'Remotion Studio returned an invalid Element catalog response.',+ );+ }++ if (+ response.ok &&+ isRecord(result) &&+ result.protocol === 'remotion-studio-protocol' &&+ result.protocolVersion === 1 &&+ result.status === 'awaiting-confirmation'+ ) {+ return {+ success: true,+ status: 'awaiting-confirmation',+ target: {+ projectName: selected.descriptor.projectName,+ studioOrigin: selected.origin,+ studioVersion: selected.descriptor.studioVersion,+ },+ };+ }++ if (+ isRecord(result) &&+ result.status === 'error' &&+ isRecord(result.error) &&+ typeof result.error.code === 'string' &&+ typeof result.error.message === 'string'+ ) {+ const {code, message} = result.error;+ return failure(+ code === 'target-expired'+ ? 'target-expired'+ : code === 'no-config-file'+ ? 'no-config-file'+ : 'request-rejected',+ message,+ );+ }++ return failure(+ 'invalid-response',+ 'Remotion Studio returned an invalid Element catalog response.',+ );+};++export const addElementLibraryToStudio = ({+ displayName,+ url,+}: AddElementLibraryToStudioInput): Promise<AddElementLibraryToStudioResult> =>+ addElementLibraryToStudioWithDependencies(+ {displayName: displayName ?? null, url},+ {+ fetchFn: fetch,+ now: Date.now,+ pageOrigin:+ typeof globalThis.location === 'undefined'+ ? null+ : globalThis.location.origin,+ ports: studioProtocolProbePorts,+ },+ );diff --git a/packages/studio-protocol/src/index.ts b/packages/studio-protocol/src/index.tsindex 61c407c6cf..df3d3ba5bc 100644--- a/packages/studio-protocol/src/index.ts+++ b/packages/studio-protocol/src/index.ts@@ -1,3 +1,4 @@+import {addElementLibraryToStudioWithDependencies} from './add-element-library-to-studio';import {makeBrowserStudioUrl,openInBrowserStudio,@@ -19,6 +20,12 @@ import {installInStudioWithDependencies} from './install-in-studio';import {isValidPublicLicenseKey} from './license-key';import {setLicenseKeyInStudio} from './set-license-key-in-studio';+export {+ addElementLibraryToStudio,+ type AddElementLibraryToStudioErrorCode,+ type AddElementLibraryToStudioInput,+ type AddElementLibraryToStudioResult,+} from './add-element-library-to-studio';export type {AssetDragData} from './asset-drag-data';export type {ComponentDimensions,@@ -77,6 +84,7 @@ export type {} from './studio-discovery';export const StudioProtocolInternals = {+ addElementLibraryToStudioWithDependencies,areComponentProps,getDragPreviewMetadata,getElementComponentNameFromSourceCode,diff --git a/packages/studio-protocol/src/studio-discovery.ts b/packages/studio-protocol/src/studio-discovery.tsindex 5fee9bcec8..68aa8029b1 100644--- a/packages/studio-protocol/src/studio-discovery.ts+++ b/packages/studio-protocol/src/studio-discovery.ts@@ -22,9 +22,15 @@ export type StudioProtocolSetLicenseKeyCapability = {readonly target: StudioProtocolTarget | null;};+export type StudioProtocolAddElementLibraryCapability = {+ readonly type: 'add-element-library';+ readonly target: StudioProtocolTarget | null;+};+export type StudioProtocolCapability =| StudioProtocolInstallCapability- | StudioProtocolSetLicenseKeyCapability;+ | StudioProtocolSetLicenseKeyCapability+ | StudioProtocolAddElementLibraryCapability;export type StudioProtocolDescriptor = {readonly protocol: 'remotion-studio-protocol';@@ -113,8 +119,12 @@ const isCapability = (value: unknown): value is StudioProtocolCapability => {);}+ if (value.type === 'set-license-key') {+ return value.target === null || isTarget(value.target);+ }+return (- value.type === 'set-license-key' &&+ value.type === 'add-element-library' &&(value.target === null || isTarget(value.target)));};@@ -156,6 +166,14 @@ export const getSetLicenseKeyCapability = (capability.type === 'set-license-key',) ?? null;+export const getAddElementLibraryCapability = (+ descriptor: StudioProtocolDescriptor,+): StudioProtocolAddElementLibraryCapability | null =>+ descriptor.capabilities.find(+ (capability): capability is StudioProtocolAddElementLibraryCapability =>+ capability.type === 'add-element-library',+ ) ?? null;+export type DiscoveredStudio = {readonly descriptor: StudioProtocolDescriptor;readonly discoveredAt: number;diff --git a/packages/studio-protocol/src/test/add-element-library-to-studio.test.ts b/packages/studio-protocol/src/test/add-element-library-to-studio.test.tsnew file mode 100644index 0000000000..7eaad20e2c--- /dev/null+++ b/packages/studio-protocol/src/test/add-element-library-to-studio.test.ts@@ -0,0 +1,268 @@+import {expect, test} from 'bun:test';+import {addElementLibraryToStudioWithDependencies} from '../add-element-library-to-studio';+import type {StudioProtocolFetcher} from '../studio-discovery';++const now = 1_000_000;++const descriptor = ({+ addElementLibrary,+ lastFocusedAt,+ projectName,+ targetId,+}: {+ readonly addElementLibrary: boolean;+ readonly lastFocusedAt: number;+ readonly projectName: string;+ readonly targetId: string;+}) => ({+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ studioVersion: '4.0.518',+ projectName,+ capabilities: [+ {+ type: 'install-element',+ payloadType: 'remotion-element',+ payloadVersions: [1],+ target: null,+ },+ ...(addElementLibrary+ ? [+ {+ type: 'add-element-library',+ target: {+ id: targetId,+ expiresAt: now + 10_000,+ lastFocusedAt,+ },+ },+ ]+ : []),+ ],+});++const jsonResponse = (value: unknown, status = 200) =>+ new Response(JSON.stringify(value), {+ headers: {'Content-Type': 'application/json'},+ status,+ });++const dependencies = {+ now: () => now,+ pageOrigin: 'https://elements.example.com',+ ports: [3000, 3001],+};++test('requests confirmation in the most recently focused compatible Studio', async () => {+ const requests: Array<{+ readonly options: RequestInit | null;+ readonly url: string;+ }> = [];+ const fetchFn: StudioProtocolFetcher = (input, options) => {+ const url = String(input);+ requests.push({options: options ?? null, url});+ if (url === 'http://localhost:3000/api/studio-protocol') {+ return Promise.resolve(+ jsonResponse(+ descriptor({+ addElementLibrary: true,+ lastFocusedAt: now - 200,+ projectName: 'Older',+ targetId: 'older-target',+ }),+ ),+ );+ }++ if (url === 'http://localhost:3001/api/studio-protocol') {+ return Promise.resolve(+ jsonResponse(+ descriptor({+ addElementLibrary: true,+ lastFocusedAt: now - 100,+ projectName: 'Focused project',+ targetId: 'focused-target',+ }),+ ),+ );+ }++ return Promise.resolve(+ jsonResponse({+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ status: 'awaiting-confirmation',+ }),+ );+ };++ expect(+ await addElementLibraryToStudioWithDependencies(+ {url: 'https://catalog.example.com', displayName: ' Catalog '},+ {...dependencies, fetchFn},+ ),+ ).toEqual({+ success: true,+ status: 'awaiting-confirmation',+ target: {+ projectName: 'Focused project',+ studioOrigin: 'http://localhost:3001',+ studioVersion: '4.0.518',+ },+ });+ const request = requests.at(-1);+ expect(request?.url).toBe(+ 'http://localhost:3001/api/studio-protocol/element-library',+ );+ expect(request?.options?.method).toBe('POST');+ expect(JSON.parse(String(request?.options?.body))).toEqual({+ operation: 'add-element-library',+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ targetId: 'focused-target',+ url: 'https://catalog.example.com/',+ displayName: 'Catalog',+ });+});++test('validates the request before probing localhost', async () => {+ for (const request of [+ {url: '/relative', displayName: null},+ {url: 'file:///tmp/catalog', displayName: null},+ {url: 'https://catalog.example.com', displayName: ' '},+ ]) {+ let requestCount = 0;+ const result = await addElementLibraryToStudioWithDependencies(request, {+ ...dependencies,+ fetchFn: () => {+ requestCount++;+ return Promise.resolve(new Response(null, {status: 404}));+ },+ });+ expect(result.success).toBe(false);+ expect(requestCount).toBe(0);+ }++ let probes = 0;+ const unsupportedOrigin = await addElementLibraryToStudioWithDependencies(+ {url: 'https://catalog.example.com', displayName: null},+ {+ ...dependencies,+ pageOrigin: 'http://elements.example.com',+ fetchFn: () => {+ probes++;+ return Promise.resolve(new Response(null, {status: 404}));+ },+ },+ );+ expect(unsupportedOrigin).toMatchObject({+ success: false,+ code: 'unsupported-origin',+ });+ expect(probes).toBe(0);+});++test('distinguishes an old Studio from one without a focused target', async () => {+ const oldStudio = await addElementLibraryToStudioWithDependencies(+ {url: 'https://catalog.example.com', displayName: null},+ {+ ...dependencies,+ ports: [3000],+ fetchFn: () =>+ Promise.resolve(+ jsonResponse(+ descriptor({+ addElementLibrary: false,+ lastFocusedAt: now,+ projectName: 'Old project',+ targetId: 'unused',+ }),+ ),+ ),+ },+ );+ expect(oldStudio).toMatchObject({+ success: false,+ code: 'studio-upgrade-required',+ });++ const withoutTarget = descriptor({+ addElementLibrary: true,+ lastFocusedAt: now,+ projectName: 'Project',+ targetId: 'unused',+ });+ const noTarget = await addElementLibraryToStudioWithDependencies(+ {url: 'https://catalog.example.com', displayName: null},+ {+ ...dependencies,+ ports: [3000],+ fetchFn: () =>+ Promise.resolve(+ jsonResponse({+ ...withoutTarget,+ capabilities: withoutTarget.capabilities.map((capability) =>+ capability.type === 'add-element-library'+ ? {...capability, target: null}+ : capability,+ ),+ }),+ ),+ },+ );+ expect(noTarget).toMatchObject({+ success: false,+ code: 'no-configurable-target',+ });+});++test('maps structured server errors and malformed responses', async () => {+ const run = (response: Response) =>+ addElementLibraryToStudioWithDependencies(+ {url: 'https://catalog.example.com', displayName: null},+ {+ ...dependencies,+ ports: [3000],+ fetchFn: (input) =>+ String(input).endsWith('/api/studio-protocol')+ ? Promise.resolve(+ jsonResponse(+ descriptor({+ addElementLibrary: true,+ lastFocusedAt: now,+ projectName: 'Project',+ targetId: 'target',+ }),+ ),+ )+ : Promise.resolve(response),+ },+ );++ expect(+ await run(+ jsonResponse(+ {+ status: 'error',+ error: {code: 'no-config-file', message: 'No config'},+ },+ 409,+ ),+ ),+ ).toEqual({success: false, code: 'no-config-file', message: 'No config'});+ expect(+ await run(+ jsonResponse(+ {+ status: 'error',+ error: {code: 'target-expired', message: 'Expired'},+ },+ 409,+ ),+ ),+ ).toEqual({success: false, code: 'target-expired', message: 'Expired'});+ expect(await run(new Response('not json'))).toMatchObject({+ success: false,+ code: 'invalid-response',+ });+});diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex cf0ff23361..11f3250e92 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -59,14 +59,15 @@ import {unsubscribeFromDefaultProps} from './routes/unsubscribe-from-default-proimport {unsubscribeFromFileExistence} from './routes/unsubscribe-from-file-existence';import {unsubscribeFromSequenceProps} from './routes/unsubscribe-from-sequence-props';import {handleUpdate} from './routes/update-available';-import {updateConfigHandler} from './routes/update-config';import {updateDefaultPropsHandler} from './routes/update-default-props';import {updateEffectKeyframeSettingsHandler} from './routes/update-effect-keyframe-settings';import {updateElementInstallTargetHandler} from './routes/update-element-install-target';import {updateSequenceKeyframeSettingsHandler} from './routes/update-sequence-keyframe-settings';+type StandardApiRoute = Exclude<keyof ApiRoutes, '/api/update-config'>;+export const allApiRoutes: {- [key in keyof ApiRoutes]: ApiHandler<+ [key in StandardApiRoute]: ApiHandler<ApiRoutes[key]['Request'],ApiRoutes[key]['Response']>;@@ -122,7 +123,6 @@ export const allApiRoutes: {'/api/delete-static-file': deleteStaticFileHandler,'/api/rename-static-file': renameStaticFileHandler,'/api/restart-studio': handleRestartStudio,- '/api/update-config': updateConfigHandler,'/api/default-coding-agent-info': getDefaultCodingAgentInfoHandler,'/api/default-editor-info': getDefaultEditorInfoHandler,'/api/install-package': handleInstallPackage,diff --git a/packages/studio-server/src/preview-server/element-install-state.ts b/packages/studio-server/src/preview-server/element-install-state.tsindex dfcaa3ece5..a2ede2d899 100644--- a/packages/studio-server/src/preview-server/element-install-state.ts+++ b/packages/studio-server/src/preview-server/element-install-state.ts@@ -15,7 +15,10 @@ export type ElementInstallTarget = {updatedAt: number;};-export type StudioProtocolTargetPurpose = 'install-element' | 'set-license-key';+export type StudioProtocolTargetPurpose =+ | 'install-element'+ | 'set-license-key'+ | 'add-element-library';const targetsByClientId = new Map<string, ElementInstallTarget>();@@ -134,7 +137,7 @@ export const consumeStudioProtocolTarget = ({return null;}- if (purpose === 'set-license-key') {+ if (purpose !== 'install-element') {return issued.target;}diff --git a/packages/studio-server/src/preview-server/routes/update-config.ts b/packages/studio-server/src/preview-server/routes/update-config.tsindex a0f4b875d9..54b51ae6d3 100644--- a/packages/studio-server/src/preview-server/routes/update-config.ts+++ b/packages/studio-server/src/preview-server/routes/update-config.ts@@ -4,6 +4,7 @@ import {configMethodLifecycles,type ConfigUpdate,type ConfigValue,+ type StudioRuntimeConfig,type UpdateConfigRequest,type UpdateConfigResponse,} from '@remotion/studio-shared';@@ -60,7 +61,7 @@ const validateUpdates = (updates: unknown): string | null => {const {setter, type} = update as Partial<ConfigUpdate>;if (typeof setter !== 'string' ||- !validSetterName.test(setter) ||+ (!validSetterName.test(setter) && setter !== 'addElementLibrary') ||!(setter in configMethodLifecycles)) {return `Invalid config setter: ${JSON.stringify(setter)}.`;@@ -71,6 +72,44 @@ const validateUpdates = (updates: unknown): string | null => {}setters.add(setter);+ if (setter === 'addElementLibrary') {+ if (+ type !== 'set' ||+ !('value' in update) ||+ typeof update.value !== 'object' ||+ update.value === null ||+ Array.isArray(update.value) ||+ (Object.getPrototypeOf(update.value) !== Object.prototype &&+ Object.getPrototypeOf(update.value) !== null)+ ) {+ return 'Config.addElementLibrary() expects an object value.';+ }++ const elementLibrary = update.value as Record<string, unknown>;+ const {displayName, url} = elementLibrary;+ if (typeof url !== 'string') {+ return 'Config.addElementLibrary() expects an HTTP or HTTPS URL.';+ }++ try {+ const parsedUrl = new URL(url);+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {+ return 'Config.addElementLibrary() expects an HTTP or HTTPS URL.';+ }+ } catch {+ return 'Config.addElementLibrary() expects an HTTP or HTTPS URL.';+ }++ if (+ displayName !== undefined &&+ (typeof displayName !== 'string' || displayName.trim() === '')+ ) {+ return 'Config.addElementLibrary() expects a non-empty display name.';+ }++ continue;+ }+if (type === 'delete') {continue;}@@ -89,26 +128,81 @@ const validateUpdates = (updates: unknown): string | null => {export const updateConfigFile = ({configContents,+ existingElementLibraryUrls,updates,}: {readonly configContents: string;+ readonly existingElementLibraryUrls: readonly string[];readonly updates: ConfigUpdate[];}) => {const setters = new Set(updates.map(({setter}) => setter));+ const elementLibraryUrls = new Set<string>();+ for (const url of existingElementLibraryUrls) {+ try {+ elementLibraryUrls.add(new URL(url).href);+ } catch {+ // Runtime config only contains validated URLs.+ }+ }++ let changed = false;const ast = parseAst(configContents);recast.types.visit(ast.program, {visitExpressionStatement(path) {const {expression} = path.node;if (- expression.type === 'CallExpression' &&- expression.callee.type === 'MemberExpression' &&- !expression.callee.computed &&- expression.callee.object.type === 'Identifier' &&- expression.callee.object.name === 'Config' &&- expression.callee.property.type === 'Identifier' &&- setters.has(expression.callee.property.name)+ expression.type !== 'CallExpression' ||+ expression.callee.type !== 'MemberExpression' ||+ expression.callee.computed ||+ expression.callee.object.type !== 'Identifier' ||+ expression.callee.object.name !== 'Config' ||+ expression.callee.property.type !== 'Identifier') {+ this.traverse(path);+ return;+ }++ const setter = expression.callee.property.name;+ if (setter === 'addElementLibrary') {+ const argument = expression.arguments[0];+ if (argument?.type === 'ObjectExpression') {+ const urlProperty = argument.properties.find((property) => {+ if (property.type !== 'ObjectProperty' || property.computed) {+ return false;+ }++ return (+ (property.key.type === 'Identifier' &&+ property.key.name === 'url') ||+ (property.key.type === 'StringLiteral' &&+ property.key.value === 'url')+ );+ });+ if (+ urlProperty?.type === 'ObjectProperty' &&+ urlProperty.value.type === 'StringLiteral'+ ) {+ try {+ const parsedUrl = new URL(urlProperty.value.value);+ if (+ parsedUrl.protocol === 'http:' ||+ parsedUrl.protocol === 'https:'+ ) {+ elementLibraryUrls.add(parsedUrl.href);+ }+ } catch {+ // Preserve invalid existing config without treating it as a match.+ }+ }+ }++ this.traverse(path);+ return;+ }++ if (setters.has(setter)) {path.prune();+ changed = true;return false;}@@ -122,11 +216,30 @@ export const updateConfigFile = ({continue;}- const serializedValue = JSON.stringify(update.value)+ const {setter, value: initialValue} = update;+ let value = initialValue;+ if (setter === 'addElementLibrary') {+ const elementLibrary = initialValue as Record<string, ConfigValue>;+ const {displayName: rawDisplayName, url} = elementLibrary;+ const normalizedUrl = new URL(url as string).href;+ if (elementLibraryUrls.has(normalizedUrl)) {+ continue;+ }++ const displayName =+ typeof rawDisplayName === 'string' ? rawDisplayName.trim() : null;+ value =+ displayName === null+ ? {url: normalizedUrl}+ : {url: normalizedUrl, displayName};+ elementLibraryUrls.add(normalizedUrl);+ }++ const serializedValue = JSON.stringify(value).replaceAll('\u2028', '\\u2028').replaceAll('\u2029', '\\u2029');- const statement = parseAst(`Config.${update.setter}(${serializedValue});`)- .program.body[0];+ const statement = parseAst(`Config.${setter}(${serializedValue});`).program+ .body[0];const separator = updatedConfig.endsWith('\n') ? '' : '\n';updatedConfig += `${separator}${recast.prettyPrint(statement, {@@ -135,15 +248,23 @@ export const updateConfigFile = ({useTabs: true,}).code}\n`;+ changed = true;}- return updatedConfig;+ return changed ? updatedConfig : configContents;+};++type UpdateConfigHandlerParams = Parameters<+ ApiHandler<UpdateConfigRequest, UpdateConfigResponse>+>[0] & {+ readonly getStudioRuntimeConfig: () => StudioRuntimeConfig;};-export const updateConfigHandler: ApiHandler<- UpdateConfigRequest,- UpdateConfigResponse-> = async ({input, configFile}) => {+export const updateConfigHandler = async ({+ input,+ configFile,+ getStudioRuntimeConfig,+}: UpdateConfigHandlerParams): Promise<UpdateConfigResponse> => {if (configFile === null || configFile === undefined) {return {success: false,@@ -211,9 +332,19 @@ export const updateConfigHandler: ApiHandler<}const configContents = readFileSync(configFile, 'utf8');+ const updatedConfig = updateConfigFile({+ configContents,+ existingElementLibraryUrls:+ getStudioRuntimeConfig().elementLibraries?.map(({url}) => url) ?? [],+ updates: input.updates,+ });+ if (updatedConfig === configContents) {+ return {success: true};+ }+writeFileAndNotifyFileWatchers({file: configFile,- content: updateConfigFile({configContents, updates: input.updates}),+ content: updatedConfig,originatorClientId: input.clientId,metadata: null,});diff --git a/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.ts b/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.tsindex c373bae1a1..84745fb32f 100644--- a/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.ts+++ b/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.ts@@ -133,6 +133,15 @@ export const handleStudioProtocolDiscovery = ({purpose: 'set-license-key',target,});+ const issuedElementLibraryTarget =+ target === null+ ? null+ : issueStudioProtocolTarget({+ now,+ origin: requestOrigin,+ purpose: 'add-element-library',+ target,+ });response.writeHead(200, {'Cache-Control': 'no-store','Content-Type': 'application/json',@@ -171,6 +180,19 @@ export const handleStudioProtocolDiscovery = ({lastFocusedAt: target.lastFocusedAt,},},+ {+ type: 'add-element-library',+ target:+ issuedElementLibraryTarget === null ||+ target === null ||+ target.lastFocusedAt === null+ ? null+ : {+ id: issuedElementLibraryTarget.id,+ expiresAt: issuedElementLibraryTarget.expiresAt,+ lastFocusedAt: target.lastFocusedAt,+ },+ },],}),);diff --git a/packages/studio-server/src/preview-server/studio-protocol/handle-element-library.ts b/packages/studio-server/src/preview-server/studio-protocol/handle-element-library.tsnew file mode 100644index 0000000000..9e541137b4--- /dev/null+++ b/packages/studio-server/src/preview-server/studio-protocol/handle-element-library.ts@@ -0,0 +1,178 @@+import type {IncomingMessage, ServerResponse} from 'node:http';+import {z} from 'zod';+import {consumeStudioProtocolTarget} from '../element-install-state';+import type {LiveEventsServer} from '../live-events';+import {parseRequestBody, RequestBodyTooLargeError} from '../parse-body';+import {+ getAllowedStudioProtocolOrigin,+ setStudioProtocolCorsHeaders,+} from './origin-policy';+import {writeStudioProtocolError} from './protocol-response';++type FocusStudioTab = (studioUrl: string) => void;++const studioProtocolElementLibraryRequestSchema = z.object({+ operation: z.literal('add-element-library'),+ protocol: z.literal('remotion-studio-protocol'),+ protocolVersion: z.literal(1),+ targetId: z.string().min(1),+ url: z.string(),+ displayName: z.string().nullable(),+});++const MAX_STUDIO_PROTOCOL_ELEMENT_LIBRARY_BODY_SIZE = 16 * 1024;++export const handleStudioProtocolElementLibrary = async ({+ configFile,+ focusStudioTab,+ liveEventsServer,+ request,+ response,+}: {+ readonly configFile: string | null;+ readonly focusStudioTab: FocusStudioTab;+ readonly liveEventsServer: LiveEventsServer;+ readonly request: IncomingMessage;+ readonly response: ServerResponse;+}): Promise<void> => {+ setStudioProtocolCorsHeaders({request, response});+ const requestOrigin = getAllowedStudioProtocolOrigin(request.headers.origin);+ if (requestOrigin === null) {+ writeStudioProtocolError({+ code: 'unsupported-origin',+ message: 'Origin not allowed',+ response,+ status: 403,+ });+ return;+ }++ if (request.method !== 'POST') {+ writeStudioProtocolError({+ code: 'method-not-allowed',+ message: 'Use POST to add an Element catalog.',+ response,+ status: 405,+ });+ return;+ }++ let body: unknown;+ try {+ body = await parseRequestBody(request, {+ maxBytes: MAX_STUDIO_PROTOCOL_ELEMENT_LIBRARY_BODY_SIZE,+ });+ } catch (error) {+ if (error instanceof RequestBodyTooLargeError) {+ writeStudioProtocolError({+ code: 'request-too-large',+ message: 'The request body is too large.',+ response,+ status: 413,+ });+ return;+ }++ writeStudioProtocolError({+ code: 'invalid-request',+ message: 'The request body is not valid JSON.',+ response,+ status: 400,+ });+ return;+ }++ const parsedRequest =+ studioProtocolElementLibraryRequestSchema.safeParse(body);+ if (!parsedRequest.success) {+ writeStudioProtocolError({+ code: 'unsupported-protocol',+ message: 'Invalid Remotion Studio Protocol request.',+ response,+ status: 400,+ });+ return;+ }++ let normalizedUrl: string;+ try {+ const parsedUrl = new URL(parsedRequest.data.url);+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {+ throw new Error('Unsupported protocol');+ }++ normalizedUrl = parsedUrl.href;+ } catch {+ writeStudioProtocolError({+ code: 'invalid-url',+ message: 'The Element catalog URL must be an absolute HTTP or HTTPS URL.',+ response,+ status: 400,+ });+ return;+ }++ const displayName = parsedRequest.data.displayName?.trim() ?? null;+ if (displayName === '') {+ writeStudioProtocolError({+ code: 'invalid-display-name',+ message: 'The Element catalog display name must not be empty.',+ response,+ status: 400,+ });+ return;+ }++ const target = consumeStudioProtocolTarget({+ now: Date.now(),+ origin: requestOrigin,+ purpose: 'add-element-library',+ targetId: parsedRequest.data.targetId,+ });+ if (target === null) {+ writeStudioProtocolError({+ code: 'target-expired',+ message: 'The selected Studio target is no longer available.',+ response,+ status: 409,+ });+ return;+ }++ if (configFile === null) {+ writeStudioProtocolError({+ code: 'no-config-file',+ message: 'The selected Studio did not load a Remotion config file.',+ response,+ status: 409,+ });+ return;+ }++ const delivered = liveEventsServer.sendEventToClientId(target.clientId, {+ type: 'element-library-add-request',+ url: normalizedUrl,+ displayName,+ origin: requestOrigin,+ });+ if (!delivered) {+ writeStudioProtocolError({+ code: 'target-expired',+ message: 'The selected Remotion Studio tab is no longer connected.',+ response,+ status: 409,+ });+ return;+ }++ focusStudioTab(target.studioUrl);++ response.writeHead(200, {'Content-Type': 'application/json'});+ response.end(+ JSON.stringify({+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ status: 'awaiting-confirmation',+ }),+ );+};diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.tsindex 671e84b28c..00d79d4c82 100644--- a/packages/studio-server/src/routes.ts+++ b/packages/studio-server/src/routes.ts@@ -20,6 +20,8 @@ import type {RenderDefaults,RenderJob,StudioRuntimeConfig,+ UpdateConfigRequest,+ UpdateConfigResponse,} from '@remotion/studio-shared';import {getProjectName} from '@remotion/studio-shared';import {focusBrowserTab} from './better-opn';@@ -37,8 +39,10 @@ import type {LiveEventsServer} from './preview-server/live-events';import {fetchFolder, getFiles} from './preview-server/public-folder';import {handleAppIcon} from './preview-server/routes/app-icon';import {getEditorName} from './preview-server/routes/open-in-editor';+import {updateConfigHandler} from './preview-server/routes/update-config';import {serveStatic} from './preview-server/serve-static';import {handleStudioProtocolDiscovery} from './preview-server/studio-protocol/handle-discovery';+import {handleStudioProtocolElementLibrary} from './preview-server/studio-protocol/handle-element-library';import {handleStudioProtocolInstall} from './preview-server/studio-protocol/handle-install';import {handleStudioProtocolLicenseKey} from './preview-server/studio-protocol/handle-license-key';import {handleStudioProtocolOptions} from './preview-server/studio-protocol/origin-policy';@@ -497,7 +501,8 @@ export const handleRoutes = ({if (url.pathname === '/api/studio-protocol' ||url.pathname === '/api/studio-protocol/install' ||- url.pathname === '/api/studio-protocol/license-key'+ url.pathname === '/api/studio-protocol/license-key' ||+ url.pathname === '/api/studio-protocol/element-library') {if (request.method === 'OPTIONS') {return handleStudioProtocolOptions({@@ -528,6 +533,18 @@ export const handleRoutes = ({});}+ if (url.pathname === '/api/studio-protocol/element-library') {+ return handleStudioProtocolElementLibrary({+ configFile,+ focusStudioTab: (studioUrl) => {+ focusBrowserTab({url: studioUrl}).catch(() => undefined);+ },+ liveEventsServer,+ request,+ response,+ });+ }+return handleStudioProtocolInstall({focusStudioTab: (studioUrl) => {focusBrowserTab({url: studioUrl}).catch(() => undefined);@@ -538,6 +555,24 @@ export const handleRoutes = ({});}+ if (url.pathname === '/api/update-config') {+ return handleRequest<UpdateConfigRequest, UpdateConfigResponse>({+ remotionRoot,+ entryPoint,+ handler: (params) =>+ updateConfigHandler({...params, getStudioRuntimeConfig}),+ request,+ response,+ logLevel,+ methods,+ binariesDirectory,+ publicDir,+ configFile,+ getDefaultCodingAgent,+ getDefaultEditor,+ });+ }+for (const [key, value] of Object.entries(allApiRoutes)) {if (url.pathname === key) {return handleRequest({diff --git a/packages/studio-server/src/test/element-install-state.test.ts b/packages/studio-server/src/test/element-install-state.test.tsindex 183b8fc91c..2db6f3181e 100644--- a/packages/studio-server/src/test/element-install-state.test.ts+++ b/packages/studio-server/src/test/element-install-state.test.ts@@ -105,7 +105,7 @@ test('binds install tokens to one origin, purpose and composition', () => {).toBe(null);});-test('license-key targets are project-level, single-use and invalidated by read-only mode', () => {+test('config targets are project-level, purpose-bound, single-use and invalidated by read-only mode', () => {clearElementInstallStateForTests();updateTarget({canInstall: false, compositionId: null});const selected = getElementInstallTarget('protocol-request');@@ -113,6 +113,21 @@ test('license-key targets are project-level, single-use and invalidated by read-throw new Error('Expected a Studio target');}+ const elementLibraryTarget = issueStudioProtocolTarget({+ now: Date.now(),+ origin: 'https://remotion.pro',+ purpose: 'add-element-library',+ target: selected,+ });+ expect(+ consumeStudioProtocolTarget({+ now: Date.now(),+ origin: 'https://remotion.pro',+ purpose: 'set-license-key',+ targetId: elementLibraryTarget.id,+ }),+ ).toBe(null);+const issued = issueStudioProtocolTarget({now: Date.now(),origin: 'https://remotion.pro',diff --git a/packages/studio-server/src/test/studio-protocol-routes.test.ts b/packages/studio-server/src/test/studio-protocol-routes.test.tsindex 4f4da5cde3..e6ef96761a 100644--- a/packages/studio-server/src/test/studio-protocol-routes.test.ts+++ b/packages/studio-server/src/test/studio-protocol-routes.test.ts@@ -12,6 +12,7 @@ import {} from '../preview-server/element-install-state';import type {LiveEventsServer} from '../preview-server/live-events';import {handleStudioProtocolDiscovery} from '../preview-server/studio-protocol/handle-discovery';+import {handleStudioProtocolElementLibrary} from '../preview-server/studio-protocol/handle-element-library';import {handleStudioProtocolInstall} from '../preview-server/studio-protocol/handle-install';import {handleStudioProtocolLicenseKey} from '../preview-server/studio-protocol/handle-license-key';import {handleStudioProtocolOptions} from '../preview-server/studio-protocol/origin-policy';@@ -346,6 +347,215 @@ test('discovers an exact Studio target and delivers one install request over HTT}});+test('delivers an Element catalog request without changing config before confirmation', async () => {+ clearElementInstallStateForTests();+ const deliveredEvents: EventSourceEvent[] = [];+ const focusedUrls: string[] = [];+ const directory = mkdtempSync(+ path.join(tmpdir(), 'remotion-element-library-protocol-'),+ );+ const configFile = path.join(directory, 'remotion.config.ts');+ const configContents = [+ "import {Config} from '@remotion/cli/config';",+ "Config.addElementLibrary({url: 'https://existing.example.com/'});",+ '',+ ].join('\n');+ writeFileSync(configFile, configContents);+ let loadedConfigFile: string | null = configFile;+ const liveEventsServer: LiveEventsServer = {+ addNewClientListener: () => () => undefined,+ closeConnections: () => Promise.resolve(),+ router: () => Promise.resolve(),+ sendEventToClient: (event) => {+ if (event.type !== 'request-element-install-target') {+ return;+ }++ updateElementInstallTarget({+ requestId: event.requestId,+ clientId: 'focused-studio-tab',+ compositionFile: null,+ compositionId: null,+ canInstall: false,+ lastFocusedAt: Date.now(),+ readOnly: false,+ studioUrl: 'http://localhost:3000',+ });+ },+ sendEventToClientId: (clientId, event) => {+ if (clientId !== 'focused-studio-tab') {+ return false;+ }++ deliveredEvents.push(event);+ return true;+ },+ };+ const server = createServer((request, response) => {+ const {pathname} = new URL(request.url ?? '/', 'http://localhost');+ if (request.method === 'OPTIONS') {+ handleStudioProtocolOptions({request, response}).catch((error) =>+ response.destroy(error),+ );+ return;+ }++ if (pathname === '/api/studio-protocol') {+ handleStudioProtocolDiscovery({+ gitSource: null,+ liveEventsServer,+ remotionRoot: directory,+ request,+ response,+ }).catch((error) => response.destroy(error));+ return;+ }++ handleStudioProtocolElementLibrary({+ configFile: loadedConfigFile,+ focusStudioTab: (studioUrl) => focusedUrls.push(studioUrl),+ liveEventsServer,+ request,+ response,+ }).catch((error) => response.destroy(error));+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));++ try {+ const address = server.address();+ if (address === null || typeof address === 'string') {+ throw new Error('Expected an HTTP server address');+ }++ const origin = `http://127.0.0.1:${address.port}`;+ const requestOrigin = 'https://catalog.example.com';+ const preflight = await fetch(+ `${origin}/api/studio-protocol/element-library`,+ {method: 'OPTIONS', headers: {Origin: requestOrigin}},+ );+ expect(preflight.status).toBe(204);+ expect(preflight.headers.get('access-control-allow-origin')).toBe(+ requestOrigin,+ );++ const discover = async () => {+ const discoveryResponse = await fetch(`${origin}/api/studio-protocol`, {+ headers: {Origin: requestOrigin},+ });+ const descriptor = (await discoveryResponse.json()) as {+ capabilities: [+ {type: 'install-element'},+ {type: 'set-license-key'},+ {type: 'add-element-library'; target: {id: string}},+ ];+ };+ return descriptor.capabilities[2].target.id;+ };++ let targetId = await discover();+ const body = {+ operation: 'add-element-library',+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ targetId,+ url: 'https://new.example.com/catalog',+ displayName: ' New catalog ',+ };++ for (const invalidBody of [+ {...body, protocolVersion: 2},+ {...body, url: 'file:///tmp/catalog'},+ {...body, displayName: ' '},+ ]) {+ const invalidResponse = await fetch(+ `${origin}/api/studio-protocol/element-library`,+ {+ method: 'POST',+ headers: {'Content-Type': 'application/json', Origin: requestOrigin},+ body: JSON.stringify(invalidBody),+ },+ );+ expect(invalidResponse.status).toBe(400);+ }++ expect(deliveredEvents).toHaveLength(0);++ const wrongOriginResponse = await fetch(+ `${origin}/api/studio-protocol/element-library`,+ {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Origin: 'https://other.example.com',+ },+ body: JSON.stringify(body),+ },+ );+ expect(wrongOriginResponse.status).toBe(409);+ expect(deliveredEvents).toHaveLength(0);++ targetId = await discover();+ const validBody = {...body, targetId};+ const response = await fetch(+ `${origin}/api/studio-protocol/element-library`,+ {+ method: 'POST',+ headers: {'Content-Type': 'application/json', Origin: requestOrigin},+ body: JSON.stringify(validBody),+ },+ );+ expect(await response.json()).toEqual({+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ status: 'awaiting-confirmation',+ });+ expect(deliveredEvents).toEqual([+ {+ type: 'element-library-add-request',+ url: 'https://new.example.com/catalog',+ displayName: 'New catalog',+ origin: requestOrigin,+ },+ ]);+ expect(focusedUrls).toEqual(['http://localhost:3000']);+ expect(readFileSync(configFile, 'utf8')).toBe(configContents);++ const replay = await fetch(+ `${origin}/api/studio-protocol/element-library`,+ {+ method: 'POST',+ headers: {'Content-Type': 'application/json', Origin: requestOrigin},+ body: JSON.stringify(validBody),+ },+ );+ expect(replay.status).toBe(409);+ expect(deliveredEvents).toHaveLength(1);++ targetId = await discover();+ loadedConfigFile = null;+ const noConfigResponse = await fetch(+ `${origin}/api/studio-protocol/element-library`,+ {+ method: 'POST',+ headers: {'Content-Type': 'application/json', Origin: requestOrigin},+ body: JSON.stringify({...body, targetId}),+ },+ );+ expect(noConfigResponse.status).toBe(409);+ expect(await noConfigResponse.json()).toMatchObject({+ status: 'error',+ error: {code: 'no-config-file'},+ });+ expect(deliveredEvents).toHaveLength(1);+ } finally {+ await new Promise<void>((resolve, reject) => {+ server.close((error) => (error ? reject(error) : resolve()));+ });+ rmSync(directory, {recursive: true, force: true});+ clearElementInstallStateForTests();+ }+});+test('opens a license key confirmation in the focused Studio project over HTTP', async () => {clearElementInstallStateForTests();const deliveredEvents: EventSourceEvent[] = [];diff --git a/packages/studio-server/src/test/update-config.test.ts b/packages/studio-server/src/test/update-config.test.tsindex d24b60918a..13b5357129 100644--- a/packages/studio-server/src/test/update-config.test.ts+++ b/packages/studio-server/src/test/update-config.test.ts@@ -12,11 +12,28 @@ import {updateConfigHandler,} from '../preview-server/routes/update-config';+const studioRuntimeConfig = (elementLibraryUrls: readonly string[]) => ({+ askAIEnabled: false,+ bufferStateDelayInMilliseconds: null,+ configFileStudioSettings: null,+ defaultCodingAgent: null,+ defaultEditor: null,+ elementLibraries: elementLibraryUrls.map((url) => ({+ displayName: null,+ url,+ })),+ interactivityEnabled: true,+ keyboardShortcutsEnabled: true,+ maxTimelineTracks: null,+ publicLicenseKey: null,+});+const apiHandlerContext = {binariesDirectory: null,entryPoint: '',getDefaultCodingAgent: () => null,getDefaultEditor: () => null,+ getStudioRuntimeConfig: () => studioRuntimeConfig([]),logLevel: 'error' as const,methods: {addJob: () => undefined,@@ -31,6 +48,7 @@ const apiHandlerContext = {test('updates multiple config settings in one rewrite', () => {expect(updateConfigFile({+ existingElementLibraryUrls: [],configContents: ["import {Config} from '@remotion/cli/config';","Config.setDefaultEditor('vscode');",@@ -67,6 +85,7 @@ test('updates multiple config settings in one rewrite', () => {test('writes JSON-compatible config values safely', () => {expect(updateConfigFile({+ existingElementLibraryUrls: [],configContents: "import {Config} from '@remotion/cli/config';",updates: [{@@ -91,6 +110,7 @@ test('writes JSON-compatible config values safely', () => {test('escapes line separators before writing a config value', () => {expect(updateConfigFile({+ existingElementLibraryUrls: [],configContents: "import {Config} from '@remotion/cli/config';",updates: [{@@ -109,6 +129,164 @@ test('escapes line separators before writing a config value', () => {);});+test('adds Element catalogs without replacing or duplicating existing calls', () => {+ const configContents = [+ "import {Config} from '@remotion/cli/config';",+ '// Keep this catalog and comment.',+ "Config.addElementLibrary({url: 'https://existing.example.com/'});",+ 'Config.setOverwriteOutput(true);',+ '',+ ].join('\n');+ const updated = updateConfigFile({+ configContents,+ existingElementLibraryUrls: [],+ updates: [+ {+ setter: 'addElementLibrary',+ type: 'set',+ value: {+ url: 'https://new.example.com/catalog',+ displayName: " O'Reilly \\ Catalog\u2028Name ",+ },+ },+ ],+ });++ expect(updated).toContain('// Keep this catalog and comment.');+ expect(updated).toContain(+ "Config.addElementLibrary({url: 'https://existing.example.com/'});",+ );+ expect(updated).toContain('Config.setOverwriteOutput(true);');+ expect(updated).toContain("'url': 'https://new.example.com/catalog'");+ expect(updated).toContain(+ "'displayName': 'O\\'Reilly \\\\ Catalog\\u2028Name'",+ );++ const repeated = updateConfigFile({+ configContents: updated,+ existingElementLibraryUrls: [],+ updates: [+ {+ setter: 'addElementLibrary',+ type: 'set',+ value: {url: 'https://new.example.com/catalog'},+ },+ ],+ });+ expect(repeated).toBe(updated);+ expect(repeated.match(/Config\.addElementLibrary/g)).toHaveLength(2);++ expect(+ updateConfigFile({+ configContents,+ existingElementLibraryUrls: [],+ updates: [+ {+ setter: 'addElementLibrary',+ type: 'set',+ value: {url: 'https://existing.example.com'},+ },+ ],+ }),+ ).toBe(configContents);+});++test('uses runtime catalogs for dynamic config deduplication and skips no-op writes', async () => {+ const directory = mkdtempSync(join(tmpdir(), 'remotion-config-update-'));+ const configFile = join(directory, 'remotion.config.ts');+ const configContents = [+ "import {Config} from '@remotion/cli/config';",+ "const existing = {url: 'https://dynamic.example.com/'};",+ 'Config.addElementLibrary(existing);',+ '',+ ].join('\n');+ writeFileSync(configFile, configContents);+ const fileWatcherRegistry = createFileWatcherRegistry();+ const cleanupFileWatcher = setFileWatcherRegistry(fileWatcherRegistry);+ let configChangeEvent: FileChangeEvent | null = null;+ const {unwatch} = fileWatcherRegistry.installFileWatcher({+ existenceOnly: false,+ file: configFile,+ onChange: (event) => {+ configChangeEvent = event;+ },+ });++ try {+ const duplicateResponse = await updateConfigHandler({+ ...apiHandlerContext,+ configFile,+ getStudioRuntimeConfig: () =>+ studioRuntimeConfig(['https://dynamic.example.com/']),+ input: {+ clientId: 'settings-client',+ updates: [+ {+ setter: 'addElementLibrary',+ type: 'set',+ value: {url: 'https://dynamic.example.com'},+ },+ ],+ },+ remotionRoot: directory,+ });+ expect(duplicateResponse).toEqual({success: true});+ expect(readFileSync(configFile, 'utf8')).toBe(configContents);+ expect(configChangeEvent).toBe(null);++ const additionResponse = await updateConfigHandler({+ ...apiHandlerContext,+ configFile,+ input: {+ clientId: 'settings-client',+ updates: [+ {+ setter: 'addElementLibrary',+ type: 'set',+ value: {+ url: 'https://new.example.com',+ displayName: ' New catalog ',+ },+ },+ ],+ },+ remotionRoot: directory,+ });+ expect(additionResponse).toEqual({success: true});+ const addedContents = readFileSync(configFile, 'utf8');+ expect(addedContents).toContain("'url': 'https://new.example.com/'");+ expect(addedContents).toContain("'displayName': 'New catalog'");+ expect(configChangeEvent).toMatchObject({+ originatorClientId: 'settings-client',+ type: 'changed',+ });++ configChangeEvent = null;+ const repeatedResponse = await updateConfigHandler({+ ...apiHandlerContext,+ configFile,+ input: {+ clientId: 'settings-client',+ updates: [+ {+ setter: 'addElementLibrary',+ type: 'set',+ value: {url: 'https://new.example.com'},+ },+ ],+ },+ remotionRoot: directory,+ });+ expect(repeatedResponse).toEqual({success: true});+ expect(readFileSync(configFile, 'utf8')).toBe(addedContents);+ expect(configChangeEvent).toBe(null);+ } finally {+ unwatch();+ cleanupFileWatcher();+ rmSync(directory, {force: true, recursive: true});+ }+});+test('persists an arbitrary valid config setter through the route', async () => {const directory = mkdtempSync(join(tmpdir(), 'remotion-config-update-'));const configFile = join(directory, 'remotion.config.ts');@@ -203,6 +381,23 @@ test('rejects invalid updates without changing the config', async () => {value: 'private-key',},],+ [+ {+ setter: 'addElementLibrary',+ type: 'set' as const,+ value: {url: 'file:///tmp/catalog'},+ },+ ],+ [+ {+ setter: 'addElementLibrary',+ type: 'set' as const,+ value: {+ url: 'https://catalog.example.com',+ displayName: ' ',+ },+ },+ ],]) {const response = await updateConfigHandler({...apiHandlerContext,diff --git a/packages/studio-shared/src/event-source-event.ts b/packages/studio-shared/src/event-source-event.tsindex 5f8e03161a..33b8e5655c 100644--- a/packages/studio-shared/src/event-source-event.ts+++ b/packages/studio-shared/src/event-source-event.ts@@ -108,6 +108,12 @@ export type EventSourceEvent =type: 'license-key-install-request';licenseKey: string;}+ | {+ type: 'element-library-add-request';+ url: string;+ displayName: string | null;+ origin: string;+ }| {type: 'visual-control-values-changed';values: Array<{diff --git a/packages/studio/src/components/Modals.tsx b/packages/studio/src/components/Modals.tsxindex f1077c5505..ce85be8c69 100644--- a/packages/studio/src/components/Modals.tsx+++ b/packages/studio/src/components/Modals.tsx@@ -4,7 +4,8 @@ import {StudioServerConnectionCtx} from '../helpers/client-id';import {getStudioAskAIEnabled} from '../helpers/studio-runtime-config';import {SelectedModalContext, SetSelectedModalContext} from '../state/modals';import {AskAiModal} from './AskAiModal';-import {ConfirmationDialog} from './ConfirmationDialog';+import {callApi} from './call-api';+import {ConfirmationDialog, useConfirmationDialog} from './ConfirmationDialog';import {EffectPickerModal} from './EffectPickerModal';import {ElementLibraryModal} from './ElementLibraryModal';import {FixComputedValueModal} from './FixComputedValueModal';@@ -16,6 +17,7 @@ import {NewFolder} from './NewComposition/NewFolder';import {RenameComposition} from './NewComposition/RenameComposition';import {RenameFolder} from './NewComposition/RenameFolder';import {RenameStaticFileModal} from './NewComposition/RenameStaticFile';+import {showNotification} from './Notifications/NotificationCenter';import {OverrideInputPropsModal} from './OverrideInputProps';import QuickSwitcher from './QuickSwitcher/QuickSwitcher';import {RenderStatusModal} from './RenderModal/RenderStatusModal';@@ -35,6 +37,7 @@ export const Modals: React.FC<{);const canRender = previewServerState.type === 'connected';const isBrowserStudio = getBrowserStudioOperations() !== null;+ const confirm = useConfirmationDialog();useEffect(() => {if (isBrowserStudio) {@@ -54,6 +57,82 @@ export const Modals: React.FC<{});}, [isBrowserStudio, setSelectedModal, subscribeToEvent]);+ useEffect(() => {+ if (isBrowserStudio) {+ return;+ }++ return subscribeToEvent('element-library-add-request', (event) => {+ if (event.type !== 'element-library-add-request') {+ return;+ }++ (async () => {+ const confirmed = await confirm({+ title: 'Add Element catalog',+ message: (+ <div>+ <p>+ The website <code>{event.origin}</code> wants to add this+ Element catalog:+ </p>+ <p>+ <code>{event.url}</code>+ </p>+ {event.displayName === null ? null : (+ <p>Display name: {event.displayName}</p>+ )}+ <p>+ Confirming permanently adds a{' '}+ <code>Config.addElementLibrary()</code> call to{' '}+ <code>remotion.config.ts</code>.+ </p>+ <p>+ Adding this catalog does not install Element source code or+ dependencies. Individual Element installations still require+ confirmation.+ </p>+ </div>+ ),+ confirmLabel: 'Add catalog',+ cancelLabel: 'Cancel',+ });+ if (!confirmed) {+ return;+ }++ if (previewServerState.type !== 'connected') {+ showNotification('Could not add catalog: Studio disconnected', 4000);+ return;+ }++ try {+ const result = await callApi('/api/update-config', {+ clientId: previewServerState.clientId,+ updates: [+ {+ setter: 'addElementLibrary',+ type: 'set',+ value:+ event.displayName === null+ ? {url: event.url}+ : {url: event.url, displayName: event.displayName},+ },+ ],+ });+ if (!result.success) {+ showNotification(`Could not add catalog: ${result.reason}`, 4000);+ }+ } catch (error) {+ showNotification(+ `Could not add catalog: ${(error as Error).message}`,+ 4000,+ );+ }+ })();+ });+ }, [confirm, isBrowserStudio, previewServerState, subscribeToEvent]);+return (<>{modalContextType && modalContextType.type === 'new-comp' && (