🎥 Make videos programmatically with React
Simplify studio-protocol validation and parsing
Igor Samokhovets18fbbd1b3518
diff --git a/packages/studio-protocol/src/add-element-library-to-studio.ts b/packages/studio-protocol/src/add-element-library-to-studio.tsindex 35c5075a33..6d62b10e35 100644--- a/packages/studio-protocol/src/add-element-library-to-studio.ts+++ b/packages/studio-protocol/src/add-element-library-to-studio.ts@@ -129,6 +129,7 @@ export const parseStudioProtocolAddElementLibraryRequest = (studioProtocolAddElementLibraryRequestSchema,value,);+return parsed.success ? parsed.data : null;};@@ -139,40 +140,40 @@ export const parseStudioProtocolIframeAddElementLibraryRequest = (studioProtocolIframeAddElementLibraryRequestSchema,value,);+return parsed.success ? parsed.data : null;};const failure = (code: AddElementLibraryToStudioErrorCode,message: string,-): AddElementLibraryToStudioResult => ({success: false, code, message});+): Extract<AddElementLibraryToStudioResult, {success: false}> => ({+ success: false,+ code,+ message,+});-export const addElementLibraryToStudioWithDependencies = async (- {- captionStylesUrl,- displayName,- url,- }: {- readonly captionStylesUrl: string | null;- readonly displayName: string | null;- readonly url: string;- },- dependencies: AddElementLibraryToStudioDependencies,-): Promise<AddElementLibraryToStudioResult> => {- if (!isAllowedStudioProtocolPageOrigin(dependencies.pageOrigin)) {- return failure(- 'unsupported-origin',- 'Adding an Element Library is only supported on HTTPS websites and local development origins.',- );- }+type ElementLibraryDetails = Pick<+ StudioProtocolAddElementLibraryRequest,+ 'url' | 'displayName' | 'captionStylesUrl'+>;- if (typeof url !== 'string') {+const normalizeElementLibraryDetails = ({+ url,+ displayName,+ captionStylesUrl,+}: ElementLibraryDetails):+ | {success: true; details: ElementLibraryDetails}+ | Extract<AddElementLibraryToStudioResult, {success: false}> => {+ if (!z.safeParse(z.string(), url).success) {return failure('invalid-url', 'The Element Library 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',@@ -189,13 +190,15 @@ export const addElementLibraryToStudioWithDependencies = async (}let normalizedCaptionStylesUrl: string | null = null;+if (captionStylesUrl !== null) {try {- if (typeof captionStylesUrl !== 'string') {+ if (!z.safeParse(z.string(), captionStylesUrl).success) {throw new Error('Invalid URL');}const parsedUrl = new URL(captionStylesUrl);+if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {throw new Error('Unsupported protocol');}@@ -209,7 +212,7 @@ export const addElementLibraryToStudioWithDependencies = async (}}- if (displayName !== null && typeof displayName !== 'string') {+ if (!z.safeParse(z.nullable(z.string()), displayName).success) {return failure('invalid-display-name','The Element Library display name must be a string.',@@ -217,6 +220,7 @@ export const addElementLibraryToStudioWithDependencies = async (}const normalizedDisplayName = displayName?.trim() ?? null;+if (normalizedDisplayName === '') {return failure('invalid-display-name',@@ -224,7 +228,47 @@ export const addElementLibraryToStudioWithDependencies = async ();}+ return {+ success: true,+ details: {+ url: normalizedUrl,+ displayName: normalizedDisplayName,+ captionStylesUrl: normalizedCaptionStylesUrl,+ },+ };+};++export const addElementLibraryToStudioWithDependencies = async (+ {+ captionStylesUrl,+ displayName,+ url,+ }: {+ readonly captionStylesUrl: string | null;+ readonly displayName: string | null;+ readonly url: string;+ },+ dependencies: AddElementLibraryToStudioDependencies,+): Promise<AddElementLibraryToStudioResult> => {+ if (!isAllowedStudioProtocolPageOrigin(dependencies.pageOrigin)) {+ return failure(+ 'unsupported-origin',+ 'Adding an Element Library is only supported on HTTPS websites and local development origins.',+ );+ }++ const normalized = normalizeElementLibraryDetails({+ url,+ displayName,+ captionStylesUrl,+ });++ if (!normalized.success) {+ return normalized;+ }+const discovery = await discoverStudios(dependencies);+if (discovery.studios.length === 0) {if (discovery.foundUnsupportedProtocol) {return failure(@@ -248,8 +292,10 @@ export const addElementLibraryToStudioWithDependencies = async (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',@@ -258,21 +304,28 @@ export const addElementLibraryToStudioWithDependencies = async (}const now = dependencies.now();+const configurable = supportedStudios- .filter(({capability}) => {- const {target} = capability;- return target !== null && target.expiresAt > now;+ .flatMap((studio) => {+ const {target} = studio.capability;++ if (target === null || target.expiresAt <= now) {+ return [];+ }++ return [{...studio, target}];}).sort((a, b) => {- const focusDifference =- b.capability.target!.lastFocusedAt - a.capability.target!.lastFocusedAt;+ const focusDifference = b.target.lastFocusedAt - a.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) {++ if (!selected) {return failure('no-configurable-target','Focus a writable Remotion Studio tab, then try again.',@@ -280,16 +333,16 @@ export const addElementLibraryToStudioWithDependencies = async (}let response: Response;+try {const requestBody = {operation: 'add-element-library',protocol: 'remotion-studio-protocol',protocolVersion: 1,- targetId: selectedTarget.id,- url: normalizedUrl,- displayName: normalizedDisplayName,- captionStylesUrl: normalizedCaptionStylesUrl,+ targetId: selected.target.id,+ ...normalized.details,} satisfies StudioProtocolAddElementLibraryRequest;+response = await fetchWithTimeout({fetchFn: dependencies.fetchFn,url: `${selected.origin}/api/studio-protocol/element-library`,@@ -301,6 +354,7 @@ export const addElementLibraryToStudioWithDependencies = async (});} catch (error) {const timedOut = isAbortError(error);+return failure(timedOut ? 'request-timed-out' : 'network-error',timedOut@@ -310,6 +364,7 @@ export const addElementLibraryToStudioWithDependencies = async (}let result: unknown;+try {result = await response.json();} catch {@@ -332,15 +387,15 @@ export const addElementLibraryToStudioWithDependencies = async (}const protocolError = parseStudioProtocolError(result);+if (protocolError !== null) {- return failure(- protocolError.code === 'target-expired'- ? 'target-expired'- : protocolError.code === 'no-config-file'- ? 'no-config-file'- : 'request-rejected',- protocolError.message,- );+ const {code, message} = protocolError;++ if (code === 'target-expired' || code === 'no-config-file') {+ return failure(code, message);+ }++ return failure('request-rejected', message);}return failure(@@ -362,6 +417,7 @@ const addElementLibraryToParentStudio = (return new Promise((resolve) => {const channel = new MessageChannel();+const timeout = setTimeout(() => {channel.port1.close();resolve(null);@@ -372,6 +428,7 @@ const addElementLibraryToParentStudio = (addElementLibraryToStudioResultSchema,event.data,);+if (!response.success) {return;}@@ -391,33 +448,26 @@ export const addElementLibraryToStudio = async ({displayName,url,}: AddElementLibraryToStudioInput): Promise<AddElementLibraryToStudioResult> => {- if (typeof url === 'string') {+ const normalized = normalizeElementLibraryDetails({+ url,+ displayName: displayName ?? null,+ captionStylesUrl: captionStylesUrl ?? null,+ });++ if (normalized.success) {try {- const parsedUrl = new URL(url);- const parsedCaptionStylesUrl =- captionStylesUrl === undefined ? null : new URL(captionStylesUrl);- const normalizedDisplayName = displayName?.trim() ?? null;- if (- (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') &&- (parsedCaptionStylesUrl === null ||- parsedCaptionStylesUrl.protocol === 'http:' ||- parsedCaptionStylesUrl.protocol === 'https:') &&- normalizedDisplayName !== ''- ) {- const parentResult = await addElementLibraryToParentStudio({- operation: 'add-element-library',- protocol: 'remotion-studio-protocol',- protocolVersion: 1,- url: parsedUrl.href,- displayName: normalizedDisplayName,- captionStylesUrl: parsedCaptionStylesUrl?.href ?? null,- });- if (parentResult !== null) {- return parentResult;- }+ const parentResult = await addElementLibraryToParentStudio({+ operation: 'add-element-library',+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ ...normalized.details,+ });++ if (parentResult !== null) {+ return parentResult;}} catch {- // The shared validation below returns the public invalid URL result.+ // If the parent is unavailable, try local Studio discovery below.}}diff --git a/packages/studio-protocol/src/asset-drag-data.ts b/packages/studio-protocol/src/asset-drag-data.tsindex 3c197c3965..e4d5165d07 100644--- a/packages/studio-protocol/src/asset-drag-data.ts+++ b/packages/studio-protocol/src/asset-drag-data.ts@@ -23,6 +23,7 @@ export const makeAssetDragData = (assetPath: string): AssetDragData => {export const parseAssetDragData = (value: string): AssetDragData | null => {try {const parsed = z.safeParse(assetDragDataSchema, JSON.parse(value));+return parsed.success ? makeAssetDragData(parsed.data.assetPath) : null;} catch {return null;diff --git a/packages/studio-protocol/src/browser-studio-link.ts b/packages/studio-protocol/src/browser-studio-link.tsindex dc81695085..f8a61b30d4 100644--- a/packages/studio-protocol/src/browser-studio-link.ts+++ b/packages/studio-protocol/src/browser-studio-link.ts@@ -5,6 +5,7 @@ import {parseStudioElementPayload} from './element-payload';const browserStudioHashKey = 'remotion-browser-studio';const defaultBrowserStudioEndpoint = 'https://www.remotion.dev/new';const maxEncodedPayloadLength = 1_100_000;+const browserStudioEnvelopeSchema = z.object({type: z.literal('remotion-browser-studio'),version: z.literal(1),@@ -15,6 +16,7 @@ const toBase64Url = (value: string) => {const bytes = new TextEncoder().encode(value);let binary = '';const chunkSize = 32_768;+for (let offset = 0; offset < bytes.length; offset += chunkSize) {binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize),@@ -34,12 +36,15 @@ const fromBase64Url = (value: string) => {try {const base64 = value.replaceAll('-', '+').replaceAll('_', '/');+const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4),'=',);+const binary = atob(padded);const bytes = new Uint8Array(binary.length);+for (let index = 0; index < binary.length; index++) {bytes[index] = binary.charCodeAt(index);}@@ -62,6 +67,7 @@ export const makeBrowserStudioUrl = ({}const url = new URL(endpoint ?? defaultBrowserStudioEndpoint);+if (url.protocol !== 'https:' && url.protocol !== 'http:') {throw new TypeError('Browser Studio endpoint must use HTTP or HTTPS');}@@ -73,11 +79,13 @@ export const makeBrowserStudioUrl = ({version: 1,}),);+if (encoded.length > maxEncodedPayloadLength) {throw new TypeError('Browser Studio payload is too large');}url.hash = new URLSearchParams({[browserStudioHashKey]: encoded}).toString();+return url.toString();};@@ -95,6 +103,7 @@ export const parseBrowserStudioHash = (const encoded = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash,).get(browserStudioHashKey);+if (encoded === null ||encoded.length === 0 ||@@ -104,6 +113,7 @@ export const parseBrowserStudioHash = (}const decoded = fromBase64Url(encoded);+if (decoded === null) {return null;}@@ -113,6 +123,7 @@ export const parseBrowserStudioHash = (browserStudioEnvelopeSchema,JSON.parse(decoded),);+return envelope.success? parseStudioElementPayload(envelope.data.payload): null;diff --git a/packages/studio-protocol/src/caption-style-selection.ts b/packages/studio-protocol/src/caption-style-selection.tsindex e7a7269c26..f8a2948107 100644--- a/packages/studio-protocol/src/caption-style-selection.ts+++ b/packages/studio-protocol/src/caption-style-selection.ts@@ -44,5 +44,6 @@ export const isStudioProtocolCaptionStyleSubscription = (export const parseStudioProtocolCaptionStyleSelection = (value: unknown) => {const parsed = z.safeParse(captionStyleSelectionMessageSchema, value);+return parsed.success ? parsed.data : null;};diff --git a/packages/studio-protocol/src/component-drag-data.ts b/packages/studio-protocol/src/component-drag-data.tsindex 2739d47ab1..1ea547cda0 100644--- a/packages/studio-protocol/src/component-drag-data.ts+++ b/packages/studio-protocol/src/component-drag-data.ts@@ -25,6 +25,7 @@ export type ComponentDragData = {const componentIdentifierSchema = z.string().check(z.regex(/^[A-Z_$][A-Za-z0-9_$]*$/));+const componentImportPathSchema = z.string().check(@@ -38,6 +39,7 @@ const componentImportPathSchema = z/^[A-Za-z0-9@._/-]+$/.test(value),),);+const componentPropNameSchema = z.string().check(@@ -45,20 +47,25 @@ const componentPropNameSchema = z(value) => value !== 'style' && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value),),);+const componentPropSchema = z.object({name: componentPropNameSchema,value: z.union([z.string(), z.number(), z.boolean()]),});+const componentPropsSchema = z.array(componentPropSchema).check(z.refine((props) => {const names = props.map((prop) => prop.name);+return new Set(names).size === names.length;}),);+const componentDimensionsSchema = z.object({width: z.number().check(z.nonnegative()),height: z.number().check(z.nonnegative()),});+const componentDragDataSchema = z.object({type: z.literal('remotion-component'),version: z.literal(1),@@ -99,16 +106,21 @@ export const makeComponentDragData = ({importPath: string;props: ComponentProp[];}): ComponentDragData => {+ const component: ComponentDragData['component'] = {+ componentName,+ importName,+ importPath,+ props,+ };++ if (dimensions) {+ component.dimensions = dimensions;+ }+return {type: 'remotion-component',version: 1,- component: {- componentName,- ...(dimensions ? {dimensions} : {}),- importName,- importPath,- props,- },+ component,};};@@ -117,6 +129,7 @@ export const parseComponentDragData = (): ComponentDragData | null => {try {const parsed = z.safeParse(componentDragDataSchema, JSON.parse(value));+if (!parsed.success) {return null;}diff --git a/packages/studio-protocol/src/drag-data.ts b/packages/studio-protocol/src/drag-data.tsindex 5ba311106a..486782ffc0 100644--- a/packages/studio-protocol/src/drag-data.ts+++ b/packages/studio-protocol/src/drag-data.ts@@ -285,21 +285,26 @@ const dimensionsMatch = (export const parseDragData = (source: SerializedDragData | DragDataTransfer,): ParsedDragData | null => {- const {mimeType, payload} =- 'types' in source- ? (() => {- const candidate = getDragPreviewMetadata(source.types);- if (candidate === null) {- return {mimeType: '', payload: ''};- }-- return {- mimeType: candidate.mimeType,- payload: source.getData(candidate.mimeType),- };- })()- : source;+ let serialized: SerializedDragData;++ if ('types' in source) {+ const candidate = getDragPreviewMetadata(source.types);++ if (candidate === null) {+ return null;+ }++ serialized = {+ mimeType: candidate.mimeType,+ payload: source.getData(candidate.mimeType),+ };+ } else {+ serialized = source;+ }++ const {mimeType, payload} = serialized;const preview = parseDragMimeType(mimeType);+if (preview === null) {return null;}@@ -313,6 +318,7 @@ export const parseDragData = (case 'component': {const data = parseComponentDragData(payload);+if (data === null ||!dimensionsMatch(preview, data.component.dimensions)@@ -331,6 +337,7 @@ export const parseDragData = (case 'element': {const data = parseElementDragData(payload);+if (!data || !dimensionsMatch(preview, data.element.dimensions)) {return null;}diff --git a/packages/studio-protocol/src/drag-preview-metadata.ts b/packages/studio-protocol/src/drag-preview-metadata.tsindex 781be929c5..958811d3f6 100644--- a/packages/studio-protocol/src/drag-preview-metadata.ts+++ b/packages/studio-protocol/src/drag-preview-metadata.ts@@ -61,7 +61,9 @@ const assertDimensions = (metadata: DragPreviewMetadata) => {return;}- const {height, width} = metadata as Dimensions;+ const width = 'width' in metadata ? metadata.width : undefined;+ const height = 'height' in metadata ? metadata.height : undefined;+if (width === undefined && height === undefined) {return;}@@ -132,6 +134,7 @@ export const makeDragMimeType = (metadata: DragPreviewMetadata): string => {}const duration = getDuration(metadata);+if (duration !== undefined) {segments.push(`duration=${duration}`);}@@ -145,6 +148,7 @@ const parsePositiveInteger = (value: string, max: number): number | null => {}const parsed = Number(value);+return isBoundedInteger(parsed, max) ? parsed : null;};@@ -154,12 +158,11 @@ const parsePositiveNumber = (value: string, max: number): number | null => {}const parsed = Number(value);+return Number.isFinite(parsed) && parsed > 0 && parsed <= max ? parsed : null;};-export const parseDragMimeType = (- mimeType: string,-): DragPreviewMetadata | null => {+const parseMimeParameters = (mimeType: string): Map<string, string> | null => {if (mimeType.length > MAX_MIME_TYPE_LENGTH ||!mimeType.startsWith(`${REMOTION_DRAG_MIME_TYPE};`)@@ -168,19 +171,23 @@ export const parseDragMimeType = (}const segments = mimeType.split(';');+if (segments.shift() !== REMOTION_DRAG_MIME_TYPE) {return null;}const values = new Map<string, string>();+for (const segment of segments) {const separator = segment.indexOf('=');+if (separator === -1) {return null;}const key = segment.slice(0, separator);const value = segment.slice(separator + 1);+if (!['v', 'type', 'width', 'height', 'duration'].includes(key) ||value === '' ||@@ -196,81 +203,97 @@ export const parseDragMimeType = (return null;}- const type = values.get('type');- if (- type !== 'asset' &&- type !== 'component' &&- type !== 'effect' &&- type !== 'element' &&- type !== 'render-output' &&- type !== 'sfx'- ) {- return null;- }+ return values;+};+const parseMimeDimensions = (+ values: Map<string, string>,+): Dimensions | null => {const widthValue = values.get('width');const heightValue = values.get('height');- if ((widthValue === undefined) !== (heightValue === undefined)) {- return null;++ if (widthValue === undefined && heightValue === undefined) {+ return {};}- if (- (type === 'effect' || type === 'render-output' || type === 'sfx') &&- (widthValue !== undefined || values.has('duration'))- ) {+ if (widthValue === undefined || heightValue === undefined) {return null;}- const width =- widthValue === undefined- ? undefined- : parsePositiveNumber(widthValue, MAX_DIMENSION);- const height =- heightValue === undefined- ? undefined- : parsePositiveNumber(heightValue, MAX_DIMENSION);+ const width = parsePositiveNumber(widthValue, MAX_DIMENSION);+ const height = parsePositiveNumber(heightValue, MAX_DIMENSION);+if (width === null || height === null) {return null;}- const durationValue = values.get('duration');- if (durationValue !== undefined && type !== 'asset' && type !== 'element') {+ return {width, height};+};++export const parseDragMimeType = (+ mimeType: string,+): DragPreviewMetadata | null => {+ const values = parseMimeParameters(mimeType);++ if (values === null) {return null;}- const duration =- durationValue === undefined- ? undefined- : type === 'asset'- ? parsePositiveNumber(durationValue, MAX_DURATION_IN_SECONDS)- : parsePositiveInteger(durationValue, MAX_DURATION_IN_FRAMES);- if (duration === null) {+ const dimensions = parseMimeDimensions(values);++ if (dimensions === null) {return null;}- const dimensions =- width === undefined ? {} : {width, height: height as number};- if (type === 'asset') {- return {- type,- ...dimensions,- ...(duration === undefined ? {} : {durationInSeconds: duration}),- };- }+ const type = values.get('type');+ const durationValue = values.get('duration');- if (type === 'element') {- if (duration === undefined) {- return null;+ switch (type) {+ case 'asset': {+ if (durationValue === undefined) {+ return {type, ...dimensions};+ }++ const durationInSeconds = parsePositiveNumber(+ durationValue,+ MAX_DURATION_IN_SECONDS,+ );++ if (durationInSeconds === null) {+ return null;+ }++ return {type, ...dimensions, durationInSeconds};}- return {- type,- ...dimensions,- durationInFrames: duration,- };- }+ case 'element': {+ if (durationValue === undefined) {+ return null;+ }++ const durationInFrames = parsePositiveInteger(+ durationValue,+ MAX_DURATION_IN_FRAMES,+ );++ if (durationInFrames === null) {+ return null;+ }- return {type, ...dimensions};+ return {type, ...dimensions, durationInFrames};+ }++ case 'component':+ return durationValue === undefined ? {type, ...dimensions} : null;+ case 'effect':+ case 'render-output':+ case 'sfx':+ return dimensions.width === undefined && durationValue === undefined+ ? {type}+ : null;+ default:+ return null;+ }};export const getDragPreviewMetadata = (@@ -279,6 +302,7 @@ export const getDragPreviewMetadata = (for (let index = 0; index < mimeTypes.length; index++) {const mimeType = mimeTypes[index];const parsed = parseDragMimeType(mimeType);+if (parsed !== null) {return {...parsed, mimeType};}diff --git a/packages/studio-protocol/src/drag-transport.ts b/packages/studio-protocol/src/drag-transport.tsindex bb87f837dd..90f6549ed8 100644--- a/packages/studio-protocol/src/drag-transport.ts+++ b/packages/studio-protocol/src/drag-transport.ts@@ -5,7 +5,7 @@ export const setStudioDragData = ({dataTransfer,payload,}: {- readonly dataTransfer: DataTransfer;+ readonly dataTransfer: Pick<DataTransfer, 'effectAllowed' | 'setData'>;readonly payload: StudioElementPayload;}): void => {const dragData = makeDragData({diff --git a/packages/studio-protocol/src/effect-drag-data.ts b/packages/studio-protocol/src/effect-drag-data.tsindex a0afc08f6a..b3c2bd1184 100644--- a/packages/studio-protocol/src/effect-drag-data.ts+++ b/packages/studio-protocol/src/effect-drag-data.ts@@ -23,6 +23,7 @@ export type EffectDragData = {};const effectConfigSchema = z.record(z.string(), z.json());+const effectDragDataSchema = z.object({type: z.literal('remotion-effect'),version: z.literal(1),@@ -50,6 +51,7 @@ export const makeEffectDragData = (export const parseEffectDragData = (value: string): EffectDragData | null => {try {const parsed = z.safeParse(effectDragDataSchema, JSON.parse(value));+if (!parsed.success) {return null;}diff --git a/packages/studio-protocol/src/element-drag-data.ts b/packages/studio-protocol/src/element-drag-data.tsindex bf649da5c2..e051594008 100644--- a/packages/studio-protocol/src/element-drag-data.ts+++ b/packages/studio-protocol/src/element-drag-data.ts@@ -81,6 +81,7 @@ const lowercaseElementFileNameSchema = z/^[a-z0-9][a-z0-9.-]*\.tsx$/.test(value),),);+const slugSchema = z.string().check(@@ -97,15 +98,22 @@ const slugSchema = zexport const isLowercaseElementFileName = (value: unknown): value is string =>z.safeParse(lowercaseElementFileNameSchema, value).success;-const isSlug = (value: unknown): value is string =>- z.safeParse(slugSchema, value).success;-export const makeElementFileNameFromSlug = (slug: string) => {- if (!isSlug(slug)) return null;+ if (!z.safeParse(slugSchema, slug).success) {+ 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;++ return z.safeParse(lowercaseElementFileNameSchema, fileName).success+ ? fileName+ : null;};export const getElementComponentNameFromSourceCode = (sourceCode: string) => {@@ -114,8 +122,13 @@ export const getElementComponentNameFromSourceCode = (sourceCode: string) => {/export\s+(?:const|function)\s+([A-Z_$][A-Za-z0-9_$]*)\b/g,),).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;@@ -134,6 +147,7 @@ const exactVersionSchema = z/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,),);+const elementDependencyEnvelopeSchema = z.looseObject({name: z.string().check(z.refine(isValidPackageName)),version: z.unknown(),@@ -141,6 +155,7 @@ const elementDependencyEnvelopeSchema = z.looseObject({const getElementDependencyError = (value: unknown): string | null => {const parsed = z.safeParse(elementDependencyEnvelopeSchema, value);+if (!parsed.success) {return `Invalid Element dependency: ${JSON.stringify(value)}`;}@@ -168,6 +183,7 @@ export function assertElementDependency(value: unknown,): asserts value is ElementDependency {const error = getElementDependencyError(value);+if (error !== null) {throw new TypeError(error);}@@ -179,32 +195,42 @@ export const isElementDependency = (z.safeParse(elementDependencySchema, value).success;const windowsReservedNames = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;+const strictBase64Regex =/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;-export const isValidElementAssetPath = (assetPath: string) =>- assetPath.length > 0 &&- assetPath.length <= 1024 &&- !assetPath.startsWith('/') &&- !assetPath.includes('\\') &&- assetPath- .split('/')- .every(- (segment) =>- segment !== '' &&- segment !== '.' &&- segment !== '..' &&- !/[<>:"|?*]/.test(segment) &&- !Array.from(segment).some(- (character) => character.charCodeAt(0) <= 31,- ) &&- !/[. ]$/.test(segment) &&- !windowsReservedNames.test(segment),- );+export const isValidElementAssetPath = (assetPath: string) => {+ if (assetPath.length === 0 || assetPath.length > 1024) {+ return false;+ }++ if (assetPath.startsWith('/') || assetPath.includes('\\')) {+ return false;+ }++ return assetPath.split('/').every((segment) => {+ if (segment === '' || segment === '.' || segment === '..') {+ return false;+ }++ if (/[<>:"|?*]/.test(segment) || /[. ]$/.test(segment)) {+ return false;+ }++ if (+ Array.from(segment).some((character) => character.charCodeAt(0) <= 31)+ ) {+ return false;+ }++ return !windowsReservedNames.test(segment);+ });+};const isValidElementAssetUrl = (value: string) => {try {const url = new URL(value);+return ((url.protocol === 'http:' || url.protocol === 'https:') &&url.username === '' &&@@ -227,6 +253,7 @@ const elementAssetSchema = z.union([data: z.string().check(z.regex(strictBase64Regex)),}),]);+const elementAssetsSchema = z.array(elementAssetSchema).check(z.maxLength(maxElementAssets));@@ -235,14 +262,17 @@ export function assertElementAssets(value: unknown,): asserts value is ElementAsset[] {const parsed = z.safeParse(elementAssetsSchema, value);+if (!parsed.success) {throw new TypeError('Invalid Element assets');}const paths = new Set<string>();let embeddedBytes = 0;+for (const asset of parsed.data) {const assetPath = asset.path.toLowerCase();+if ([...paths].some((existingPath) =>@@ -257,10 +287,15 @@ export function assertElementAssets(}paths.add(assetPath);+if (asset.type === 'base64') {- embeddedBytes +=- (asset.data.length / 4) * 3 -- (asset.data.endsWith('==') ? 2 : asset.data.endsWith('=') ? 1 : 0);+ embeddedBytes += (asset.data.length / 4) * 3;++ if (asset.data.endsWith('==')) {+ embeddedBytes -= 2;+ } else if (asset.data.endsWith('=')) {+ embeddedBytes -= 1;+ }}}@@ -273,15 +308,19 @@ const dimensionsSchema = z.object({width: z.number().check(z.positive()),height: z.number().check(z.positive()),});+const elementInstallationModeSchema = z.union([z.literal('wrapped'),z.literal('component-owned-sequence'),]);+const durationSchema = z.number().check(z.int(), z.positive(), z.lte(100_000_000));+const elementInitialPropsSchema = z.record(z.string(), z.unknown());const initialPropNameRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;+const componentOwnedInstallationProps = new Set(['durationInFrames','from',@@ -308,43 +347,74 @@ const isJsonCompatibleValue = (return false;}+ if (!Array.isArray(value)) {+ // Plain objects from another realm have a different Object.prototype.+ const prototype = Object.getPrototypeOf(value);++ if (prototype !== null && Object.getPrototypeOf(prototype) !== null) {+ return false;+ }+ }+seen.add(value);- // Plain objects from another realm have a different Object.prototype.- const prototype = Object.getPrototypeOf(value);- const valid = Array.isArray(value)- ? value.every((item) => isJsonCompatibleValue(item, seen))- : (prototype === null || Object.getPrototypeOf(prototype) === null) &&- Object.values(value).every((item) => isJsonCompatibleValue(item, seen));++ const values = Array.isArray(value) ? value : Object.values(value);+ const valid = values.every((item) => isJsonCompatibleValue(item, seen));+seen.delete(value);+return valid;};export const isElementInitialProps = (value: unknown,-): value is ElementInitialProps | null =>- value === null ||- (!Array.isArray(value) &&- typeof value === 'object' &&- value !== null &&- Object.keys(value).every((key) => initialPropNameRegex.test(key)) &&- isJsonCompatibleValue(value, new Set()));+): value is ElementInitialProps | null => {+ if (value === null) {+ return true;+ }++ if (typeof value !== 'object' || Array.isArray(value)) {+ return false;+ }++ if (!Object.keys(value).every((key) => initialPropNameRegex.test(key))) {+ return false;+ }++ return isJsonCompatibleValue(value, new Set());+};++const elementAssetPathSchema = z+ .string()+ .check(z.refine(isValidElementAssetPath));export const staticFileRef = (path: string): StaticFileRef => {- if (typeof path !== 'string' || !isValidElementAssetPath(path)) {+ if (!z.safeParse(elementAssetPathSchema, path).success) {throw new TypeError('staticFileRef() requires a safe Element asset path');}return {__remotion_element_asset: path};};-export const isStaticFileRef = (value: unknown): value is StaticFileRef =>- typeof value === 'object' &&- value !== null &&- !Array.isArray(value) &&- Object.keys(value).length === 1 &&- Object.hasOwn(value, '__remotion_element_asset') &&- typeof (value as StaticFileRef).__remotion_element_asset === 'string' &&- isValidElementAssetPath((value as StaticFileRef).__remotion_element_asset);+export const isStaticFileRef = (value: unknown): value is StaticFileRef => {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {+ return false;+ }++ if (Object.keys(value).length !== 1) {+ return false;+ }++ if (+ !Object.hasOwn(value, '__remotion_element_asset') ||+ !('__remotion_element_asset' in value)+ ) {+ return false;+ }++ return z.safeParse(elementAssetPathSchema, value.__remotion_element_asset)+ .success;+};export function assertElementAssetReferences({assets,@@ -355,7 +425,8 @@ export function assertElementAssetReferences({}): void {const paths = new Set(assets.map((asset) => asset.path));const seen = new Set<object>();- const visit = (value: unknown): void => {++ const visit = (value: ElementInitialPropValue): void => {if (value === null || typeof value !== 'object') {return;}@@ -410,12 +481,17 @@ export const hasValidElementInitialPropsForInstallationMode = ({return false;}- return (- initialProps.style === undefined ||- (initialProps.style !== null &&- typeof initialProps.style === 'object' &&- !Array.isArray(initialProps.style))- );+ const {style} = initialProps;++ if (style === undefined) {+ return true;+ }++ if (style === null || Array.isArray(style)) {+ return false;+ }++ return typeof style === 'object';};export const makeElementDragData = ({@@ -434,31 +510,41 @@ export const makeElementDragData = ({}): ElementDragData => {assertElementAssets(assets);assertElementAssetReferences({assets, initialProps});+for (const dependency of dependencies) {assertElementDependency(dependency);}+ const uniqueDependencies = new Map(+ dependencies.map((dependency) => [dependency.name, dependency]),+ );++ const element: ElementDragData['element'] = {+ assets: [...assets],+ dependencies: Array.from(uniqueDependencies.values()),+ dimensions,+ displayName,+ initialProps,+ slug,+ sourceCode,+ };++ if (durationInFrames !== undefined) {+ element.durationInFrames = durationInFrames;+ }++ if (installationMode !== undefined) {+ element.installationMode = installationMode;+ }++ if (isCaptionStyle !== undefined) {+ element.isCaptionStyle = isCaptionStyle;+ }+return {type: 'remotion-element',version: assets.length === 0 ? 1 : 2,- element: {- assets: [...assets],- dependencies: Array.from(- new Map(- dependencies.map(- (dependency) => [dependency.name, dependency] as const,- ),- ).values(),- ),- dimensions,- displayName,- ...(durationInFrames === undefined ? {} : {durationInFrames}),- initialProps,- ...(installationMode === undefined ? {} : {installationMode}),- ...(isCaptionStyle === undefined ? {} : {isCaptionStyle}),- slug,- sourceCode,- },+ element,};};@@ -491,6 +577,7 @@ const elementDragDataSchema = z.object({export const parseElementDragData = (value: string): ElementDragData | null => {try {const parsed = z.safeParse(elementDragDataSchema, JSON.parse(value));+if (!parsed.success ||makeElementFileNameFromSlug(parsed.data.element.slug) === null@@ -499,6 +586,7 @@ export const parseElementDragData = (value: string): ElementDragData | null => {}const assets = parsed.data.element.assets ?? [];+try {assertElementAssets(assets);} catch {@@ -506,6 +594,7 @@ export const parseElementDragData = (value: string): ElementDragData | null => {}const dependencies: ElementDependency[] = [];+for (const dependency of parsed.data.element.dependencies) {if (!isElementDependency(dependency)) {return null;@@ -515,6 +604,7 @@ export const parseElementDragData = (value: string): ElementDragData | null => {}const initialProps = parsed.data.element.initialProps ?? null;+if (!isElementInitialProps(initialProps) ||!hasValidElementInitialPropsForInstallationMode({@@ -537,6 +627,7 @@ export const parseElementDragData = (value: string): ElementDragData | null => {installationMode: parsed.data.element.installationMode,isCaptionStyle: parsed.data.element.isCaptionStyle,});+return result.version === parsed.data.version ? result : null;} catch {return null;diff --git a/packages/studio-protocol/src/element-payload.ts b/packages/studio-protocol/src/element-payload.tsindex b129791a6e..e2a70885b3 100644--- a/packages/studio-protocol/src/element-payload.ts+++ b/packages/studio-protocol/src/element-payload.ts@@ -37,6 +37,7 @@ export type StudioElementPayload = ElementDragData & {};const durationSchema = z.int().check(z.positive(), z.lte(100_000_000));+const studioElementPayloadEnvelopeSchema = z.object({type: z.literal('remotion-element'),version: z.union([z.literal(1), z.literal(2)]),@@ -44,61 +45,76 @@ const studioElementPayloadEnvelopeSchema = z.object({element: z.unknown(),});-const isDuration = (value: unknown): value is number =>- z.safeParse(durationSchema, value).success;+const displayNameSchema = z.string().check(z.minLength(1));++const sourceCodeSchema = z+ .string()+ .check(z.refine((value) => value.trim().length > 0));++const installationModeSchema = z.optional(+ z.enum(['wrapped', 'component-owned-sequence']),+);++const captionStyleSchema = z.optional(z.boolean());const assertCreateElementPayloadInput = (input: CreateElementPayloadInput,): void => {- if (typeof input.displayName !== 'string' || input.displayName.length === 0) {+ if (!z.safeParse(displayNameSchema, input.displayName).success) {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- )+ }++ if (!z.safeParse(sourceCodeSchema, input.sourceCode).success) {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) {assertElementDependency(dependency);}- if (!isDuration(input.durationInFrames))+ if (!z.safeParse(durationSchema, input.durationInFrames).success) {throw new TypeError('durationInFrames must be an integer between 1 and 100000000',);- if (- input.installationMode !== undefined &&- input.installationMode !== 'wrapped' &&- input.installationMode !== 'component-owned-sequence'- ) {+ }++ if (!z.safeParse(installationModeSchema, input.installationMode).success) {throw new TypeError('installationMode must be "wrapped" or "component-owned-sequence"',);}- if (- input.isCaptionStyle !== undefined &&- typeof input.isCaptionStyle !== 'boolean'- ) {+ if (!z.safeParse(captionStyleSchema, input.isCaptionStyle).success) {throw new TypeError('isCaptionStyle must be a boolean');}@@ -112,6 +128,7 @@ const assertCreateElementPayloadInput = (}const initialProps = input.initialProps ?? null;+if (!isElementInitialProps(initialProps)) {throw new TypeError('initialProps must be null or an object containing JSON-compatible values with valid JSX attribute names',@@ -134,6 +151,7 @@ export const createElementPayload = (input: CreateElementPayloadInput,): StudioElementPayload => {assertCreateElementPayloadInput(input);+const constructed = makeDragData({type: 'element',assets: [...(input.assets ?? [])],@@ -147,14 +165,18 @@ export const createElementPayload = (installationMode: input.installationMode ?? 'wrapped',isCaptionStyle: input.isCaptionStyle,});+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;};@@ -162,6 +184,7 @@ export const parseStudioElementPayload = (value: unknown,): StudioElementPayload | null => {const parsed = z.safeParse(studioElementPayloadEnvelopeSchema, value);+if (!parsed.success) {return null;}@@ -174,14 +197,18 @@ export const parseStudioElementPayload = (return null;}- const rawInitialProps = Object.hasOwn(parsed.data.element, 'initialProps')- ? (parsed.data.element as {initialProps: unknown}).initialProps- : null;+ const rawInitialProps =+ Object.hasOwn(parsed.data.element, 'initialProps') &&+ 'initialProps' in parsed.data.element+ ? parsed.data.element.initialProps+ : null;+if (!isElementInitialProps(rawInitialProps)) {return null;}let serializedElement: string;+try {serializedElement = JSON.stringify({type: parsed.data.type,@@ -193,7 +220,11 @@ export const parseStudioElementPayload = (}const element = parseElementDragData(serializedElement);- if (element === null) return null;++ if (element === null) {+ return null;+ }+const payload: StudioElementPayload = {...element,element: {@@ -202,5 +233,6 @@ export const parseStudioElementPayload = (},durationInFrames: parsed.data.durationInFrames,};+return JSON.stringify(payload).length <= MAX_PAYLOAD_SIZE ? payload : null;};diff --git a/packages/studio-protocol/src/index.ts b/packages/studio-protocol/src/index.tsindex d1c53040f8..145ea62d9e 100644--- a/packages/studio-protocol/src/index.ts+++ b/packages/studio-protocol/src/index.ts@@ -47,14 +47,19 @@ export {type AddElementLibraryToStudioInput,type AddElementLibraryToStudioResult,} from './add-element-library-to-studio';+export type {AssetDragData} from './asset-drag-data';+export type {StudioCaptionStyleSelection} from './caption-style-selection';+export {buildOpenInRemotionNewUrl} from './browser-studio-link';+export type {ComponentDimensions,ComponentDragData,ComponentProp,} from './component-drag-data';+export type {ConstructedDragData,DragDataTransfer,@@ -69,6 +74,7 @@ export type {RemotionDragData,SerializedDragData,} from './drag-data';+export type {AssetDragPreviewMetadata,ComponentDragPreviewMetadata,@@ -79,13 +85,17 @@ export type {RenderOutputDragPreviewMetadata,SfxDragPreviewMetadata,} from './drag-preview-metadata';+export {setStudioDragData} from './drag-transport';+export type {EffectConfig,EffectConfigValue,EffectDragData,} from './effect-drag-data';+export {staticFileRef} from './element-drag-data';+export type {ElementAsset,StaticFileRef,@@ -95,20 +105,27 @@ export type {ElementInitialPropValue,ElementInstallationMode,} from './element-drag-data';+export {createElementPayload,type CreateElementPayloadInput,type StudioElementPayload,} from './element-payload';+export {installInStudio,type InstallInStudioErrorCode,type InstallInStudioResult,} from './install-in-studio';+export {isInsideStudio} from './is-inside-studio';+export {subscribeToCaptionStyleSelection} from './subscribe-to-caption-style-selection';+export type {RenderOutputDragData} from './render-output-drag-data';+export type {SfxDragData} from './sfx-drag-data';+export type {StudioProtocolDescriptor,StudioProtocolInstallTarget,diff --git a/packages/studio-protocol/src/install-in-studio.ts b/packages/studio-protocol/src/install-in-studio.tsindex 6ff7f79ded..bc0bbbc1c0 100644--- a/packages/studio-protocol/src/install-in-studio.ts+++ b/packages/studio-protocol/src/install-in-studio.ts@@ -3,7 +3,11 @@ import {parseStudioElementPayload,type StudioElementPayload,} from './element-payload';-import type {StudioProtocolFetcher} from './studio-discovery';+import type {+ DiscoveredStudio,+ StudioProtocolFetcher,+ StudioProtocolInstallTarget,+} from './studio-discovery';import {discoverStudios,fetchWithTimeout,@@ -108,6 +112,7 @@ export const parseStudioProtocolIframeInstallRequest = (value: unknown,): StudioElementPayload | null => {const envelope = z.safeParse(studioProtocolIframeInstallRequestSchema, value);+return envelope.success? parseStudioElementPayload(envelope.data.payload): null;@@ -122,11 +127,13 @@ export const parseStudioProtocolInstallRequest = (studioProtocolInstallRequestEnvelopeSchema,value,);+if (!envelope.success) {return {status: 'invalid-request'};}const payload = parseStudioElementPayload(envelope.data.payload);+if (payload === null) {return {status: 'invalid-payload'};}@@ -157,6 +164,7 @@ export const isAllowedStudioProtocolPageOrigin = (try {const parsed = new URL(origin);+return (parsed.protocol === 'https:' ||(parsed.protocol === 'http:' &&@@ -167,6 +175,109 @@ export const isAllowedStudioProtocolPageOrigin = (}};+const isLoopbackPermissionDenied = async (+ permissionQueryFn: PermissionQueryFn | null,+): Promise<boolean> => {+ if (permissionQueryFn === null) {+ return false;+ }++ for (const name of ['loopback-network', 'local-network-access'] as const) {+ try {+ const permission = await permissionQueryFn({name});++ return permission.state === 'denied';+ } catch {+ // The compatibility alias may still be supported.+ }+ }++ return false;+};++const requestElementInstallation = async ({+ fetchFn,+ studio,+ target,+ payload,+}: {+ fetchFn: StudioProtocolFetcher;+ studio: DiscoveredStudio;+ target: StudioProtocolInstallTarget;+ payload: StudioElementPayload;+}): Promise<InstallInStudioResult> => {+ let response: Response;++ try {+ const requestBody = {+ operation: 'install-element',+ protocol: 'remotion-studio-protocol',+ protocolVersion: 1,+ targetId: target.id,+ payload,+ } satisfies StudioProtocolInstallRequest;++ response = await fetchWithTimeout({+ fetchFn,+ url: `${studio.origin}/api/studio-protocol/install`,+ 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 installation response.',+ );+ }++ if (response.ok && isAwaitingConfirmationResponse(result)) {+ return {+ success: true,+ status: 'awaiting-confirmation',+ target: {+ projectName: studio.descriptor.projectName,+ compositionId: target.compositionId,+ studioOrigin: studio.origin,+ studioVersion: studio.descriptor.studioVersion,+ },+ };+ }++ const protocolError = parseStudioProtocolError(result);++ if (protocolError !== null) {+ return failure(+ protocolError.code === 'target-expired'+ ? 'target-expired'+ : 'request-rejected',+ protocolError.message,+ );+ }++ return failure(+ 'invalid-response',+ 'Remotion Studio returned an invalid installation response.',+ );+};+export const installInStudioWithDependencies = async (payload: StudioElementPayload,dependencies: InstallInStudioDependencies,@@ -180,6 +291,7 @@ export const installInStudioWithDependencies = async (}const discovery = await discoverStudios(dependencies);+if (discovery.studios.length === 0) {if (discovery.foundUnsupportedProtocol) {return failure(@@ -195,25 +307,11 @@ export const installInStudioWithDependencies = async ();}- if (dependencies.permissionQueryFn !== null) {- for (const name of [- 'loopback-network',- 'local-network-access',- ] as const) {- try {- const permission = await dependencies.permissionQueryFn({name});- if (permission.state === 'denied') {- return failure(- 'loopback-network-permission-denied',- 'Access to localhost is blocked by your browser. Open the site settings, allow local network access for this site, then try again.',- );- }-- break;- } catch {- // The compatibility alias may still be supported.- }- }+ if (await isLoopbackPermissionDenied(dependencies.permissionQueryFn)) {+ return failure(+ 'loopback-network-permission-denied',+ 'Access to localhost is blocked by your browser. Open the site settings, allow local network access for this site, then try again.',+ );}return failure(@@ -224,12 +322,26 @@ export const installInStudioWithDependencies = async (const supportedStudios = discovery.studios.flatMap((studio) => {const capability = getInstallCapability(studio.descriptor);- return capability?.payloadVersions.includes(payload.version) ||- (fallbackPayload !== null &&- capability?.payloadVersions.includes(fallbackPayload.version))- ? [{...studio, capability}]- : [];++ if (capability === null) {+ return [];+ }++ const supportsPayload = capability.payloadVersions.includes(+ payload.version,+ );++ const supportsFallback =+ fallbackPayload !== null &&+ capability.payloadVersions.includes(fallbackPayload.version);++ if (!supportsPayload && !supportsFallback) {+ return [];+ }++ return [{...studio, capability}];});+if (supportedStudios.length === 0) {return failure(payload.version === 2@@ -242,26 +354,31 @@ export const installInStudioWithDependencies = async (}const now = dependencies.now();+const installable = supportedStudios- .filter(({capability}) => {- const {target} = capability;- return target !== null && target.expiresAt > now;+ .flatMap((studio) => {+ const {target} = studio.capability;++ if (target === null || target.expiresAt <= now) {+ return [];+ }++ return [{...studio, target}];}).sort((a, b) => {const focusDifference =- (b.capability.target!.lastFocusedAt ?? 0) -- (a.capability.target!.lastFocusedAt ?? 0);+ (b.target.lastFocusedAt ?? 0) - (a.target.lastFocusedAt ?? 0);+return focusDifference === 0? b.discoveredAt - a.discoveredAt: focusDifference;});+const selected = installable[0];- const selectedTarget = selected?.capability.target;+if (!selected ||- selectedTarget === null ||- selectedTarget === undefined ||- (selectedTarget.lastFocusedAt === null && installable.length > 1)+ (selected.target.lastFocusedAt === null && installable.length > 1)) {return failure('no-installable-target',@@ -276,6 +393,7 @@ export const installInStudioWithDependencies = async ()? payload: fallbackPayload;+if (selectedPayload === null) {return failure('unsupported-protocol',@@ -283,70 +401,12 @@ export const installInStudioWithDependencies = async ();}- let response: Response;- try {- const requestBody = {- operation: 'install-element',- protocol: 'remotion-studio-protocol',- protocolVersion: 1,- targetId: selectedTarget.id,- payload: selectedPayload,- } satisfies StudioProtocolInstallRequest;- response = await fetchWithTimeout({- fetchFn: dependencies.fetchFn,- url: `${selected.origin}/api/studio-protocol/install`,- options: {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify(requestBody),- },- });- } catch (error) {- return failure(- isAbortError(error) ? 'request-timed-out' : 'network-error',- isAbortError(error)- ? '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 installation response.',- );- }-- if (response.ok && isAwaitingConfirmationResponse(result)) {- return {- success: true,- status: 'awaiting-confirmation',- target: {- projectName: selected.descriptor.projectName,- compositionId: selectedTarget.compositionId,- studioOrigin: selected.origin,- studioVersion: selected.descriptor.studioVersion,- },- };- }-- const protocolError = parseStudioProtocolError(result);- if (protocolError !== null) {- return failure(- protocolError.code === 'target-expired'- ? 'target-expired'- : 'request-rejected',- protocolError.message,- );- }-- return failure(- 'invalid-response',- 'Remotion Studio returned an invalid installation response.',- );+ return requestElementInstallation({+ fetchFn: dependencies.fetchFn,+ studio: selected,+ target: selected.target,+ payload: selectedPayload,+ });};const installInParentStudio = (@@ -362,6 +422,7 @@ const installInParentStudio = (return new Promise((resolve) => {const channel = new MessageChannel();+const timeout = setTimeout(() => {channel.port1.close();resolve(null);@@ -369,6 +430,7 @@ const installInParentStudio = (channel.port1.onmessage = (event) => {const response = z.safeParse(installInStudioResultSchema, event.data);+if (!response.success) {return;}@@ -400,6 +462,7 @@ export const installInStudio = async ({readonly fallbackPayload?: StudioElementPayload;}): Promise<InstallInStudioResult> => {const parentResult = await installInParentStudio(payload);+if (parentResult !== null) {return parentResult;}@@ -408,6 +471,7 @@ export const installInStudio = async ({// response timeout rather than preventing new parent Studios from using assets.if (fallbackPayload !== undefined) {const fallbackResult = await installInParentStudio(fallbackPayload);+if (fallbackResult !== null) {return fallbackResult;}@@ -424,7 +488,8 @@ export const installInStudio = async ({: globalThis.location.origin,permissionQueryFn:typeof globalThis.navigator === 'undefined' ||- typeof globalThis.navigator.permissions?.query !== 'function'+ !z.safeParse(z.function(), globalThis.navigator.permissions?.query)+ .success? null: (descriptor) =>// @ts-expect-error Chromium's loopback permission names are not in lib.dom yet.diff --git a/packages/studio-protocol/src/license-key.ts b/packages/studio-protocol/src/license-key.tsindex 037706dd3a..0d6d983d7a 100644--- a/packages/studio-protocol/src/license-key.ts+++ b/packages/studio-protocol/src/license-key.ts@@ -1,6 +1,10 @@-const publicLicenseKeyPattern = /^rm_pub_[a-zA-Z0-9]{48}$/;+import * as z from 'zod/mini';++const publicLicenseKeySchema = z+ .string()+ .check(z.regex(/^rm_pub_[a-zA-Z0-9]{48}$/));export const isValidPublicLicenseKey = (licenseKey: unknown,): licenseKey is string =>- typeof licenseKey === 'string' && publicLicenseKeyPattern.test(licenseKey);+ z.safeParse(publicLicenseKeySchema, licenseKey).success;diff --git a/packages/studio-protocol/src/render-output-drag-data.ts b/packages/studio-protocol/src/render-output-drag-data.tsindex f4513ee390..c825b9ebe9 100644--- a/packages/studio-protocol/src/render-output-drag-data.ts+++ b/packages/studio-protocol/src/render-output-drag-data.ts@@ -41,6 +41,7 @@ export const parseRenderOutputDragData = (): RenderOutputDragData | null => {try {const parsed = z.safeParse(renderOutputDragDataSchema, JSON.parse(value));+return parsed.success? makeRenderOutputDragData({outputPath: parsed.data.outputPath,diff --git a/packages/studio-protocol/src/resolve-element-assets.ts b/packages/studio-protocol/src/resolve-element-assets.tsindex e086daeaab..33aec35c33 100644--- a/packages/studio-protocol/src/resolve-element-assets.ts+++ b/packages/studio-protocol/src/resolve-element-assets.ts@@ -9,6 +9,7 @@ export const resolveElementAssets = async ({}) => {const resolved: Array<{path: string; contents: Uint8Array}> = [];let totalBytes = 0;+for (const asset of assets) {const contents =asset.type === 'base64'@@ -19,7 +20,9 @@ export const resolveElementAssets = async ({url: new URL(asset.url),maxSize: maxElementAssetBytes - totalBytes,});+totalBytes += contents.byteLength;+if (totalBytes > maxElementAssetBytes) {throw new Error('Element assets exceed the 50MB aggregate limit');}diff --git a/packages/studio-protocol/src/set-license-key-in-studio.ts b/packages/studio-protocol/src/set-license-key-in-studio.tsindex 1ae40bf0ad..b2b4b13856 100644--- a/packages/studio-protocol/src/set-license-key-in-studio.ts+++ b/packages/studio-protocol/src/set-license-key-in-studio.ts@@ -68,6 +68,7 @@ export const parseStudioProtocolSetLicenseKeyRequest = (value: unknown,): StudioProtocolSetLicenseKeyRequest | null => {const parsed = z.safeParse(studioProtocolSetLicenseKeyRequestSchema, value);+return parsed.success ? parsed.data : null;};@@ -84,6 +85,7 @@ export const setLicenseKeyInStudioWithDependencies = async (}const discovery = await discoverStudios(dependencies);+if (discovery.studios.length === 0) {if (discovery.foundUnsupportedProtocol) {return {@@ -112,8 +114,10 @@ export const setLicenseKeyInStudioWithDependencies = async (const supportedStudios = discovery.studios.flatMap((studio) => {const capability = getSetLicenseKeyCapability(studio.descriptor);+return capability === null ? [] : [{...studio, capability}];});+if (supportedStudios.length === 0) {return {success: false,@@ -124,21 +128,28 @@ export const setLicenseKeyInStudioWithDependencies = async (}const now = dependencies.now();+const configurable = supportedStudios- .filter(({capability}) => {- const {target} = capability;- return target !== null && target.expiresAt > now;+ .flatMap((studio) => {+ const {target} = studio.capability;++ if (target === null || target.expiresAt <= now) {+ return [];+ }++ return [{...studio, target}];}).sort((a, b) => {- const focusDifference =- b.capability.target!.lastFocusedAt - a.capability.target!.lastFocusedAt;+ const focusDifference = b.target.lastFocusedAt - a.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) {++ if (!selected) {return {success: false,code: 'no-configurable-target',@@ -147,14 +158,16 @@ export const setLicenseKeyInStudioWithDependencies = async (}let response: Response;+try {const requestBody = {operation: 'set-license-key',protocol: 'remotion-studio-protocol',protocolVersion: 1,- targetId: selectedTarget.id,+ targetId: selected.target.id,licenseKey,} satisfies StudioProtocolSetLicenseKeyRequest;+response = await fetchWithTimeout({fetchFn: dependencies.fetchFn,url: `${selected.origin}/api/studio-protocol/license-key`,@@ -166,6 +179,7 @@ export const setLicenseKeyInStudioWithDependencies = async (});} catch (error) {const timedOut = isAbortError(error);+return {success: false,code: timedOut ? 'request-timed-out' : 'network-error',@@ -176,6 +190,7 @@ export const setLicenseKeyInStudioWithDependencies = async (}let result: unknown;+try {result = await response.json();} catch {@@ -199,6 +214,7 @@ export const setLicenseKeyInStudioWithDependencies = async (}const protocolError = parseStudioProtocolError(result);+if (protocolError !== null) {return {success: false,diff --git a/packages/studio-protocol/src/sfx-drag-data.ts b/packages/studio-protocol/src/sfx-drag-data.tsindex 01b5848cfe..b80d5c3977 100644--- a/packages/studio-protocol/src/sfx-drag-data.ts+++ b/packages/studio-protocol/src/sfx-drag-data.ts@@ -33,6 +33,7 @@ export const makeSfxDragData = ({export const parseSfxDragData = (value: string): SfxDragData | null => {try {const parsed = z.safeParse(sfxDragDataSchema, JSON.parse(value));+return parsed.success? makeSfxDragData({name: parsed.data.sfx.name,diff --git a/packages/studio-protocol/src/studio-discovery.ts b/packages/studio-protocol/src/studio-discovery.tsindex 9605c2106f..ad7e56d2c7 100644--- a/packages/studio-protocol/src/studio-discovery.ts+++ b/packages/studio-protocol/src/studio-discovery.ts@@ -61,6 +61,7 @@ export type StudioProtocolDiscoveryDependencies = {export const studioProtocolProbePorts = [3000, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009,];+const requestTimeout = 2_000;const targetSchema = z.looseObject({@@ -68,31 +69,37 @@ const targetSchema = z.looseObject({expiresAt: z.number(),lastFocusedAt: z.number(),});+const installTargetSchema = z.looseObject({id: z.string().check(z.minLength(1)),expiresAt: z.number(),lastFocusedAt: z.nullable(z.number()),compositionId: z.nullable(z.string().check(z.minLength(1))),});+const installCapabilitySchema = z.looseObject({type: z.literal('install-element'),payloadType: z.literal('remotion-element'),payloadVersions: z.array(z.number()),target: z.nullable(installTargetSchema),});+const setLicenseKeyCapabilitySchema = z.looseObject({type: z.literal('set-license-key'),target: z.nullable(targetSchema),});+const addElementLibraryCapabilitySchema = z.looseObject({type: z.literal('add-element-library'),target: z.nullable(targetSchema),});+const capabilitySchema = z.union([installCapabilitySchema,setLicenseKeyCapabilitySchema,addElementLibraryCapabilitySchema,]);+const descriptorEnvelopeSchema = z.looseObject({protocol: z.literal('remotion-studio-protocol'),protocolVersion: z.literal(1),@@ -100,6 +107,7 @@ const descriptorEnvelopeSchema = z.looseObject({projectName: z.nullable(z.string()),capabilities: z.array(z.unknown()),});+const descriptorSchema = z.looseObject({protocol: z.literal('remotion-studio-protocol'),@@ -113,16 +121,20 @@ const descriptorSchema = zconst capabilityTypes = descriptor.capabilities.map((capability) => capability.type,);+return new Set(capabilityTypes).size === capabilityTypes.length;}),);+const protocolEnvelopeSchema = z.looseObject({protocol: z.literal('remotion-studio-protocol'),});+const protocolVersionEnvelopeSchema = z.looseObject({protocol: z.literal('remotion-studio-protocol'),protocolVersion: z.unknown(),});+export const fetchWithTimeout = async ({fetchFn,options,@@ -134,6 +146,7 @@ export const fetchWithTimeout = async ({}) => {const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), requestTimeout);+try {return await fetchFn(url, {...(options ?? {}),@@ -153,13 +166,16 @@ export const parseStudioProtocolDescriptor = (value: unknown,): StudioProtocolDescriptor | null => {const envelope = z.safeParse(descriptorEnvelopeSchema, value);+if (!envelope.success) {return null;}const capabilities: StudioProtocolCapability[] = [];+for (const capability of envelope.data.capabilities) {const parsedCapability = z.safeParse(capabilitySchema, capability);+if (parsedCapability.success) {capabilities.push(parsedCapability.data);}@@ -169,6 +185,7 @@ export const parseStudioProtocolDescriptor = (...envelope.data,capabilities,});+return descriptor.success ? descriptor.data : null;};@@ -212,10 +229,12 @@ export const discoverStudios = async (let foundUnsupportedProtocol = false;let foundInvalidResponse = false;const {fetchFn} = dependencies;+const studios = await Promise.all(dependencies.ports.map(async (port): Promise<DiscoveredStudio | null> => {const origin = `http://localhost:${port}`;let response: Response;+try {response = await fetchFn(`${origin}/api/studio-protocol`, {cache: 'no-store',@@ -229,6 +248,7 @@ export const discoverStudios = async (}let value: unknown;+try {value = await response.json();} catch {@@ -236,6 +256,7 @@ export const discoverStudios = async (}const protocolEnvelope = z.safeParse(protocolEnvelopeSchema, value);+if (!protocolEnvelope.success) {return null;}@@ -244,19 +265,24 @@ export const discoverStudios = async (protocolVersionEnvelopeSchema,value,);+if (!protocolVersionEnvelope.success) {foundInvalidResponse = true;+return null;}if (protocolVersionEnvelope.data.protocolVersion !== 1) {foundUnsupportedProtocol = true;+return null;}const descriptor = parseStudioProtocolDescriptor(value);+if (descriptor === null) {foundInvalidResponse = true;+return null;}@@ -277,5 +303,5 @@ export const discoverStudios = async (};};-export const isAbortError = (error: unknown): boolean =>- error instanceof Error && error.name === 'AbortError';+export const isAbortError = (cause: unknown): boolean =>+ cause instanceof Error && cause.name === 'AbortError';diff --git a/packages/studio-protocol/src/studio-response.ts b/packages/studio-protocol/src/studio-response.tsindex 05f0cc516c..6cdc5ad0bf 100644--- a/packages/studio-protocol/src/studio-response.ts+++ b/packages/studio-protocol/src/studio-response.ts@@ -5,6 +5,7 @@ const awaitingConfirmationResponseSchema = z.object({protocolVersion: z.literal(1),status: z.literal('awaiting-confirmation'),});+const studioProtocolErrorSchema = z.object({status: z.literal('error'),error: z.object({@@ -20,6 +21,7 @@ export const parseStudioProtocolError = (value: unknown,): {readonly code: string; readonly message: string} | null => {const parsed = z.safeParse(studioProtocolErrorSchema, value);+return parsed.success? {code: parsed.data.error.code, message: parsed.data.error.message}: null;diff --git a/packages/studio-protocol/src/subscribe-to-caption-style-selection.ts b/packages/studio-protocol/src/subscribe-to-caption-style-selection.tsindex a184d2395f..9d7674260e 100644--- a/packages/studio-protocol/src/subscribe-to-caption-style-selection.ts+++ b/packages/studio-protocol/src/subscribe-to-caption-style-selection.ts@@ -34,7 +34,9 @@ export const subscribeToCaptionStyleSelection = (hasSelection: false,dispose: () => {},};+let port: MessagePort | null = null;+const disconnect = () => {if (port !== null) {port.onmessage = null;@@ -56,6 +58,7 @@ export const subscribeToCaptionStyleSelection = (}const message = parseStudioProtocolCaptionStyleSelection(event.data);+if (message === null) {return;}@@ -65,6 +68,7 @@ export const subscribeToCaptionStyleSelection = (? message.selection.slug: null;state.hasSelection = true;+for (const entry of [...state.listeners]) {if (!state.listeners.has(entry)) {continue;@@ -113,6 +117,7 @@ export const subscribeToCaptionStyleSelection = (const current = subscription;const listener = {onChange};current.listeners.add(listener);+if (current.hasSelection) {queueMicrotask(() => {if (current.listeners.has(listener) && current.hasSelection) {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.tsindex 11070e217c..df6309e368 100644--- 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.ts@@ -58,9 +58,11 @@ test('requests confirmation in the most recently focused compatible Studio', asyreadonly 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(@@ -132,6 +134,7 @@ test('requests confirmation in the most recently focused compatible Studio', asytest('returns an actionable result when no Studio is running', async () => {const requests: string[] = [];+const result = await addElementLibraryToStudioWithDependencies({url: 'https://library.example.com',@@ -142,6 +145,7 @@ test('returns an actionable result when no Studio is running', async () => {...dependencies,fetchFn: (input) => {requests.push(String(input));+return Promise.resolve(new Response(null, {status: 404}));},},@@ -169,18 +173,22 @@ test('validates the request before probing localhost', async () => {},]) {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://library.example.com',@@ -192,10 +200,12 @@ test('validates the request before probing localhost', async () => {pageOrigin: 'http://elements.example.com',fetchFn: () => {probes++;+return Promise.resolve(new Response(null, {status: 404}));},},);+expect(unsupportedOrigin).toMatchObject({success: false,code: 'unsupported-origin',@@ -226,6 +236,7 @@ test('distinguishes an old Studio from one without a focused target', async () =),},);+expect(oldStudio).toMatchObject({success: false,code: 'studio-upgrade-required',@@ -237,6 +248,7 @@ test('distinguishes an old Studio from one without a focused target', async () =projectName: 'Project',targetId: 'unused',});+const noTarget = await addElementLibraryToStudioWithDependencies({url: 'https://library.example.com',@@ -259,6 +271,7 @@ test('distinguishes an old Studio from one without a focused target', async () =),},);+expect(noTarget).toMatchObject({success: false,code: 'no-configurable-target',diff --git a/packages/studio-protocol/src/test/asset-drag-data.test.ts b/packages/studio-protocol/src/test/asset-drag-data.test.tsindex 0eea34e659..8a427b18c5 100644--- a/packages/studio-protocol/src/test/asset-drag-data.test.ts+++ b/packages/studio-protocol/src/test/asset-drag-data.test.ts@@ -8,6 +8,7 @@ const assetMimeType = StudioProtocolInternals.makeDragData({height: null,durationInSeconds: null,}).mimeType;+const makeAssetDragData = (assetPath: string) =>StudioProtocolInternals.makeDragData({type: 'asset',@@ -16,11 +17,13 @@ const makeAssetDragData = (assetPath: string) =>height: null,durationInSeconds: null,}).data;+const parseAssetDragData = (payload: string) => {const parsed = StudioProtocolInternals.parseDragData({mimeType: assetMimeType,payload,});+return parsed?.type === 'asset' ? parsed.data : null;};diff --git a/packages/studio-protocol/src/test/browser-studio-link.test.ts b/packages/studio-protocol/src/test/browser-studio-link.test.tsindex c6815dba8e..f99167e979 100644--- a/packages/studio-protocol/src/test/browser-studio-link.test.ts+++ b/packages/studio-protocol/src/test/browser-studio-link.test.ts@@ -29,6 +29,7 @@ test('preserves a configured Browser Studio endpoint', () => {endpoint: 'https://studio.example.test/new?template=blank',payload,});+const parsedUrl = new URL(url);expect(parsedUrl.origin).toBe('https://studio.example.test');diff --git a/packages/studio-protocol/src/test/component-drag-data.test.ts b/packages/studio-protocol/src/test/component-drag-data.test.tsindex 49cb475270..3bd629560c 100644--- a/packages/studio-protocol/src/test/component-drag-data.test.ts+++ b/packages/studio-protocol/src/test/component-drag-data.test.ts@@ -1,4 +1,5 @@import {expect, test} from 'bun:test';+import * as z from 'zod/mini';import {StudioProtocolInternals,type MakeComponentDragDataInput,@@ -7,17 +8,23 @@ import {const makeComponentDragData = (input: Omit<MakeComponentDragDataInput, 'type'>,) => StudioProtocolInternals.makeDragData({type: 'component', ...input}).data;++const dimensionsSchema = z.object({+ width: z.number().check(z.positive()),+ height: z.number().check(z.positive()),+});+const parseComponentDragData = (payload: string) => {let dimensions: MakeComponentDragDataInput['dimensions'];+try {- const candidate = JSON.parse(payload)?.component?.dimensions;- if (- typeof candidate?.width === 'number' &&- candidate.width > 0 &&- typeof candidate?.height === 'number' &&- candidate.height > 0- ) {- dimensions = candidate;+ const parsedDimensions = z.safeParse(+ dimensionsSchema,+ JSON.parse(payload)?.component?.dimensions,+ );++ if (parsedDimensions.success) {+ dimensions = parsedDimensions.data;}} catch {// The unified parser handles the malformed payload below.@@ -31,7 +38,9 @@ const parseComponentDragData = (payload: string) => {importPath: 'test',props: [],});+const parsed = StudioProtocolInternals.parseDragData({mimeType, payload});+return parsed?.type === 'component' ? parsed.data : null;};diff --git a/packages/studio-protocol/src/test/drag-data.test.ts b/packages/studio-protocol/src/test/drag-data.test.tsindex 346f6e719c..c95c4e1994 100644--- a/packages/studio-protocol/src/test/drag-data.test.ts+++ b/packages/studio-protocol/src/test/drag-data.test.ts@@ -1,10 +1,5 @@import {expect, test} from 'bun:test';-import {- StudioProtocolInternals,- type MakeDragDataInput,- type MakeElementDragDataInput,- type MakeAssetDragDataInput,-} from '../index';+import {StudioProtocolInternals, type MakeDragDataInput} from '../index';const inputs: MakeDragDataInput[] = [{@@ -109,10 +104,11 @@ test('requires asset metadata and accepts explicit null values', () => {type: 'asset',});expect(() =>+ // @ts-expect-error JavaScript callers can omit required asset metadata.StudioProtocolInternals.makeDragData({type: 'asset',assetPath: 'missing-metadata.png',- } as MakeAssetDragDataInput),+ }),).toThrow('must be set to a value or null');expect(() =>StudioProtocolInternals.makeDragData({@@ -144,6 +140,7 @@ test('requires a duration for element drags', () => {}),).toBe(null);expect(() =>+ // @ts-expect-error JavaScript callers can omit the required duration.StudioProtocolInternals.makeDragData({type: 'element',dependencies: [],@@ -151,7 +148,7 @@ test('requires a duration for element drags', () => {displayName: 'Lower Third',sourceCode: 'export const LowerThird = () => null;',dimensions: null,- } as unknown as MakeElementDragDataInput),+ }),).toThrow('durationInFrames must be an integer');});@@ -177,6 +174,7 @@ test('rejects malformed and mismatched drag data', () => {outputPath: 'out/video.mp4',fileName: 'video.mp4',});+expect(StudioProtocolInternals.parseDragData({mimeType: renderOutput.mimeType,diff --git a/packages/studio-protocol/src/test/element-drag-data.test.ts b/packages/studio-protocol/src/test/element-drag-data.test.tsindex 74b1c0f97e..f795267aa4 100644--- a/packages/studio-protocol/src/test/element-drag-data.test.ts+++ b/packages/studio-protocol/src/test/element-drag-data.test.ts@@ -1,4 +1,5 @@import {expect, test} from 'bun:test';+import * as z from 'zod/mini';import {StudioProtocolInternals, type ElementDragData} from '../index';type ElementInput = Omit<ElementDragData['element'], 'durationInFrames'>;@@ -12,23 +13,30 @@ const validElement = {sourceCode: 'export const LowerThird = () => null;',dimensions: {width: 900, height: 260},} satisfies ElementInput;+const makeElementDragData = (element: ElementInput) =>StudioProtocolInternals.makeDragData({type: 'element',...element,durationInFrames: 120,}).data;++const dimensionsSchema = z.object({+ width: z.number().check(z.positive()),+ height: z.number().check(z.positive()),+});+const parseElementDragData = (payload: string) => {let dimensions: (typeof validElement)['dimensions'] | null = null;+try {- const candidate = JSON.parse(payload)?.element?.dimensions;- if (- typeof candidate?.width === 'number' &&- candidate.width > 0 &&- typeof candidate?.height === 'number' &&- candidate.height > 0- ) {- dimensions = candidate;+ const parsedDimensions = z.safeParse(+ dimensionsSchema,+ JSON.parse(payload)?.element?.dimensions,+ );++ if (parsedDimensions.success) {+ dimensions = parsedDimensions.data;}} catch {// The unified parser handles the malformed payload below.@@ -40,7 +48,9 @@ const parseElementDragData = (payload: string) => {dimensions,durationInFrames: 120,});+const parsed = StudioProtocolInternals.parseDragData({mimeType, payload});+return parsed?.type === 'element' ? parsed.data : null;};@@ -74,6 +84,7 @@ test('normalizes legacy drag data without initial props', () => {test('rejects element drag data without dependencies', () => {const {dependencies: _dependencies, ...elementWithoutDependencies} =validElement;+expect(parseElementDragData(JSON.stringify({@@ -90,6 +101,7 @@ test('preserves component-owned-sequence Element drag data', () => {...validElement,installationMode: 'component-owned-sequence' as const,};+expect(parseElementDragData(JSON.stringify(makeElementDragData(componentOwnedSequenceElement)),@@ -206,6 +218,7 @@ test('rejects invalid element drag data', () => {}),),).toBe(null);+for (const initialProps of [{'invalid-name': true},{from: 10},diff --git a/packages/studio-protocol/src/test/element-payload.test.ts b/packages/studio-protocol/src/test/element-payload.test.tsindex a825a17ad1..5a35498f32 100644--- a/packages/studio-protocol/src/test/element-payload.test.ts+++ b/packages/studio-protocol/src/test/element-payload.test.ts@@ -27,7 +27,8 @@ const validInput = {} satisfies CreateElementPayloadInput;const createInvalidPayload = (input: unknown) =>- createElementPayload(input as CreateElementPayloadInput);+ // @ts-expect-error Exercise runtime validation of invalid JavaScript inputs.+ createElementPayload(input);test('creates one canonical Element payload for HTTP and drag transports', () => {const payload = createElementPayload(validInput);@@ -56,15 +57,19 @@ test('creates one canonical Element payload for HTTP and drag transports', () =>expect(parseStudioElementPayload(payload)).toEqual(payload);const data = new Map<string, string>();- const dataTransfer = {++ const dataTransfer: Pick<DataTransfer, 'effectAllowed' | 'setData'> = {effectAllowed: 'none',setData: (type: string, value: string) => data.set(type, value),- } as unknown as DataTransfer;+ };+setStudioDragData({dataTransfer, payload});expect(dataTransfer.effectAllowed).toBe('copy');+const mimeType ='application/vnd.remotion.drag+json;v=1;type=element;width=800;height=200;duration=90';+expect([...data.keys()]).toEqual([mimeType, 'text/plain']);expect(data.get('text/plain')).toBe(data.get(mimeType));expect(parseDragData({mimeType, payload: data.get(mimeType)!})).toMatchObject(@@ -94,6 +99,7 @@ test('validates asset payloads and references for both transports', () => {],initialProps: {media: [{src: staticFileRef('my-element/logo.png')}]},});+const serialized = JSON.stringify(payload);expect(payload.version).toBe(2);expect(parseStudioElementPayload(JSON.parse(serialized))).toEqual(payload);@@ -144,11 +150,13 @@ test('defaults new Element payloads to wrapped installation', () => {test('normalizes legacy payloads without initial props or assets', () => {const payload = createElementPayload(validInput);+const {initialProps: _initialProps,assets: _assets,...legacyElement} = payload.element;+expect(parseStudioElementPayload({...payload, element: legacyElement}),).toMatchObject({version: 1, element: {initialProps: null, assets: []}});@@ -169,6 +177,7 @@ test('rejects invalid and reserved initial props', () => {}const payload = createElementPayload(validInput);+for (const initialProps of [{invalid: undefined},{invalid: Number.NaN},diff --git a/packages/studio-protocol/src/test/install-in-studio.test.ts b/packages/studio-protocol/src/test/install-in-studio.test.tsindex 1143eacbb6..1821c09463 100644--- a/packages/studio-protocol/src/test/install-in-studio.test.ts+++ b/packages/studio-protocol/src/test/install-in-studio.test.ts@@ -56,15 +56,18 @@ const dependencies = {test('delivers the payload when a newer Studio advertises an unknown capability', async () => {const requests: Array<{url: string; options?: RequestInit}> = [];+const newestStudio = descriptor({compositionId: null,lastFocusedAt: 400_000,projectName: 'Newest project',targetId: 'newest-target',});+const fetchFn = (input: string | URL | Request, options?: RequestInit) => {const url = String(input);requests.push({url, options});+if (url === 'http://localhost:3000/api/studio-protocol') {return Promise.resolve(jsonResponse(@@ -141,6 +144,7 @@ test('requires a Studio that supports asset payloads', async () => {sourceCode: 'export const AssetElement = () => null;',assets: [{path: 'asset.bin', type: 'base64', data: 'AA=='}],});+const result = await installInStudioWithDependencies(payload, {...dependencies,fetchFn: () =>@@ -155,6 +159,7 @@ test('requires a Studio that supports asset payloads', async () => {),),});+expect(result).toMatchObject({success: false,code: 'studio-upgrade-required',@@ -171,6 +176,7 @@ test('sends remote URLs to a focused v1 Studio and local asset references to a fsourceCode: 'export const AudioElement = () => null;',initialProps: {audioSrc: 'https://remotion.media/audio.mp3'},});+const assetPayload = createElementPayload({dependencies: [],dimensions: null,@@ -183,12 +189,16 @@ test('sends remote URLs to a focused v1 Studio and local asset references to a f],initialProps: {audioSrc: {__remotion_element_asset: 'audio.mp3'}},});+for (const supportsAssets of [false, true]) {const requests: unknown[] = [];+const fetchFn = (input: string | URL | Request, options?: RequestInit) => {const url = String(input);+if (url.endsWith('/api/studio-protocol/install')) {requests.push(JSON.parse(String(options?.body)));+return Promise.resolve(jsonResponse({protocol: 'remotion-studio-protocol',@@ -245,6 +255,7 @@ test('sends remote URLs to a focused v1 Studio and local asset references to a ftest('distinguishes a compatible Studio without an installable target', async () => {const fetchFn = (input: string | URL | Request) => {const url = String(input);+if (url === 'http://localhost:3000/api/studio-protocol') {return Promise.resolve(jsonResponse({@@ -286,10 +297,12 @@ test('distinguishes a compatible Studio without an installable target', async ()test('returns an actionable result when no Studio is running', async () => {const requests: string[] = [];+const result = await installInStudioWithDependencies(elementPayload, {...dependencies,fetchFn: (input) => {requests.push(String(input));+return Promise.resolve(new Response(null, {status: 404}));},});@@ -326,14 +339,17 @@ test('ignores a non-Studio development server on a probed port', async () => {test('reports when loopback network access is explicitly denied after discovery', async () => {const events: string[] = [];+const result = await installInStudioWithDependencies(elementPayload, {...dependencies,fetchFn: (input) => {events.push(String(input));+return Promise.resolve(new Response(null, {status: 404}));},permissionQueryFn: ({name}) => {events.push(`permission:${name}`);+return Promise.resolve({state: 'denied'});},});@@ -353,11 +369,13 @@ test('reports when loopback network access is explicitly denied after discovery'test('uses the legacy local network permission alias when necessary', async () => {const queriedPermissions: string[] = [];+const result = await installInStudioWithDependencies(elementPayload, {...dependencies,fetchFn: () => Promise.resolve(new Response(null, {status: 404})),permissionQueryFn: ({name}) => {queriedPermissions.push(name);+if (name === 'loopback-network') {return Promise.reject(new TypeError('Unsupported permission name'));}@@ -405,6 +423,7 @@ test('waits for Studio discovery while local network permission is pending', asy) {expect(this).toBeUndefined();const url = String(input);+if (url === 'http://localhost:3000/api/studio-protocol') {return new Promise<Response>((resolve, reject) => {const timeout = setTimeout(() => {@@ -419,6 +438,7 @@ test('waits for Studio discovery while local network permission is pending', asy),);}, 2100);+options?.signal?.addEventListener('abort',() => {@@ -491,6 +511,7 @@ test('reports malformed Studio Protocol data as an invalid response', async () =test('returns a structured error when the selected target expired', async () => {const fetchFn = (input: string | URL | Request) => {const url = String(input);+if (url.endsWith('/api/studio-protocol')) {return Promise.resolve(jsonResponse(@@ -533,6 +554,7 @@ test('returns a structured error when the selected target expired', async () =>test('reports a truncated install response as invalid', async () => {const fetchFn = (input: string | URL | Request) => {const url = String(input);+if (url === 'http://localhost:3000/api/studio-protocol') {return Promise.resolve(jsonResponse(@@ -572,10 +594,12 @@ test('reports a truncated install response as invalid', async () => {test('does not probe Studio from a non-loopback HTTP origin', async () => {let requests = 0;+const result = await installInStudioWithDependencies(elementPayload, {...dependencies,fetchFn: () => {requests++;+return Promise.resolve(new Response(null, {status: 404}));},pageOrigin: 'http://example.com',diff --git a/packages/studio-protocol/src/test/set-license-key-in-studio.test.ts b/packages/studio-protocol/src/test/set-license-key-in-studio.test.tsindex a4805954db..b617fdd040 100644--- a/packages/studio-protocol/src/test/set-license-key-in-studio.test.ts+++ b/packages/studio-protocol/src/test/set-license-key-in-studio.test.ts@@ -57,9 +57,11 @@ test('requests confirmation in the most recently focused Studio project', asyncreadonly options?: RequestInit;readonly url: string;}> = [];+const fetchFn = (input: string | URL | Request, options?: RequestInit) => {const url = String(input);requests.push({options, url});+if (url === 'http://localhost:3000/api/studio-protocol') {return Promise.resolve(jsonResponse(@@ -123,10 +125,12 @@ test('requests confirmation in the most recently focused Studio project', asynctest('returns an actionable result when no Studio is running', async () => {const requests: string[] = [];+const result = await setLicenseKeyInStudioWithDependencies(licenseKey, {...dependencies,fetchFn: (input) => {requests.push(String(input));+return Promise.resolve(new Response(null, {status: 404}));},});@@ -144,8 +148,10 @@ test('returns an actionable result when no Studio is running', async () => {test('rejects malformed keys before discovery', async () => {let requests = 0;+const fetchFn = () => {requests++;+return Promise.resolve(new Response(null, {status: 404}));};@@ -174,6 +180,7 @@ test('distinguishes old Studios from a Studio without a focused target', async (),),});+expect(oldStudio).toMatchObject({success: false,code: 'studio-upgrade-required',@@ -202,6 +209,7 @@ test('distinguishes old Studios from a Studio without a focused target', async (}),),});+expect(noTarget).toMatchObject({success: false,code: 'no-configurable-target',diff --git a/packages/studio-protocol/src/test/sfx-drag-data.test.ts b/packages/studio-protocol/src/test/sfx-drag-data.test.tsindex 582501297c..b080d7497b 100644--- a/packages/studio-protocol/src/test/sfx-drag-data.test.ts+++ b/packages/studio-protocol/src/test/sfx-drag-data.test.ts@@ -6,11 +6,13 @@ const sfxMimeType = StudioProtocolInternals.makeDragData({name: 'Test',url: 'https://remotion.media/test.wav',}).mimeType;+const parseSfxDragData = (payload: string) => {const parsed = StudioProtocolInternals.parseDragData({mimeType: sfxMimeType,payload,});+return parsed?.type === 'sfx' ? parsed.data : null;};@@ -37,6 +39,7 @@ test('accepts any URL in SFX drag data', () => {url: 'https://example.com/whip.wav',},};+expect(parseSfxDragData(JSON.stringify(nonRemotionUrlDragData))).toEqual(nonRemotionUrlDragData,);diff --git a/packages/studio-protocol/src/test/studio-discovery.test.ts b/packages/studio-protocol/src/test/studio-discovery.test.tsindex 9b3fa9379e..46b2e7f57e 100644--- a/packages/studio-protocol/src/test/studio-discovery.test.ts+++ b/packages/studio-protocol/src/test/studio-discovery.test.ts@@ -26,6 +26,7 @@ const descriptor = {test('filters future capabilities, preserves extensions, and rejects duplicates', () => {const parsed =StudioProtocolInternals.parseStudioProtocolDescriptor(descriptor);+expect(parsed).toEqual({...descriptor,capabilities: [installCapability],diff --git a/packages/studio-protocol/src/validation.ts b/packages/studio-protocol/src/validation.tsindex cc5c990785..fc07541157 100644--- a/packages/studio-protocol/src/validation.ts+++ b/packages/studio-protocol/src/validation.ts@@ -1,6 +1,7 @@export const isUrl = (value: string): boolean => {try {const parsed = new URL(value);+return parsed.href.length > 0;} catch {return false;@@ -79,11 +80,13 @@ export const isValidPackageName = (packageName: string): boolean => {}const match = packageName.match(scopedPackagePattern);+if (!match) {return false;}const [, scope, name] = match;+return (scope !== undefined &&name !== undefined &&