From f6f68ea6441b4ec62055294e7f415d25881ff8be Mon Sep 17 00:00:00 2001 From: Tobias Koppers Date: Thu, 14 Sep 2023 12:15:22 +0000 Subject: [PATCH] fix memory leak in require.cache cleanup --- .../nextjs-require-cache-hot-reloader.ts | 46 ++++++++++--------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/packages/next/src/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts b/packages/next/src/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts index f14071a5df009..da098043c0f5b 100644 --- a/packages/next/src/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts +++ b/packages/next/src/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts @@ -12,6 +12,7 @@ const originModules = [ require.resolve('../../../server/require'), require.resolve('../../../server/load-components'), require.resolve('../../../server/next-server'), + require.resolve('../../../server/app-renderer/use-flight-response'), require.resolve('../../../compiled/react-server-dom-webpack/client.edge'), require.resolve( '../../../compiled/react-server-dom-webpack-experimental/client.edge' @@ -20,27 +21,7 @@ const originModules = [ const RUNTIME_NAMES = ['webpack-runtime', 'webpack-api-runtime'] -export function deleteAppClientCache() { - // ensure we reset the cache for rsc components - // loaded via react-server-dom-webpack - const reactServerDomModId = require.resolve( - 'react-server-dom-webpack/client.edge' - ) - const reactServerDomMod = require.cache[reactServerDomModId] - - if (reactServerDomMod) { - for (const child of reactServerDomMod.children) { - child.parent = null - delete require.cache[child.id] - } - } - delete require.cache[reactServerDomModId] -} - -export function deleteCache(filePath: string) { - // try to clear it from the fs cache - clearManifestCache(filePath) - +function deleteFromRequireCache(filePath: string) { try { filePath = realpathSync(filePath) } catch (e) { @@ -66,6 +47,29 @@ export function deleteCache(filePath: string) { return false } +export function deleteAppClientCache() { + // ensure we reset the cache for rsc components + // loaded via react-server-dom-webpack + const reactServerDomModId = require.resolve( + 'react-server-dom-webpack/client.edge' + ) + const reactServerDomMod = require.cache[reactServerDomModId] + + if (reactServerDomMod) { + for (const child of [...reactServerDomMod.children]) { + deleteFromRequireCache(child.id) + } + deleteFromRequireCache(reactServerDomModId) + } +} + +export function deleteCache(filePath: string) { + // try to clear it from the fs cache + clearManifestCache(filePath) + + deleteFromRequireCache(filePath) +} + const PLUGIN_NAME = 'NextJsRequireCacheHotReloader' // This plugin flushes require.cache after emitting the files. Providing 'hot reloading' of server files.