import { promises as fs } from 'fs' ; interface ExportRecord { require : string ; import : string ; } /**
 * Add './' to export
 */ function formatExport ( path ) { return path . slice ( 0 , 2 ) === './' ? path : './' + path ; } /**
 * Update package.json
 */ export async function updatePackageJSON ( root , target , files ) { const packageData = JSON . parse ( await fs . readFile ( root + 'package.json' , 'utf8' ) ) ; const data = { './*' : './*' , } ; if ( packageData . main && packageData . module ) { data [ '.' ] = { require : formatExport ( packageData . main ) , import : formatExport ( packageData . module ) , } ; } const dirKeys = new Set ( ) ; files . forEach ( ( file ) => { const key = formatExport ( target + file ) ; const parts = key . split ( '/' ) ; if ( parts . pop ( ) === 'index' ) { const dirKey = parts . join ( '/' ) ; dirKeys . add ( dirKey ) ; if ( ! data [ dirKey ] ) { data [ dirKey ] = { require : key + '.js' , import : key + '.mjs' , } ; } } if ( data [ key ] && ! dirKeys . has ( key ) ) { throw new Error ( `Duplicate entries for ${ key } in exports` ) ; } data [ key ] = { require : key + '.js' , import : key + '.mjs' , } ; } ) ; if ( packageData [ 'exports' ] && JSON . stringify ( packageData [ 'exports' ] ) === JSON . stringify ( data ) ) { return ; } packageData . exports = data ; const content = JSON . stringify ( packageData , null , '\t' ) + '\n' ; await fs . writeFile ( 'package.json' , content , 'utf8' ) ; console . log ( 'Updated exports in package.json' ) ; }