1
- const probe = require ( 'probe-image-size' ) ;
1
+ const fetch = require ( 'node-fetch' ) ;
2
+ const { imageSize } = require ( 'image-size' ) ;
2
3
const errorLogger = require ( './error-logger' ) ;
3
4
const { getCache, setCache } = require ( './cache' ) ;
4
5
const defaultDimensions = { width : 600 , height : 400 } ;
5
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
+
17
+ const probeImage = async url => {
18
+ const response = await fetch ( url ) ;
19
+ if ( ! response . ok )
20
+ throw new Error ( `Failed to fetch image: ${ response . statusText } ` ) ;
21
+
22
+ const chunks = [ ] ;
23
+ let totalLength = 0 ;
24
+ const reader = response . body ;
25
+
26
+ for await ( const chunk of reader ) {
27
+ chunks . push ( chunk ) ;
28
+ totalLength += chunk . length ;
29
+
30
+ try {
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 ) ;
42
+ if ( dimensions . width && dimensions . height ) {
43
+ response . body . destroy ( ) ; // Stop downloading
44
+ return dimensions ;
45
+ }
46
+ } catch ( err ) {
47
+ // Continue reading if more data is needed
48
+ }
49
+ }
50
+
51
+ throw new Error ( 'Could not determine image size' ) ;
52
+ } ;
53
+
6
54
const getImageDimensions = async ( url , description ) => {
7
55
try {
56
+ if ( url . startsWith ( 'data:' ) ) {
57
+ console . warn ( `
58
+ ---------------------------------------------------------------
59
+ Warning: Skipping data URL for image dimensions in ${ description . substring ( 0 , 350 ) } ...
60
+ ---------------------------------------------------------------
61
+ ` ) ;
62
+
63
+ throw new Error ( 'Data URL' ) ;
64
+ }
8
65
let imageDimensions = getCache ( url ) ;
9
66
if ( imageDimensions ) return imageDimensions ;
10
67
11
- const res = await probe ( url ) ;
68
+ const res = await probeImage ( url ) ;
12
69
imageDimensions = {
13
70
width : res ?. width ? res ?. width : defaultDimensions . width ,
14
71
height : res ?. height ? res ?. height : defaultDimensions . height
@@ -17,7 +74,7 @@ const getImageDimensions = async (url, description) => {
17
74
18
75
return imageDimensions ;
19
76
} catch ( err ) {
20
- if ( err . statusCode ) errorLogger ( { type : 'image' , name : description } ) ; // Only write HTTP status code errors to log
77
+ errorLogger ( { type : 'image' , name : description } ) ;
21
78
22
79
return defaultDimensions ;
23
80
}
0 commit comments