🎥 Make videos programmatically with React
Remove process-update.ts HMR client, add disk fallback for rspack hot-update files
Jonny Burger600c05f80ff1
diff --git a/packages/bundler/src/rspack-config.ts b/packages/bundler/src/rspack-config.tsindex 303d1a3896..2c66a29736 100644--- a/packages/bundler/src/rspack-config.ts+++ b/packages/bundler/src/rspack-config.ts@@ -92,7 +92,6 @@ export const rspackConfig = async ({// Rspack config is structurally compatible with webpack config at runtime,// but the TypeScript types differ. Cast through `any` for the override.- // eslint-disable-next-line @typescript-eslint/no-explicit-anyconst conf = (await webpackOverride({...getBaseConfig(environment, poll),ignoreWarnings: [@@ -110,7 +109,7 @@ export const rspackConfig = async ({plugins:environment === 'development'? [- new ReactRefreshPlugin(),+ new ReactRefreshPlugin({overlay: false}),new rspack.HotModuleReplacementPlugin(),define,]diff --git a/packages/studio-server/src/preview-server/dev-middleware/middleware.ts b/packages/studio-server/src/preview-server/dev-middleware/middleware.tsindex a923699209..107039048b 100644--- a/packages/studio-server/src/preview-server/dev-middleware/middleware.ts+++ b/packages/studio-server/src/preview-server/dev-middleware/middleware.ts@@ -1,4 +1,5 @@import {RenderInternals} from '@remotion/renderer';+import fs from 'node:fs';import type {ReadStream} from 'node:fs';import type {IncomingMessage, ServerResponse} from 'node:http';import path from 'node:path';@@ -117,6 +118,58 @@ function getFilenameFromUrl(return foundFilename;}+// Rspack's native compiler may write HMR update files to disk+// rather than the in-memory outputFileSystem. Check the real filesystem+// as a fallback for .hot-update. files.+function getFilenameFromUrlDiskFallback(+ context: DevMiddlewareContext,+ url: string | undefined,+): {filename: string; fromDisk: true} | undefined {+ const paths = getPaths(context);++ let urlObject;+ try {+ urlObject = memoizedParse(url, false, true);+ } catch {+ return;+ }++ const pathname = urlObject.pathname;+ if (!pathname || !pathname.includes('.hot-update.')) {+ return;+ }++ for (const {publicPath, outputPath} of paths) {+ let publicPathObject;+ try {+ publicPathObject = memoizedParse(+ publicPath !== 'auto' && publicPath ? publicPath : '/',+ false,+ true,+ );+ } catch {+ continue;+ }++ if (pathname.startsWith(publicPathObject.pathname)) {+ const stripped = pathname.substr(publicPathObject.pathname.length);+ const filename = stripped+ ? path.join(outputPath, querystring.unescape(stripped))+ : outputPath;++ try {+ if (fs.statSync(filename).isFile()) {+ return {filename, fromDisk: true};+ }+ } catch {+ continue;+ }+ }+ }++ return undefined;+}+export function getValueContentRangeHeader(type: string,size: number,@@ -177,6 +230,25 @@ export function middleware(context: DevMiddlewareContext) {const filename = getFilenameFromUrl(context, req.url);if (!filename) {+ // Rspack may write HMR update files to disk instead of memfs.+ // Try serving from the real filesystem as a fallback.+ const diskResult = getFilenameFromUrlDiskFallback(+ context,+ req.url,+ );+ if (diskResult) {+ const contentType = RenderInternals.mimeContentType(+ path.extname(diskResult.filename),+ );+ if (contentType) {+ setHeaderForResponse(res, 'Content-Type', contentType);+ }++ const content = fs.readFileSync(diskResult.filename);+ send(req, res, content, content.byteLength);+ return;+ }+goNext();return;diff --git a/packages/studio/src/hot-middleware-client/client.ts b/packages/studio/src/hot-middleware-client/client.tsindex 82d84a95ed..f399ac44ff 100644--- a/packages/studio/src/hot-middleware-client/client.ts+++ b/packages/studio/src/hot-middleware-client/client.ts@@ -9,7 +9,6 @@*/import type {HotMiddlewareMessage} from '@remotion/studio-shared';import {hotMiddlewareOptions, stripAnsi} from '@remotion/studio-shared';-import {processUpdate} from './process-update';function eventSourceWrapper() {let source: EventSource;@@ -180,7 +179,20 @@ function processMessage(obj: HotMiddlewareMessage) {if (applyUpdate) {window.remotion_finishedBuilding?.();- processUpdate(obj.hash, obj.modules, hotMiddlewareOptions);+ if (+ obj.hash &&+ obj.hash !== __webpack_hash__ &&+ __webpack_module__.hot?.status() === 'idle'+ ) {+ __webpack_module__.hot+ ?.check(true)+ .catch((err: Error) => {+ console.warn(+ '[Fast refresh] Update check failed: ' ++ (err.stack || err.message),+ );+ });+ }}break;diff --git a/packages/studio/src/hot-middleware-client/process-update.ts b/packages/studio/src/hot-middleware-client/process-update.tsdeleted file mode 100644index 1aad3a0b28..0000000000--- a/packages/studio/src/hot-middleware-client/process-update.ts+++ /dev/null@@ -1,202 +0,0 @@-/* eslint-disable no-console */-/**- * Source code is adapted from- * https://github.com/webpack-contrib/webpack-hot-middleware#readme- * and rewritten in TypeScript. This file is MIT licensed- */--/**- * Based heavily on https://github.com/webpack/webpack/blob/- * c0afdf9c6abc1dd70707c594e473802a566f7b6e/hot/only-dev-server.js- * Original copyright Tobias Koppers @sokra (MIT license)- */--import type {HotMiddlewareOptions, ModuleMap} from '@remotion/studio-shared';-import {showNotification} from '../components/Notifications/NotificationCenter';-import {reloadUrl} from '../helpers/url-state';--if (!__webpack_module__.hot) {- throw new Error('[Fast refresh] Hot Module Replacement is disabled.');-}--const hmrDocsUrl = 'https://webpack.js.org/concepts/hot-module-replacement/';--let lastHash: string | undefined;-const failureStatuses = {abort: 1, fail: 1};-const applyOptions: AcceptOptions = {- ignoreUnaccepted: true,- ignoreDeclined: true,- ignoreErrored: true,- onUnaccepted(data) {- console.warn(- 'Ignored an update to unaccepted module ' +- (data.chain ?? []).join(' -> '),- );-- // Case:- // 1. Import a CSS file with a bad filename in Root.tsx- // 2. Fix the import and save it- if (!window.remotion_isStudio) {- reloadUrl();- }- },- onDeclined(data) {- console.warn(- 'Ignored an update to declined module ' + (data.chain ?? []).join(' -> '),- );- },- onErrored(data) {- console.error(data.error);- console.warn(- 'Ignored an error while updating module ' +- data.moduleId +- ' (' +- data.type +- ')',- );- },-};--function upToDate(hash?: string) {- if (hash) lastHash = hash;- return lastHash === __webpack_hash__;-}--export const processUpdate = function (- hash: string | undefined,- moduleMap: ModuleMap,- options: HotMiddlewareOptions,-) {- const {reload} = options;- if (!upToDate(hash) && __webpack_module__.hot?.status() === 'idle') {- check();- }-- async function check() {- const cb = function (err: Error | null, updatedModules: ModuleId[] | null) {- if (err) return handleError(err);-- if (!updatedModules) {- if (options.warn) {- console.warn(- '[Fast refresh] Cannot find update (Full reload needed)',- );- console.warn(- '[Fast refresh] (Probably because of restarting the server)',- );- }-- performReload();- return null;- }-- const applyCallback = function (- applyErr: Error | null,- renewedModules: ModuleId[],- ) {- if (applyErr) return handleError(applyErr);-- if (!upToDate()) {- check();- }-- logUpdates(updatedModules, renewedModules);- };-- const applyResult = __webpack_module__.hot?.apply(applyOptions);- if ((applyResult as unknown as Promise<unknown>)?.then) {- // HotModuleReplacement.runtime.js refers to the result as `outdatedModules`- (applyResult as unknown as Promise<ModuleId[]>)- .then((outdatedModules) => {- applyCallback(null, outdatedModules);- })- .catch((_err: Error) => applyCallback(_err, []));- }- };-- try {- const result = await __webpack_module__.hot?.check(false);- cb(null, result);- } catch (err) {- cb(err as Error, []);- }- }-- function logUpdates(updatedModules: ModuleId[], renewedModules: ModuleId[]) {- const unacceptedModules =- updatedModules?.filter((moduleId) => {- return renewedModules && renewedModules.indexOf(moduleId) < 0;- }) ?? [];-- if (unacceptedModules.length > 0) {- if (options.warn) {- console.warn(- "[Fast refresh] The following modules couldn't be hot updated: " +- '(Full reload needed)\n' +- 'This is usually because the modules which have changed ' +- '(and their parents) do not know how to hot reload themselves. ' +- 'See ' +- hmrDocsUrl +- ' for more details.',- );- unacceptedModules.forEach((moduleId) => {- console.warn(- '[Fast refresh] - ' + (moduleMap[moduleId] || moduleId),- );- });- }-- performReload();- return;- }-- if (!renewedModules || renewedModules.length === 0) {- console.log('[Fast refresh] Nothing hot updated.');- } else {- renewedModules.forEach((moduleId) => {- console.log(- `[Fast refresh] ${moduleMap[moduleId] || moduleId} fast refreshed.`,- );- });- }- }-- function handleError(err: Error) {- if ((__webpack_module__.hot?.status() ?? 'nope') in failureStatuses) {- if (options.warn) {- console.warn(- '[Fast refresh] Cannot check for update (Full reload needed)',- );- console.warn('[Fast refresh] ' + (err.stack || err.message));- }-- performReload();- return;- }-- if (options.warn) {- console.warn(- '[Fast refresh] Update check failed: ' + (err.stack || err.message),- );- if (!window.remotion_unsavedProps) {- reloadUrl();- }- }- }-- function performReload() {- if (!reload) {- return;- }-- if (options.warn) console.warn('[Fast refresh] Reloading page');- if (window.remotion_unsavedProps) {- showNotification(- 'Fast refresh needs to reload the page, but you have unsaved props. Save then reload the page to apply changes.',- 1000,- );- } else {- reloadUrl();- }- }-};