🎥 Make videos programmatically with React
`@remotion/browser-studio`: Prebundle Studio dependencies (#10675)
Jonny Burger9ac34ea7bf99
diff --git a/packages/browser-studio/bundle.ts b/packages/browser-studio/bundle.tsindex 8f8f860ec3..23ee9fa258 100644--- a/packages/browser-studio/bundle.ts+++ b/packages/browser-studio/bundle.ts@@ -44,17 +44,35 @@ if (!output.success) {process.exit(1);}+// These artifacts deliberately have different linkage contracts. The preview+// entry is the compatibility fallback for custom dependency resolutions and+// mismatched releases, so its shared dependencies must remain external. The+// vendor entry is the fast path and must bundle the stable dependency graph.+const vendorOutput = await build({+ define: {'process.env.NODE_ENV': JSON.stringify('development')},+ entrypoints: ['src/browser-studio-vendor-entry.ts'],+ format: 'iife',+ minify: true,+ naming: '[name].mjs',+ target: 'browser',+});++if (!vendorOutput.success) {+ console.log(vendorOutput.logs.join('\n'));+ process.exit(1);+}+const externalVersionSensitiveImport =/^[^'"\n]*\bfrom\s*["']@remotion\/(?:player|studio-shared|timeline-utils)["'];?\s*$|^\s*import\s*["']@remotion\/(?:player|studio-shared|timeline-utils)["'];?\s*$/m;-for (const file of output.outputs) {+for (const file of [...output.outputs, ...vendorOutput.outputs]) {const str = await file.text();if (- path.basename(file.path) === 'browser-studio-preview-entry.mjs' &&+ path.basename(file.path) === 'browser-studio-vendor-entry.mjs' &&externalVersionSensitiveImport.test(str)) {throw new Error(- 'Browser Studio must bundle version-sensitive workspace packages into its preview entry so it cannot link against an incompatible published version.',+ 'Browser Studio must bundle version-sensitive workspace packages into its vendor entry so it cannot link against an incompatible published version.',);}diff --git a/packages/browser-studio/e2e/app.tsx b/packages/browser-studio/e2e/app.tsxindex 5353a1e896..5cec2a2362 100644--- a/packages/browser-studio/e2e/app.tsx+++ b/packages/browser-studio/e2e/app.tsx@@ -34,8 +34,15 @@ if (!root) {throw new Error('Could not find root element');}+const source = new URLSearchParams(window.location.search).get('source');+createRoot(root).render(<BrowserStudio+ dependencyResolver={+ source === 'fallback'+ ? ({name, version}) => (name === 'react' ? version : null)+ : undefined+ }iframeSrc="/frame.html"initialElement={initialElementPayload === null@@ -50,7 +57,7 @@ createRoot(root).render().__browserStudioProject = nextProject;}}remotionPackageSource={- new URLSearchParams(window.location.search).get('source') === 'release'+ source === 'release'? {baseUrl: new URL(`/__remotion_browser_studio_release__/${VERSION}/`,diff --git a/packages/browser-studio/e2e/browser-studio.test.ts b/packages/browser-studio/e2e/browser-studio.test.tsindex 25c7c7b3a8..67c20c3b6e 100644--- a/packages/browser-studio/e2e/browser-studio.test.ts+++ b/packages/browser-studio/e2e/browser-studio.test.ts@@ -10,6 +10,7 @@ test('loads Browser Studio, opens external links, and can add, delete, and dupliconst pageErrors: Error[] = [];const remoteRemotionRequests: string[] = [];const studioApiRequests: string[] = [];+ const vendorBundleRequests: string[] = [];const workspacePackageRequests: string[] = [];let rejectPageError: (error: Error) => void = () => undefined;const pageError = new Promise<never>((_resolve, reject) => {@@ -17,6 +18,10 @@ test('loads Browser Studio, opens external links, and can add, delete, and dupli});page.on('request', (request) => {const requestUrl = new URL(request.url());+ if (requestUrl.searchParams.has('projectBundleUrl')) {+ vendorBundleRequests.push(request.url());+ }+if (requestUrl.pathname.startsWith('/api/') &&requestUrl.origin === new URL(page.url()).origin@@ -172,15 +177,16 @@ test('loads Browser Studio, opens external links, and can add, delete, and dupli]);expect(pageErrors).toEqual([]);- expect(workspacePackageRequests).toContain(+ expect(workspacePackageRequests).not.toContain('/__remotion_browser_studio_workspace__/commits/e2e/packages/core/dist/esm/index.mjs',);- expect(workspacePackageRequests).toContain(+ expect(workspacePackageRequests).not.toContain('/__remotion_browser_studio_workspace__/commits/e2e/packages/studio/dist/esm/previewEntry.mjs',);expect(workspacePackageRequests).toContain('/__remotion_browser_studio_workspace__/commits/e2e/packages/transitions/dist/esm/fade.mjs',);+ expect(vendorBundleRequests).toHaveLength(1);expect(remoteRemotionRequests).toEqual([]);expect(studioApiRequests).toEqual([]);});@@ -190,8 +196,13 @@ test('loads Browser Studio from one immutable release artifact set', async ({}) => {const releasePackageRequests: string[] = [];const remoteRemotionRequests: string[] = [];+ const vendorBundleRequests: string[] = [];page.on('request', (request) => {const requestUrl = new URL(request.url());+ if (requestUrl.searchParams.has('projectBundleUrl')) {+ vendorBundleRequests.push(request.url());+ }+if (requestUrl.pathname.startsWith('/__remotion_browser_studio_release__/')) {@@ -214,12 +225,52 @@ test('loads Browser Studio from one immutable release artifact set', async ({await expect(studio.locator('.remotion-studio-composition-container'),).toBeVisible();- expect(releasePackageRequests).toContain(- `/__remotion_browser_studio_release__/${await page.evaluate(() => (window as typeof window & {__browserStudioRemotionVersion: string}).__browserStudioRemotionVersion)}/packages/studio/dist/esm/previewEntry.mjs`,- );+ expect(releasePackageRequests).toEqual([+ `/__remotion_browser_studio_release__/${await page.evaluate(() => (window as typeof window & {__browserStudioRemotionVersion: string}).__browserStudioRemotionVersion)}/packages/transitions/dist/esm/fade.mjs`,+ ]);+ expect(vendorBundleRequests).toHaveLength(1);expect(remoteRemotionRequests).toEqual([]);});+test('fetches each HTTP module once when the vendor bundle is overridden', async ({+ page,+}) => {+ const workspacePackageRequests: string[] = [];+ page.on('request', (request) => {+ const requestUrl = new URL(request.url());+ if (+ requestUrl.pathname.startsWith('/__remotion_browser_studio_workspace__/')+ ) {+ workspacePackageRequests.push(requestUrl.pathname);+ }+ });++ await page.goto('/?source=fallback');+ const studio = page.frameLocator('iframe');+ await expect(studio.getByTitle('/project').getByText('MyComp')).toBeVisible();+ await expect(+ studio.locator('.remotion-studio-composition-container'),+ ).toBeVisible();++ expect(+ workspacePackageRequests.filter(+ (request) =>+ request ===+ '/__remotion_browser_studio_workspace__/commits/e2e/packages/core/dist/esm/index.mjs',+ ),+ ).toHaveLength(1);+ expect(+ workspacePackageRequests.filter(+ (request) =>+ request ===+ '/__remotion_browser_studio_workspace__/commits/e2e/packages/core/dist/esm/no-react.mjs',+ ),+ ).toHaveLength(1);+ expect(workspacePackageRequests).toContain(+ '/__remotion_browser_studio_workspace__/commits/e2e/packages/studio/dist/esm/previewEntry.mjs',+ );+});+test('drops and imports an Element payload with the deployment Remotion version', async ({page,}) => {diff --git a/packages/browser-studio/src/BrowserStudio.tsx b/packages/browser-studio/src/BrowserStudio.tsxindex 2ee1b6b0ce..9b18ab398e 100644--- a/packages/browser-studio/src/BrowserStudio.tsx+++ b/packages/browser-studio/src/BrowserStudio.tsx@@ -11,6 +11,7 @@ import {createBrowserStudioPublicFileManager,} from './browser-studio-project-controller';import {browserStudioDependencyVersions} from './dependency-versions';+import {studioRenderEntryExternal} from './dev/studio-render-entry-external';import {Spinner} from './Spinner';import type {BrowserStudioDependencyResolution,@@ -34,6 +35,11 @@ const localStudioPreviewEntry = new URL(import.meta.url,).href;+const localVendorEntry = new URL(+ './browser-studio-vendor-entry.mjs',+ import.meta.url,+).href;+type BrowserStudioContentWindow = Window & {remotion_browserStudioHmr: BrowserStudioHmrBridge;};@@ -320,6 +326,37 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({setIframeHtml(null);setCompileState({status: 'compiling'});+ const configuredDependencyResolutions = Object.fromEntries(+ Object.entries(browserStudioDependencyVersions).map(([name, version]) => [+ name,+ dependencyResolver?.({name, version}) ?? null,+ ]),+ );+ const dependencyResolutions = {+ ...configuredDependencyResolutions,+ ...installedDependencyResolutionsRef.current,+ };+ const hasVendorOverride = Object.entries(dependencyResolutions).some(+ ([name, resolution]) =>+ resolution !== null &&+ (name.startsWith('@remotion/') ||+ name === 'react-refresh' ||+ studioRenderEntryExternal.includes(name)),+ );+ const releaseMatchesVendor =+ remotionPackageSource?.type !== 'release' ||+ remotionPackageSource.version ===+ browserStudioDependencyVersions.remotion;+ const useVendorBundle = !hasVendorOverride && releaseMatchesVendor;+ if (+ !useVendorBundle &&+ !remotionPackageSource &&+ dependencyResolutions['@remotion/studio'] === null+ ) {+ dependencyResolutions['@remotion/studio'] = {+ url: localStudioPreviewEntry,+ };+ }const worker = new Worker(new URL('./browser-studio-worker.mjs', import.meta.url),@@ -365,11 +402,15 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({new Blob([response.bundle], {type: 'text/javascript'}),);const currentProject = activeProjectRef.current;+ const bundleScriptUrl = useVendorBundle+ ? `${localVendorEntry}?projectBundleUrl=${encodeURIComponent(bundleUrlRef.current)}`+ : bundleUrlRef.current;const html = studioHtml({audioLatencyHint: 'playback',experimentalKeepAudioContextAlive: false,- bundleScriptUrl: bundleUrlRef.current,+ bundleScriptUrl,+ bundleScriptType: useVendorBundle ? 'module' : undefined,completedClientRenders: [],editorName: null,envVariables: {NODE_ENV: 'development'},@@ -423,32 +464,13 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({});};- const request: BrowserStudioWorkerCompileRequest = {+ worker.postMessage({type: 'init',- dependencyResolutions: {- ...Object.fromEntries(- Object.entries(browserStudioDependencyVersions).map(- ([name, version]) => {- const customResolution = dependencyResolver?.({name, version});- if (customResolution) {- return [name, customResolution];- }-- if (name === '@remotion/studio') {- return [name, {url: localStudioPreviewEntry}];- }-- return [name, null];- },- ),- ),- ...installedDependencyResolutionsRef.current,- },+ dependencyResolutions,project: activeProjectRef.current,remotionPackageSource: remotionPackageSource ?? null,- };-- worker.postMessage(request);+ useVendorBundle,+ } satisfies BrowserStudioWorkerCompileRequest);return () => {didCancel = true;diff --git a/packages/browser-studio/src/browser-studio-http-client.ts b/packages/browser-studio/src/browser-studio-http-client.tsnew file mode 100644index 0000000000..94e1b5a502--- /dev/null+++ b/packages/browser-studio/src/browser-studio-http-client.ts@@ -0,0 +1,51 @@+type BrowserStudioHttpResponse = {+ body: Buffer;+ headers: Record<string, string>;+ status: number;+};++export const makeBrowserStudioHttpClient = ({+ fetchImplementation,+}: {+ fetchImplementation: (+ input: RequestInfo | URL,+ init?: RequestInit,+ ) => Promise<Response>;+}) => {+ const responseCache = new Map<string, Promise<BrowserStudioHttpResponse>>();++ return (url: string, headers: Record<string, string>) => {+ const cacheKey = JSON.stringify([+ url,+ Object.entries(headers).sort(([left], [right]) =>+ left.localeCompare(right),+ ),+ ]);+ const cached = responseCache.get(cacheKey);+ if (cached) {+ return cached;+ }++ const responsePromise = fetchImplementation(url, {headers})+ .then(async (response) => {+ const responseHeaders: Record<string, string> = {};+ response.headers.forEach((value, key) => {+ responseHeaders[key] = value;+ });++ return {+ body: new Uint8Array(+ await response.arrayBuffer(),+ ) as unknown as Buffer,+ headers: responseHeaders,+ status: response.status,+ };+ })+ .catch((error: unknown) => {+ responseCache.delete(cacheKey);+ throw error;+ });+ responseCache.set(cacheKey, responsePromise);+ return responsePromise;+ };+};diff --git a/packages/browser-studio/src/browser-studio-vendor-entry.ts b/packages/browser-studio/src/browser-studio-vendor-entry.tsnew file mode 100644index 0000000000..c1c5803018--- /dev/null+++ b/packages/browser-studio/src/browser-studio-vendor-entry.ts@@ -0,0 +1,15 @@+import ReactRefreshRuntime from 'react-refresh/runtime';++ReactRefreshRuntime.injectIntoGlobalHook(globalThis);++const projectBundleUrl = new URL(import.meta.url).searchParams.get(+ 'projectBundleUrl',+);+if (!projectBundleUrl) {+ throw new Error('Browser Studio project bundle URL was not provided');+}++import('./browser-studio-vendor-runtime').then(+ ({initializeBrowserStudioVendor}) =>+ initializeBrowserStudioVendor(projectBundleUrl),+);diff --git a/packages/browser-studio/src/browser-studio-vendor-runtime.ts b/packages/browser-studio/src/browser-studio-vendor-runtime.tsnew file mode 100644index 0000000000..d7b39d910a--- /dev/null+++ b/packages/browser-studio/src/browser-studio-vendor-runtime.ts@@ -0,0 +1,93 @@+import * as React from 'react';+import * as ReactDom from 'react-dom';+import * as ReactDomClient from 'react-dom/client';+import * as ReactRefreshRuntime from 'react-refresh/runtime';+import * as ReactJsxDevRuntime from 'react/jsx-dev-runtime';+import * as ReactJsxRuntime from 'react/jsx-runtime';+import * as Remotion from 'remotion';+import * as RemotionNoReact from 'remotion/no-react';+import * as RemotionVersion from 'remotion/version';++let studioPromise: Promise<void> | null = null;+const makeMutableNamespace = <Namespace extends object>(+ namespace: Namespace,+): Namespace => ({+ ...((namespace as {default?: object}).default ?? {}),+ ...namespace,+});++// Studio is prebuilt separately from the project, but its update client must+// still drive the project's Rspack runtime. The project boot module installs+// this bridge before starting Studio.+globalThis.__webpack_module__ = {+ hot: {+ addStatusHandler: (callback) =>+ globalThis.remotion_browserStudioProjectHot.addStatusHandler(callback),+ apply: (options) =>+ globalThis.remotion_browserStudioProjectHot.apply(options),+ check: (autoApply) =>+ globalThis.remotion_browserStudioProjectHot.check(autoApply),+ status: () => globalThis.remotion_browserStudioProjectHot.status(),+ },+};+Object.defineProperty(globalThis, '__webpack_hash__', {+ configurable: true,+ get: () => globalThis.remotion_browserStudioProjectHot.getHash(),+});++globalThis.remotion_browserStudioVendor = {+ react: makeMutableNamespace(React),+ reactDom: makeMutableNamespace(ReactDom),+ reactDomClient: makeMutableNamespace(ReactDomClient),+ reactJsxDevRuntime: makeMutableNamespace(ReactJsxDevRuntime),+ reactJsxRuntime: makeMutableNamespace(ReactJsxRuntime),+ reactRefreshRuntime: makeMutableNamespace(ReactRefreshRuntime),+ remotion: makeMutableNamespace(Remotion),+ remotionNoReact: makeMutableNamespace(RemotionNoReact),+ remotionVersion: makeMutableNamespace(RemotionVersion),+ startStudio: () => {+ studioPromise ??= import('@remotion/studio/previewEntry').then(+ () => undefined,+ );+ return studioPromise;+ },+};++export const initializeBrowserStudioVendor = (projectBundleUrl: string) => {+ return import(projectBundleUrl);+};++declare global {+ // eslint-disable-next-line no-var+ var __webpack_hash__: string;+ // eslint-disable-next-line no-var+ var __webpack_module__: {+ hot: {+ addStatusHandler: (callback: (status: string) => void) => void;+ apply: (options?: unknown) => Promise<unknown[]>;+ check: (autoApply?: boolean) => Promise<null | unknown[]>;+ status: () => string;+ };+ };+ // eslint-disable-next-line no-var+ var remotion_browserStudioProjectHot: {+ addStatusHandler: (callback: (status: string) => void) => void;+ apply: (options?: unknown) => Promise<unknown[]>;+ check: (autoApply?: boolean) => Promise<null | unknown[]>;+ getHash: () => string;+ status: () => string;+ };+ // eslint-disable-next-line no-var+ var remotion_browserStudioVendor: {+ react: typeof React;+ reactDom: typeof ReactDom;+ reactDomClient: typeof ReactDomClient;+ reactJsxDevRuntime: typeof ReactJsxDevRuntime;+ reactJsxRuntime: typeof ReactJsxRuntime;+ reactRefreshRuntime: typeof ReactRefreshRuntime;+ remotion: typeof Remotion;+ remotionNoReact: typeof RemotionNoReact;+ remotionVersion: typeof RemotionVersion;+ startStudio: () => Promise<void>;+ };+}diff --git a/packages/browser-studio/src/browser-studio-worker.ts b/packages/browser-studio/src/browser-studio-worker.tsindex 7a63b054d6..a9d8c478d7 100644--- a/packages/browser-studio/src/browser-studio-worker.ts+++ b/packages/browser-studio/src/browser-studio-worker.ts@@ -1,6 +1,7 @@import type {HotMiddlewareMessage} from '@remotion/studio-shared';import {getStudioEntryPoints} from '@remotion/studio-shared/studio-entry-points';import type * as RspackBrowser from '@rspack/browser';+import {makeBrowserStudioHttpClient} from './browser-studio-http-client';import {browserStudioDependencyVersions} from './dependency-versions';import {studioRenderEntryExternal} from './dev/studio-render-entry-external';import type {@@ -46,6 +47,22 @@ const loadRspackBrowser = () => {return rspackBrowserPromise;};+const browserStudioVendorExternals = {+ react: 'globalThis.remotion_browserStudioVendor.react',+ 'react-dom': 'globalThis.remotion_browserStudioVendor.reactDom',+ 'react-dom/client': 'globalThis.remotion_browserStudioVendor.reactDomClient',+ 'react/jsx-dev-runtime':+ 'globalThis.remotion_browserStudioVendor.reactJsxDevRuntime',+ 'react/jsx-runtime':+ 'globalThis.remotion_browserStudioVendor.reactJsxRuntime',+ 'react-refresh/runtime':+ 'globalThis.remotion_browserStudioVendor.reactRefreshRuntime',+ remotion: 'globalThis.remotion_browserStudioVendor.remotion',+ 'remotion/no-react':+ 'globalThis.remotion_browserStudioVendor.remotionNoReact',+ 'remotion/version': 'globalThis.remotion_browserStudioVendor.remotionVersion',+};+const normalizePath = (path: string) =>path.startsWith('/') ? path : `/${path}`;@@ -244,6 +261,7 @@ const createCompiler = async ({dependencyResolutions,project,remotionPackageSource,+ useVendorBundle,}: Extract<BrowserStudioWorkerCompileRequest, {type: 'init'}>) => {const rspackBrowser = await loadRspackBrowser();const {BrowserHttpImportEsmPlugin, builtinMemFs, rspack} = rspackBrowser;@@ -274,7 +292,9 @@ const createCompiler = async ({fastRefreshRuntime: browserStudioVirtualFilePaths.reactRefreshEntry,reactShim: browserStudioVirtualFilePaths.reactShim,sequenceStackTraces: browserStudioVirtualFilePaths.setupSequenceStackTraces,- studioRenderEntry: '@remotion/studio/previewEntry',+ studioRenderEntry: useVendorBundle+ ? browserStudioVirtualFilePaths.studioPreviewEntry+ : '@remotion/studio/previewEntry',userDefinedComponent: normalizePath(project.entryPoint),});entryPoints.splice(@@ -295,8 +315,13 @@ const createCompiler = async ({...(remotionPackageSource ? [remotionPackageSource.baseUrl] : []),],cacheLocation: false,+ httpClient: makeBrowserStudioHttpClient({+ fetchImplementation: fetch,+ }),},},+ externals: useVendorBundle ? browserStudioVendorExternals : undefined,+ externalsType: useVendorBundle ? 'var' : undefined,mode: 'development',module: {rules: [@@ -373,6 +398,12 @@ const createCompiler = async ({return undefined;}+ const packageName = getPackageName(request);+ const resolvedUrl = resolvedUrls[packageName];+ if (resolvedUrl) {+ return resolvedUrl;+ }+const remotionPackageUrl = resolveBrowserStudioRemotionPackage({packages: workspacePackageExports,request,@@ -382,12 +413,6 @@ const createCompiler = async ({return remotionPackageUrl;}- const packageName = getPackageName(request);- const resolvedUrl = resolvedUrls[packageName];- if (resolvedUrl) {- return resolvedUrl;- }-const version = resolvedVersions[packageName] ?? 'latest';const url = new URL(getVersionedPackageRequest(request, version),diff --git a/packages/browser-studio/src/dev/server.ts b/packages/browser-studio/src/dev/server.tsindex 30dd715e43..c649193dfe 100644--- a/packages/browser-studio/src/dev/server.ts+++ b/packages/browser-studio/src/dev/server.ts@@ -113,6 +113,21 @@ const buildDevAssets = async () => {process.exit(1);}+ const vendorEntryOutput = await build({+ define: {'process.env.NODE_ENV': JSON.stringify('development')},+ entrypoints: ['src/browser-studio-vendor-entry.ts'],+ format: 'iife',+ naming: '[name].mjs',+ outdir: outDir,+ sourcemap: 'linked',+ target: 'browser',+ });++ if (!vendorEntryOutput.success) {+ process.stderr.write(`${vendorEntryOutput.logs.join('\n')}\n`);+ process.exit(1);+ }+const rspackBrowserEntry = fileURLToPath(import.meta.resolve('@rspack/browser'),);diff --git a/packages/browser-studio/src/react-refresh-runtime.d.ts b/packages/browser-studio/src/react-refresh-runtime.d.tsnew file mode 100644index 0000000000..b618afdf30--- /dev/null+++ b/packages/browser-studio/src/react-refresh-runtime.d.ts@@ -0,0 +1,10 @@+declare module 'react-refresh/runtime' {+ type ReactRefreshRuntime = {+ createSignatureFunctionForTransform: (...args: unknown[]) => unknown;+ injectIntoGlobalHook: (globalObject: typeof globalThis) => void;+ register: (type: unknown, id: string) => void;+ };++ const runtime: ReactRefreshRuntime;+ export = runtime;+}diff --git a/packages/browser-studio/src/test/browser-studio-http-client.test.ts b/packages/browser-studio/src/test/browser-studio-http-client.test.tsnew file mode 100644index 0000000000..c5679a4698--- /dev/null+++ b/packages/browser-studio/src/test/browser-studio-http-client.test.ts@@ -0,0 +1,56 @@+import {expect, test} from 'bun:test';+import {makeBrowserStudioHttpClient} from '../browser-studio-http-client';++test('coalesces concurrent requests with equivalent headers', async () => {+ let requests = 0;+ const httpClient = makeBrowserStudioHttpClient({+ fetchImplementation: async () => {+ requests++;+ await Promise.resolve();+ return new Response('module', {+ headers: {'x-test': 'value'},+ status: 200,+ });+ },+ });++ const first = httpClient('https://example.com/module.js', {+ accept: 'text/javascript',+ authorization: 'token',+ });+ const second = httpClient('https://example.com/module.js', {+ authorization: 'token',+ accept: 'text/javascript',+ });++ expect(first).toBe(second);+ const response = await second;+ expect({...response, body: new TextDecoder().decode(response.body)}).toEqual({+ body: 'module',+ headers: {'x-test': 'value'},+ status: 200,+ });+ expect(requests).toBe(1);+});++test('allows a failed request to be retried', async () => {+ let requests = 0;+ const httpClient = makeBrowserStudioHttpClient({+ fetchImplementation: () => {+ requests++;+ if (requests === 1) {+ return Promise.reject(new Error('Network error'));+ }++ return Promise.resolve(new Response('module'));+ },+ });++ await expect(httpClient('https://example.com/module.js', {})).rejects.toThrow(+ 'Network error',+ );+ await expect(+ httpClient('https://example.com/module.js', {}),+ ).resolves.toMatchObject({status: 200});+ expect(requests).toBe(2);+});diff --git a/packages/browser-studio/src/types.ts b/packages/browser-studio/src/types.tsindex e0599ef32f..79c758dacb 100644--- a/packages/browser-studio/src/types.ts+++ b/packages/browser-studio/src/types.ts@@ -82,6 +82,7 @@ export type BrowserStudioWorkerCompileRequest =project: VirtualProject;dependencyResolutions: Record<string, BrowserStudioDependencyResolution>;remotionPackageSource: BrowserStudioRemotionPackageSource | null;+ useVendorBundle: boolean;}| {type: 'update-project';diff --git a/packages/browser-studio/src/virtual-files.ts b/packages/browser-studio/src/virtual-files.tsindex 425d615d27..490f20ad0c 100644--- a/packages/browser-studio/src/virtual-files.ts+++ b/packages/browser-studio/src/virtual-files.ts@@ -6,6 +6,7 @@ export const browserStudioVirtualFilePaths = {setupEnvironment: '/__remotion_browser_studio__/setup-environment.ts',setupSequenceStackTraces:'/__remotion_browser_studio__/setup-sequence-stack-traces.ts',+ studioPreviewEntry: '/__remotion_browser_studio__/studio-preview-entry.js',jsxRuntime: '/__remotion_browser_studio__/jsx-runtime.ts',jsxDevRuntime: '/__remotion_browser_studio__/jsx-dev-runtime.ts',jsxImportSource: '/__remotion_browser_studio__',@@ -141,6 +142,21 @@ globalThis.require = (id) => {};`;+const studioPreviewEntry = `if (!globalThis.remotion_browserStudioVendor) {+ throw new Error('Browser Studio vendor bundle was not loaded');+}++globalThis.remotion_browserStudioProjectHot = {+ addStatusHandler: (callback) => module.hot.addStatusHandler(callback),+ apply: (options) => module.hot.apply(options),+ check: (autoApply) => module.hot.check(autoApply),+ getHash: () => __webpack_hash__,+ status: () => module.hot.status(),+};++void globalThis.remotion_browserStudioVendor.startStudio();+`;+export const getBrowserStudioVirtualFiles = (): Record<string, string> => {const reactRefreshFiles = getInjectedReactRefreshFiles();@@ -154,6 +170,7 @@ export const getBrowserStudioVirtualFiles = (): Record<string, string> => {getInjectedSetupEnvironment(),[browserStudioVirtualFilePaths.setupSequenceStackTraces]:setupSequenceStackTraces,+ [browserStudioVirtualFilePaths.studioPreviewEntry]: studioPreviewEntry,[browserStudioVirtualFilePaths.jsxRuntime]: jsxRuntime,[browserStudioVirtualFilePaths.jsxDevRuntime]: jsxDevRuntime,[browserStudioVirtualFilePaths.reactShim]: reactShim,diff --git a/packages/studio-shared/src/studio-html.ts b/packages/studio-shared/src/studio-html.tsindex 94e4134db0..d02a2fbbe7 100644--- a/packages/studio-shared/src/studio-html.ts+++ b/packages/studio-shared/src/studio-html.ts@@ -32,6 +32,7 @@ export type StudioHtmlOptions = {logLevel: LogLevel;mode: 'dev' | 'bundle';bundleScriptUrl?: string;+ bundleScriptType?: 'classic' | 'module';readOnlyStudio?: boolean;studioRuntimeConfig?: StudioRuntimeConfig;};@@ -63,6 +64,7 @@ export const studioHtml = ({logLevel,mode,bundleScriptUrl,+ bundleScriptType,readOnlyStudio,studioRuntimeConfig,}: StudioHtmlOptions) => {@@ -186,7 +188,7 @@ export const studioHtml = ({<div id="menuportal-3"></div><div id="menuportal-4"></div><div id="menuportal-5"></div>- <script src="${scriptUrl}"></script>+ <script${bundleScriptType === 'module' ? ' type="module"' : ''} src="${scriptUrl}"></script></body></html>`.trim();diff --git a/packages/studio-shared/src/test/studio-html.test.ts b/packages/studio-shared/src/test/studio-html.test.tsindex 0dfb7bbec1..4d06235b9d 100644--- a/packages/studio-shared/src/test/studio-html.test.ts+++ b/packages/studio-shared/src/test/studio-html.test.ts@@ -2,10 +2,12 @@ import {expect, test} from 'bun:test';import {studioHtml} from '../studio-html';const makeHtml = ({+ bundleScriptType,publicPath,staticHash,publicFolderExists,}: {+ bundleScriptType?: 'module';publicPath: string;staticHash: string;publicFolderExists: string;@@ -41,6 +43,7 @@ const makeHtml = ({packageManager: 'unknown',logLevel: 'info',mode: 'bundle',+ bundleScriptType,});};@@ -87,3 +90,14 @@ test('preserves explicitly absolute bundle paths', () => {);expect(html).not.toContain('.map((file)');});++test('marks an explicitly requested module bundle', () => {+ const html = makeHtml({+ bundleScriptType: 'module',+ publicPath: './',+ staticHash: './public',+ publicFolderExists: './public',+ });++ expect(html).toContain('<script type="module" src="./bundle.js"></script>');+});