@@ -12,8 +12,31 @@ const wasmHelperId = '\0vite/wasm-helper.js'
1212const wasmInitRE = / (?< ! [ ? # ] .* ) \. w a s m \? i n i t /
1313const wasmDirectRE = / (?< ! [ ? # ] .* ) \. w a s m $ /
1414
15+ // Lower "instance" layer of a directly imported `.wasm` module that exports a
16+ // WebAssembly.Global. It owns the WebAssembly.Instance and exposes exports
17+ // verbatim (globals stay WebAssembly.Global objects), so that wasm-to-wasm
18+ // global imports receive the actual Global. The user-facing `.wasm` module is a
19+ // thin wrapper around this layer that unwraps globals for JS consumers.
20+ const wasmInstanceSuffix = '?vite-wasm-instance'
21+ const wasmInstanceRE = / [ ? & ] v i t e - w a s m - i n s t a n c e (?: & | $ ) /
22+
1523const wasmInitUrlRE : RegExp = / _ _ V I T E _ W A S M _ I N I T _ _ ( [ \w $ ] + ) _ _ / g
1624
25+ // Enabled per spec
26+ const wasmCompileOptions = {
27+ builtins : [ 'js-string' ] ,
28+ importedStringConstants : 'wasm:js/string-constants' ,
29+ }
30+
31+ // Modules satisfied by the engine when the above proposals are enabled. They
32+ // must never surface as JS imports in the generated glue. The host Node running
33+ // `parseWasm` may not support these proposals yet (older versions), in which
34+ // case `WebAssembly.Module.imports` still reports them, so we filter explicitly.
35+ const wasmReservedModules = new Set < string > ( [
36+ ...wasmCompileOptions . builtins . map ( ( name ) => `wasm:${ name } ` ) ,
37+ wasmCompileOptions . importedStringConstants ,
38+ ] )
39+
1740const wasmHelper = async ( opts = { } , url : string ) => {
1841 let result
1942 if ( url . startsWith ( 'data:' ) ) {
@@ -32,7 +55,7 @@ const wasmHelper = async (opts = {}, url: string) => {
3255 'Failed to decode base64-encoded data URL, Buffer and atob are not supported' ,
3356 )
3457 }
35- result = await WebAssembly . instantiate ( bytes , opts )
58+ result = await WebAssembly . instantiate ( bytes , opts , wasmCompileOptions )
3659 } else {
3760 result = await instantiateFromUrl ( url , opts )
3861 }
@@ -53,10 +76,10 @@ const instantiateFromUrl = async (url: string, opts?: WebAssembly.Imports) => {
5376 'instantiateStreaming' in WebAssembly &&
5477 contentType . startsWith ( 'application/wasm' )
5578 ) {
56- return WebAssembly . instantiateStreaming ( response , opts )
79+ return WebAssembly . instantiateStreaming ( response , opts , wasmCompileOptions )
5780 } else {
5881 const buffer = await response . arrayBuffer ( )
59- return WebAssembly . instantiate ( buffer , opts )
82+ return WebAssembly . instantiate ( buffer , opts , wasmCompileOptions )
6083 }
6184}
6285
@@ -69,7 +92,7 @@ const instantiateFromFile = async (
6992 const { readFile } = await import ( 'node:fs/promises' )
7093 const fileUrl = new URL ( fileUrlString , /** #__KEEP__ */ import . meta. url )
7194 const buffer = await readFile ( fileUrl )
72- return WebAssembly . instantiate ( buffer , opts )
95+ return WebAssembly . instantiate ( buffer , opts , wasmCompileOptions )
7396}
7497
7598const instantiateFromFileCode = instantiateFromFile . toString ( )
@@ -87,19 +110,43 @@ export const wasmHelperPlugin = (): Plugin => {
87110 } ,
88111
89112 load : {
90- filter : { id : [ exactRegex ( wasmHelperId ) , wasmInitRE , wasmDirectRE ] } ,
113+ filter : {
114+ id : [
115+ exactRegex ( wasmHelperId ) ,
116+ wasmInitRE ,
117+ wasmDirectRE ,
118+ wasmInstanceRE ,
119+ ] ,
120+ } ,
91121 async handler ( id ) {
92122 const ssr = this . environment . config . consumer === 'server'
93123
94124 if ( id === wasmHelperId ) {
95125 return `
126+ const wasmCompileOptions = ${ JSON . stringify ( wasmCompileOptions ) }
96127const instantiateFromUrl = ${ ssr ? instantiateFromFileCode : instantiateFromUrlCode }
97128export default ${ wasmHelperCode }
98129`
99130 }
100131
101132 const isInit = wasmInitRE . test ( id )
102- const cleanedId = id . split ( '?' ) [ 0 ]
133+ const isInstance = wasmInstanceRE . test ( id )
134+ const cleanedId = isInstance ? cleanUrl ( id ) : id . split ( '?' ) [ 0 ]
135+
136+ // Direct .wasm import (WASM ESM Integration)
137+ let wasmInfo : WasmInfo | undefined
138+ if ( ! isInit ) {
139+ wasmInfo = await parseWasm ( cleanedId )
140+ // The user-facing module of a wasm that exports a global is a thin
141+ // wrapper that re-exports the instance layer, unwrapping globals for JS.
142+ if ( ! isInstance && wasmInfo . hasGlobalExport ) {
143+ return generateWrapperGlue (
144+ wasmInfo ,
145+ cleanedId + wasmInstanceSuffix ,
146+ )
147+ }
148+ }
149+
103150 let url = await fileToUrl ( this , cleanedId , ssr )
104151 assetUrlRE . lastIndex = 0
105152 if ( ssr && assetUrlRE . test ( url ) ) {
@@ -113,9 +160,7 @@ export default ${wasmHelperCode}
113160 `
114161 }
115162
116- // Direct .wasm import (WASM ESM Integration)
117- const wasmInfo = await parseWasm ( cleanedId )
118- const glueCode = generateGlueCode ( wasmInfo , {
163+ const glueCode = generateInstanceGlue ( wasmInfo ! , {
119164 initWasm : '__vite__initWasm' ,
120165 wasmUrl : '__vite__wasmUrl' ,
121166 } )
@@ -179,33 +224,41 @@ ${glueCode}
179224 } )
180225}
181226
227+ interface WasmName {
228+ name : string
229+ isGlobal : boolean
230+ }
231+
182232interface WasmInfo {
183233 imports : {
184234 from : string
185- names : string [ ]
235+ names : WasmName [ ]
186236 } [ ]
187- exports : string [ ]
237+ exports : WasmName [ ]
238+ hasGlobalExport : boolean
188239}
189240
190241async function parseWasm ( wasmFilePath : string ) : Promise < WasmInfo > {
191242 try {
192243 const wasmBinary = await fsp . readFile ( wasmFilePath )
193- const wasmModule = await WebAssembly . compile ( wasmBinary )
194- const importMap : Record < string , string [ ] > = Object . create ( null )
244+ const wasmModule = await WebAssembly . compile ( wasmBinary , wasmCompileOptions )
245+ const importMap = new Map < string , WasmName [ ] > ( )
195246 for ( const item of WebAssembly . Module . imports ( wasmModule ) ) {
196- importMap [ item . module ] ??= [ ]
197- importMap [ item . module ] . push ( item . name )
247+ if ( wasmReservedModules . has ( item . module ) ) continue
248+ let names = importMap . get ( item . module )
249+ if ( ! names ) importMap . set ( item . module , ( names = [ ] ) )
250+ names . push ( { name : item . name , isGlobal : item . kind === 'global' } )
198251 }
199- const imports = Object . entries ( importMap ) . map ( ( [ from , names ] ) => ( {
200- from,
201- names,
202- } ) )
252+ const imports = [ ...importMap ] . map ( ( [ from , names ] ) => ( { from, names } ) )
203253
204- const exports = WebAssembly . Module . exports ( wasmModule ) . map (
205- ( item ) => item . name ,
206- )
254+ let hasGlobalExport = false
255+ const exports = WebAssembly . Module . exports ( wasmModule ) . map ( ( item ) => {
256+ const isGlobal = item . kind === 'global'
257+ if ( isGlobal ) hasGlobalExport = true
258+ return { name : item . name , isGlobal }
259+ } )
207260
208- return { imports, exports }
261+ return { imports, exports, hasGlobalExport }
209262 } catch ( e ) {
210263 throw new Error (
211264 `Failed to parse WASM file "${ wasmFilePath } ": ${ ( e as Error ) . message } ` ,
@@ -214,25 +267,43 @@ async function parseWasm(wasmFilePath: string): Promise<WasmInfo> {
214267 }
215268}
216269
217- function generateGlueCode (
270+ // Instantiates the wasm module and re-exports its exports verbatim. Globals stay
271+ // WebAssembly.Global objects so wasm-to-wasm global imports get the live cell.
272+ function generateInstanceGlue (
218273 wasmInfo : WasmInfo ,
219274 names : { initWasm : string ; wasmUrl : string } ,
220275) : string {
221- const importStatements = wasmInfo . imports . map ( ( { from } , i ) => {
222- return `import * as __vite__wasmImport_${ i } from ${ JSON . stringify ( from ) } ;`
223- } )
224-
276+ const importStatements : string [ ] = [ ]
225277 const importObject : SimpleObject = wasmInfo . imports . map (
226278 ( { from, names : importNames } , i ) => {
227- return {
228- key : JSON . stringify ( from ) ,
229- value : importNames . map ( ( name ) => {
230- return {
279+ const value : SimpleObject = [ ]
280+ const globals = importNames . filter ( ( n ) => n . isGlobal )
281+ const others = importNames . filter ( ( n ) => ! n . isGlobal )
282+ if ( others . length > 0 ) {
283+ const ns = `__vite__wasmImport_${ i } `
284+ importStatements . push ( `import * as ${ ns } from ${ JSON . stringify ( from ) } ;` )
285+ for ( const { name } of others ) {
286+ value . push ( {
231287 key : JSON . stringify ( name ) ,
232- value : `__vite__wasmImport_${ i } [${ JSON . stringify ( name ) } ]` ,
233- }
234- } ) ,
288+ value : `${ ns } [${ JSON . stringify ( name ) } ]` ,
289+ } )
290+ }
291+ }
292+ if ( globals . length > 0 ) {
293+ // Wasm global imports need the WebAssembly.Global object, so import them
294+ // from the exporter's instance layer instead of its JS-unwrapped value.
295+ const ns = `__vite__wasmImportInstance_${ i } `
296+ importStatements . push (
297+ `import * as ${ ns } from ${ JSON . stringify ( from + wasmInstanceSuffix ) } ;` ,
298+ )
299+ for ( const { name } of globals ) {
300+ value . push ( {
301+ key : JSON . stringify ( name ) ,
302+ value : `${ ns } [${ JSON . stringify ( name ) } ]` ,
303+ } )
304+ }
235305 }
306+ return { key : JSON . stringify ( from ) , value }
236307 } ,
237308 )
238309
@@ -244,7 +315,7 @@ function generateGlueCode(
244315
245316 const exportStatements : string [ ] = [ ]
246317 const nameMap = new Map < string , string > ( )
247- for ( const [ index , name ] of wasmInfo . exports . entries ( ) ) {
318+ for ( const [ index , { name } ] of wasmInfo . exports . entries ( ) ) {
248319 if ( isValidJsDeclareName ( name ) ) {
249320 exportStatements . push ( ` ${ name } ,` )
250321 } else {
@@ -258,7 +329,7 @@ function generateGlueCode(
258329 exportStatements . unshift ( `const {` )
259330 exportStatements . push ( `} = __vite__wasmModule;` )
260331 exportStatements . push ( `export {` )
261- for ( const name of wasmInfo . exports ) {
332+ for ( const { name } of wasmInfo . exports ) {
262333 const localName = nameMap . get ( name )
263334 if ( localName ) {
264335 exportStatements . push ( ` ${ localName } as ${ JSON . stringify ( name ) } ,` )
@@ -275,6 +346,52 @@ function generateGlueCode(
275346 return [ ...importStatements , initCode , ...exportStatements ] . join ( '\n' )
276347}
277348
349+ // User-facing module of a wasm that exports a global. Re-exports the instance
350+ // layer and overrides each global with its unwrapped JS value.
351+ function generateWrapperGlue ( wasmInfo : WasmInfo , instanceId : string ) : string {
352+ const instanceIdLiteral = JSON . stringify ( instanceId )
353+ const lines = [ `export * from ${ instanceIdLiteral } ;` ]
354+
355+ // `export *` skips `default`, so re-export it explicitly when present.
356+ if ( wasmInfo . exports . some ( ( e ) => e . name === 'default' ) ) {
357+ lines . push ( `export { default } from ${ instanceIdLiteral } ;` )
358+ }
359+
360+ const imports : string [ ] = [ ]
361+ const bindings : string [ ] = [ ]
362+ const unwraps : string [ ] = [ ]
363+ const reExports : string [ ] = [ ]
364+ for ( const [ index , { name, isGlobal } ] of wasmInfo . exports . entries ( ) ) {
365+ if ( ! isGlobal || name === 'default' ) continue
366+ const alias = `__vite__wasmGlobal_${ index } `
367+ imports . push ( `${ codegenModuleExportName ( name ) } as ${ alias } ` )
368+ // Use the export name as the binding directly; only non-identifier names
369+ // need a separate aliased local.
370+ const binding = isValidJsDeclareName ( name )
371+ ? name
372+ : `__vite__wasmGlobalValue_${ index } `
373+ bindings . push ( binding )
374+ // v128 globals throw in GetGlobalValue and have no JS value, so stay undefined.
375+ unwraps . push ( `try { ${ binding } = ${ alias } .value; } catch {}` )
376+ reExports . push (
377+ binding === name ? name : `${ binding } as ${ JSON . stringify ( name ) } ` ,
378+ )
379+ }
380+
381+ if ( bindings . length > 0 ) {
382+ lines . push ( `import { ${ imports . join ( ', ' ) } } from ${ instanceIdLiteral } ;` )
383+ lines . push ( `let ${ bindings . join ( ', ' ) } ;` )
384+ lines . push ( ...unwraps )
385+ lines . push ( `export { ${ reExports . join ( ', ' ) } };` )
386+ }
387+
388+ return lines . join ( '\n' )
389+ }
390+
391+ function codegenModuleExportName ( name : string ) : string {
392+ return isValidJsDeclareName ( name ) ? name : JSON . stringify ( name )
393+ }
394+
278395type SimpleObject = SimpleObjectKeyValue [ ]
279396
280397interface SimpleObjectKeyValue {
0 commit comments