import { Plugin , InternalModuleFormat , RenderChunkHook } from 'rollup' ; import { transform , CommonOptions , Format } from 'esbuild' ; import { warn } from './warn' ; const getEsbuildFormat = ( rollupFormat ) : Format | undefined => { if ( rollupFormat === 'es' ) { return 'esm' ; } if ( rollupFormat === 'cjs' ) { return rollupFormat ; } } ; export type Options = { sourceMap ? : boolean ; minify ? : boolean ; minifyWhitespace ? : boolean ; minifyIdentifiers ? : boolean ; minifySyntax ? : boolean ; keepNames ? : boolean ; legalComments ? : CommonOptions [ 'legalComments' ] ; target ? : CommonOptions [ 'target' ] ; } ; export const getRenderChunk = ( options ) : RenderChunkHook => async function ( code , _ , rollupOptions ) { if ( options . minify || options . minifyWhitespace || options . minifyIdentifiers || options . minifySyntax ) { const format = getEsbuildFormat ( rollupOptions . format ) ; const result = await transform ( code , { format , loader : 'js' , minify : options . minify , minifyWhitespace : options . minifyWhitespace , minifyIdentifiers : options . minifyIdentifiers , minifySyntax : options . minifySyntax , keepNames : options . keepNames , legalComments : options . legalComments , sourcemap : options . sourceMap !== false , target : options . target , } ) ; await warn ( this , result . warnings ) ; if ( result . code ) { return { code : result . code , map : result . map || null , } ; } } return null ; } ; export const minify = ( options = { } ) : Plugin => { let sourceMap = false ; return { name : 'esbuild-minify' , outputOptions ( { sourcemap } ) { sourceMap = options . sourceMap ?? ! ! sourcemap ; return null ; } , renderChunk : getRenderChunk ( { minify : true , ... options , sourceMap , } ) , } ; } ;