import wasmLoader , { GlueModule , PostRunModule , PreRunModule , } from "./WasmModule.js" ; export { GlueModule } from "./WasmModule.js" ; type Deletable = { delete ( ) : void ; } ; type Scope = Deletable [ ] ; const scopeStack = [ ] ; function pushScope ( ) { scopeStack . push ( [ ] ) ; } function currentScope ( ) { return scopeStack [ scopeStack . length - 1 ] ; } function popScope ( ) { const scope = scopeStack . pop ( ) ; if ( scope ) { for ( const v of scope ) { v . delete ( ) ; } } else { console . warn ( "wasm scope underflow" ) ; } } let loaded ; let wasmModule ; /**
 * Returns a promise that will resolve after the main method has finished
 */ function getWasm ( ) { if ( wasmModule ) { return Promise . resolve ( wasmModule ) ; } else { return new Promise < GlueModule > ( ( res , rej ) => { if ( wasmModule ) { res ( wasmModule ) ; } else { loaded = loaded || wasmLoader ( ) ; loaded . then ( ( module ) => { if ( ! wasmModule ) { module . callMain ( ) ; module . setConstructCallback ( ( v ) => currentScope ( ) ?. push ( v ) ) ; wasmModule = module ; ( loaded as any ) [ "then" ] = undefined ; } res ( wasmModule ) ; } ) ; } } ) ; } } param idx export function __getCurrentWasmScope ( idx = 0 ) { return scopeStack [ scopeStack . length - 1 - idx ] ; } /**
 * get the scope stack size for debugging and testing
 */ export function __getCurrentWasmScopeStackSize ( ) { return scopeStack . length ; } param value export function persistWasmValue < V > ( value ) { const scope = currentScope ( ) ; if ( scope ) { const idx = scope . indexOf ( ( value as any ) [ "__glue_instance" ] ) ; if ( idx != - 1 ) { scope . splice ( idx , 1 ) ; } else { console . error ( `could not persist value: value not found in current scope.` ) ; } } else { console . error ( `persisting a value outside of the current scope.` ) ; } return value ; } /**
 * delete persisted values
 */ export function deletePersistedValue ( value ) { ( value as Deletable ) . delete ( ) ; } param callback export function withWasmScope < R > ( callback ) { pushScope ( ) ; let result ; try { result = callback ( ) ; } catch ( error ) { if ( typeof error === "number" ) { throw new Error ( wasmModule ! . getExceptionMessage ( error ) ) ; } else { throw error ; } } finally { popScope ( ) ; } return result ; } param callback export async function withWasm < R > ( callback ) { const glue = await getWasm ( ) ; return withWasmScope ( ( ) => callback ( glue ) ) ; }