11import type { SatoriOptions } from 'satori'
2+ import type { JpegOptions } from 'sharp'
23import type { OgImageRenderEventContext , Renderer , ResolvedFontConfig } from '../../../types'
34import { fontCache } from '#og-image-cache'
45import { theme } from '#og-image-virtual/unocss-config.mjs'
@@ -8,6 +9,8 @@ import { normaliseFontInput, useOgImageRuntimeConfig } from '../../../shared'
89import { loadFont } from './font'
910import { useResvg , useSatori , useSharp } from './instances'
1011import { createVNodes } from './vnodes'
12+ // @ts -expect-error untyped
13+ import compatibility from '#og-image/compatibility'
1114
1215const fontPromises : Record < string , Promise < ResolvedFontConfig > > = { }
1316
@@ -78,11 +81,35 @@ async function createPng(event: OgImageRenderEventContext) {
7881
7982async function createJpeg ( event : OgImageRenderEventContext ) {
8083 const { sharpOptions } = useOgImageRuntimeConfig ( )
81- const png = await createPng ( event )
82- const sharp = await useSharp ( )
83- return sharp ( png , defu ( event . options . sharp , sharpOptions ) ) . jpeg ( ) . toBuffer ( )
84- return sharp ( svgBuffer , defu ( event . options . sharp , sharpOptions ) )
85- . jpeg ( sharp as JpegOptions )
84+ if ( compatibility . sharp === false ) {
85+ if ( import . meta. dev ) {
86+ throw new Error ( 'Sharp dependency is not accessible. Please check you have it installed and are using a compatible runtime.' )
87+ }
88+ else {
89+ // TODO this should be an error in next major
90+ console . error ( 'Sharp dependency is not accessible. Please check you have it installed and are using a compatible runtime. Falling back to png.' )
91+ }
92+ return createPng ( event )
93+ }
94+ const svg = await createSvg ( event )
95+ if ( ! svg ) {
96+ throw new Error ( 'Failed to create SVG for JPEG rendering.' )
97+ }
98+ const svgBuffer = Buffer . from ( svg )
99+ const sharp = await useSharp ( ) . catch ( ( ) => {
100+ if ( import . meta. dev ) {
101+ throw new Error ( 'Sharp dependency could not be loaded. Please check you have it installed and are using a compatible runtime.' )
102+ }
103+ return null
104+ } )
105+ if ( ! sharp ) {
106+ // TODO this should be an error in next major
107+ console . error ( 'Sharp dependency is not accessible. Please check you have it installed and are using a compatible runtime. Falling back to png.' )
108+ return createPng ( event )
109+ }
110+ const options = defu ( event . options . sharp , sharpOptions )
111+ return sharp ( svgBuffer , options )
112+ . jpeg ( options as JpegOptions )
86113 . toBuffer ( )
87114}
88115
0 commit comments