@@ -64,6 +64,43 @@ const CACHE_COMPRESS_LEVEL = 4;
6464const CACHE_DIR = path . join ( root , '.next' , 'cache' , 'mdx-bundler' ) ;
6565if ( process . env . CI ) {
6666 mkdirSync ( CACHE_DIR , { recursive : true } ) ;
67+
68+ // Clean up old cache files in background to prevent unbounded growth
69+ // This runs once per worker process and doesn't block the build
70+ ( async ( ) => {
71+ try {
72+ const MAX_CACHE_AGE_MS = 7 * 24 * 60 * 60 * 1000 ; // 7 days
73+ const now = Date . now ( ) ;
74+ let cleanedCount = 0 ;
75+
76+ const { opendir, rm, stat} = await import ( 'node:fs/promises' ) ;
77+ const dir = await opendir ( CACHE_DIR ) ;
78+
79+ for await ( const dirent of dir ) {
80+ if ( ! dirent . isFile ( ) && ! dirent . isDirectory ( ) ) continue ;
81+
82+ const itemPath = path . join ( CACHE_DIR , dirent . name ) ;
83+ try {
84+ const stats = await stat ( itemPath ) ;
85+ const age = now - stats . atimeMs ; // Time since last access
86+
87+ if ( age > MAX_CACHE_AGE_MS ) {
88+ await rm ( itemPath , { recursive : true , force : true } ) ;
89+ cleanedCount ++ ;
90+ }
91+ } catch ( err ) {
92+ // Skip items we can't stat/delete
93+ }
94+ }
95+
96+ if ( cleanedCount > 0 ) {
97+ // eslint-disable-next-line no-console
98+ console . log ( `🧹 MDX cache: Cleaned up ${ cleanedCount } old items (>7 days)` ) ;
99+ }
100+ } catch ( err ) {
101+ // Silently fail - cache cleanup is not critical
102+ }
103+ } ) ( ) ;
67104}
68105
69106const md5 = ( data : BinaryLike ) => createHash ( 'md5' ) . update ( data ) . digest ( 'hex' ) ;
0 commit comments