import EventEmitter from 'events' ; import { Stream , Writable , WritableOptions } from 'stream' ; import { Callback , ensurePromiseCallback } from './callback' ; import { handleData , handleError , toStream } from './internals' ; import { defaultOptions , FastImageError , ImageInfo , Options } from './models' ; import { FastImageStream } from './stream' ; export async function info ( source , options ? , cb ? ) { if ( typeof options === 'function' ) { cb = options ; options = { } ; } const { timeout , threshold , userAgent } = { ... defaultOptions , ... options } ; let finished = false ; let buffer = Buffer . alloc ( 0 ) ; const [ callback , promise ] = ensurePromiseCallback ( cb ) ; const start = process . hrtime . bigint ( ) ; try { const aborter = new EventEmitter ( ) ; const [ stream , url , headers ] = await toStream ( source , timeout , threshold , userAgent , aborter ) ; stream . on ( 'data' , ( chunk ) => { if ( finished ) { return ; } buffer = Buffer . concat ( [ buffer , chunk ] ) ; finished = handleData ( buffer , headers , threshold , start , aborter , callback ) ; } ) ; stream . on ( 'error' , ( error ) => { callback ( handleError ( error , url ! ) ) ; } ) ; stream . on ( 'end' , ( ) => { if ( finished ) { return ; } callback ( new FastImageError ( 'Unsupported data.' , 'UNSUPPORTED' ) ) ; } ) ; return promise ! ; } catch ( e ) { callback ( e ) ; return promise ! ; } } export function stream ( options ? ) { return new FastImageStream ( options ?? { } ) ; }