@@ -4,26 +4,47 @@ const errorLogger = require('./error-logger');
4
4
const { getCache, setCache } = require ( './cache' ) ;
5
5
const defaultDimensions = { width : 600 , height : 400 } ;
6
6
7
+ // Minimum required bytes for common image formats (approximate)
8
+ const imageMinBytes = {
9
+ jpg : 410 ,
10
+ png : 33 ,
11
+ gif : 14 ,
12
+ webp : 30 ,
13
+ bmp : 26 ,
14
+ default : 256 // Fallback for other image types
15
+ } ;
16
+
7
17
const probeImage = async url => {
8
18
const response = await fetch ( url ) ;
9
19
if ( ! response . ok )
10
20
throw new Error ( `Failed to fetch image: ${ response . statusText } ` ) ;
11
21
12
22
const chunks = [ ] ;
23
+ let totalLength = 0 ;
13
24
const reader = response . body ;
14
25
15
26
for await ( const chunk of reader ) {
16
27
chunks . push ( chunk ) ;
28
+ totalLength += chunk . length ;
17
29
18
30
try {
19
- // Try to determine image size with available data
20
- const dimensions = imageSize ( Buffer . concat ( chunks ) ) ;
31
+ const buffer = Buffer . concat ( chunks , totalLength ) ;
32
+
33
+ // Try to detect image format (first few bytes)
34
+ const { type } = imageSize ( buffer ) ;
35
+ const minBytes = imageMinBytes [ type ] || imageMinBytes . default ;
36
+
37
+ // Check buffer length before probing image
38
+ if ( buffer . length < minBytes ) continue ;
39
+
40
+ // Get dimensions
41
+ const dimensions = imageSize ( buffer ) ;
21
42
if ( dimensions . width && dimensions . height ) {
22
- response . body . destroy ( ) ; // Stop data stream
43
+ response . body . destroy ( ) ; // Stop downloading
23
44
return dimensions ;
24
45
}
25
46
} catch ( err ) {
26
- // Keep reading if more data is needed
47
+ // Continue reading if more data is needed
27
48
}
28
49
}
29
50
0 commit comments