type Input = string | HTMLImageElement ; type Output = HTMLImageElement ; type Attributes = Record < string , string > ; type ImagePromise = Promise < HTMLImageElement > & { image : HTMLImageElement ; } ; function isArrayLike ( input ) { return input . length !== undefined ; } function loadSingleImage ( image ) { const promise = new Promise < HTMLImageElement > ( ( resolve , reject ) => { if ( image . naturalWidth ) { resolve ( image ) ; } else if ( image . complete ) { reject ( image ) ; } else { image . addEventListener ( 'load' , fulfill ) ; image . addEventListener ( 'error' , fulfill ) ; } function fulfill ( ) { if ( image . naturalWidth ) { resolve ( image ) ; } else { reject ( image ) ; } image . removeEventListener ( 'load' , fulfill ) ; image . removeEventListener ( 'error' , fulfill ) ; } } ) ; return Object . assign ( promise , { image } ) ; } function loadImages ( input , attributes ? ) ; function loadImages ( input , attributes ? ) ; function loadImages ( input , attributes = { } ) { if ( input instanceof HTMLImageElement ) { return loadSingleImage ( input ) ; } if ( typeof input === 'string' ) { const src = input ; const image = new Image ( ) ; Object . keys ( attributes ) . forEach ( name => image . setAttribute ( name , attributes [ name ] ) ) ; image . src = src ; return loadSingleImage ( image ) ; } if ( isArrayLike ( input ) ) { const reflect = ( img ) : Promise < HTMLImageElement | Error > => loadImages ( img , attributes ) . catch ( ( error ) => error ) ; const reflected = [ ] . map . call ( input , reflect ) as Array < HTMLImageElement | Error > ; const tsFix = Promise . all ( reflected ) . then ( ( results ) => { const loaded = results . filter ( ( x ) : x is HTMLImageElement => x . naturalWidth ) ; if ( loaded . length === results . length ) { return loaded ; } return Promise . reject ( { loaded , errored : results . filter ( ( x ) : x is Error => ! x . naturalWidth ) } ) ; } ) ; return tsFix ; } const tsFix = Promise . reject ( new TypeError ( 'input is not an image, a URL string, or an array of them.' ) ) ; return tsFix ; } export default loadImages ;