import path from 'path' ; import fs from 'fs' ; import sharp , { OutputInfo , Metadata } from 'sharp' ; import rimraf from 'rimraf' ; const keepImageOutput = process . env . KEEP_IMAGE_OUTPUT === 'true' ; let basePath ; let tmpFolder ; /**
 * Cleans up after the test
 */ export const cleanup = ( force = false ) : void => { if ( ! keepImageOutput || force ) { rimraf . sync ( tmpFolder ) ; } } ; param { string } nextBasePath export const initTestUtils = ( nextBasePath ) : void => { basePath = nextBasePath ; tmpFolder = path . resolve ( basePath , keepImageOutput ? 'out' : 'tmp' ) ; cleanup ( true ) ; } ; param { string } fileName returns { Promise < { data : Buffer ; info : OutputInfo } > } export const getImage = async ( fileName ) : Promise < { data : Buffer ; info : OutputInfo ; } > => { return sharp ( path . resolve ( basePath , fileName ) ) . toBuffer ( { resolveWithObject : true } ) ; } ; param { string } fileName returns { Buffer } export const getImageFile = ( fileName ) : Buffer => { return fs . readFileSync ( path . resolve ( basePath , fileName ) ) ; } ; param { string } fileName returns { Promise < { data : Buffer ; info : OutputInfo } } export const getRawImage = async ( fileName ) : Promise < { data : Buffer ; info : OutputInfo ; } > => { return sharp ( path . resolve ( basePath , fileName ) ) . raw ( ) . toBuffer ( { resolveWithObject : true } ) ; } ; param { string } fileName returns { Promise < Metadata > } export const getImageMetadata = async ( fileName ) : Promise < Metadata > => { return sharp ( path . resolve ( basePath , fileName ) ) . metadata ( ) ; } ; param { string } fileName returns { number } export const getFileSize = ( fileName ) : number => { return fs . statSync ( path . resolve ( basePath , fileName ) ) . size ; } ; param { Buffer } data param { string } fileName returns { string } export const writeTmpBuffer = ( data , fileName ) : string => { const outputPath = path . resolve ( tmpFolder , fileName ) ; if ( ! fs . existsSync ( tmpFolder ) ) { fs . mkdirSync ( tmpFolder ) ; } fs . writeFileSync ( outputPath , data ) ; return `${ keepImageOutput ? 'out' : 'tmp' }/${ fileName }` ; } ;