import Gifsicle from './gifsicle' ; import { EncodeOptions } from './types' ; import { defaultEncodeOptions } from './options' ; import { stdout , stderr , flush } from './io' ; const queue = [ ] ; /**
 * Initialize the gifsicle module
 */ const initModule = ( ) : Promise < void > => { return new Promise ( ( resolve ) => { queue . push ( resolve ) ; if ( queue . length === 1 ) { queue [ 0 ] ( ) ; } } ) ; } ; /**
 * Reset the gifsicle module
 */ const resetModule = ( ) : void => { if ( queue . length > 0 ) { queue . shift ( ) ; if ( queue . length > 0 ) { queue [ 0 ] ( ) ; } } } ; async param { Buffer } image param { EncodeOptions } encodeOptions returns { Buffer } const encode = async ( image , encodeOptions = { } ) : Promise < Buffer > => { await initModule ( ) ; return new Promise ( ( resolve , reject ) => { const filledEncodeOptions = { ... defaultEncodeOptions , ... encodeOptions } ; const gifsicleArguments = [ '--no-warnings' , '--no-app-extensions' , `--optimize=${ filledEncodeOptions . optimizationLevel }` , filledEncodeOptions . interlaced === true ? '--interlace' : false , typeof filledEncodeOptions . colors === 'number' ? `--colors=${ filledEncodeOptions . colors }` : false , ... ( filledEncodeOptions . width || filledEncodeOptions . height ? [ '--resize' , `${ filledEncodeOptions . width || '_' }x${ filledEncodeOptions . height || '_' }` ] : [ ] ) , '-i' , '/input.gif' , '-o' , '/output.gif' , ] . filter ( Boolean ) ; let resolved = false ; Gifsicle ( { stdout , stderr , arguments : gifsicleArguments as string [ ] , input : new Uint8Array ( image . buffer ) , output : ( res ) => { resolve ( Buffer . from ( res ) ) ; resolved = true ; } , } ) . then ( ( ) => { flush ( ) ; if ( ! resolved ) { reject ( ) ; } resetModule ( ) ; } ) ; } ) ; } ; export default encode ; export type { EncodeOptions } from './types' ; module . exports = encode ;