import Module from 'module' ; import path from 'path' ; import { homedir } from 'os' ; import { existsSync , readFileSync , writeFileSync } from 'fs' ; import loading from './loading' ; import { LooseObject } from '@balm-core/index' ; const _require = Module . prototype . require ; const SAVE_FILE = path . join ( homedir ( ) , process . env . BALM_CORE_CACHE || '.balm-core-cache.json' ) ; function cacheBalmCore ( ) { let nameCache ; let originLastFilename ; try { nameCache = existsSync ( SAVE_FILE ) ? JSON . parse ( readFileSync ( SAVE_FILE , 'utf-8' ) ) : { } ; originLastFilename = nameCache . lastFilename || '' ; } catch ( err ) { nameCache = { } ; } let currentModuleCache ; let pathToLoad ; ( Module as any ) . prototype . require = function cachePathsRequire ( name ) { currentModuleCache = nameCache [ this . filename ] ; if ( ! currentModuleCache ) { currentModuleCache = { } ; if ( /\/balm-core\// . test ( this . filename ) ) { nameCache [ this . filename ] = currentModuleCache ; nameCache . lastFilename = this . filename ; } } if ( currentModuleCache [ name ] && typeof currentModuleCache [ name ] === 'string' && existsSync ( currentModuleCache [ name ] ) ) { pathToLoad = currentModuleCache [ name ] ; } else { pathToLoad = ( Module as any ) . _resolveFilename ( name , this ) ; currentModuleCache [ name ] = pathToLoad ; } if ( BalmJS . loading ) { loading . render ( ) ; } return _require . call ( this , pathToLoad ) ; } ; BalmJS . emitter . once ( 'exit' , function ( ) { if ( nameCache . lastFilename !== originLastFilename ) { try { writeFileSync ( SAVE_FILE , JSON . stringify ( nameCache , null , 2 ) , 'utf-8' ) ; } catch ( error ) { const err = error as Error ; console . error ( `BalmJS: Failed saving cache: ${ err . toString ( ) }` ) ; } } } ) ; } export default cacheBalmCore ;