@ruby/4.0-wasm-wasi 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1556 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["ruby-wasm-wasi"] = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ const CLOCKID_REALTIME=0;const CLOCKID_MONOTONIC=1;const ERRNO_SUCCESS=0;const ERRNO_BADF=8;const ERRNO_EXIST=20;const ERRNO_INVAL=28;const ERRNO_ISDIR=31;const ERRNO_NAMETOOLONG=37;const ERRNO_NOENT=44;const ERRNO_NOSYS=52;const ERRNO_NOTDIR=54;const ERRNO_NOTEMPTY=55;const ERRNO_NOTSUP=58;const ERRNO_PERM=63;const ERRNO_NOTCAPABLE=76;const RIGHTS_FD_WRITE=1<<6;class Iovec{static read_bytes(view,ptr){const iovec=new Iovec;iovec.buf=view.getUint32(ptr,true);iovec.buf_len=view.getUint32(ptr+4,true);return iovec}static read_bytes_array(view,ptr,len){const iovecs=[];for(let i=0;i<len;i++){iovecs.push(Iovec.read_bytes(view,ptr+8*i));}return iovecs}}class Ciovec{static read_bytes(view,ptr){const iovec=new Ciovec;iovec.buf=view.getUint32(ptr,true);iovec.buf_len=view.getUint32(ptr+4,true);return iovec}static read_bytes_array(view,ptr,len){const iovecs=[];for(let i=0;i<len;i++){iovecs.push(Ciovec.read_bytes(view,ptr+8*i));}return iovecs}}const WHENCE_SET=0;const WHENCE_CUR=1;const WHENCE_END=2;const FILETYPE_DIRECTORY=3;const FILETYPE_REGULAR_FILE=4;class Dirent{head_length(){return 24}name_length(){return this.dir_name.byteLength}write_head_bytes(view,ptr){view.setBigUint64(ptr,this.d_next,true);view.setBigUint64(ptr+8,this.d_ino,true);view.setUint32(ptr+16,this.dir_name.length,true);view.setUint8(ptr+20,this.d_type);}write_name_bytes(view8,ptr,buf_len){view8.set(this.dir_name.slice(0,Math.min(this.dir_name.byteLength,buf_len)),ptr);}constructor(next_cookie,name,type){this.d_ino=0n;const encoded_name=new TextEncoder().encode(name);this.d_next=next_cookie;this.d_namlen=encoded_name.byteLength;this.d_type=type;this.dir_name=encoded_name;}}const FDFLAGS_APPEND=1<<0;class Fdstat{write_bytes(view,ptr){view.setUint8(ptr,this.fs_filetype);view.setUint16(ptr+2,this.fs_flags,true);view.setBigUint64(ptr+8,this.fs_rights_base,true);view.setBigUint64(ptr+16,this.fs_rights_inherited,true);}constructor(filetype,flags){this.fs_rights_base=0n;this.fs_rights_inherited=0n;this.fs_filetype=filetype;this.fs_flags=flags;}}const OFLAGS_CREAT=1<<0;const OFLAGS_DIRECTORY=1<<1;const OFLAGS_EXCL=1<<2;const OFLAGS_TRUNC=1<<3;class Filestat{write_bytes(view,ptr){view.setBigUint64(ptr,this.dev,true);view.setBigUint64(ptr+8,this.ino,true);view.setUint8(ptr+16,this.filetype);view.setBigUint64(ptr+24,this.nlink,true);view.setBigUint64(ptr+32,this.size,true);view.setBigUint64(ptr+38,this.atim,true);view.setBigUint64(ptr+46,this.mtim,true);view.setBigUint64(ptr+52,this.ctim,true);}constructor(filetype,size){this.dev=0n;this.ino=0n;this.nlink=0n;this.atim=0n;this.mtim=0n;this.ctim=0n;this.filetype=filetype;this.size=size;}}const PREOPENTYPE_DIR=0;class PrestatDir{write_bytes(view,ptr){view.setUint32(ptr,this.pr_name.byteLength,true);}constructor(name){this.pr_name=new TextEncoder().encode(name);}}class Prestat{static dir(name){const prestat=new Prestat;prestat.tag=PREOPENTYPE_DIR;prestat.inner=new PrestatDir(name);return prestat}write_bytes(view,ptr){view.setUint32(ptr,this.tag,true);this.inner.write_bytes(view,ptr+4);}}
8
+
9
+ let Debug=class Debug{enable(enabled){this.log=createLogger(enabled===undefined?true:enabled,this.prefix);}get enabled(){return this.isEnabled}constructor(isEnabled){this.isEnabled=isEnabled;this.prefix="wasi:";this.enable(isEnabled);}};function createLogger(enabled,prefix){if(enabled){const a=console.log.bind(console,"%c%s","color: #265BA0",prefix);return a}else {return ()=>{}}}const debug=new Debug(false);
10
+
11
+ class WASIProcExit extends Error{constructor(code){super("exit with exit code "+code);this.code=code;}}let WASI=class WASI{start(instance){this.inst=instance;try{instance.exports._start();return 0}catch(e){if(e instanceof WASIProcExit){return e.code}else {throw e}}}initialize(instance){this.inst=instance;if(instance.exports._initialize){instance.exports._initialize();}}constructor(args,env,fds,options={}){this.args=[];this.env=[];this.fds=[];debug.enable(options.debug);this.args=args;this.env=env;this.fds=fds;const self=this;this.wasiImport={args_sizes_get(argc,argv_buf_size){const buffer=new DataView(self.inst.exports.memory.buffer);buffer.setUint32(argc,self.args.length,true);let buf_size=0;for(const arg of self.args){buf_size+=arg.length+1;}buffer.setUint32(argv_buf_size,buf_size,true);debug.log(buffer.getUint32(argc,true),buffer.getUint32(argv_buf_size,true));return 0},args_get(argv,argv_buf){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);const orig_argv_buf=argv_buf;for(let i=0;i<self.args.length;i++){buffer.setUint32(argv,argv_buf,true);argv+=4;const arg=new TextEncoder().encode(self.args[i]);buffer8.set(arg,argv_buf);buffer.setUint8(argv_buf+arg.length,0);argv_buf+=arg.length+1;}if(debug.enabled){debug.log(new TextDecoder("utf-8").decode(buffer8.slice(orig_argv_buf,argv_buf)));}return 0},environ_sizes_get(environ_count,environ_size){const buffer=new DataView(self.inst.exports.memory.buffer);buffer.setUint32(environ_count,self.env.length,true);let buf_size=0;for(const environ of self.env){buf_size+=environ.length+1;}buffer.setUint32(environ_size,buf_size,true);debug.log(buffer.getUint32(environ_count,true),buffer.getUint32(environ_size,true));return 0},environ_get(environ,environ_buf){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);const orig_environ_buf=environ_buf;for(let i=0;i<self.env.length;i++){buffer.setUint32(environ,environ_buf,true);environ+=4;const e=new TextEncoder().encode(self.env[i]);buffer8.set(e,environ_buf);buffer.setUint8(environ_buf+e.length,0);environ_buf+=e.length+1;}if(debug.enabled){debug.log(new TextDecoder("utf-8").decode(buffer8.slice(orig_environ_buf,environ_buf)));}return 0},clock_res_get(id,res_ptr){let resolutionValue;switch(id){case CLOCKID_MONOTONIC:{resolutionValue=5000n;break}case CLOCKID_REALTIME:{resolutionValue=1000000n;break}default:return ERRNO_NOSYS}const view=new DataView(self.inst.exports.memory.buffer);view.setBigUint64(res_ptr,resolutionValue,true);return ERRNO_SUCCESS},clock_time_get(id,precision,time){const buffer=new DataView(self.inst.exports.memory.buffer);if(id===CLOCKID_REALTIME){buffer.setBigUint64(time,BigInt(new Date().getTime())*1000000n,true);}else if(id==CLOCKID_MONOTONIC){let monotonic_time;try{monotonic_time=BigInt(Math.round(performance.now()*1e6));}catch(e){monotonic_time=0n;}buffer.setBigUint64(time,monotonic_time,true);}else {buffer.setBigUint64(time,0n,true);}return 0},fd_advise(fd,offset,len,advice){if(self.fds[fd]!=undefined){return ERRNO_SUCCESS}else {return ERRNO_BADF}},fd_allocate(fd,offset,len){if(self.fds[fd]!=undefined){return self.fds[fd].fd_allocate(offset,len)}else {return ERRNO_BADF}},fd_close(fd){if(self.fds[fd]!=undefined){const ret=self.fds[fd].fd_close();self.fds[fd]=undefined;return ret}else {return ERRNO_BADF}},fd_datasync(fd){if(self.fds[fd]!=undefined){return self.fds[fd].fd_sync()}else {return ERRNO_BADF}},fd_fdstat_get(fd,fdstat_ptr){if(self.fds[fd]!=undefined){const{ret,fdstat}=self.fds[fd].fd_fdstat_get();if(fdstat!=null){fdstat.write_bytes(new DataView(self.inst.exports.memory.buffer),fdstat_ptr);}return ret}else {return ERRNO_BADF}},fd_fdstat_set_flags(fd,flags){if(self.fds[fd]!=undefined){return self.fds[fd].fd_fdstat_set_flags(flags)}else {return ERRNO_BADF}},fd_fdstat_set_rights(fd,fs_rights_base,fs_rights_inheriting){if(self.fds[fd]!=undefined){return self.fds[fd].fd_fdstat_set_rights(fs_rights_base,fs_rights_inheriting)}else {return ERRNO_BADF}},fd_filestat_get(fd,filestat_ptr){if(self.fds[fd]!=undefined){const{ret,filestat}=self.fds[fd].fd_filestat_get();if(filestat!=null){filestat.write_bytes(new DataView(self.inst.exports.memory.buffer),filestat_ptr);}return ret}else {return ERRNO_BADF}},fd_filestat_set_size(fd,size){if(self.fds[fd]!=undefined){return self.fds[fd].fd_filestat_set_size(size)}else {return ERRNO_BADF}},fd_filestat_set_times(fd,atim,mtim,fst_flags){if(self.fds[fd]!=undefined){return self.fds[fd].fd_filestat_set_times(atim,mtim,fst_flags)}else {return ERRNO_BADF}},fd_pread(fd,iovs_ptr,iovs_len,offset,nread_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const iovecs=Iovec.read_bytes_array(buffer,iovs_ptr,iovs_len);let nread=0;for(const iovec of iovecs){const{ret,data}=self.fds[fd].fd_pread(iovec.buf_len,offset);if(ret!=ERRNO_SUCCESS){buffer.setUint32(nread_ptr,nread,true);return ret}buffer8.set(data,iovec.buf);nread+=data.length;offset+=BigInt(data.length);if(data.length!=iovec.buf_len){break}}buffer.setUint32(nread_ptr,nread,true);return ERRNO_SUCCESS}else {return ERRNO_BADF}},fd_prestat_get(fd,buf_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const{ret,prestat}=self.fds[fd].fd_prestat_get();if(prestat!=null){prestat.write_bytes(buffer,buf_ptr);}return ret}else {return ERRNO_BADF}},fd_prestat_dir_name(fd,path_ptr,path_len){if(self.fds[fd]!=undefined){const{ret,prestat}=self.fds[fd].fd_prestat_get();if(prestat==null){return ret}const prestat_dir_name=prestat.inner.pr_name;const buffer8=new Uint8Array(self.inst.exports.memory.buffer);buffer8.set(prestat_dir_name.slice(0,path_len),path_ptr);return prestat_dir_name.byteLength>path_len?ERRNO_NAMETOOLONG:ERRNO_SUCCESS}else {return ERRNO_BADF}},fd_pwrite(fd,iovs_ptr,iovs_len,offset,nwritten_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const iovecs=Ciovec.read_bytes_array(buffer,iovs_ptr,iovs_len);let nwritten=0;for(const iovec of iovecs){const data=buffer8.slice(iovec.buf,iovec.buf+iovec.buf_len);const{ret,nwritten:nwritten_part}=self.fds[fd].fd_pwrite(data,offset);if(ret!=ERRNO_SUCCESS){buffer.setUint32(nwritten_ptr,nwritten,true);return ret}nwritten+=nwritten_part;offset+=BigInt(nwritten_part);if(nwritten_part!=data.byteLength){break}}buffer.setUint32(nwritten_ptr,nwritten,true);return ERRNO_SUCCESS}else {return ERRNO_BADF}},fd_read(fd,iovs_ptr,iovs_len,nread_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const iovecs=Iovec.read_bytes_array(buffer,iovs_ptr,iovs_len);let nread=0;for(const iovec of iovecs){const{ret,data}=self.fds[fd].fd_read(iovec.buf_len);if(ret!=ERRNO_SUCCESS){buffer.setUint32(nread_ptr,nread,true);return ret}buffer8.set(data,iovec.buf);nread+=data.length;if(data.length!=iovec.buf_len){break}}buffer.setUint32(nread_ptr,nread,true);return ERRNO_SUCCESS}else {return ERRNO_BADF}},fd_readdir(fd,buf,buf_len,cookie,bufused_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){let bufused=0;while(true){const{ret,dirent}=self.fds[fd].fd_readdir_single(cookie);if(ret!=0){buffer.setUint32(bufused_ptr,bufused,true);return ret}if(dirent==null){break}if(buf_len-bufused<dirent.head_length()){bufused=buf_len;break}const head_bytes=new ArrayBuffer(dirent.head_length());dirent.write_head_bytes(new DataView(head_bytes),0);buffer8.set(new Uint8Array(head_bytes).slice(0,Math.min(head_bytes.byteLength,buf_len-bufused)),buf);buf+=dirent.head_length();bufused+=dirent.head_length();if(buf_len-bufused<dirent.name_length()){bufused=buf_len;break}dirent.write_name_bytes(buffer8,buf,buf_len-bufused);buf+=dirent.name_length();bufused+=dirent.name_length();cookie=dirent.d_next;}buffer.setUint32(bufused_ptr,bufused,true);return 0}else {return ERRNO_BADF}},fd_renumber(fd,to){if(self.fds[fd]!=undefined&&self.fds[to]!=undefined){const ret=self.fds[to].fd_close();if(ret!=0){return ret}self.fds[to]=self.fds[fd];self.fds[fd]=undefined;return 0}else {return ERRNO_BADF}},fd_seek(fd,offset,whence,offset_out_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const{ret,offset:offset_out}=self.fds[fd].fd_seek(offset,whence);buffer.setBigInt64(offset_out_ptr,offset_out,true);return ret}else {return ERRNO_BADF}},fd_sync(fd){if(self.fds[fd]!=undefined){return self.fds[fd].fd_sync()}else {return ERRNO_BADF}},fd_tell(fd,offset_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const{ret,offset}=self.fds[fd].fd_tell();buffer.setBigUint64(offset_ptr,offset,true);return ret}else {return ERRNO_BADF}},fd_write(fd,iovs_ptr,iovs_len,nwritten_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const iovecs=Ciovec.read_bytes_array(buffer,iovs_ptr,iovs_len);let nwritten=0;for(const iovec of iovecs){const data=buffer8.slice(iovec.buf,iovec.buf+iovec.buf_len);const{ret,nwritten:nwritten_part}=self.fds[fd].fd_write(data);if(ret!=ERRNO_SUCCESS){buffer.setUint32(nwritten_ptr,nwritten,true);return ret}nwritten+=nwritten_part;if(nwritten_part!=data.byteLength){break}}buffer.setUint32(nwritten_ptr,nwritten,true);return ERRNO_SUCCESS}else {return ERRNO_BADF}},path_create_directory(fd,path_ptr,path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));return self.fds[fd].path_create_directory(path)}else {return ERRNO_BADF}},path_filestat_get(fd,flags,path_ptr,path_len,filestat_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));const{ret,filestat}=self.fds[fd].path_filestat_get(flags,path);if(filestat!=null){filestat.write_bytes(buffer,filestat_ptr);}return ret}else {return ERRNO_BADF}},path_filestat_set_times(fd,flags,path_ptr,path_len,atim,mtim,fst_flags){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));return self.fds[fd].path_filestat_set_times(flags,path,atim,mtim,fst_flags)}else {return ERRNO_BADF}},path_link(old_fd,old_flags,old_path_ptr,old_path_len,new_fd,new_path_ptr,new_path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[old_fd]!=undefined&&self.fds[new_fd]!=undefined){const old_path=new TextDecoder("utf-8").decode(buffer8.slice(old_path_ptr,old_path_ptr+old_path_len));const new_path=new TextDecoder("utf-8").decode(buffer8.slice(new_path_ptr,new_path_ptr+new_path_len));const{ret,inode_obj}=self.fds[old_fd].path_lookup(old_path,old_flags);if(inode_obj==null){return ret}return self.fds[new_fd].path_link(new_path,inode_obj,false)}else {return ERRNO_BADF}},path_open(fd,dirflags,path_ptr,path_len,oflags,fs_rights_base,fs_rights_inheriting,fd_flags,opened_fd_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));debug.log(path);const{ret,fd_obj}=self.fds[fd].path_open(dirflags,path,oflags,fs_rights_base,fs_rights_inheriting,fd_flags);if(ret!=0){return ret}self.fds.push(fd_obj);const opened_fd=self.fds.length-1;buffer.setUint32(opened_fd_ptr,opened_fd,true);return 0}else {return ERRNO_BADF}},path_readlink(fd,path_ptr,path_len,buf_ptr,buf_len,nread_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));debug.log(path);const{ret,data}=self.fds[fd].path_readlink(path);if(data!=null){const data_buf=new TextEncoder().encode(data);if(data_buf.length>buf_len){buffer.setUint32(nread_ptr,0,true);return ERRNO_BADF}buffer8.set(data_buf,buf_ptr);buffer.setUint32(nread_ptr,data_buf.length,true);}return ret}else {return ERRNO_BADF}},path_remove_directory(fd,path_ptr,path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));return self.fds[fd].path_remove_directory(path)}else {return ERRNO_BADF}},path_rename(fd,old_path_ptr,old_path_len,new_fd,new_path_ptr,new_path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined&&self.fds[new_fd]!=undefined){const old_path=new TextDecoder("utf-8").decode(buffer8.slice(old_path_ptr,old_path_ptr+old_path_len));const new_path=new TextDecoder("utf-8").decode(buffer8.slice(new_path_ptr,new_path_ptr+new_path_len));let{ret,inode_obj}=self.fds[fd].path_unlink(old_path);if(inode_obj==null){return ret}ret=self.fds[new_fd].path_link(new_path,inode_obj,true);if(ret!=ERRNO_SUCCESS){if(self.fds[fd].path_link(old_path,inode_obj,true)!=ERRNO_SUCCESS){throw "path_link should always return success when relinking an inode back to the original place"}}return ret}else {return ERRNO_BADF}},path_symlink(old_path_ptr,old_path_len,fd,new_path_ptr,new_path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){new TextDecoder("utf-8").decode(buffer8.slice(old_path_ptr,old_path_ptr+old_path_len));new TextDecoder("utf-8").decode(buffer8.slice(new_path_ptr,new_path_ptr+new_path_len));return ERRNO_NOTSUP}else {return ERRNO_BADF}},path_unlink_file(fd,path_ptr,path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));return self.fds[fd].path_unlink_file(path)}else {return ERRNO_BADF}},poll_oneoff(in_,out,nsubscriptions){throw "async io not supported"},proc_exit(exit_code){throw new WASIProcExit(exit_code)},proc_raise(sig){throw "raised signal "+sig},sched_yield(){},random_get(buf,buf_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);for(let i=0;i<buf_len;i++){buffer8[buf+i]=Math.random()*256|0;}},sock_recv(fd,ri_data,ri_flags){throw "sockets not supported"},sock_send(fd,si_data,si_flags){throw "sockets not supported"},sock_shutdown(fd,how){throw "sockets not supported"},sock_accept(fd,flags){throw "sockets not supported"}};}};
12
+
13
+ class Fd{fd_allocate(offset,len){return ERRNO_NOTSUP}fd_close(){return 0}fd_fdstat_get(){return {ret:ERRNO_NOTSUP,fdstat:null}}fd_fdstat_set_flags(flags){return ERRNO_NOTSUP}fd_fdstat_set_rights(fs_rights_base,fs_rights_inheriting){return ERRNO_NOTSUP}fd_filestat_get(){return {ret:ERRNO_NOTSUP,filestat:null}}fd_filestat_set_size(size){return ERRNO_NOTSUP}fd_filestat_set_times(atim,mtim,fst_flags){return ERRNO_NOTSUP}fd_pread(size,offset){return {ret:ERRNO_NOTSUP,data:new Uint8Array}}fd_prestat_get(){return {ret:ERRNO_NOTSUP,prestat:null}}fd_pwrite(data,offset){return {ret:ERRNO_NOTSUP,nwritten:0}}fd_read(size){return {ret:ERRNO_NOTSUP,data:new Uint8Array}}fd_readdir_single(cookie){return {ret:ERRNO_NOTSUP,dirent:null}}fd_seek(offset,whence){return {ret:ERRNO_NOTSUP,offset:0n}}fd_sync(){return 0}fd_tell(){return {ret:ERRNO_NOTSUP,offset:0n}}fd_write(data){return {ret:ERRNO_NOTSUP,nwritten:0}}path_create_directory(path){return ERRNO_NOTSUP}path_filestat_get(flags,path){return {ret:ERRNO_NOTSUP,filestat:null}}path_filestat_set_times(flags,path,atim,mtim,fst_flags){return ERRNO_NOTSUP}path_link(path,inode,allow_dir){return ERRNO_NOTSUP}path_unlink(path){return {ret:ERRNO_NOTSUP,inode_obj:null}}path_lookup(path,dirflags){return {ret:ERRNO_NOTSUP,inode_obj:null}}path_open(dirflags,path,oflags,fs_rights_base,fs_rights_inheriting,fd_flags){return {ret:ERRNO_NOTDIR,fd_obj:null}}path_readlink(path){return {ret:ERRNO_NOTSUP,data:null}}path_remove_directory(path){return ERRNO_NOTSUP}path_rename(old_path,new_fd,new_path){return ERRNO_NOTSUP}path_unlink_file(path){return ERRNO_NOTSUP}}class Inode{}
14
+
15
+ class OpenFile extends Fd{fd_allocate(offset,len){if(this.file.size>offset+len);else {const new_data=new Uint8Array(Number(offset+len));new_data.set(this.file.data,0);this.file.data=new_data;}return ERRNO_SUCCESS}fd_fdstat_get(){return {ret:0,fdstat:new Fdstat(FILETYPE_REGULAR_FILE,0)}}fd_filestat_set_size(size){if(this.file.size>size){this.file.data=new Uint8Array(this.file.data.buffer.slice(0,Number(size)));}else {const new_data=new Uint8Array(Number(size));new_data.set(this.file.data,0);this.file.data=new_data;}return ERRNO_SUCCESS}fd_read(size){const slice=this.file.data.slice(Number(this.file_pos),Number(this.file_pos+BigInt(size)));this.file_pos+=BigInt(slice.length);return {ret:0,data:slice}}fd_pread(size,offset){const slice=this.file.data.slice(Number(offset),Number(offset+BigInt(size)));return {ret:0,data:slice}}fd_seek(offset,whence){let calculated_offset;switch(whence){case WHENCE_SET:calculated_offset=offset;break;case WHENCE_CUR:calculated_offset=this.file_pos+offset;break;case WHENCE_END:calculated_offset=BigInt(this.file.data.byteLength)+offset;break;default:return {ret:ERRNO_INVAL,offset:0n}}if(calculated_offset<0){return {ret:ERRNO_INVAL,offset:0n}}this.file_pos=calculated_offset;return {ret:0,offset:this.file_pos}}fd_tell(){return {ret:0,offset:this.file_pos}}fd_write(data){if(this.file.readonly)return {ret:ERRNO_BADF,nwritten:0};if(this.file_pos+BigInt(data.byteLength)>this.file.size){const old=this.file.data;this.file.data=new Uint8Array(Number(this.file_pos+BigInt(data.byteLength)));this.file.data.set(old);}this.file.data.set(data,Number(this.file_pos));this.file_pos+=BigInt(data.byteLength);return {ret:0,nwritten:data.byteLength}}fd_pwrite(data,offset){if(this.file.readonly)return {ret:ERRNO_BADF,nwritten:0};if(offset+BigInt(data.byteLength)>this.file.size){const old=this.file.data;this.file.data=new Uint8Array(Number(offset+BigInt(data.byteLength)));this.file.data.set(old);}this.file.data.set(data,Number(offset));return {ret:0,nwritten:data.byteLength}}fd_filestat_get(){return {ret:0,filestat:this.file.stat()}}constructor(file){super();this.file_pos=0n;this.file=file;}}class OpenDirectory extends Fd{fd_seek(offset,whence){return {ret:ERRNO_BADF,offset:0n}}fd_tell(){return {ret:ERRNO_BADF,offset:0n}}fd_allocate(offset,len){return ERRNO_BADF}fd_fdstat_get(){return {ret:0,fdstat:new Fdstat(FILETYPE_DIRECTORY,0)}}fd_readdir_single(cookie){if(debug.enabled){debug.log("readdir_single",cookie);debug.log(cookie,this.dir.contents.keys());}if(cookie==0n){return {ret:ERRNO_SUCCESS,dirent:new Dirent(1n,".",FILETYPE_DIRECTORY)}}else if(cookie==1n){return {ret:ERRNO_SUCCESS,dirent:new Dirent(2n,"..",FILETYPE_DIRECTORY)}}if(cookie>=BigInt(this.dir.contents.size)+2n){return {ret:0,dirent:null}}const[name,entry]=Array.from(this.dir.contents.entries())[Number(cookie-2n)];return {ret:0,dirent:new Dirent(cookie+1n,name,entry.stat().filetype)}}path_filestat_get(flags,path_str){const{ret:path_err,path}=Path.from(path_str);if(path==null){return {ret:path_err,filestat:null}}const{ret,entry}=this.dir.get_entry_for_path(path);if(entry==null){return {ret,filestat:null}}return {ret:0,filestat:entry.stat()}}path_lookup(path_str,dirflags){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return {ret:path_ret,inode_obj:null}}const{ret,entry}=this.dir.get_entry_for_path(path);if(entry==null){return {ret,inode_obj:null}}return {ret:ERRNO_SUCCESS,inode_obj:entry}}path_open(dirflags,path_str,oflags,fs_rights_base,fs_rights_inheriting,fd_flags){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return {ret:path_ret,fd_obj:null}}let{ret,entry}=this.dir.get_entry_for_path(path);if(entry==null){if(ret!=ERRNO_NOENT){return {ret,fd_obj:null}}if((oflags&OFLAGS_CREAT)==OFLAGS_CREAT){const{ret,entry:new_entry}=this.dir.create_entry_for_path(path_str,(oflags&OFLAGS_DIRECTORY)==OFLAGS_DIRECTORY);if(new_entry==null){return {ret,fd_obj:null}}entry=new_entry;}else {return {ret:ERRNO_NOENT,fd_obj:null}}}else if((oflags&OFLAGS_EXCL)==OFLAGS_EXCL){return {ret:ERRNO_EXIST,fd_obj:null}}if((oflags&OFLAGS_DIRECTORY)==OFLAGS_DIRECTORY&&entry.stat().filetype!==FILETYPE_DIRECTORY){return {ret:ERRNO_NOTDIR,fd_obj:null}}return entry.path_open(oflags,fs_rights_base,fd_flags)}path_create_directory(path){return this.path_open(0,path,OFLAGS_CREAT|OFLAGS_DIRECTORY,0n,0n,0).ret}path_link(path_str,inode,allow_dir){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return path_ret}if(path.is_dir){return ERRNO_NOENT}const{ret:parent_ret,parent_entry,filename,entry}=this.dir.get_parent_dir_and_entry_for_path(path,true);if(parent_entry==null||filename==null){return parent_ret}if(entry!=null){const source_is_dir=inode.stat().filetype==FILETYPE_DIRECTORY;const target_is_dir=entry.stat().filetype==FILETYPE_DIRECTORY;if(source_is_dir&&target_is_dir){if(allow_dir&&entry instanceof Directory){if(entry.contents.size==0);else {return ERRNO_NOTEMPTY}}else {return ERRNO_EXIST}}else if(source_is_dir&&!target_is_dir){return ERRNO_NOTDIR}else if(!source_is_dir&&target_is_dir){return ERRNO_ISDIR}else if(inode.stat().filetype==FILETYPE_REGULAR_FILE&&entry.stat().filetype==FILETYPE_REGULAR_FILE);else {return ERRNO_EXIST}}if(!allow_dir&&inode.stat().filetype==FILETYPE_DIRECTORY){return ERRNO_PERM}parent_entry.contents.set(filename,inode);return ERRNO_SUCCESS}path_unlink(path_str){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return {ret:path_ret,inode_obj:null}}const{ret:parent_ret,parent_entry,filename,entry}=this.dir.get_parent_dir_and_entry_for_path(path,true);if(parent_entry==null||filename==null){return {ret:parent_ret,inode_obj:null}}if(entry==null){return {ret:ERRNO_NOENT,inode_obj:null}}parent_entry.contents.delete(filename);return {ret:ERRNO_SUCCESS,inode_obj:entry}}path_unlink_file(path_str){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return path_ret}const{ret:parent_ret,parent_entry,filename,entry}=this.dir.get_parent_dir_and_entry_for_path(path,false);if(parent_entry==null||filename==null||entry==null){return parent_ret}if(entry.stat().filetype===FILETYPE_DIRECTORY){return ERRNO_ISDIR}parent_entry.contents.delete(filename);return ERRNO_SUCCESS}path_remove_directory(path_str){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return path_ret}const{ret:parent_ret,parent_entry,filename,entry}=this.dir.get_parent_dir_and_entry_for_path(path,false);if(parent_entry==null||filename==null||entry==null){return parent_ret}if(!(entry instanceof Directory)||entry.stat().filetype!==FILETYPE_DIRECTORY){return ERRNO_NOTDIR}if(entry.contents.size!==0){return ERRNO_NOTEMPTY}if(!parent_entry.contents.delete(filename)){return ERRNO_NOENT}return ERRNO_SUCCESS}fd_filestat_get(){return {ret:0,filestat:this.dir.stat()}}fd_filestat_set_size(size){return ERRNO_BADF}fd_read(size){return {ret:ERRNO_BADF,data:new Uint8Array}}fd_pread(size,offset){return {ret:ERRNO_BADF,data:new Uint8Array}}fd_write(data){return {ret:ERRNO_BADF,nwritten:0}}fd_pwrite(data,offset){return {ret:ERRNO_BADF,nwritten:0}}constructor(dir){super();this.dir=dir;}}class PreopenDirectory extends OpenDirectory{fd_prestat_get(){return {ret:0,prestat:Prestat.dir(this.prestat_name)}}constructor(name,contents){super(new Directory(contents));this.prestat_name=name;}}class File extends Inode{path_open(oflags,fs_rights_base,fd_flags){if(this.readonly&&(fs_rights_base&BigInt(RIGHTS_FD_WRITE))==BigInt(RIGHTS_FD_WRITE)){return {ret:ERRNO_PERM,fd_obj:null}}if((oflags&OFLAGS_TRUNC)==OFLAGS_TRUNC){if(this.readonly)return {ret:ERRNO_PERM,fd_obj:null};this.data=new Uint8Array([]);}const file=new OpenFile(this);if(fd_flags&FDFLAGS_APPEND)file.fd_seek(0n,WHENCE_END);return {ret:ERRNO_SUCCESS,fd_obj:file}}get size(){return BigInt(this.data.byteLength)}stat(){return new Filestat(FILETYPE_REGULAR_FILE,this.size)}constructor(data,options){super();this.data=new Uint8Array(data);this.readonly=!!options?.readonly;}}let Path=class Path{static from(path){const self=new Path;self.is_dir=path.endsWith("/");if(path.startsWith("/")){return {ret:ERRNO_NOTCAPABLE,path:null}}if(path.includes("\x00")){return {ret:ERRNO_INVAL,path:null}}for(const component of path.split("/")){if(component===""||component==="."){continue}if(component===".."){if(self.parts.pop()==undefined){return {ret:ERRNO_NOTCAPABLE,path:null}}continue}self.parts.push(component);}return {ret:ERRNO_SUCCESS,path:self}}to_path_string(){let s=this.parts.join("/");if(this.is_dir){s+="/";}return s}constructor(){this.parts=[];this.is_dir=false;}};class Directory extends Inode{path_open(oflags,fs_rights_base,fd_flags){return {ret:ERRNO_SUCCESS,fd_obj:new OpenDirectory(this)}}stat(){return new Filestat(FILETYPE_DIRECTORY,0n)}get_entry_for_path(path){let entry=this;for(const component of path.parts){if(!(entry instanceof Directory)){return {ret:ERRNO_NOTDIR,entry:null}}const child=entry.contents.get(component);if(child!==undefined){entry=child;}else {debug.log(component);return {ret:ERRNO_NOENT,entry:null}}}if(path.is_dir){if(entry.stat().filetype!=FILETYPE_DIRECTORY){return {ret:ERRNO_NOTDIR,entry:null}}}return {ret:ERRNO_SUCCESS,entry}}get_parent_dir_and_entry_for_path(path,allow_undefined){const filename=path.parts.pop();if(filename===undefined){return {ret:ERRNO_INVAL,parent_entry:null,filename:null,entry:null}}const{ret:entry_ret,entry:parent_entry}=this.get_entry_for_path(path);if(parent_entry==null){return {ret:entry_ret,parent_entry:null,filename:null,entry:null}}if(!(parent_entry instanceof Directory)){return {ret:ERRNO_NOTDIR,parent_entry:null,filename:null,entry:null}}const entry=parent_entry.contents.get(filename);if(entry===undefined){if(!allow_undefined){return {ret:ERRNO_NOENT,parent_entry:null,filename:null,entry:null}}else {return {ret:ERRNO_SUCCESS,parent_entry,filename,entry:null}}}if(path.is_dir){if(entry.stat().filetype!=FILETYPE_DIRECTORY){return {ret:ERRNO_NOTDIR,parent_entry:null,filename:null,entry:null}}}return {ret:ERRNO_SUCCESS,parent_entry,filename,entry}}create_entry_for_path(path_str,is_dir){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return {ret:path_ret,entry:null}}let{ret:parent_ret,parent_entry,filename,entry}=this.get_parent_dir_and_entry_for_path(path,true);if(parent_entry==null||filename==null){return {ret:parent_ret,entry:null}}if(entry!=null){return {ret:ERRNO_EXIST,entry:null}}debug.log("create",path);let new_child;if(!is_dir){new_child=new File(new ArrayBuffer(0));}else {new_child=new Directory(new Map);}parent_entry.contents.set(filename,new_child);entry=new_child;return {ret:ERRNO_SUCCESS,entry}}constructor(contents){super();if(contents instanceof Array){this.contents=new Map(contents);}else {this.contents=contents;}}}
16
+
17
+ /**
18
+ * Create a console printer that can be used as an overlay of WASI imports.
19
+ * See the example below for how to use it.
20
+ *
21
+ * ```javascript
22
+ * const imports = {
23
+ * "wasi_snapshot_preview1": wasi.wasiImport,
24
+ * }
25
+ * const printer = consolePrinter();
26
+ * printer.addToImports(imports);
27
+ *
28
+ * const instance = await WebAssembly.instantiate(module, imports);
29
+ * printer.setMemory(instance.exports.memory);
30
+ * ```
31
+ *
32
+ * Note that the `stdout` and `stderr` functions are called with text, not
33
+ * bytes. This means that bytes written to stdout/stderr will be decoded as
34
+ * UTF-8 and then passed to the `stdout`/`stderr` functions every time a write
35
+ * occurs without buffering.
36
+ *
37
+ * @param stdout A function that will be called when stdout is written to.
38
+ * Defaults to `console.log`.
39
+ * @param stderr A function that will be called when stderr is written to.
40
+ * Defaults to `console.warn`.
41
+ * @returns An object that can be used as an overlay of WASI imports.
42
+ */
43
+ function consolePrinter({ stdout, stderr, } = {
44
+ stdout: console.log,
45
+ stderr: console.warn,
46
+ }) {
47
+ let memory = undefined;
48
+ let _view = undefined;
49
+ function getMemoryView() {
50
+ if (typeof memory === "undefined") {
51
+ throw new Error("Memory is not set");
52
+ }
53
+ if (_view === undefined || _view.buffer.byteLength === 0) {
54
+ _view = new DataView(memory.buffer);
55
+ }
56
+ return _view;
57
+ }
58
+ const decoder = new TextDecoder();
59
+ return {
60
+ addToImports(imports) {
61
+ const wasiImport = imports.wasi_snapshot_preview1;
62
+ const original_fd_write = wasiImport.fd_write;
63
+ wasiImport.fd_write = (fd, iovs, iovsLen, nwritten) => {
64
+ if (fd !== 1 && fd !== 2) {
65
+ return original_fd_write(fd, iovs, iovsLen, nwritten);
66
+ }
67
+ const view = getMemoryView();
68
+ const buffers = Array.from({ length: iovsLen }, (_, i) => {
69
+ const ptr = iovs + i * 8;
70
+ const buf = view.getUint32(ptr, true);
71
+ const bufLen = view.getUint32(ptr + 4, true);
72
+ return new Uint8Array(memory.buffer, buf, bufLen);
73
+ });
74
+ let written = 0;
75
+ let str = "";
76
+ for (const buffer of buffers) {
77
+ str += decoder.decode(buffer);
78
+ written += buffer.byteLength;
79
+ }
80
+ view.setUint32(nwritten, written, true);
81
+ const log = fd === 1 ? stdout : stderr;
82
+ log(str);
83
+ return 0;
84
+ };
85
+ const original_fd_filestat_get = wasiImport.fd_filestat_get;
86
+ wasiImport.fd_filestat_get = (fd, filestat) => {
87
+ if (fd !== 1 && fd !== 2) {
88
+ return original_fd_filestat_get(fd, filestat);
89
+ }
90
+ const view = getMemoryView();
91
+ const result = original_fd_filestat_get(fd, filestat);
92
+ if (result !== 0) {
93
+ return result;
94
+ }
95
+ const filetypePtr = filestat + 0;
96
+ view.setUint8(filetypePtr, 2); // FILETYPE_CHARACTER_DEVICE
97
+ return 0;
98
+ };
99
+ const original_fd_fdstat_get = wasiImport.fd_fdstat_get;
100
+ wasiImport.fd_fdstat_get = (fd, fdstat) => {
101
+ if (fd !== 1 && fd !== 2) {
102
+ return original_fd_fdstat_get(fd, fdstat);
103
+ }
104
+ const view = getMemoryView();
105
+ const fs_filetypePtr = fdstat + 0;
106
+ view.setUint8(fs_filetypePtr, 2); // FILETYPE_CHARACTER_DEVICE
107
+ const fs_rights_basePtr = fdstat + 8;
108
+ // See https://github.com/WebAssembly/WASI/blob/v0.2.0/legacy/preview1/docs.md#record-members
109
+ const RIGHTS_FD_WRITE = 1 << 6;
110
+ view.setBigUint64(fs_rights_basePtr, BigInt(RIGHTS_FD_WRITE), true);
111
+ return 0;
112
+ };
113
+ },
114
+ setMemory(m) {
115
+ memory = m;
116
+ },
117
+ };
118
+ }
119
+
120
+ let DATA_VIEW = new DataView(new ArrayBuffer());
121
+
122
+ function data_view(mem) {
123
+ if (DATA_VIEW.buffer !== mem.buffer) DATA_VIEW = new DataView(mem.buffer);
124
+ return DATA_VIEW;
125
+ }
126
+
127
+ function to_uint32(val) {
128
+ return val >>> 0;
129
+ }
130
+ const UTF8_DECODER = new TextDecoder('utf-8');
131
+
132
+ const UTF8_ENCODER = new TextEncoder('utf-8');
133
+
134
+ function utf8_encode(s, realloc, memory) {
135
+ if (typeof s !== 'string') throw new TypeError('expected a string');
136
+
137
+ if (s.length === 0) {
138
+ UTF8_ENCODED_LEN = 0;
139
+ return 1;
140
+ }
141
+
142
+ let alloc_len = 0;
143
+ let ptr = 0;
144
+ let writtenTotal = 0;
145
+ while (s.length > 0) {
146
+ ptr = realloc(ptr, alloc_len, 1, alloc_len + s.length);
147
+ alloc_len += s.length;
148
+ const { read, written } = UTF8_ENCODER.encodeInto(
149
+ s,
150
+ new Uint8Array(memory.buffer, ptr + writtenTotal, alloc_len - writtenTotal),
151
+ );
152
+ writtenTotal += written;
153
+ s = s.slice(read);
154
+ }
155
+ if (alloc_len > writtenTotal)
156
+ ptr = realloc(ptr, alloc_len, 1, writtenTotal);
157
+ UTF8_ENCODED_LEN = writtenTotal;
158
+ return ptr;
159
+ }
160
+ let UTF8_ENCODED_LEN = 0;
161
+
162
+ class Slab {
163
+ constructor() {
164
+ this.list = [];
165
+ this.head = 0;
166
+ }
167
+
168
+ insert(val) {
169
+ if (this.head >= this.list.length) {
170
+ this.list.push({
171
+ next: this.list.length + 1,
172
+ val: undefined,
173
+ });
174
+ }
175
+ const ret = this.head;
176
+ const slot = this.list[ret];
177
+ this.head = slot.next;
178
+ slot.next = -1;
179
+ slot.val = val;
180
+ return ret;
181
+ }
182
+
183
+ get(idx) {
184
+ if (idx >= this.list.length)
185
+ throw new RangeError('handle index not valid');
186
+ const slot = this.list[idx];
187
+ if (slot.next === -1)
188
+ return slot.val;
189
+ throw new RangeError('handle index not valid');
190
+ }
191
+
192
+ remove(idx) {
193
+ const ret = this.get(idx); // validate the slot
194
+ const slot = this.list[idx];
195
+ slot.val = undefined;
196
+ slot.next = this.head;
197
+ this.head = idx;
198
+ return ret;
199
+ }
200
+ }
201
+
202
+ function throw_invalid_bool() {
203
+ throw new RangeError("invalid variant discriminant for bool");
204
+ }
205
+
206
+ class RbAbiGuest {
207
+ constructor() {
208
+ this._resource0_slab = new Slab();
209
+ }
210
+ addToImports(imports) {
211
+ if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
212
+
213
+ imports.canonical_abi['resource_drop_rb-abi-value'] = i => {
214
+ this._resource0_slab.remove(i).drop();
215
+ };
216
+ imports.canonical_abi['resource_clone_rb-abi-value'] = i => {
217
+ const obj = this._resource0_slab.get(i);
218
+ return this._resource0_slab.insert(obj.clone())
219
+ };
220
+ imports.canonical_abi['resource_get_rb-abi-value'] = i => {
221
+ return this._resource0_slab.get(i)._wasm_val;
222
+ };
223
+ imports.canonical_abi['resource_new_rb-abi-value'] = i => {
224
+ this._registry0;
225
+ return this._resource0_slab.insert(new RbAbiValue(i, this));
226
+ };
227
+ }
228
+
229
+ async instantiate(module, imports) {
230
+ imports = imports || {};
231
+ this.addToImports(imports);
232
+
233
+ if (module instanceof WebAssembly.Instance) {
234
+ this.instance = module;
235
+ } else if (module instanceof WebAssembly.Module) {
236
+ this.instance = await WebAssembly.instantiate(module, imports);
237
+ } else if (module instanceof ArrayBuffer || module instanceof Uint8Array) {
238
+ const { instance } = await WebAssembly.instantiate(module, imports);
239
+ this.instance = instance;
240
+ } else {
241
+ const { instance } = await WebAssembly.instantiateStreaming(module, imports);
242
+ this.instance = instance;
243
+ }
244
+ this._exports = this.instance.exports;
245
+ this._registry0 = new FinalizationRegistry(this._exports['canonical_abi_drop_rb-abi-value']);
246
+ }
247
+ rubyShowVersion() {
248
+ this._exports['ruby-show-version: func() -> ()']();
249
+ }
250
+ rubyInit(arg0) {
251
+ const memory = this._exports.memory;
252
+ const realloc = this._exports["cabi_realloc"];
253
+ const vec1 = arg0;
254
+ const len1 = vec1.length;
255
+ const result1 = realloc(0, 0, 4, len1 * 8);
256
+ for (let i = 0; i < vec1.length; i++) {
257
+ const e = vec1[i];
258
+ const base = result1 + i * 8;
259
+ const ptr0 = utf8_encode(e, realloc, memory);
260
+ const len0 = UTF8_ENCODED_LEN;
261
+ data_view(memory).setInt32(base + 4, len0, true);
262
+ data_view(memory).setInt32(base + 0, ptr0, true);
263
+ }
264
+ this._exports['ruby-init: func(args: list<string>) -> ()'](result1, len1);
265
+ }
266
+ rubyInitLoadpath() {
267
+ this._exports['ruby-init-loadpath: func() -> ()']();
268
+ }
269
+ rbEvalStringProtect(arg0) {
270
+ const memory = this._exports.memory;
271
+ const realloc = this._exports["cabi_realloc"];
272
+ const ptr0 = utf8_encode(arg0, realloc, memory);
273
+ const len0 = UTF8_ENCODED_LEN;
274
+ const ret = this._exports['rb-eval-string-protect: func(str: string) -> tuple<handle<rb-abi-value>, s32>'](ptr0, len0);
275
+ return [this._resource0_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
276
+ }
277
+ rbFuncallvProtect(arg0, arg1, arg2) {
278
+ const memory = this._exports.memory;
279
+ const realloc = this._exports["cabi_realloc"];
280
+ const obj0 = arg0;
281
+ if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
282
+ const vec2 = arg2;
283
+ const len2 = vec2.length;
284
+ const result2 = realloc(0, 0, 4, len2 * 4);
285
+ for (let i = 0; i < vec2.length; i++) {
286
+ const e = vec2[i];
287
+ const base = result2 + i * 4;
288
+ const obj1 = e;
289
+ if (!(obj1 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
290
+ data_view(memory).setInt32(base + 0, this._resource0_slab.insert(obj1.clone()), true);
291
+ }
292
+ const ret = this._exports['rb-funcallv-protect: func(recv: handle<rb-abi-value>, mid: u32, args: list<handle<rb-abi-value>>) -> tuple<handle<rb-abi-value>, s32>'](this._resource0_slab.insert(obj0.clone()), to_uint32(arg1), result2, len2);
293
+ return [this._resource0_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
294
+ }
295
+ rbIntern(arg0) {
296
+ const memory = this._exports.memory;
297
+ const realloc = this._exports["cabi_realloc"];
298
+ const ptr0 = utf8_encode(arg0, realloc, memory);
299
+ const len0 = UTF8_ENCODED_LEN;
300
+ const ret = this._exports['rb-intern: func(name: string) -> u32'](ptr0, len0);
301
+ return ret >>> 0;
302
+ }
303
+ rbErrinfo() {
304
+ const ret = this._exports['rb-errinfo: func() -> handle<rb-abi-value>']();
305
+ return this._resource0_slab.remove(ret);
306
+ }
307
+ rbClearErrinfo() {
308
+ this._exports['rb-clear-errinfo: func() -> ()']();
309
+ }
310
+ rstringPtr(arg0) {
311
+ const memory = this._exports.memory;
312
+ const obj0 = arg0;
313
+ if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
314
+ const ret = this._exports['rstring-ptr: func(value: handle<rb-abi-value>) -> string'](this._resource0_slab.insert(obj0.clone()));
315
+ const ptr1 = data_view(memory).getInt32(ret + 0, true);
316
+ const len1 = data_view(memory).getInt32(ret + 4, true);
317
+ const result1 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr1, len1));
318
+ this._exports["cabi_post_rstring-ptr"](ret);
319
+ return result1;
320
+ }
321
+ rbVmBugreport() {
322
+ this._exports['rb-vm-bugreport: func() -> ()']();
323
+ }
324
+ rbGcEnable() {
325
+ const ret = this._exports['rb-gc-enable: func() -> bool']();
326
+ const bool0 = ret;
327
+ return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
328
+ }
329
+ rbGcDisable() {
330
+ const ret = this._exports['rb-gc-disable: func() -> bool']();
331
+ const bool0 = ret;
332
+ return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
333
+ }
334
+ rbSetShouldProhibitRewind(arg0) {
335
+ const ret = this._exports['rb-set-should-prohibit-rewind: func(new-value: bool) -> bool'](arg0 ? 1 : 0);
336
+ const bool0 = ret;
337
+ return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
338
+ }
339
+ }
340
+
341
+ class RbAbiValue {
342
+ constructor(wasm_val, obj) {
343
+ this._wasm_val = wasm_val;
344
+ this._obj = obj;
345
+ this._refcnt = 1;
346
+ obj._registry0.register(this, wasm_val, this);
347
+ }
348
+
349
+ clone() {
350
+ this._refcnt += 1;
351
+ return this;
352
+ }
353
+
354
+ drop() {
355
+ this._refcnt -= 1;
356
+ if (this._refcnt !== 0)
357
+ return;
358
+ this._obj._registry0.unregister(this);
359
+ const dtor = this._obj._exports['canonical_abi_drop_rb-abi-value'];
360
+ const wasm_val = this._wasm_val;
361
+ delete this._obj;
362
+ delete this._refcnt;
363
+ delete this._wasm_val;
364
+ dtor(wasm_val);
365
+ }
366
+ }
367
+
368
+ function addRbJsAbiHostToImports(imports, obj, get_export) {
369
+ if (!("rb-js-abi-host" in imports)) imports["rb-js-abi-host"] = {};
370
+ imports["rb-js-abi-host"]["eval-js: func(code: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2) {
371
+ const memory = get_export("memory");
372
+ const ptr0 = arg0;
373
+ const len0 = arg1;
374
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
375
+ const ret0 = obj.evalJs(result0);
376
+ const variant1 = ret0;
377
+ switch (variant1.tag) {
378
+ case "success": {
379
+ const e = variant1.val;
380
+ data_view(memory).setInt8(arg2 + 0, 0, true);
381
+ data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
382
+ break;
383
+ }
384
+ case "failure": {
385
+ const e = variant1.val;
386
+ data_view(memory).setInt8(arg2 + 0, 1, true);
387
+ data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
388
+ break;
389
+ }
390
+ default:
391
+ throw new RangeError("invalid variant specified for JsAbiResult");
392
+ }
393
+ };
394
+ imports["rb-js-abi-host"]["is-js: func(value: handle<js-abi-value>) -> bool"] = function(arg0) {
395
+ const ret0 = obj.isJs(resources0.get(arg0));
396
+ return ret0 ? 1 : 0;
397
+ };
398
+ imports["rb-js-abi-host"]["instance-of: func(value: handle<js-abi-value>, klass: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
399
+ const ret0 = obj.instanceOf(resources0.get(arg0), resources0.get(arg1));
400
+ return ret0 ? 1 : 0;
401
+ };
402
+ imports["rb-js-abi-host"]["global-this: func() -> handle<js-abi-value>"] = function() {
403
+ const ret0 = obj.globalThis();
404
+ return resources0.insert(ret0);
405
+ };
406
+ imports["rb-js-abi-host"]["int-to-js-number: func(value: s32) -> handle<js-abi-value>"] = function(arg0) {
407
+ const ret0 = obj.intToJsNumber(arg0);
408
+ return resources0.insert(ret0);
409
+ };
410
+ imports["rb-js-abi-host"]["float-to-js-number: func(value: float64) -> handle<js-abi-value>"] = function(arg0) {
411
+ const ret0 = obj.floatToJsNumber(arg0);
412
+ return resources0.insert(ret0);
413
+ };
414
+ imports["rb-js-abi-host"]["string-to-js-string: func(value: string) -> handle<js-abi-value>"] = function(arg0, arg1) {
415
+ const memory = get_export("memory");
416
+ const ptr0 = arg0;
417
+ const len0 = arg1;
418
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
419
+ const ret0 = obj.stringToJsString(result0);
420
+ return resources0.insert(ret0);
421
+ };
422
+ imports["rb-js-abi-host"]["bool-to-js-bool: func(value: bool) -> handle<js-abi-value>"] = function(arg0) {
423
+ const bool0 = arg0;
424
+ const ret0 = obj.boolToJsBool(bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool()));
425
+ return resources0.insert(ret0);
426
+ };
427
+ imports["rb-js-abi-host"]["proc-to-js-function: func(value: u32) -> handle<js-abi-value>"] = function(arg0) {
428
+ const ret0 = obj.procToJsFunction(arg0 >>> 0);
429
+ return resources0.insert(ret0);
430
+ };
431
+ imports["rb-js-abi-host"]["rb-object-to-js-rb-value: func(raw-rb-abi-value: u32) -> handle<js-abi-value>"] = function(arg0) {
432
+ const ret0 = obj.rbObjectToJsRbValue(arg0 >>> 0);
433
+ return resources0.insert(ret0);
434
+ };
435
+ imports["rb-js-abi-host"]["js-value-to-string: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
436
+ const memory = get_export("memory");
437
+ const realloc = get_export("cabi_realloc");
438
+ const ret0 = obj.jsValueToString(resources0.get(arg0));
439
+ const ptr0 = utf8_encode(ret0, realloc, memory);
440
+ const len0 = UTF8_ENCODED_LEN;
441
+ data_view(memory).setInt32(arg1 + 4, len0, true);
442
+ data_view(memory).setInt32(arg1 + 0, ptr0, true);
443
+ };
444
+ imports["rb-js-abi-host"]["js-value-to-integer: func(value: handle<js-abi-value>) -> variant { as-float(float64), bignum(string) }"] = function(arg0, arg1) {
445
+ const memory = get_export("memory");
446
+ const realloc = get_export("cabi_realloc");
447
+ const ret0 = obj.jsValueToInteger(resources0.get(arg0));
448
+ const variant1 = ret0;
449
+ switch (variant1.tag) {
450
+ case "as-float": {
451
+ const e = variant1.val;
452
+ data_view(memory).setInt8(arg1 + 0, 0, true);
453
+ data_view(memory).setFloat64(arg1 + 8, +e, true);
454
+ break;
455
+ }
456
+ case "bignum": {
457
+ const e = variant1.val;
458
+ data_view(memory).setInt8(arg1 + 0, 1, true);
459
+ const ptr0 = utf8_encode(e, realloc, memory);
460
+ const len0 = UTF8_ENCODED_LEN;
461
+ data_view(memory).setInt32(arg1 + 12, len0, true);
462
+ data_view(memory).setInt32(arg1 + 8, ptr0, true);
463
+ break;
464
+ }
465
+ default:
466
+ throw new RangeError("invalid variant specified for RawInteger");
467
+ }
468
+ };
469
+ imports["rb-js-abi-host"]["export-js-value-to-host: func(value: handle<js-abi-value>) -> ()"] = function(arg0) {
470
+ obj.exportJsValueToHost(resources0.get(arg0));
471
+ };
472
+ imports["rb-js-abi-host"]["import-js-value-from-host: func() -> handle<js-abi-value>"] = function() {
473
+ const ret0 = obj.importJsValueFromHost();
474
+ return resources0.insert(ret0);
475
+ };
476
+ imports["rb-js-abi-host"]["js-value-typeof: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
477
+ const memory = get_export("memory");
478
+ const realloc = get_export("cabi_realloc");
479
+ const ret0 = obj.jsValueTypeof(resources0.get(arg0));
480
+ const ptr0 = utf8_encode(ret0, realloc, memory);
481
+ const len0 = UTF8_ENCODED_LEN;
482
+ data_view(memory).setInt32(arg1 + 4, len0, true);
483
+ data_view(memory).setInt32(arg1 + 0, ptr0, true);
484
+ };
485
+ imports["rb-js-abi-host"]["js-value-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
486
+ const ret0 = obj.jsValueEqual(resources0.get(arg0), resources0.get(arg1));
487
+ return ret0 ? 1 : 0;
488
+ };
489
+ imports["rb-js-abi-host"]["js-value-strictly-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
490
+ const ret0 = obj.jsValueStrictlyEqual(resources0.get(arg0), resources0.get(arg1));
491
+ return ret0 ? 1 : 0;
492
+ };
493
+ imports["rb-js-abi-host"]["reflect-apply: func(target: handle<js-abi-value>, this-argument: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
494
+ const memory = get_export("memory");
495
+ const len0 = arg3;
496
+ const base0 = arg2;
497
+ const result0 = [];
498
+ for (let i = 0; i < len0; i++) {
499
+ const base = base0 + i * 4;
500
+ result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
501
+ }
502
+ const ret0 = obj.reflectApply(resources0.get(arg0), resources0.get(arg1), result0);
503
+ const variant1 = ret0;
504
+ switch (variant1.tag) {
505
+ case "success": {
506
+ const e = variant1.val;
507
+ data_view(memory).setInt8(arg4 + 0, 0, true);
508
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
509
+ break;
510
+ }
511
+ case "failure": {
512
+ const e = variant1.val;
513
+ data_view(memory).setInt8(arg4 + 0, 1, true);
514
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
515
+ break;
516
+ }
517
+ default:
518
+ throw new RangeError("invalid variant specified for JsAbiResult");
519
+ }
520
+ };
521
+ imports["rb-js-abi-host"]["reflect-construct: func(target: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
522
+ const memory = get_export("memory");
523
+ const len0 = arg2;
524
+ const base0 = arg1;
525
+ const result0 = [];
526
+ for (let i = 0; i < len0; i++) {
527
+ const base = base0 + i * 4;
528
+ result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
529
+ }
530
+ const ret0 = obj.reflectConstruct(resources0.get(arg0), result0);
531
+ return resources0.insert(ret0);
532
+ };
533
+ imports["rb-js-abi-host"]["reflect-delete-property: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
534
+ const memory = get_export("memory");
535
+ const ptr0 = arg1;
536
+ const len0 = arg2;
537
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
538
+ const ret0 = obj.reflectDeleteProperty(resources0.get(arg0), result0);
539
+ return ret0 ? 1 : 0;
540
+ };
541
+ imports["rb-js-abi-host"]["reflect-get: func(target: handle<js-abi-value>, property-key: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3) {
542
+ const memory = get_export("memory");
543
+ const ptr0 = arg1;
544
+ const len0 = arg2;
545
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
546
+ const ret0 = obj.reflectGet(resources0.get(arg0), result0);
547
+ const variant1 = ret0;
548
+ switch (variant1.tag) {
549
+ case "success": {
550
+ const e = variant1.val;
551
+ data_view(memory).setInt8(arg3 + 0, 0, true);
552
+ data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
553
+ break;
554
+ }
555
+ case "failure": {
556
+ const e = variant1.val;
557
+ data_view(memory).setInt8(arg3 + 0, 1, true);
558
+ data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
559
+ break;
560
+ }
561
+ default:
562
+ throw new RangeError("invalid variant specified for JsAbiResult");
563
+ }
564
+ };
565
+ imports["rb-js-abi-host"]["reflect-get-own-property-descriptor: func(target: handle<js-abi-value>, property-key: string) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
566
+ const memory = get_export("memory");
567
+ const ptr0 = arg1;
568
+ const len0 = arg2;
569
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
570
+ const ret0 = obj.reflectGetOwnPropertyDescriptor(resources0.get(arg0), result0);
571
+ return resources0.insert(ret0);
572
+ };
573
+ imports["rb-js-abi-host"]["reflect-get-prototype-of: func(target: handle<js-abi-value>) -> handle<js-abi-value>"] = function(arg0) {
574
+ const ret0 = obj.reflectGetPrototypeOf(resources0.get(arg0));
575
+ return resources0.insert(ret0);
576
+ };
577
+ imports["rb-js-abi-host"]["reflect-has: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
578
+ const memory = get_export("memory");
579
+ const ptr0 = arg1;
580
+ const len0 = arg2;
581
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
582
+ const ret0 = obj.reflectHas(resources0.get(arg0), result0);
583
+ return ret0 ? 1 : 0;
584
+ };
585
+ imports["rb-js-abi-host"]["reflect-is-extensible: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
586
+ const ret0 = obj.reflectIsExtensible(resources0.get(arg0));
587
+ return ret0 ? 1 : 0;
588
+ };
589
+ imports["rb-js-abi-host"]["reflect-own-keys: func(target: handle<js-abi-value>) -> list<handle<js-abi-value>>"] = function(arg0, arg1) {
590
+ const memory = get_export("memory");
591
+ const realloc = get_export("cabi_realloc");
592
+ const ret0 = obj.reflectOwnKeys(resources0.get(arg0));
593
+ const vec0 = ret0;
594
+ const len0 = vec0.length;
595
+ const result0 = realloc(0, 0, 4, len0 * 4);
596
+ for (let i = 0; i < vec0.length; i++) {
597
+ const e = vec0[i];
598
+ const base = result0 + i * 4;
599
+ data_view(memory).setInt32(base + 0, resources0.insert(e), true);
600
+ }
601
+ data_view(memory).setInt32(arg1 + 4, len0, true);
602
+ data_view(memory).setInt32(arg1 + 0, result0, true);
603
+ };
604
+ imports["rb-js-abi-host"]["reflect-prevent-extensions: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
605
+ const ret0 = obj.reflectPreventExtensions(resources0.get(arg0));
606
+ return ret0 ? 1 : 0;
607
+ };
608
+ imports["rb-js-abi-host"]["reflect-set: func(target: handle<js-abi-value>, property-key: string, value: handle<js-abi-value>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
609
+ const memory = get_export("memory");
610
+ const ptr0 = arg1;
611
+ const len0 = arg2;
612
+ const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
613
+ const ret0 = obj.reflectSet(resources0.get(arg0), result0, resources0.get(arg3));
614
+ const variant1 = ret0;
615
+ switch (variant1.tag) {
616
+ case "success": {
617
+ const e = variant1.val;
618
+ data_view(memory).setInt8(arg4 + 0, 0, true);
619
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
620
+ break;
621
+ }
622
+ case "failure": {
623
+ const e = variant1.val;
624
+ data_view(memory).setInt8(arg4 + 0, 1, true);
625
+ data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
626
+ break;
627
+ }
628
+ default:
629
+ throw new RangeError("invalid variant specified for JsAbiResult");
630
+ }
631
+ };
632
+ imports["rb-js-abi-host"]["reflect-set-prototype-of: func(target: handle<js-abi-value>, prototype: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
633
+ const ret0 = obj.reflectSetPrototypeOf(resources0.get(arg0), resources0.get(arg1));
634
+ return ret0 ? 1 : 0;
635
+ };
636
+ if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
637
+
638
+ const resources0 = new Slab();
639
+ imports.canonical_abi["resource_drop_js-abi-value"] = (i) => {
640
+ const val = resources0.remove(i);
641
+ if (obj.dropJsAbiValue)
642
+ obj.dropJsAbiValue(val);
643
+ };
644
+ }
645
+
646
+ class LegacyBinding extends RbAbiGuest {
647
+ async setInstance(instance) {
648
+ await this.instantiate(instance);
649
+ }
650
+ }
651
+ class ComponentBinding {
652
+ constructor() { }
653
+ setUnderlying(underlying) {
654
+ this.underlying = underlying;
655
+ }
656
+ rubyShowVersion() {
657
+ this.underlying.rubyShowVersion();
658
+ }
659
+ rubyInit(args) {
660
+ this.underlying.rubyInit(args);
661
+ }
662
+ rubyInitLoadpath() {
663
+ this.underlying.rubyInitLoadpath();
664
+ }
665
+ rbEvalStringProtect(str) {
666
+ return this.underlying.rbEvalStringProtect(str);
667
+ }
668
+ rbFuncallvProtect(recv, mid, args) {
669
+ return this.underlying.rbFuncallvProtect(recv, mid, args);
670
+ }
671
+ rbIntern(name) {
672
+ return this.underlying.rbIntern(name);
673
+ }
674
+ rbErrinfo() {
675
+ return this.underlying.rbErrinfo();
676
+ }
677
+ rbClearErrinfo() {
678
+ return this.underlying.rbClearErrinfo();
679
+ }
680
+ rstringPtr(value) {
681
+ return this.underlying.rstringPtr(value);
682
+ }
683
+ rbVmBugreport() {
684
+ this.underlying.rbVmBugreport();
685
+ }
686
+ rbGcEnable() {
687
+ return this.underlying.rbGcEnable();
688
+ }
689
+ rbGcDisable() {
690
+ return this.underlying.rbGcDisable();
691
+ }
692
+ rbSetShouldProhibitRewind(newValue) {
693
+ return this.underlying.rbSetShouldProhibitRewind(newValue);
694
+ }
695
+ async setInstance(instance) {
696
+ // No-op
697
+ }
698
+ addToImports(imports) {
699
+ // No-op
700
+ }
701
+ }
702
+
703
+ /**
704
+ * A Ruby VM instance
705
+ * @see {@link RubyVM.instantiateComponent} and {@link RubyVM.instantiateModule} to create a new instance
706
+ * @category Essentials
707
+ */
708
+ class RubyVM {
709
+ /**
710
+ * Instantiate a Ruby VM with the given WebAssembly Core module with WASI Preview 1 implementation.
711
+ *
712
+ * @param options The options to instantiate the Ruby VM
713
+ * @returns A promise that resolves to the Ruby VM instance and the WebAssembly instance
714
+ * @category Essentials
715
+ *
716
+ * @example
717
+ *
718
+ * import { WASI } from "@bjorn3/browser_wasi_shim";
719
+ * const wasip1 = new WASI([], [], []);
720
+ * const module = await WebAssembly.compile("./path/to/ruby.wasm");
721
+ * const { vm } = await RubyVM.instantiateModule({ module, wasip1 });
722
+ *
723
+ */
724
+ static async instantiateModule(options) {
725
+ var _a, _b;
726
+ const { module, wasip1 } = options;
727
+ const vm = new RubyVM();
728
+ const imports = {
729
+ wasi_snapshot_preview1: wasip1.wasiImport,
730
+ };
731
+ vm.addToImports(imports);
732
+ (_a = options.addToImports) === null || _a === void 0 ? void 0 : _a.call(options, imports);
733
+ const instance = await WebAssembly.instantiate(module, imports);
734
+ try {
735
+ await vm.setInstance(instance);
736
+ }
737
+ catch (e) {
738
+ console.error("Failed to instantiate Ruby VM. Please make sure that you have added `gem \"js\"` to your Gemfile.");
739
+ throw e;
740
+ }
741
+ (_b = options.setMemory) === null || _b === void 0 ? void 0 : _b.call(options, instance.exports.memory);
742
+ wasip1.initialize(instance);
743
+ vm.initialize(options.args);
744
+ return { vm, instance };
745
+ }
746
+ /**
747
+ * Instantiate a Ruby VM with the given WebAssembly component with WASI Preview 2 implementation.
748
+ *
749
+ * @param options The options to instantiate the Ruby VM
750
+ * @returns A promise that resolves to the Ruby VM instance
751
+ * @category Essentials
752
+ *
753
+ * @example
754
+ *
755
+ * // First, you need to transpile the Ruby component to a JavaScript module using jco.
756
+ * // $ jco transpile --no-wasi-shim --instantiation --valid-lifting-optimization ./ruby.component.wasm -o ./component
757
+ * // Then, you can instantiate the Ruby VM with the component:
758
+ *
759
+ * import * as wasip2 from "@bytecodealliance/preview2-shim"
760
+ * import fs from "fs/promises";
761
+ * import path from "path";
762
+ *
763
+ * const { instantiate } = await import("./component/ruby.component.js");
764
+ * const getCoreModule = async (relativePath) => {
765
+ * const buffer = await fs.readFile(path.join("./component", relativePath));
766
+ * return WebAssembly.compile(buffer);
767
+ * }
768
+ *
769
+ * const { vm } = await RubyVM.instantiateComponent({
770
+ * instantiate, getCoreModule, wasip2,
771
+ * });
772
+ *
773
+ */
774
+ static async instantiateComponent(options) {
775
+ let initComponent;
776
+ if ("getCoreModule" in options) {
777
+ // A convenience overload to instantiate with "instantiate" function generated by jco
778
+ initComponent = async (jsRuntime) => {
779
+ const { instantiate, getCoreModule, wasip2 } = options;
780
+ const { cli, clocks, filesystem, io, random, sockets, http } = wasip2;
781
+ const importObject = {
782
+ "ruby:js/js-runtime": jsRuntime,
783
+ "wasi:cli/environment": cli.environment,
784
+ "wasi:cli/exit": cli.exit,
785
+ "wasi:cli/stderr": cli.stderr,
786
+ "wasi:cli/stdin": cli.stdin,
787
+ "wasi:cli/stdout": cli.stdout,
788
+ "wasi:cli/terminal-input": cli.terminalInput,
789
+ "wasi:cli/terminal-output": cli.terminalOutput,
790
+ "wasi:cli/terminal-stderr": cli.terminalStderr,
791
+ "wasi:cli/terminal-stdin": cli.terminalStdin,
792
+ "wasi:cli/terminal-stdout": cli.terminalStdout,
793
+ "wasi:clocks/monotonic-clock": clocks.monotonicClock,
794
+ "wasi:clocks/wall-clock": clocks.wallClock,
795
+ "wasi:filesystem/preopens": filesystem.preopens,
796
+ "wasi:filesystem/types": filesystem.types,
797
+ "wasi:io/error": io.error,
798
+ "wasi:io/poll": io.poll,
799
+ "wasi:io/streams": io.streams,
800
+ "wasi:random/random": random.random,
801
+ "wasi:sockets/tcp": sockets.tcp,
802
+ "wasi:http/types": http.types,
803
+ "wasi:http/incoming-handler": http.incomingHandler,
804
+ "wasi:http/outgoing-handler": http.outgoingHandler,
805
+ };
806
+ const component = await instantiate(getCoreModule, importObject, options.instantiateCore);
807
+ return component.rubyRuntime;
808
+ };
809
+ }
810
+ else {
811
+ initComponent = options.instantiate;
812
+ }
813
+ const vm = await this._instantiate({}, initComponent);
814
+ return { vm };
815
+ }
816
+ constructor(binding) {
817
+ this.instance = null;
818
+ this.interfaceState = {
819
+ hasJSFrameAfterRbFrame: false,
820
+ };
821
+ // Wrap exported functions from Ruby VM to prohibit nested VM operation
822
+ // if the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby.
823
+ const proxyExports = (exports) => {
824
+ const excludedMethods = [
825
+ "setInstance",
826
+ "addToImports",
827
+ "instantiate",
828
+ "rbSetShouldProhibitRewind",
829
+ "rbGcDisable",
830
+ "rbGcEnable",
831
+ ];
832
+ const excluded = ["constructor"].concat(excludedMethods);
833
+ // wrap all methods in RbAbi.RbAbiGuest class
834
+ for (const key of Object.getOwnPropertyNames(RbAbiGuest.prototype)) {
835
+ if (excluded.includes(key)) {
836
+ continue;
837
+ }
838
+ const value = exports[key];
839
+ if (typeof value === "function") {
840
+ exports[key] = (...args) => {
841
+ const isNestedVMCall = this.interfaceState.hasJSFrameAfterRbFrame;
842
+ if (isNestedVMCall) {
843
+ const oldShouldProhibitRewind = this.guest.rbSetShouldProhibitRewind(true);
844
+ const oldIsDisabledGc = this.guest.rbGcDisable();
845
+ const result = Reflect.apply(value, exports, args);
846
+ this.guest.rbSetShouldProhibitRewind(oldShouldProhibitRewind);
847
+ if (!oldIsDisabledGc) {
848
+ this.guest.rbGcEnable();
849
+ }
850
+ return result;
851
+ }
852
+ else {
853
+ return Reflect.apply(value, exports, args);
854
+ }
855
+ };
856
+ }
857
+ }
858
+ return exports;
859
+ };
860
+ this.guest = proxyExports(binding !== null && binding !== void 0 ? binding : new LegacyBinding());
861
+ this.transport = new JsValueTransport();
862
+ this.exceptionFormatter = new RbExceptionFormatter();
863
+ }
864
+ static async _instantiate(options, initComponent) {
865
+ const binding = new ComponentBinding();
866
+ const vm = new RubyVM(binding);
867
+ class JsAbiValue {
868
+ constructor(underlying) {
869
+ this.underlying = underlying;
870
+ }
871
+ }
872
+ const imports = vm.getImports((from) => new JsAbiValue(from), (to) => to.underlying);
873
+ const component = await initComponent(Object.assign(Object.assign({}, imports), { throwProhibitRewindException: (message) => {
874
+ vm.throwProhibitRewindException(message);
875
+ }, procToJsFunction: () => {
876
+ const rbValue = new RbValue(component.exportRbValueToJs(), vm, vm.privateObject());
877
+ return new JsAbiValue((...args) => {
878
+ return rbValue.call("call", ...args.map((arg) => vm.wrap(arg))).toJS();
879
+ });
880
+ }, rbObjectToJsRbValue: () => {
881
+ const rbValue = new RbValue(component.exportRbValueToJs(), vm, vm.privateObject());
882
+ return new JsAbiValue(rbValue);
883
+ }, JsAbiValue: JsAbiValue }));
884
+ binding.setUnderlying(component);
885
+ vm.initialize(options.args);
886
+ return vm;
887
+ }
888
+ /**
889
+ * Initialize the Ruby VM with the given command line arguments
890
+ * @param args The command line arguments to pass to Ruby. Must be
891
+ * an array of strings starting with the Ruby program name.
892
+ * @category Low-level initialization
893
+ */
894
+ initialize(args = ["ruby.wasm", "-EUTF-8", "-e_=0"]) {
895
+ const c_args = args.map((arg) => arg + "\0");
896
+ this.guest.rubyInit(c_args);
897
+ try {
898
+ this.eval(`
899
+ # Require Bundler standalone setup
900
+ if File.exist?("/bundle/bundler/setup.rb")
901
+ require "/bundle/bundler/setup.rb"
902
+ elsif File.exist?("/bundle/setup.rb")
903
+ # For non-CM builds, which doesn't use Bundler's standalone mode
904
+ require "/bundle/setup.rb"
905
+ end
906
+ `);
907
+ }
908
+ catch (e) {
909
+ console.warn("Failed to load /bundle/setup", e);
910
+ }
911
+ }
912
+ /**
913
+ * Set a given instance to interact JavaScript and Ruby's
914
+ * WebAssembly instance. This method must be called before calling
915
+ * Ruby API.
916
+ *
917
+ * @param instance The WebAssembly instance to interact with. Must
918
+ * be instantiated from a Ruby built with JS extension, and built
919
+ * with Reactor ABI instead of command line.
920
+ * @category Low-level initialization
921
+ */
922
+ async setInstance(instance) {
923
+ this.instance = instance;
924
+ await this.guest.setInstance(instance);
925
+ }
926
+ /**
927
+ * Add intrinsic import entries, which is necessary to interact JavaScript
928
+ * and Ruby's WebAssembly instance.
929
+ * @param imports The import object to add to the WebAssembly instance
930
+ * @category Low-level initialization
931
+ */
932
+ addToImports(imports) {
933
+ this.guest.addToImports(imports);
934
+ imports["rb-js-abi-host"] = {
935
+ rb_wasm_throw_prohibit_rewind_exception: (messagePtr, messageLen) => {
936
+ const memory = this.instance.exports.memory;
937
+ const str = new TextDecoder().decode(new Uint8Array(memory.buffer, messagePtr, messageLen));
938
+ this.throwProhibitRewindException(str);
939
+ },
940
+ };
941
+ addRbJsAbiHostToImports(imports, this.getImports((value) => value, (value) => value), (name) => {
942
+ return this.instance.exports[name];
943
+ });
944
+ }
945
+ throwProhibitRewindException(str) {
946
+ let message = "Ruby APIs that may rewind the VM stack are prohibited under nested VM operation " +
947
+ `(${str})\n` +
948
+ "Nested VM operation means that the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby " +
949
+ "caused by something like `window.rubyVM.eval(\"JS.global[:rubyVM].eval('Fiber.yield')\")`\n" +
950
+ "\n" +
951
+ "Please check your call stack and make sure that you are **not** doing any of the following inside the nested Ruby frame:\n" +
952
+ " 1. Switching fibers (e.g. Fiber#resume, Fiber.yield, and Fiber#transfer)\n" +
953
+ " Note that `evalAsync` JS API switches fibers internally\n" +
954
+ " 2. Raising uncaught exceptions\n" +
955
+ " Please catch all exceptions inside the nested operation\n" +
956
+ " 3. Calling Continuation APIs\n";
957
+ const error = new RbValue(this.guest.rbErrinfo(), this, this.privateObject());
958
+ if (error.call("nil?").toString() === "false") {
959
+ message += "\n" + this.exceptionFormatter.format(error, this, this.privateObject());
960
+ }
961
+ throw new RbFatalError(message);
962
+ }
963
+ getImports(toJSAbiValue, fromJSAbiValue) {
964
+ // NOTE: The GC may collect objects that are still referenced by Wasm
965
+ // locals because Asyncify cannot scan the Wasm stack above the JS frame.
966
+ // So we need to keep track whether the JS frame is sandwitched by Ruby
967
+ // frames or not, and prohibit nested VM operation if it is.
968
+ const proxyImports = (imports) => {
969
+ for (const [key, value] of Object.entries(imports)) {
970
+ if (typeof value === "function") {
971
+ imports[key] = (...args) => {
972
+ const oldValue = this.interfaceState.hasJSFrameAfterRbFrame;
973
+ this.interfaceState.hasJSFrameAfterRbFrame = true;
974
+ const result = Reflect.apply(value, imports, args);
975
+ this.interfaceState.hasJSFrameAfterRbFrame = oldValue;
976
+ return result;
977
+ };
978
+ }
979
+ }
980
+ return imports;
981
+ };
982
+ function wrapTry(f) {
983
+ return (...args) => {
984
+ try {
985
+ return { tag: "success", val: f(...args) };
986
+ }
987
+ catch (e) {
988
+ if (e instanceof RbFatalError) {
989
+ // RbFatalError should not be caught by Ruby because it Ruby VM
990
+ // can be already in an inconsistent state.
991
+ throw e;
992
+ }
993
+ return { tag: "failure", val: toJSAbiValue(e) };
994
+ }
995
+ };
996
+ }
997
+ return proxyImports({
998
+ evalJs: wrapTry((code) => {
999
+ return toJSAbiValue(Function(code)());
1000
+ }),
1001
+ isJs: (value) => {
1002
+ // Just for compatibility with the old JS API
1003
+ return true;
1004
+ },
1005
+ globalThis: () => {
1006
+ if (typeof globalThis !== "undefined") {
1007
+ return toJSAbiValue(globalThis);
1008
+ }
1009
+ else if (typeof global !== "undefined") {
1010
+ return toJSAbiValue(global);
1011
+ }
1012
+ else if (typeof window !== "undefined") {
1013
+ return toJSAbiValue(window);
1014
+ }
1015
+ throw new Error("unable to locate global object");
1016
+ },
1017
+ intToJsNumber: (value) => {
1018
+ return toJSAbiValue(value);
1019
+ },
1020
+ floatToJsNumber: (value) => {
1021
+ return toJSAbiValue(value);
1022
+ },
1023
+ stringToJsString: (value) => {
1024
+ return toJSAbiValue(value);
1025
+ },
1026
+ boolToJsBool: (value) => {
1027
+ return toJSAbiValue(value);
1028
+ },
1029
+ procToJsFunction: (rawRbAbiValue) => {
1030
+ const rbValue = this.rbValueOfPointer(rawRbAbiValue);
1031
+ return toJSAbiValue((...args) => {
1032
+ return rbValue.call("call", ...args.map((arg) => this.wrap(arg))).toJS();
1033
+ });
1034
+ },
1035
+ rbObjectToJsRbValue: (rawRbAbiValue) => {
1036
+ return toJSAbiValue(this.rbValueOfPointer(rawRbAbiValue));
1037
+ },
1038
+ jsValueToString: (value) => {
1039
+ value = fromJSAbiValue(value);
1040
+ // According to the [spec](https://tc39.es/ecma262/multipage/text-processing.html#sec-string-constructor-string-value)
1041
+ // `String(value)` always returns a string.
1042
+ return String(value);
1043
+ },
1044
+ jsValueToInteger(value) {
1045
+ value = fromJSAbiValue(value);
1046
+ if (typeof value === "number") {
1047
+ return { tag: "as-float", val: value };
1048
+ }
1049
+ else if (typeof value === "bigint") {
1050
+ return { tag: "bignum", val: BigInt(value).toString(10) + "\0" };
1051
+ }
1052
+ else if (typeof value === "string") {
1053
+ return { tag: "bignum", val: value + "\0" };
1054
+ }
1055
+ else if (typeof value === "undefined") {
1056
+ return { tag: "as-float", val: 0 };
1057
+ }
1058
+ else {
1059
+ return { tag: "as-float", val: Number(value) };
1060
+ }
1061
+ },
1062
+ exportJsValueToHost: (value) => {
1063
+ // See `JsValueExporter` for the reason why we need to do this
1064
+ this.transport.takeJsValue(fromJSAbiValue(value));
1065
+ },
1066
+ importJsValueFromHost: () => {
1067
+ return toJSAbiValue(this.transport.consumeJsValue());
1068
+ },
1069
+ instanceOf: (value, klass) => {
1070
+ klass = fromJSAbiValue(klass);
1071
+ if (typeof klass === "function") {
1072
+ return fromJSAbiValue(value) instanceof klass;
1073
+ }
1074
+ else {
1075
+ return false;
1076
+ }
1077
+ },
1078
+ jsValueTypeof(value) {
1079
+ return typeof fromJSAbiValue(value);
1080
+ },
1081
+ jsValueEqual(lhs, rhs) {
1082
+ return fromJSAbiValue(lhs) == fromJSAbiValue(rhs);
1083
+ },
1084
+ jsValueStrictlyEqual(lhs, rhs) {
1085
+ return fromJSAbiValue(lhs) === fromJSAbiValue(rhs);
1086
+ },
1087
+ reflectApply: wrapTry((target, thisArgument, args) => {
1088
+ const jsArgs = args.map((arg) => fromJSAbiValue(arg));
1089
+ return toJSAbiValue(Reflect.apply(fromJSAbiValue(target), fromJSAbiValue(thisArgument), jsArgs));
1090
+ }),
1091
+ reflectConstruct: function (target, args) {
1092
+ throw new Error("Function not implemented.");
1093
+ },
1094
+ reflectDeleteProperty: function (target, propertyKey) {
1095
+ throw new Error("Function not implemented.");
1096
+ },
1097
+ reflectGet: wrapTry((target, propertyKey) => {
1098
+ return toJSAbiValue(fromJSAbiValue(target)[propertyKey]);
1099
+ }),
1100
+ reflectGetOwnPropertyDescriptor: function (target, propertyKey) {
1101
+ throw new Error("Function not implemented.");
1102
+ },
1103
+ reflectGetPrototypeOf: function (target) {
1104
+ throw new Error("Function not implemented.");
1105
+ },
1106
+ reflectHas: function (target, propertyKey) {
1107
+ throw new Error("Function not implemented.");
1108
+ },
1109
+ reflectIsExtensible: function (target) {
1110
+ throw new Error("Function not implemented.");
1111
+ },
1112
+ reflectOwnKeys: function (target) {
1113
+ throw new Error("Function not implemented.");
1114
+ },
1115
+ reflectPreventExtensions: function (target) {
1116
+ throw new Error("Function not implemented.");
1117
+ },
1118
+ reflectSet: wrapTry((target, propertyKey, value) => {
1119
+ return toJSAbiValue(Reflect.set(fromJSAbiValue(target), propertyKey, fromJSAbiValue(value)));
1120
+ }),
1121
+ reflectSetPrototypeOf: function (target, prototype) {
1122
+ throw new Error("Function not implemented.");
1123
+ },
1124
+ });
1125
+ }
1126
+ /**
1127
+ * Print the Ruby version to stdout
1128
+ */
1129
+ printVersion() {
1130
+ this.guest.rubyShowVersion();
1131
+ }
1132
+ /**
1133
+ * Runs a string of Ruby code from JavaScript
1134
+ * @param code The Ruby code to run
1135
+ * @returns the result of the last expression
1136
+ * @category Essentials
1137
+ *
1138
+ * @example
1139
+ * vm.eval("puts 'hello world'");
1140
+ * const result = vm.eval("1 + 2");
1141
+ * console.log(result.toString()); // 3
1142
+ *
1143
+ */
1144
+ eval(code) {
1145
+ return evalRbCode(this, this.privateObject(), code);
1146
+ }
1147
+ /**
1148
+ * Runs a string of Ruby code with top-level `JS::Object#await`
1149
+ * Returns a promise that resolves when execution completes.
1150
+ * @param code The Ruby code to run
1151
+ * @returns a promise that resolves to the result of the last expression
1152
+ * @category Essentials
1153
+ *
1154
+ * @example
1155
+ * const text = await vm.evalAsync(`
1156
+ * require 'js'
1157
+ * response = JS.global.fetch('https://example.com').await
1158
+ * response.text.await
1159
+ * `);
1160
+ * console.log(text.toString()); // <html>...</html>
1161
+ */
1162
+ evalAsync(code) {
1163
+ const JS = this.eval("require 'js'; JS");
1164
+ return newRbPromise(this, this.privateObject(), (future) => {
1165
+ JS.call("__eval_async_rb", this.wrap(code), future);
1166
+ });
1167
+ }
1168
+ /**
1169
+ * Wrap a JavaScript value into a Ruby JS::Object
1170
+ * @param value The value to convert to RbValue
1171
+ * @returns the RbValue object representing the given JS value
1172
+ *
1173
+ * @example
1174
+ * const hash = vm.eval(`Hash.new`)
1175
+ * hash.call("store", vm.eval(`"key1"`), vm.wrap(new Object()));
1176
+ */
1177
+ wrap(value) {
1178
+ return this.transport.importJsValue(value, this);
1179
+ }
1180
+ /** @private */
1181
+ privateObject() {
1182
+ return {
1183
+ transport: this.transport,
1184
+ exceptionFormatter: this.exceptionFormatter,
1185
+ };
1186
+ }
1187
+ /** @private */
1188
+ rbValueOfPointer(pointer) {
1189
+ const abiValue = new RbAbiValue(pointer, this.guest);
1190
+ return new RbValue(abiValue, this, this.privateObject());
1191
+ }
1192
+ }
1193
+ /**
1194
+ * Export a JS value held by the Ruby VM to the JS environment.
1195
+ * This is implemented in a dirty way since wit cannot reference resources
1196
+ * defined in other interfaces.
1197
+ * In our case, we can't express `function(v: rb-abi-value) -> js-abi-value`
1198
+ * because `rb-js-abi-host.wit`, that defines `js-abi-value`, is implemented
1199
+ * by embedder side (JS) but `rb-abi-guest.wit`, that defines `rb-abi-value`
1200
+ * is implemented by guest side (Wasm).
1201
+ *
1202
+ * This class is a helper to export by:
1203
+ * 1. Call `function __export_to_js(v: rb-abi-value)` defined in guest from embedder side.
1204
+ * 2. Call `function takeJsValue(v: js-abi-value)` defined in embedder from guest side with
1205
+ * underlying JS value of given `rb-abi-value`.
1206
+ * 3. Then `takeJsValue` implementation escapes the given JS value to the `_takenJsValues`
1207
+ * stored in embedder side.
1208
+ * 4. Finally, embedder side can take `_takenJsValues`.
1209
+ *
1210
+ * Note that `exportJsValue` is not reentrant.
1211
+ *
1212
+ * @private
1213
+ */
1214
+ class JsValueTransport {
1215
+ constructor() {
1216
+ this._takenJsValue = null;
1217
+ }
1218
+ takeJsValue(value) {
1219
+ this._takenJsValue = value;
1220
+ }
1221
+ consumeJsValue() {
1222
+ return this._takenJsValue;
1223
+ }
1224
+ exportJsValue(value) {
1225
+ value.call("__export_to_js");
1226
+ return this._takenJsValue;
1227
+ }
1228
+ importJsValue(value, vm) {
1229
+ this._takenJsValue = value;
1230
+ return vm.eval('require "js"; JS::Object').call("__import_from_js");
1231
+ }
1232
+ }
1233
+ /**
1234
+ * A RbValue is an object that represents a value in Ruby
1235
+ * @category Essentials
1236
+ */
1237
+ class RbValue {
1238
+ /**
1239
+ * @hideconstructor
1240
+ */
1241
+ constructor(inner, vm, privateObject) {
1242
+ this.inner = inner;
1243
+ this.vm = vm;
1244
+ this.privateObject = privateObject;
1245
+ }
1246
+ /**
1247
+ * Call a given method with given arguments
1248
+ *
1249
+ * @param callee name of the Ruby method to call
1250
+ * @param args arguments to pass to the method. Must be an array of RbValue
1251
+ * @returns The result of the method call as a new RbValue.
1252
+ *
1253
+ * @example
1254
+ * const ary = vm.eval("[1, 2, 3]");
1255
+ * ary.call("push", 4);
1256
+ * console.log(ary.call("sample").toString());
1257
+ */
1258
+ call(callee, ...args) {
1259
+ const innerArgs = args.map((arg) => arg.inner);
1260
+ return new RbValue(callRbMethod(this.vm, this.privateObject, this.inner, callee, innerArgs), this.vm, this.privateObject);
1261
+ }
1262
+ /**
1263
+ * Call a given method that may call `JS::Object#await` with given arguments
1264
+ *
1265
+ * @param callee name of the Ruby method to call
1266
+ * @param args arguments to pass to the method. Must be an array of RbValue
1267
+ * @returns A Promise that resolves to the result of the method call as a new RbValue.
1268
+ *
1269
+ * @example
1270
+ * const client = vm.eval(`
1271
+ * require 'js'
1272
+ * class HttpClient
1273
+ * def get(url)
1274
+ * JS.global.fetch(url).await
1275
+ * end
1276
+ * end
1277
+ * HttpClient.new
1278
+ * `);
1279
+ * const response = await client.callAsync("get", vm.eval(`"https://example.com"`));
1280
+ */
1281
+ callAsync(callee, ...args) {
1282
+ const JS = this.vm.eval("require 'js'; JS");
1283
+ return newRbPromise(this.vm, this.privateObject, (future) => {
1284
+ JS.call("__call_async_method", this, this.vm.wrap(callee), future, ...args);
1285
+ });
1286
+ }
1287
+ /**
1288
+ * @see {@link https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive}
1289
+ * @param hint Preferred type of the result primitive value. `"number"`, `"string"`, or `"default"`.
1290
+ */
1291
+ [Symbol.toPrimitive](hint) {
1292
+ if (hint === "string" || hint === "default") {
1293
+ return this.toString();
1294
+ }
1295
+ else if (hint === "number") {
1296
+ return null;
1297
+ }
1298
+ return null;
1299
+ }
1300
+ /**
1301
+ * Returns a string representation of the value by calling `to_s`
1302
+ */
1303
+ toString() {
1304
+ const rbString = callRbMethod(this.vm, this.privateObject, this.inner, "to_s", []);
1305
+ return this.vm.guest.rstringPtr(rbString);
1306
+ }
1307
+ /**
1308
+ * Returns a JavaScript object representation of the value
1309
+ * by calling `to_js`.
1310
+ *
1311
+ * Returns null if the value is not convertible to a JavaScript object.
1312
+ */
1313
+ toJS() {
1314
+ const JS = this.vm.eval("JS");
1315
+ const jsValue = JS.call("try_convert", this);
1316
+ if (jsValue.call("nil?").toString() === "true") {
1317
+ return null;
1318
+ }
1319
+ return this.privateObject.transport.exportJsValue(jsValue);
1320
+ }
1321
+ }
1322
+ var ruby_tag_type;
1323
+ (function (ruby_tag_type) {
1324
+ ruby_tag_type[ruby_tag_type["None"] = 0] = "None";
1325
+ ruby_tag_type[ruby_tag_type["Return"] = 1] = "Return";
1326
+ ruby_tag_type[ruby_tag_type["Break"] = 2] = "Break";
1327
+ ruby_tag_type[ruby_tag_type["Next"] = 3] = "Next";
1328
+ ruby_tag_type[ruby_tag_type["Retry"] = 4] = "Retry";
1329
+ ruby_tag_type[ruby_tag_type["Redo"] = 5] = "Redo";
1330
+ ruby_tag_type[ruby_tag_type["Raise"] = 6] = "Raise";
1331
+ ruby_tag_type[ruby_tag_type["Throw"] = 7] = "Throw";
1332
+ ruby_tag_type[ruby_tag_type["Fatal"] = 8] = "Fatal";
1333
+ ruby_tag_type[ruby_tag_type["Mask"] = 15] = "Mask";
1334
+ })(ruby_tag_type || (ruby_tag_type = {}));
1335
+ class RbExceptionFormatter {
1336
+ constructor() {
1337
+ this.literalsCache = null;
1338
+ this.isFormmatting = false;
1339
+ }
1340
+ format(error, vm, privateObject) {
1341
+ // All Ruby exceptions raised during formatting exception message should
1342
+ // be caught and return a fallback message.
1343
+ // Therefore, we don't need to worry about infinite recursion here ideally
1344
+ // but checking re-entrancy just in case.
1345
+ class RbExceptionFormatterError extends Error {
1346
+ }
1347
+ if (this.isFormmatting) {
1348
+ throw new RbExceptionFormatterError("Unexpected exception occurred during formatting exception message");
1349
+ }
1350
+ this.isFormmatting = true;
1351
+ try {
1352
+ return this._format(error, vm, privateObject);
1353
+ }
1354
+ finally {
1355
+ this.isFormmatting = false;
1356
+ }
1357
+ }
1358
+ _format(error, vm, privateObject) {
1359
+ const [zeroLiteral, oneLiteral, newLineLiteral] = (() => {
1360
+ if (this.literalsCache == null) {
1361
+ const zeroOneNewLine = [
1362
+ evalRbCode(vm, privateObject, "0"),
1363
+ evalRbCode(vm, privateObject, "1"),
1364
+ evalRbCode(vm, privateObject, `"\n"`),
1365
+ ];
1366
+ this.literalsCache = zeroOneNewLine;
1367
+ return zeroOneNewLine;
1368
+ }
1369
+ else {
1370
+ return this.literalsCache;
1371
+ }
1372
+ })();
1373
+ let className;
1374
+ let backtrace;
1375
+ let message;
1376
+ try {
1377
+ className = error.call("class").toString();
1378
+ }
1379
+ catch (e) {
1380
+ className = "unknown";
1381
+ }
1382
+ try {
1383
+ message = error.call("message").toString();
1384
+ }
1385
+ catch (e) {
1386
+ message = "unknown";
1387
+ }
1388
+ try {
1389
+ backtrace = error.call("backtrace");
1390
+ }
1391
+ catch (e) {
1392
+ return this.formatString(className, message);
1393
+ }
1394
+ if (backtrace.call("nil?").toString() === "true") {
1395
+ return this.formatString(className, message);
1396
+ }
1397
+ try {
1398
+ const firstLine = backtrace.call("at", zeroLiteral);
1399
+ const restLines = backtrace
1400
+ .call("drop", oneLiteral)
1401
+ .call("join", newLineLiteral);
1402
+ return this.formatString(className, message, [
1403
+ firstLine.toString(),
1404
+ restLines.toString(),
1405
+ ]);
1406
+ }
1407
+ catch (e) {
1408
+ return this.formatString(className, message);
1409
+ }
1410
+ }
1411
+ formatString(klass, message, backtrace) {
1412
+ if (backtrace) {
1413
+ return `${backtrace[0]}: ${message} (${klass})\n${backtrace[1]}`;
1414
+ }
1415
+ else {
1416
+ return `${klass}: ${message}`;
1417
+ }
1418
+ }
1419
+ }
1420
+ const checkStatusTag = (rawTag, vm, privateObject) => {
1421
+ switch (rawTag & ruby_tag_type.Mask) {
1422
+ case ruby_tag_type.None:
1423
+ break;
1424
+ case ruby_tag_type.Return:
1425
+ throw new RbError("unexpected return");
1426
+ case ruby_tag_type.Next:
1427
+ throw new RbError("unexpected next");
1428
+ case ruby_tag_type.Break:
1429
+ throw new RbError("unexpected break");
1430
+ case ruby_tag_type.Redo:
1431
+ throw new RbError("unexpected redo");
1432
+ case ruby_tag_type.Retry:
1433
+ throw new RbError("retry outside of rescue clause");
1434
+ case ruby_tag_type.Throw:
1435
+ throw new RbError("unexpected throw");
1436
+ case ruby_tag_type.Raise:
1437
+ case ruby_tag_type.Fatal:
1438
+ const error = new RbValue(vm.guest.rbErrinfo(), vm, privateObject);
1439
+ if (error.call("nil?").toString() === "true") {
1440
+ throw new RbError("no exception object");
1441
+ }
1442
+ // clear errinfo if got exception due to no rb_jump_tag
1443
+ vm.guest.rbClearErrinfo();
1444
+ throw new RbError(privateObject.exceptionFormatter.format(error, vm, privateObject));
1445
+ default:
1446
+ throw new RbError(`unknown error tag: ${rawTag}`);
1447
+ }
1448
+ };
1449
+ function wrapRbOperation(vm, body) {
1450
+ try {
1451
+ return body();
1452
+ }
1453
+ catch (e) {
1454
+ if (e instanceof RbError) {
1455
+ throw e;
1456
+ }
1457
+ // All JS exceptions triggered by Ruby code are translated to Ruby exceptions,
1458
+ // so non-RbError exceptions are unexpected.
1459
+ try {
1460
+ vm.guest.rbVmBugreport();
1461
+ }
1462
+ catch (e) {
1463
+ console.error("Tried to report internal Ruby VM state but failed: ", e);
1464
+ }
1465
+ if (e instanceof WebAssembly.RuntimeError && e.message === "unreachable") {
1466
+ const error = new RbError(`Something went wrong in Ruby VM: ${e}`);
1467
+ error.stack = e.stack;
1468
+ throw error;
1469
+ }
1470
+ else {
1471
+ throw e;
1472
+ }
1473
+ }
1474
+ }
1475
+ const callRbMethod = (vm, privateObject, recv, callee, args) => {
1476
+ const mid = vm.guest.rbIntern(callee + "\0");
1477
+ return wrapRbOperation(vm, () => {
1478
+ const [value, status] = vm.guest.rbFuncallvProtect(recv, mid, args);
1479
+ checkStatusTag(status, vm, privateObject);
1480
+ return value;
1481
+ });
1482
+ };
1483
+ const evalRbCode = (vm, privateObject, code) => {
1484
+ return wrapRbOperation(vm, () => {
1485
+ const [value, status] = vm.guest.rbEvalStringProtect(code + "\0");
1486
+ checkStatusTag(status, vm, privateObject);
1487
+ return new RbValue(value, vm, privateObject);
1488
+ });
1489
+ };
1490
+ function newRbPromise(vm, privateObject, body) {
1491
+ return new Promise((resolve, reject) => {
1492
+ const future = vm.wrap({
1493
+ resolve,
1494
+ reject: (error) => {
1495
+ const rbError = new RbError(privateObject.exceptionFormatter.format(error, vm, privateObject));
1496
+ reject(rbError);
1497
+ },
1498
+ });
1499
+ body(future);
1500
+ });
1501
+ }
1502
+ /**
1503
+ * Error class thrown by Ruby execution
1504
+ */
1505
+ class RbError extends Error {
1506
+ /**
1507
+ * @hideconstructor
1508
+ */
1509
+ constructor(message) {
1510
+ super(message);
1511
+ }
1512
+ }
1513
+ /**
1514
+ * Error class thrown by Ruby execution when it is not possible to recover.
1515
+ * This is usually caused when Ruby VM is in an inconsistent state.
1516
+ */
1517
+ class RbFatalError extends RbError {
1518
+ /**
1519
+ * @hideconstructor
1520
+ */
1521
+ constructor(message) {
1522
+ super("Ruby Fatal Error: " + message);
1523
+ }
1524
+ }
1525
+
1526
+ const DefaultRubyVM = async (rubyModule, options = {}) => {
1527
+ var _a, _b;
1528
+ const args = [];
1529
+ const env = Object.entries((_a = options.env) !== null && _a !== void 0 ? _a : {}).map(([k, v]) => `${k}=${v}`);
1530
+ const fds = [
1531
+ new OpenFile(new File([])),
1532
+ new OpenFile(new File([])),
1533
+ new OpenFile(new File([])),
1534
+ new PreopenDirectory("/", new Map()),
1535
+ ];
1536
+ const wasi = new WASI(args, env, fds, { debug: false });
1537
+ const printer = ((_b = options.consolePrint) !== null && _b !== void 0 ? _b : true) ? consolePrinter() : undefined;
1538
+ const { vm, instance } = await RubyVM.instantiateModule({
1539
+ module: rubyModule, wasip1: wasi,
1540
+ addToImports: (imports) => {
1541
+ printer === null || printer === void 0 ? void 0 : printer.addToImports(imports);
1542
+ },
1543
+ setMemory: (memory) => {
1544
+ printer === null || printer === void 0 ? void 0 : printer.setMemory(memory);
1545
+ }
1546
+ });
1547
+ return {
1548
+ vm,
1549
+ wasi,
1550
+ instance,
1551
+ };
1552
+ };
1553
+
1554
+ exports.DefaultRubyVM = DefaultRubyVM;
1555
+
1556
+ }));