@@ -53,21 +53,61 @@ const NODE_FALLBACK_ENABLED = typeof process !== 'undefined' && process.env && (
5353let nodeExtractorPromise = null ;
5454let nodeExtractorError = null ;
5555
56+ function createSharpStub ( ) {
57+ const stub = function sharpUnavailable ( ) {
58+ throw new Error ( 'sharp unavailable' ) ;
59+ } ;
60+ stub . default = stub ;
61+ return stub ;
62+ }
63+
64+ function withSharpStub ( loadFn ) {
65+ if ( typeof require !== 'function' ) {
66+ return loadFn ( ) ;
67+ }
68+ let Module = null ;
69+ try {
70+ Module = require ( 'module' ) ;
71+ } catch ( err ) {
72+ return loadFn ( ) ;
73+ }
74+ let sharpPath = null ;
75+ try {
76+ sharpPath = require . resolve ( 'sharp' ) ;
77+ } catch ( err ) {
78+ return loadFn ( ) ;
79+ }
80+ const existing = require . cache [ sharpPath ] ;
81+ const stubModule = new Module ( sharpPath ) ;
82+ stubModule . exports = createSharpStub ( ) ;
83+ stubModule . loaded = true ;
84+ require . cache [ sharpPath ] = stubModule ;
85+ try {
86+ return loadFn ( ) ;
87+ } finally {
88+ if ( existing ) {
89+ require . cache [ sharpPath ] = existing ;
90+ } else {
91+ delete require . cache [ sharpPath ] ;
92+ }
93+ }
94+ }
95+
5696async function getNodeExtractor ( ) {
5797 if ( ! NODE_FALLBACK_ENABLED ) return null ;
5898 if ( ! nodeExtractorPromise ) {
5999 nodeExtractorPromise = ( async ( ) => {
60100 let mod = null ;
61101 try {
62102 if ( typeof require === 'function' ) {
63- mod = require ( '@xenova/transformers' ) ;
103+ mod = withSharpStub ( ( ) => require ( '@xenova/transformers' ) ) ;
64104 } else {
65- mod = await import ( '@xenova/transformers' ) ;
105+ mod = await withSharpStub ( ( ) => import ( '@xenova/transformers' ) ) ;
66106 }
67107 } catch ( primaryErr ) {
68108 // Fallback to dynamic import if require failed, or vice versa
69109 try {
70- mod = await import ( '@xenova/transformers' ) ;
110+ mod = await withSharpStub ( ( ) => import ( '@xenova/transformers' ) ) ;
71111 } catch ( importErr ) {
72112 throw importErr || primaryErr ;
73113 }
0 commit comments