trealla-multibundle
Version:
Trealla Prolog bindings for JS
3,637 lines • 109 kB
JavaScript
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// node_modules/browser_wasi_shim_gaiden/dist/wasi_defs.js
var wasi_defs_exports = {};
__export(wasi_defs_exports, {
ADVICE_DONTNEED: () => ADVICE_DONTNEED,
ADVICE_NOREUSE: () => ADVICE_NOREUSE,
ADVICE_NORMAL: () => ADVICE_NORMAL,
ADVICE_RANDOM: () => ADVICE_RANDOM,
ADVICE_SEQUENTIAL: () => ADVICE_SEQUENTIAL,
ADVICE_WILLNEED: () => ADVICE_WILLNEED,
CLOCKID_MONOTONIC: () => CLOCKID_MONOTONIC,
CLOCKID_PROCESS_CPUTIME_ID: () => CLOCKID_PROCESS_CPUTIME_ID,
CLOCKID_REALTIME: () => CLOCKID_REALTIME,
CLOCKID_THREAD_CPUTIME_ID: () => CLOCKID_THREAD_CPUTIME_ID,
Ciovec: () => Ciovec,
Dirent: () => Dirent,
ERRNO_2BIG: () => ERRNO_2BIG,
ERRNO_ACCES: () => ERRNO_ACCES,
ERRNO_ADDRINUSE: () => ERRNO_ADDRINUSE,
ERRNO_ADDRNOTAVAIL: () => ERRNO_ADDRNOTAVAIL,
ERRNO_AFNOSUPPORT: () => ERRNO_AFNOSUPPORT,
ERRNO_AGAIN: () => ERRNO_AGAIN,
ERRNO_ALREADY: () => ERRNO_ALREADY,
ERRNO_BADF: () => ERRNO_BADF,
ERRNO_BADMSG: () => ERRNO_BADMSG,
ERRNO_BUSY: () => ERRNO_BUSY,
ERRNO_CANCELED: () => ERRNO_CANCELED,
ERRNO_CHILD: () => ERRNO_CHILD,
ERRNO_CONNABORTED: () => ERRNO_CONNABORTED,
ERRNO_CONNREFUSED: () => ERRNO_CONNREFUSED,
ERRNO_CONNRESET: () => ERRNO_CONNRESET,
ERRNO_DEADLK: () => ERRNO_DEADLK,
ERRNO_DESTADDRREQ: () => ERRNO_DESTADDRREQ,
ERRNO_DOM: () => ERRNO_DOM,
ERRNO_DQUOT: () => ERRNO_DQUOT,
ERRNO_EXIST: () => ERRNO_EXIST,
ERRNO_FAULT: () => ERRNO_FAULT,
ERRNO_FBIG: () => ERRNO_FBIG,
ERRNO_HOSTUNREACH: () => ERRNO_HOSTUNREACH,
ERRNO_IDRM: () => ERRNO_IDRM,
ERRNO_ILSEQ: () => ERRNO_ILSEQ,
ERRNO_INPROGRESS: () => ERRNO_INPROGRESS,
ERRNO_INTR: () => ERRNO_INTR,
ERRNO_INVAL: () => ERRNO_INVAL,
ERRNO_IO: () => ERRNO_IO,
ERRNO_ISCONN: () => ERRNO_ISCONN,
ERRNO_ISDIR: () => ERRNO_ISDIR,
ERRNO_LOOP: () => ERRNO_LOOP,
ERRNO_MFILE: () => ERRNO_MFILE,
ERRNO_MLINK: () => ERRNO_MLINK,
ERRNO_MSGSIZE: () => ERRNO_MSGSIZE,
ERRNO_MULTIHOP: () => ERRNO_MULTIHOP,
ERRNO_NAMETOOLONG: () => ERRNO_NAMETOOLONG,
ERRNO_NETDOWN: () => ERRNO_NETDOWN,
ERRNO_NETRESET: () => ERRNO_NETRESET,
ERRNO_NETUNREACH: () => ERRNO_NETUNREACH,
ERRNO_NFILE: () => ERRNO_NFILE,
ERRNO_NOBUFS: () => ERRNO_NOBUFS,
ERRNO_NODEV: () => ERRNO_NODEV,
ERRNO_NOENT: () => ERRNO_NOENT,
ERRNO_NOEXEC: () => ERRNO_NOEXEC,
ERRNO_NOLCK: () => ERRNO_NOLCK,
ERRNO_NOLINK: () => ERRNO_NOLINK,
ERRNO_NOMEM: () => ERRNO_NOMEM,
ERRNO_NOMSG: () => ERRNO_NOMSG,
ERRNO_NOPROTOOPT: () => ERRNO_NOPROTOOPT,
ERRNO_NOSPC: () => ERRNO_NOSPC,
ERRNO_NOSYS: () => ERRNO_NOSYS,
ERRNO_NOTCAPABLE: () => ERRNO_NOTCAPABLE,
ERRNO_NOTCONN: () => ERRNO_NOTCONN,
ERRNO_NOTDIR: () => ERRNO_NOTDIR,
ERRNO_NOTEMPTY: () => ERRNO_NOTEMPTY,
ERRNO_NOTRECOVERABLE: () => ERRNO_NOTRECOVERABLE,
ERRNO_NOTSOCK: () => ERRNO_NOTSOCK,
ERRNO_NOTSUP: () => ERRNO_NOTSUP,
ERRNO_NOTTY: () => ERRNO_NOTTY,
ERRNO_NXIO: () => ERRNO_NXIO,
ERRNO_OVERFLOW: () => ERRNO_OVERFLOW,
ERRNO_OWNERDEAD: () => ERRNO_OWNERDEAD,
ERRNO_PERM: () => ERRNO_PERM,
ERRNO_PIPE: () => ERRNO_PIPE,
ERRNO_PROTO: () => ERRNO_PROTO,
ERRNO_PROTONOSUPPORT: () => ERRNO_PROTONOSUPPORT,
ERRNO_PROTOTYPE: () => ERRNO_PROTOTYPE,
ERRNO_RANGE: () => ERRNO_RANGE,
ERRNO_ROFS: () => ERRNO_ROFS,
ERRNO_SPIPE: () => ERRNO_SPIPE,
ERRNO_SRCH: () => ERRNO_SRCH,
ERRNO_STALE: () => ERRNO_STALE,
ERRNO_SUCCESS: () => ERRNO_SUCCESS,
ERRNO_TIMEDOUT: () => ERRNO_TIMEDOUT,
ERRNO_TXTBSY: () => ERRNO_TXTBSY,
ERRNO_XDEV: () => ERRNO_XDEV,
EVENTRWFLAGS_FD_READWRITE_HANGUP: () => EVENTRWFLAGS_FD_READWRITE_HANGUP,
EVENTTYPE_CLOCK: () => EVENTTYPE_CLOCK,
EVENTTYPE_FD_READ: () => EVENTTYPE_FD_READ,
EVENTTYPE_FD_WRITE: () => EVENTTYPE_FD_WRITE,
FDFLAGS_APPEND: () => FDFLAGS_APPEND,
FDFLAGS_DSYNC: () => FDFLAGS_DSYNC,
FDFLAGS_NONBLOCK: () => FDFLAGS_NONBLOCK,
FDFLAGS_RSYNC: () => FDFLAGS_RSYNC,
FDFLAGS_SYNC: () => FDFLAGS_SYNC,
FD_STDERR: () => FD_STDERR,
FD_STDIN: () => FD_STDIN,
FD_STDOUT: () => FD_STDOUT,
FILETYPE_BLOCK_DEVICE: () => FILETYPE_BLOCK_DEVICE,
FILETYPE_CHARACTER_DEVICE: () => FILETYPE_CHARACTER_DEVICE,
FILETYPE_DIRECTORY: () => FILETYPE_DIRECTORY,
FILETYPE_REGULAR_FILE: () => FILETYPE_REGULAR_FILE,
FILETYPE_SOCKET_DGRAM: () => FILETYPE_SOCKET_DGRAM,
FILETYPE_SOCKET_STREAM: () => FILETYPE_SOCKET_STREAM,
FILETYPE_SYMBOLIC_LINK: () => FILETYPE_SYMBOLIC_LINK,
FILETYPE_UNKNOWN: () => FILETYPE_UNKNOWN,
FSTFLAGS_ATIM: () => FSTFLAGS_ATIM,
FSTFLAGS_ATIM_NOW: () => FSTFLAGS_ATIM_NOW,
FSTFLAGS_MTIM: () => FSTFLAGS_MTIM,
FSTFLAGS_MTIM_NOW: () => FSTFLAGS_MTIM_NOW,
Fdstat: () => Fdstat,
Filestat: () => Filestat,
Iovec: () => Iovec,
OFLAGS_CREAT: () => OFLAGS_CREAT,
OFLAGS_DIRECTORY: () => OFLAGS_DIRECTORY,
OFLAGS_EXCL: () => OFLAGS_EXCL,
OFLAGS_TRUNC: () => OFLAGS_TRUNC,
PREOPENTYPE_DIR: () => PREOPENTYPE_DIR,
Prestat: () => Prestat,
PrestatDir: () => PrestatDir,
RIFLAGS_RECV_PEEK: () => RIFLAGS_RECV_PEEK,
RIFLAGS_RECV_WAITALL: () => RIFLAGS_RECV_WAITALL,
RIGHTS_FD_ADVISE: () => RIGHTS_FD_ADVISE,
RIGHTS_FD_ALLOCATE: () => RIGHTS_FD_ALLOCATE,
RIGHTS_FD_DATASYNC: () => RIGHTS_FD_DATASYNC,
RIGHTS_FD_FDSTAT_SET_FLAGS: () => RIGHTS_FD_FDSTAT_SET_FLAGS,
RIGHTS_FD_FILESTAT_GET: () => RIGHTS_FD_FILESTAT_GET,
RIGHTS_FD_FILESTAT_SET_SIZE: () => RIGHTS_FD_FILESTAT_SET_SIZE,
RIGHTS_FD_FILESTAT_SET_TIMES: () => RIGHTS_FD_FILESTAT_SET_TIMES,
RIGHTS_FD_READ: () => RIGHTS_FD_READ,
RIGHTS_FD_READDIR: () => RIGHTS_FD_READDIR,
RIGHTS_FD_SEEK: () => RIGHTS_FD_SEEK,
RIGHTS_FD_SYNC: () => RIGHTS_FD_SYNC,
RIGHTS_FD_TELL: () => RIGHTS_FD_TELL,
RIGHTS_FD_WRITE: () => RIGHTS_FD_WRITE,
RIGHTS_PATH_CREATE_DIRECTORY: () => RIGHTS_PATH_CREATE_DIRECTORY,
RIGHTS_PATH_CREATE_FILE: () => RIGHTS_PATH_CREATE_FILE,
RIGHTS_PATH_FILESTAT_GET: () => RIGHTS_PATH_FILESTAT_GET,
RIGHTS_PATH_FILESTAT_SET_SIZE: () => RIGHTS_PATH_FILESTAT_SET_SIZE,
RIGHTS_PATH_FILESTAT_SET_TIMES: () => RIGHTS_PATH_FILESTAT_SET_TIMES,
RIGHTS_PATH_LINK_SOURCE: () => RIGHTS_PATH_LINK_SOURCE,
RIGHTS_PATH_LINK_TARGET: () => RIGHTS_PATH_LINK_TARGET,
RIGHTS_PATH_OPEN: () => RIGHTS_PATH_OPEN,
RIGHTS_PATH_READLINK: () => RIGHTS_PATH_READLINK,
RIGHTS_PATH_REMOVE_DIRECTORY: () => RIGHTS_PATH_REMOVE_DIRECTORY,
RIGHTS_PATH_RENAME_SOURCE: () => RIGHTS_PATH_RENAME_SOURCE,
RIGHTS_PATH_RENAME_TARGET: () => RIGHTS_PATH_RENAME_TARGET,
RIGHTS_PATH_SYMLINK: () => RIGHTS_PATH_SYMLINK,
RIGHTS_PATH_UNLINK_FILE: () => RIGHTS_PATH_UNLINK_FILE,
RIGHTS_POLL_FD_READWRITE: () => RIGHTS_POLL_FD_READWRITE,
RIGHTS_SOCK_SHUTDOWN: () => RIGHTS_SOCK_SHUTDOWN,
ROFLAGS_RECV_DATA_TRUNCATED: () => ROFLAGS_RECV_DATA_TRUNCATED,
SDFLAGS_RD: () => SDFLAGS_RD,
SDFLAGS_WR: () => SDFLAGS_WR,
SIGNAL_ABRT: () => SIGNAL_ABRT,
SIGNAL_ALRM: () => SIGNAL_ALRM,
SIGNAL_BUS: () => SIGNAL_BUS,
SIGNAL_CHLD: () => SIGNAL_CHLD,
SIGNAL_CONT: () => SIGNAL_CONT,
SIGNAL_FPE: () => SIGNAL_FPE,
SIGNAL_HUP: () => SIGNAL_HUP,
SIGNAL_ILL: () => SIGNAL_ILL,
SIGNAL_INT: () => SIGNAL_INT,
SIGNAL_KILL: () => SIGNAL_KILL,
SIGNAL_NONE: () => SIGNAL_NONE,
SIGNAL_PIPE: () => SIGNAL_PIPE,
SIGNAL_POLL: () => SIGNAL_POLL,
SIGNAL_PROF: () => SIGNAL_PROF,
SIGNAL_PWR: () => SIGNAL_PWR,
SIGNAL_QUIT: () => SIGNAL_QUIT,
SIGNAL_SEGV: () => SIGNAL_SEGV,
SIGNAL_STOP: () => SIGNAL_STOP,
SIGNAL_SYS: () => SIGNAL_SYS,
SIGNAL_TERM: () => SIGNAL_TERM,
SIGNAL_TRAP: () => SIGNAL_TRAP,
SIGNAL_TSTP: () => SIGNAL_TSTP,
SIGNAL_TTIN: () => SIGNAL_TTIN,
SIGNAL_TTOU: () => SIGNAL_TTOU,
SIGNAL_URG: () => SIGNAL_URG,
SIGNAL_USR1: () => SIGNAL_USR1,
SIGNAL_USR2: () => SIGNAL_USR2,
SIGNAL_VTALRM: () => SIGNAL_VTALRM,
SIGNAL_WINCH: () => SIGNAL_WINCH,
SIGNAL_XCPU: () => SIGNAL_XCPU,
SIGNAL_XFSZ: () => SIGNAL_XFSZ,
SUBCLOCKFLAGS_SUBSCRIPTION_CLOCK_ABSTIME: () => SUBCLOCKFLAGS_SUBSCRIPTION_CLOCK_ABSTIME,
WHENCE_CUR: () => WHENCE_CUR,
WHENCE_END: () => WHENCE_END,
WHENCE_SET: () => WHENCE_SET
});
var FD_STDIN = 0;
var FD_STDOUT = 1;
var FD_STDERR = 2;
var CLOCKID_REALTIME = 0;
var CLOCKID_MONOTONIC = 1;
var CLOCKID_PROCESS_CPUTIME_ID = 2;
var CLOCKID_THREAD_CPUTIME_ID = 3;
var ERRNO_SUCCESS = 0;
var ERRNO_2BIG = 1;
var ERRNO_ACCES = 2;
var ERRNO_ADDRINUSE = 3;
var ERRNO_ADDRNOTAVAIL = 4;
var ERRNO_AFNOSUPPORT = 5;
var ERRNO_AGAIN = 6;
var ERRNO_ALREADY = 7;
var ERRNO_BADF = 8;
var ERRNO_BADMSG = 9;
var ERRNO_BUSY = 10;
var ERRNO_CANCELED = 11;
var ERRNO_CHILD = 12;
var ERRNO_CONNABORTED = 13;
var ERRNO_CONNREFUSED = 14;
var ERRNO_CONNRESET = 15;
var ERRNO_DEADLK = 16;
var ERRNO_DESTADDRREQ = 17;
var ERRNO_DOM = 18;
var ERRNO_DQUOT = 19;
var ERRNO_EXIST = 20;
var ERRNO_FAULT = 21;
var ERRNO_FBIG = 22;
var ERRNO_HOSTUNREACH = 23;
var ERRNO_IDRM = 24;
var ERRNO_ILSEQ = 25;
var ERRNO_INPROGRESS = 26;
var ERRNO_INTR = 27;
var ERRNO_INVAL = 28;
var ERRNO_IO = 29;
var ERRNO_ISCONN = 30;
var ERRNO_ISDIR = 31;
var ERRNO_LOOP = 32;
var ERRNO_MFILE = 33;
var ERRNO_MLINK = 34;
var ERRNO_MSGSIZE = 35;
var ERRNO_MULTIHOP = 36;
var ERRNO_NAMETOOLONG = 37;
var ERRNO_NETDOWN = 38;
var ERRNO_NETRESET = 39;
var ERRNO_NETUNREACH = 40;
var ERRNO_NFILE = 41;
var ERRNO_NOBUFS = 42;
var ERRNO_NODEV = 43;
var ERRNO_NOENT = 44;
var ERRNO_NOEXEC = 45;
var ERRNO_NOLCK = 46;
var ERRNO_NOLINK = 47;
var ERRNO_NOMEM = 48;
var ERRNO_NOMSG = 49;
var ERRNO_NOPROTOOPT = 50;
var ERRNO_NOSPC = 51;
var ERRNO_NOSYS = 52;
var ERRNO_NOTCONN = 53;
var ERRNO_NOTDIR = 54;
var ERRNO_NOTEMPTY = 55;
var ERRNO_NOTRECOVERABLE = 56;
var ERRNO_NOTSOCK = 57;
var ERRNO_NOTSUP = 58;
var ERRNO_NOTTY = 59;
var ERRNO_NXIO = 60;
var ERRNO_OVERFLOW = 61;
var ERRNO_OWNERDEAD = 62;
var ERRNO_PERM = 63;
var ERRNO_PIPE = 64;
var ERRNO_PROTO = 65;
var ERRNO_PROTONOSUPPORT = 66;
var ERRNO_PROTOTYPE = 67;
var ERRNO_RANGE = 68;
var ERRNO_ROFS = 69;
var ERRNO_SPIPE = 70;
var ERRNO_SRCH = 71;
var ERRNO_STALE = 72;
var ERRNO_TIMEDOUT = 73;
var ERRNO_TXTBSY = 74;
var ERRNO_XDEV = 75;
var ERRNO_NOTCAPABLE = 76;
var RIGHTS_FD_DATASYNC = 1 << 0;
var RIGHTS_FD_READ = 1 << 1;
var RIGHTS_FD_SEEK = 1 << 2;
var RIGHTS_FD_FDSTAT_SET_FLAGS = 1 << 3;
var RIGHTS_FD_SYNC = 1 << 4;
var RIGHTS_FD_TELL = 1 << 5;
var RIGHTS_FD_WRITE = 1 << 6;
var RIGHTS_FD_ADVISE = 1 << 7;
var RIGHTS_FD_ALLOCATE = 1 << 8;
var RIGHTS_PATH_CREATE_DIRECTORY = 1 << 9;
var RIGHTS_PATH_CREATE_FILE = 1 << 10;
var RIGHTS_PATH_LINK_SOURCE = 1 << 11;
var RIGHTS_PATH_LINK_TARGET = 1 << 12;
var RIGHTS_PATH_OPEN = 1 << 13;
var RIGHTS_FD_READDIR = 1 << 14;
var RIGHTS_PATH_READLINK = 1 << 15;
var RIGHTS_PATH_RENAME_SOURCE = 1 << 16;
var RIGHTS_PATH_RENAME_TARGET = 1 << 17;
var RIGHTS_PATH_FILESTAT_GET = 1 << 18;
var RIGHTS_PATH_FILESTAT_SET_SIZE = 1 << 19;
var RIGHTS_PATH_FILESTAT_SET_TIMES = 1 << 20;
var RIGHTS_FD_FILESTAT_GET = 1 << 21;
var RIGHTS_FD_FILESTAT_SET_SIZE = 1 << 22;
var RIGHTS_FD_FILESTAT_SET_TIMES = 1 << 23;
var RIGHTS_PATH_SYMLINK = 1 << 24;
var RIGHTS_PATH_REMOVE_DIRECTORY = 1 << 25;
var RIGHTS_PATH_UNLINK_FILE = 1 << 26;
var RIGHTS_POLL_FD_READWRITE = 1 << 27;
var RIGHTS_SOCK_SHUTDOWN = 1 << 28;
var Iovec = class _Iovec {
static {
__name(this, "Iovec");
}
//@ts-ignore strictPropertyInitialization
buf;
//@ts-ignore strictPropertyInitialization
buf_len;
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;
}
};
var Ciovec = class _Ciovec {
static {
__name(this, "Ciovec");
}
//@ts-ignore strictPropertyInitialization
buf;
//@ts-ignore strictPropertyInitialization
buf_len;
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;
}
};
var WHENCE_SET = 0;
var WHENCE_CUR = 1;
var WHENCE_END = 2;
var FILETYPE_UNKNOWN = 0;
var FILETYPE_BLOCK_DEVICE = 1;
var FILETYPE_CHARACTER_DEVICE = 2;
var FILETYPE_DIRECTORY = 3;
var FILETYPE_REGULAR_FILE = 4;
var FILETYPE_SOCKET_DGRAM = 5;
var FILETYPE_SOCKET_STREAM = 6;
var FILETYPE_SYMBOLIC_LINK = 7;
var Dirent = class {
static {
__name(this, "Dirent");
}
d_next;
d_ino = 0n;
d_namlen;
d_type;
dir_name;
constructor(next_cookie, name, type) {
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;
}
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);
}
};
var ADVICE_NORMAL = 0;
var ADVICE_SEQUENTIAL = 1;
var ADVICE_RANDOM = 2;
var ADVICE_WILLNEED = 3;
var ADVICE_DONTNEED = 4;
var ADVICE_NOREUSE = 5;
var FDFLAGS_APPEND = 1 << 0;
var FDFLAGS_DSYNC = 1 << 1;
var FDFLAGS_NONBLOCK = 1 << 2;
var FDFLAGS_RSYNC = 1 << 3;
var FDFLAGS_SYNC = 1 << 4;
var Fdstat = class {
static {
__name(this, "Fdstat");
}
fs_filetype;
fs_flags;
fs_rights_base = 0n;
fs_rights_inherited = 0n;
constructor(filetype, flags) {
this.fs_filetype = filetype;
this.fs_flags = flags;
}
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);
}
};
var FSTFLAGS_ATIM = 1 << 0;
var FSTFLAGS_ATIM_NOW = 1 << 1;
var FSTFLAGS_MTIM = 1 << 2;
var FSTFLAGS_MTIM_NOW = 1 << 3;
var OFLAGS_CREAT = 1 << 0;
var OFLAGS_DIRECTORY = 1 << 1;
var OFLAGS_EXCL = 1 << 2;
var OFLAGS_TRUNC = 1 << 3;
var Filestat = class {
static {
__name(this, "Filestat");
}
dev = 0n;
ino = 0n;
filetype;
nlink = 0n;
size;
atim = 0n;
mtim = 0n;
ctim = 0n;
constructor(filetype, size) {
this.filetype = filetype;
this.size = size;
}
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);
}
};
var EVENTTYPE_CLOCK = 0;
var EVENTTYPE_FD_READ = 1;
var EVENTTYPE_FD_WRITE = 2;
var EVENTRWFLAGS_FD_READWRITE_HANGUP = 1 << 0;
var SUBCLOCKFLAGS_SUBSCRIPTION_CLOCK_ABSTIME = 1 << 0;
var SIGNAL_NONE = 0;
var SIGNAL_HUP = 1;
var SIGNAL_INT = 2;
var SIGNAL_QUIT = 3;
var SIGNAL_ILL = 4;
var SIGNAL_TRAP = 5;
var SIGNAL_ABRT = 6;
var SIGNAL_BUS = 7;
var SIGNAL_FPE = 8;
var SIGNAL_KILL = 9;
var SIGNAL_USR1 = 10;
var SIGNAL_SEGV = 11;
var SIGNAL_USR2 = 12;
var SIGNAL_PIPE = 13;
var SIGNAL_ALRM = 14;
var SIGNAL_TERM = 15;
var SIGNAL_CHLD = 16;
var SIGNAL_CONT = 17;
var SIGNAL_STOP = 18;
var SIGNAL_TSTP = 19;
var SIGNAL_TTIN = 20;
var SIGNAL_TTOU = 21;
var SIGNAL_URG = 22;
var SIGNAL_XCPU = 23;
var SIGNAL_XFSZ = 24;
var SIGNAL_VTALRM = 25;
var SIGNAL_PROF = 26;
var SIGNAL_WINCH = 27;
var SIGNAL_POLL = 28;
var SIGNAL_PWR = 29;
var SIGNAL_SYS = 30;
var RIFLAGS_RECV_PEEK = 1 << 0;
var RIFLAGS_RECV_WAITALL = 1 << 1;
var ROFLAGS_RECV_DATA_TRUNCATED = 1 << 0;
var SDFLAGS_RD = 1 << 0;
var SDFLAGS_WR = 1 << 1;
var PREOPENTYPE_DIR = 0;
var PrestatDir = class {
static {
__name(this, "PrestatDir");
}
pr_name;
constructor(name) {
this.pr_name = new TextEncoder().encode(name);
}
write_bytes(view, ptr) {
view.setUint32(ptr, this.pr_name.byteLength, true);
}
};
var Prestat = class _Prestat {
static {
__name(this, "Prestat");
}
//@ts-ignore strictPropertyInitialization
tag;
//@ts-ignore strictPropertyInitialization
inner;
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);
}
};
// node_modules/browser_wasi_shim_gaiden/dist/debug.js
var Debug = class {
static {
__name(this, "Debug");
}
isEnabled;
prefix = "wasi:";
log;
constructor(isEnabled) {
this.isEnabled = isEnabled;
this.enable(isEnabled);
}
// Recreate the logger function with the new enabled state.
enable(enabled) {
this.log = createLogger(enabled === void 0 ? true : enabled, this.prefix);
}
// Getter for the private isEnabled property.
get enabled() {
return this.isEnabled;
}
};
function createLogger(enabled, prefix) {
if (enabled) {
const a = console.log.bind(console, "%c%s", "color: #265BA0", prefix);
return a;
} else {
return () => {
};
}
}
__name(createLogger, "createLogger");
var debug = new Debug(false);
// node_modules/browser_wasi_shim_gaiden/dist/wasi.js
var WASIProcExit = class extends Error {
static {
__name(this, "WASIProcExit");
}
code;
constructor(code) {
super("exit with exit code " + code);
this.code = code;
}
};
var WASI = class {
static {
__name(this, "WASI");
}
args = [];
env = [];
fds = [];
inst;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
wasiImport;
/// Start a WASI command
start(instance) {
this.inst = instance;
try {
instance.exports._start();
return 0;
} catch (e) {
if (e instanceof WASIProcExit) {
return e.code;
} else {
throw e;
}
}
}
/// Initialize a WASI reactor
initialize(instance) {
this.inst = instance;
if (instance.exports._initialize) {
instance.exports._initialize();
}
}
constructor(args, env, fds, options = {}) {
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;
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
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((/* @__PURE__ */ 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] != void 0) {
return ERRNO_SUCCESS;
} else {
return ERRNO_BADF;
}
},
fd_allocate(fd, offset, len) {
if (self.fds[fd] != void 0) {
return self.fds[fd].fd_allocate(offset, len);
} else {
return ERRNO_BADF;
}
},
fd_close(fd) {
if (self.fds[fd] != void 0) {
const ret = self.fds[fd].fd_close();
self.fds[fd] = void 0;
return ret;
} else {
return ERRNO_BADF;
}
},
fd_datasync(fd) {
if (self.fds[fd] != void 0) {
return self.fds[fd].fd_sync();
} else {
return ERRNO_BADF;
}
},
fd_fdstat_get(fd, fdstat_ptr) {
if (self.fds[fd] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0 && self.fds[to] != void 0) {
const ret = self.fds[to].fd_close();
if (ret != 0) {
return ret;
}
self.fds[to] = self.fds[fd];
self.fds[fd] = void 0;
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0 && self.fds[new_fd] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0) {
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] != void 0 && self.fds[new_fd] != void 0) {
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] != void 0) {
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));
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] != void 0) {
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;
}
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
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).subarray(buf, buf + buf_len);
if ("crypto" in globalThis && !(self.inst.exports.memory.buffer instanceof SharedArrayBuffer)) {
for (let i = 0; i < buf_len; i += 65536) {
crypto.getRandomValues(buffer8.subarray(i, i + 65536));
}
} else {
for (let i = 0; i < buf_len; i++) {
buffer8[i] = Math.random() * 256 | 0;
}
}
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
sock_recv(fd, ri_data, ri_flags) {
throw "sockets not supported";
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
sock_send(fd, si_data, si_flags) {
throw "sockets not supported";
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
sock_shutdown(fd, how) {
throw "sockets not supported";
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
sock_accept(fd, flags) {
throw "sockets not supported";
}
};
}
};
// node_modules/browser_wasi_shim_gaiden/dist/fd.js
var Fd = class {
static {
__name(this, "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;
}
};
var Inode = class {
static {
__name(this, "Inode");
}
};
// node_modules/browser_wasi_shim_gaiden/dist/fs_mem.js
var OpenFile = class extends Fd {
static {
__name(this, "OpenFile");
}
file;
file_pos = 0n;
constructor(file) {
super();
this.file = file;
}
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() };
}
};
var OpenDirectory = class extends Fd {
static {
__name(this, "OpenDirectory");
}
dir;
constructor(dir) {
super();
this.dir = dir;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fd_seek(offset, whence) {
return { ret: ERRNO_BADF, offset: 0n };
}
fd_tell() {
return { ret: ERRNO_BADF, offset: 0n };
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
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: ret2, entry: new_entry } = this.dir.create_entry_for_path(path_str, (oflags & OFLAGS_DIRECTORY) == OFLAGS_DIRECTORY);
if (new_entry == null) {
return { ret: ret2, 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() };
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fd_filestat_set_size(size) {
return ERRNO_BADF;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fd_read(size) {
return { ret: ERRNO_BADF, data: new Uint8Array() };
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fd_pread(size, offset) {
return { ret: ERRNO_BADF, data: new Uint8Array() };
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fd_write(data) {
return { ret: ERRNO_BADF, nwritten: 0 };
}
fd_pwrite(data, offset) {
return { ret: ERRNO_BADF, nwritten: 0 };
}
};
var PreopenDirectory = class extends OpenDirectory {
static {
__name(this, "PreopenDirectory");
}
prestat_name;
constructor(name, contents) {
super(new Directory(contents));
this.prestat_name = name;
}
fd_prestat_get() {
return {
ret: 0,
prestat: Prestat.dir(this.prestat_name)
};
}
};
var File = class extends Inode {
static {
__name(this, "File");
}
data;
readonly;
constructor(data, options) {
super();
this.data = new Uint8Array(data);
this.readonly = !!options?.readonly;
}
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);
}
};
var Path = class _Path {
static {
__name(this, "Path");
}
parts = [];
is_dir = false;
static from(path) {
const self = new _Path();
self.is_dir = path.endsWith("/");
if (path.startsWith("/")) {
return { ret: ERRNO_NOTCAPABLE, path: null };
}
if (path.includes("\0")) {
return { ret: ERRNO_INVAL, path: null };
}
for (const component of path.split("/")) {
if (component === "" || component === ".") {
continue;
}
if (component === "..") {
if (self.parts.pop() == void 0) {
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;
}
};
var Directory = class _Directory extends Inode {
static {
__name(this, "Directory");
}
contents;
constructor(contents) {
super();
if (contents instanceof Array) {
this.contents = new Map(contents);
} else {
this.contents = contents;
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
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 !== void 0) {
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 === void 0) {
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 === void 0) {
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 {
// eslint-disable-next-line prefer-const
ret: parent_ret,
// eslint-disable-next-line prefer-const
parent_entry,
// eslint-disable-next-line prefer-const
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(/* @__PURE__ */ new Map());
}
parent_entry.contents.set(filename, new_child);
entry = new_child;
return { ret: ERRNO_SUCCESS, entry };
}
};
var ConsoleStdout = class _ConsoleStdout extends Fd {
static {
__name(this, "ConsoleStdout");
}
write;
constructor(write) {
super();
this.write = write;
}
fd_filestat_get() {
const filestat = new Filestat(FILETYPE_CHARACTER_DEVICE, BigInt(0));
return { ret: 0, filestat };
}
fd_fdstat_get() {
const fdstat = new Fdstat(FILETYPE_CHARACTER_DEVICE, 0);
fdstat.fs_rights_base = BigInt(RIGHTS_FD_WRITE);
return { ret: 0, fdstat };
}
fd_write(data) {
this.write(data);
return { ret: 0, nwritten: data.byteLength };
}
static lineBuffered(write) {
const dec = new TextDecoder("utf-8", { fatal: false });
let line_buf = "";
return new _ConsoleStdout((buffer) => {
line_buf += dec.decode(buffer, { stream: true });
const lines = line_buf.split("\n");
for (const [i, line] of lines.entries()) {
if (i < lines.length - 1) {
write(line);
} else {
line_buf = line;
}
}
});
}
};
// src/c.ts
var PTRSIZE = 4;
var ALIGN = 1;
var NULL = 0;
var FALSE = 0;
var TRUE = 1;
var CString = class {
static {
__name(this, "CString");
}
instance;
ptr;
size;
constructor(instance, text) {
this.instance = instance;
const realloc = instance.exports.canonical_abi_realloc;
const buf = new TextEncoder().encode(text);
this.size = buf.byteLength + 1;
this.ptr = realloc(NULL, 0, ALIGN, this.size);
if (this.ptr === NULL) {
throw new Error("could not allocate cstring: " + text);
}
try {
const mem = new Uint8Array(instance.exports.memory.buffer, this.ptr, this.size);
mem.set(buf);
mem[buf.byteLength] = 0;
} catch (err) {
this.free();
throw err;
}
}
free() {
if (this.ptr === NULL) {
return;
}
const free = this.instance.exports.canonical_abi_free;
free(this.ptr, this.size, ALIGN);
this.ptr = NULL;
this.size = 0;
}
};
function readString(instance, ptr, size) {
const mem = new Uint8Array(instance.exports.memory.buffer);
const idx = size ? ptr + size : mem.indexOf(0, ptr);
if (idx === -1) {
throw new Error(`unterminated string at address ${ptr}`);
}
return new TextDecoder().decode(mem.subarray(ptr, idx));
}
__name(readString, "readString");
function indirect(instance, addr) {
return new Uint32Array(instance.exports.memory.buffer)[addr / 4];
}
__name(indirect, "indirect");
function writeUint32(instance, addr, int) {
new Uint32Array(instance.exports.memory.buffer)[addr / 4] = int;
}
__name(writeUint32, "writeUint32");
function wasiError(errno, context = "WASI error") {
let desc = strerror[errno] ?? "unknown error code";
return new Error(`${context}: ${desc} (${errno})`);
}
__name(wasiError, "wasiError");
var strerror = [
"ERRNO_SUCCESS",
"ERRNO_2BIG",
"ERRNO_ACCES",
"ERRNO_ADDRINUSE",
"ERRNO_ADDRNOTAVAIL",
"ERRNO_AFNOSUPPORT",
"ERRNO_AGAIN",
"ERRNO_ALREADY",
"ERRNO_BADF",
"ERRNO_BADMSG",
"ERRNO_BUSY",
"ERRNO_CANCELED",
"ERRNO_CHILD",
"ERRNO_CONNABORTED",
"ERRNO_CONNREFUSED",
"ERRNO_CONNRESET",
"ERRNO_DEADLK",
"ERRNO_DESTADDRREQ",
"ERRNO_DOM",
"ERRNO_DQUOT",
"ERRNO_EXIST",
"ERRNO_FAULT",
"ERRNO_FBIG",
"ERRNO_HOSTUNREACH",
"ERRNO_IDRM",
"ERRNO_ILSEQ",
"ERRNO_INPROGRESS",
"ERRNO_INTR",
"ERRNO_INVAL",
"ERRNO_IO",
"ERRNO_ISCONN",
"ERRNO_ISDIR",
"ERRNO_LOOP",
"ERRNO_MFILE",
"ERRNO_MLINK",
"ERRNO_MSGSIZE",
"ERRNO_MULTIHOP",
"ERRNO_NAMETOOLONG",
"ERRNO_NETDOWN",
"ERRNO_NETRESET",
"ERRNO_NETUNREACH",
"ERRNO_NFILE",
"ERRNO_NOBUFS",
"ERRNO_NODEV",
"ERRNO_NOENT",
"ERRNO_NOEXEC",
"ERRNO_NOLCK",
"ERRNO_NOLINK",
"ERRNO_NOMEM",
"ERRNO_NOMSG",
"ERRNO_NOPROTOOPT",
"ERRNO_NOSPC",
"ERRNO_NOSYS",
"ERRNO_NOTCONN",
"ERRNO_NOTDIR",
"ERRNO_NOTEMPTY",
"ERRNO_NOTRECOVERABLE",
"ERRNO_NOTSOCK",
"ERRNO_NOTSUP",
"ERRNO_NOTTY",
"ERRNO_NXIO",
"ERRNO_OVERFLOW",
"ERRNO_OWNERDEAD",
"ERRNO_PERM",
"ERRNO_PIPE",
"ERRNO_PROTO",
"ERRNO_PROTONOSUPPORT",
"ERRNO_PROTOTYPE",
"ERRNO_RANGE",
"ERRNO_ROFS",
"ERRNO_SPIPE",
"ERRNO_SRCH",
"ERRNO_STALE",
"ERRNO_TIMEDOUT",
"ERRNO_TXTBSY",
"ERRNO_XDEV",
"ERRNO_NOTCAPABLE"
];
// src/term.ts
var Atom = class {
static {
__name(this, "Atom");
}
/** Value of the atom. */
functor;
args = [];
constructor(functor) {
this.functor = functor;
}
/** Value of the atom. */
// TODO: change `functor` to just `value`, here is for backwards compatibility
get value() {
return this.functor;
}
set value(v) {
this.functor = v;
}
get pi() {
return piTerm(this.functor, 0);
}
toProlog() {
return escapeAtom(this.functor);
}
toString() {
return this.toProlog();
}
};
function atom(text, ...values) {
let functor = "";
for (let i = 0; i < text.length; i++) {
functor += text[i];
if (i < values.length) {
functor += values[i];
}
}
return new Atom(functor);
}
__name(atom, "atom");
function prolog(text, ...values) {
let str = "";
for (let i = 0; i < text.length; i++) {
str += text[i];
if (values[i]) str += toProlog(values[i]);
}
return str;
}
__name(prolog, "prolog");
function Atomic(functor, args) {
if (!args || args.length === 0)
return new Atom(functor);
return new Compound(functor, args);
}
__name(Atomic, "Atomic");
var Compound = class {
static {
__name(this, "Compound");
}
functor;
args;
constructor(functor, args) {
this.functor = functor;
this.args = args;
if (typeof args?.length === "undefined")
throw new Error("bad compound, not a list: " + functor);
}
get pi() {
return piTerm(this.functor, this.args.length);
}
toProlog() {
if (this.args.length === 0)
return escapeAtom(this.functor);
if (this.args.length === 2 && (this.functor === ":" || this.functor === "/"))
return `${toProlog(this.args[0])}${this.functor}${toProlog(this.args[1])}`;
return `${escapeAtom(this.functor)}(${this.args.map(toProlog).join(",")})`;
}
toString() {
return this.toProlog();
}
};
var Rational = class {
static {
__name(this, "Rational");
}
numerator;
denominator;
constructor(numerator, denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
toProlog() {
return `${this.numerator} rdiv ${this.denominator}`;
}
toString() {
return `${this.numerator}/${this.denominator}`;
}
};
function isAtom(x, name) {
return x instanceof Atom && (typeof name == "undefined" || x.functor == name) && !x.args?.length;
}
__name(isAtom, "isAtom");
function isCompound(x, name, arity) {
return x instanceof Compound && (typeof name === "undefined" || x.functor === name) && (typeof arity === "undefined" || x.args.length === arity);
}
__name(isCompound, "isCompound");
function isList(x) {
return Array.isArray(x) && x.every(isTerm);
}
__name(isList, "isList");
function isNumber(x) {
return typeof x === "number" || typeof x === "bigint";
}
__name(isNumber, "isNumber");
function isRational(x) {
return x instanceof Rational;
}
__name(isRational, "isRational");
function isString(x) {
return typeof x === "string";
}
__name(isString, "isString");
function isCallable(term) {
return isAtom(term) || isCompound(term);
}
__name(isCallable, "isCallable");
function isVariable(term) {
return term instanceof Variable;
}
__name(isVariable, "isVariable");
function isTerm(term) {
switch (typeof term) {
case "number":
case "bigint":
case "string":
return true;
}
return isAtom(term) || isCompound(term) || isList(term) || isVariable(term) || isRational(term);
}
__name(isTerm, "isTerm");
var Variable = class {
static {
__name(this, "Variable");
}
var;
attr;
constructor(name, attr) {
if (!validVar(name))
throw new Error("trealla: invalid variable name: " + name);
this.var = name;
if (attr && attr?.length > 0)
this.attr = attr;
}
toProlog() {
if (this.attr?.length) {
return this.attr.map(toProlog).join(",");
}
return `${this.var}`;
}
toString() {
return this.toProlog();
}
};
var Literal = class {
static {
__name(this, "Literal");
}
value;
constructor(value) {
this.value = value;
}
toProlog() {
return this.value;
}
};
var FLOAT_FORMAT = new Intl.NumberFormat("en-US", { useGrouping: false, minimumFractionDigits: 1, notation: "standard" });
var Float = class {
static {
__name(this, "Float");
}
value;
constructor(value) {
this.value = value;
}
[Symbol.toPrimitive]() {
return this.value;
}
toProlog() {
if (!Number.isFinite(this.value))
throw new Error(`can't encode ${this.value} to Prolog term`);
return FLOAT_FORMAT.format(this.value);
}
toJSON() {
return this.value;
}
};
function validVar(name) {
if (typeof name !== "string" || name.length === 0)
return false;
if (name[0] === "_")
return true;
if (name[0].toLowerCase() !== name[0])
return true;
return false;
}
__name(validVar, "validVar");
function piTerm(name, arity) {
return new Compound("/", [new Atom(name), arity]);
}
__name(piTerm, "piTerm");
function toProlog(obj) {
switch (typeof obj) {
case "number":
const str = obj.toString();
const eidx = str.indexOf("e");
if (eidx === -1 || str.includes(".")) {
return str;
}
return `${str.slice(0, eidx)}.0${str.slice(eidx)}`;
case "bigint":
return obj.toString();
case "string":
return escapeString(obj);
case "boolean":
return obj ? "{true}" : "{false}";
case "undefined":
return "{undefined}";
case "object":
break;
default:
throw new Error("trealla: can't convert object to Prolog term: " + obj);
}
if (obj === null)
return "{null}";
if ("toProlog" in obj && typeof obj.toProlog === "function")
return obj.toProlog();
if (obj instanceof Uint8Array)
return escapeString(new TextDecoder().decode(obj));
if (Array.isArray(obj))
return `[${obj.map(toProlog).join(",")}]`;
throw new Error("trealla: can't convert object to Prolog term: " + obj);
}
__name(toProlog, "toProlog");
function needsEscape(atom2) {
if (atom2.length === 0) {
return true;
}
let code = atom2.charCodeAt(0);
if (!(code >= 97 && code <= 122)) {
return true;
}
for (let i = 1; i < atom2.length; i++) {
code = atom2.charCodeAt(i);
if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95) {
continue;
}
return true;
}
return false;
}
__name(needsEscape, "needsEscape");
function escapeAtom(atom2) {
if (!needsEscape(atom2))
return atom2;
return `'${atom2.replaceAll("\\", "\\\\").replaceAll(`'`, `\\'`).replaceAll("\n", "\\n").replaceAll(" ", "\\t")}'`;
}
__name(escapeAtom, "escapeAtom");
function escapeString(str) {
return `"${str.replaceAll("\\", "\\\\").replaceAll(`"`, `\\"`).replaceAll("\n", "\\n").replaceAll(" ", "\\t")}"`;
}
__name(escapeString, "escapeString");
function fromJSON(json, options = {}) {
return JSON.parse(json, reviver(options));
}
__name(fromJSON, "fromJSON");
function toJSON(term, indent) {
return JSON.stringify(term, function(_, v) {
if (typeof v === "bigint")
return { number: v.toString() };
return v;
}, indent);
}
__name(toJSON, "toJSON");
function reviver(opts = {}) {
const { atoms, strings, integers, booleans, nulls, undefineds } = opts;
return function(k, v) {
if (v === null)
return new Compound("{}", [new Atom("null")]);
if (v && typeof v === "object") {
if ("functor" in v) {
const functor = Array.isArray(v.functor) && v.functor.length === 0 ? "" : v.functor;
if (!("args" in v) || !v.args.length) {
switch (atoms) {
case "string":
return functor;
default:
return new Atom(functor);
}
}
if ((booleans || nulls || undefineds) && typeof v === "object" && "args" in v && Array.isArray(v.args) && v.args.length === 1) {
const atom2 = typeof v.args[0] === "string" ? v.args[0] : v.args[0].functor;
if (v.functor === booleans) {
switch (atom2) {
case "true":
return true;
case "false":
return false;
}
}
if (v.functor === nulls && atom2 === "null") {
return null;
}
if (v.functor === undefineds && atom2 === "undefined") {
return void 0;
}
}
return new Compound(functor, v.args);
}
if ("var" in v && typeof v.var === "string") {
return new Variable(v.var, v.attr);
}
if ("numerator" in v && "denominator" in v) {
if (!isNumber(v.numerator) || !isNumber(v.denominator)) {
throw new Error(`invalid rational: ${JSON.stringify(v)}`);
}
return new Rational(v.numerator, v.denominator);
}
if ("int" in v) {
if (typeof v.int !== "number" && typeof v.int !== "string")
throw Error(`invalid int: ${JSON.stringify(v)}`);
if (!integers || integers === "fit") {
if (typeof v.int === "number") return v.int;
if (typeof v.int === "string") return BigInt(v.int);
}
if (integers === "bigint") {
return BigInt(v.int);
}
return Number(v.int);
}
if ("number" in v && typeof v.number === "string") {
if (integers === "number") return Number(v.number);
return BigInt(v.number);
}
}
if (typeof v === "string" && k !== "result" && k !== "stdin" && k !== "stdout") {
switch (strings) {
case "list":
return v.split("").map((char) => new Atom(char));
case "string":
return v;
}
}
return v;
};
}
__name(reviver, "reviver");
// src/toplevel.ts
var FORMATS = {
json: {
query: /* @__PURE__ */ __name(function(_, query, bind) {
if (bind) query = bindVars(query, bind);
return `'$json_ask'(${escapeString(query)}).`;
}, "query"),
parse: /* @__PURE__ */ __name(function(_pl, _status, stdout, stderr, opts, answer) {
const dec = new TextDecoder();
const json = answer;
let msg;
try {
msg = JSON.parse(json, reviver(opts));
} catch (ex) {
console.error("Bad stdout:\n" + json);
if (stderr?.length > 0) {
console.warn("stderr:\n" + dec.decode(stderr));
}
throw ex;
}
if (stdout?.byteLength > 0) {
msg.stdout = dec.decode(stdout);
}
if (stderr?.byteLength > 0) {
msg.stderr = dec.decode(stderr);
}
if (typeof msg?.answer?.__GOAL__ === "object") {
msg.goal = msg.answer.__GOAL__;
delete msg.answer.__GOAL__;
}
return msg;
}, "parse"),
truth: /* @__PURE__ */ __name(function() {
return null;
}, "truth")
},
/*
json_old: {
query: function(_: Prolog, query: string, bind: Record<string, Termlike>) {
if (bind) query = bindVars(query, bind);
return `wasm:js_ask(${escapeString(query)}).`;
},
parse: function(_pl: Prolog, _status: boolean, stdout: Uint8Array, stderr: Uint8Array, opts: JSONEncodingOptions) {
let start = stdout.indexOf(2); // ASCII START OF TEXT
const end = stdout.indexOf(3, start+1); // ASCII END OF TEXT
const jsonStart = stdout.indexOf(123, end+1); // {
let jsonEnd = stdout.indexOf(10, jsonStart+1); // LINE FEED
if (jsonEnd === -1) {
jsonEnd = stdout.lastIndexOf(125); // }
}
// console.log("msg:", new TextDecoder().decode(stdout));
const dec = new TextDecoder();
const json = dec.decode(stdout.slice(jsonStart, jsonEnd));
let msg;
try {
msg = JSON.parse(json, reviver(opts));
} catch (ex) {
console.error("Bad stdout:\n" + json);
if (stderr?.length > 0) {
console.warn("stderr:\n" + new TextDecoder().decode(stderr));
}
throw ex;
}
if (start + 1 !== end) {
msg.stdout = dec.decode(stdout.slice(start + 1, end));
}
if (stderr.byteLength > 0) {
msg.stderr = dec.decode(stderr);
}
if (typeof msg?.answer?.__GOAL__ === "object") {
msg.goal = msg.answer.__GOAL__;
delete msg.answer.__GOAL__;
}
// if (typeof opts?.extra !== "undefined") {
// msg.extra = opts.extra;
// }
return msg;
},
truth: function() { return null; }
},
*/
prolog: {
query: /* @__PURE__ */ __name(function(_, query, bind) {
if (bind) query = bindVars(query, bind);
return query;
}, "query"),
parse: /* @__PURE__ */ __name(function(_, _status, stdout, stderr, opts) {
const dec = new TextDecoder();
if (stderr.byteLength > 0) {
console.log(dec.decode(stderr));
}
if (opts?.dot === false && stdout[stdout.length - 1] === 46)
return dec.decode(stdout.subarray(0, stdout.length - 1));
return dec.decode(stdout);
}, "parse"),
truth: /* @__PURE__ */ __name(function(_, status, stderr, opts) {
if (stderr.byteLength > 0) {
console.log(new TextDecoder().decode(stderr));
}
return (status ? "true" : "false") + (opts?.dot === false ? "" : ".");
}, "truth")
}
};
function bindVars(query, bind) {
const vars = Object.entries(bind).map(([k, v]) => `${k} ${isRational(v) ? "is" : "="} ${toProlog(v)}`).join(", ");
if (vars.length === 0) return query;
return `${vars}, ${query}`;
}
__name(bindVars, "bindVars");
// src/interop.ts
var Predicate = class {
static {
__name(this, "Predicate");
}
name;
arity;
proc;
async;
constructor(name, arity, fn, async = true) {
this.name = name;
this.arity = arity;
this.proc = fn;
this.async = async;
}
async *eval(pl, subquery, goal, ctrl) {
const x = this.proc(pl, subquery, goal, ctrl);
try {
if (typeof x === "object" && Symbol.asyncIterator in x) {
yield yield* x;
} else {
if (x instanceof Promise) {
yield await x;
} else {
yield x;
}
}
} catch (error) {
if (isTerm(error))
return new Compound("throw", [error]);
return system_error("js_exception", `${error}`, goal.pi);
}
return false;
}
shim() {
const args = [];
for (let i = 0; i < this.arity; i++) {
args.push(new Variable(`_${i}`));
}
const head = Atomic(this.name, args);
return `${head.toProlog()} :- wasm_generic:host_rpc(${head.toProlog()}). `;
}
get pi() {
return piTerm(this.name, this.arity);
}
};
var sleep_1 = new Predicate(
"sleep",
1,
async function(_pl, _subquery, goal) {
const time = goal.args[0];
if (typeof time !== "number")
throw type_error("number", time, goal.pi);
if (time < 0)
throw domain_error("not_less_than_zero", time, goal.pi);
await new Promise((resolve) => setTimeout(resolve, time * 1e3));
return true;
}
);
var delay_1 = new Predicate(
"delay",
1,
async function(_pl, _subquery, goal) {
const time = goal.args[0];
if (typeof time !== "number")
throw type_error("number", time, goal.pi);
if (time < 0)
throw domain_error("not_less_than_zero", time, goal.pi);
await new Promise((resolve) => setTimeout(resolve, time));
return true;
}
);
var console_log_1 = new Predicate(
"console_log",
1,
function(_pl, _subquery, goal) {
console.log(goal.args[0]);
return true;
},
false
);
var js_eval_2 = new Predicate(
"js_eval",
2,
async function(pl, subquery, goal) {
const expr = goal.args[0];
if (typeof expr !== "string")
throw type_error("chars", expr, goal.pi);
let value;
try {
value = await js_eval(pl, subquery, goal, expr);
} catch (error) {
console.error(error);
throw system_error("js_exception", `${error}`, goal.pi);
}
if (!value)
return true;
return new Compound(goal.functor, [goal.args[0], value]);
}
);
var js_eval_json_2 = new Predicate(
"js_eval_json",
2,
async function(pl, subquery, goal) {
const expr = goal.args[0];
if (typeof expr !== "string")
throw type_error("chars", expr, goal.pi);
let value;
try {
value = await js_eval(pl, subquery, goal, expr);
} catch (error) {
console.error(error);
throw system_error("js_exception", `${error}`, goal.pi);
}
if (!value)
return true;
const term = JSON.stringify(value);
return new Compound(goal.functor, [goal.args[0], term]);
}
);
async function js_eval(pl, subquery, goal, expr) {
if (typeof expr !== "string")
throw type_error("chars", expr, goal.pi);
let value = new Function("pl", "subquery", "goal", "trealla", expr)(pl, subquery, goal, EVAL_BINDINGS);
if (value instanceof Promise)
value = await value;
return value;
}
__name(js_eval, "js_eval");
var future_2 = new Predicate(
"future",
2,
function(pl, _subq, goal) {
const call = goal.args[0];
if (!isCallable(call))
throw type_error("callable", call, goal.pi);
const goalvar = new Variable("__GOAL__");
const ask = new Compound(",", [new Compound("=", [goalvar, goal.args[0]]), goalvar]);
const task = pl.query(ask.toProlog());
const id = pl.addTask(task);
const promise = new Compound("$promise", [id, goal.args[0]]);
return new Compound(goal.functor, [goal.args[0], promise]);
}
);
var sys_await_1 = new Predicate(
"$await",
1,
async function(pl, _subq, goal, ctrl) {
const token = goal.args[0];
if (!isCompound(token, "$promise", 2)) {
throw type_error("promise", token, goal.pi);
}
const id = token.args[0];
if (typeof id !== "number") {
throw type_error("integer", token, goal.pi);
}
const task = pl.tasks.get(id);
if (!task) {
return false;
}
const tick = await pl.tickTask(task);
if (!tick || !tick.answer) {
return false;
}
if (tick.answer.stdout)
ctrl.stdout(tick.answer.stdout);
if (tick.answer.stderr)
ctrl.stderr(tick.answer.stderr);
if (tick.answer.status === "failure" || !tick.answer.goal)
return false;
if (tick.answer.status === "error")
throw tick.answer.error;
token.args[1] = tick.answer.goal;
return goal;
}
);
var await_any_3 = new Predicate(
// '$await_any'(Ps, Winner, Rest)
"await_any",
3,
async function(pl, _subq, goal, ctrl) {
const tokens = goal.args[0];
if (!isList(tokens)) {
throw type_error("list", tokens, goal.pi);
}
const ticks = tokens.map((token) => {
if (!isCompound(token, "$promise")) {
return {
result: {
status: "error",
error: type_error("promise", token, goal.pi)
}
};
}
const id = token.args[0];
if (!isNumber(id)) {
return {
result: {
status: "error",
error: type_error("integer", id, goal.pi)
}
};
}
const task = pl.tasks.get(id);
if (!task) return;
return pl.tickTask(task);
});
const ps = ticks.map((p) => new Promise(async (resolve, reject) => {
const x = await p;
if (!x) {
reject();
} else {
resolve(x);
}
}));
const tick = await Promise.any(ps);
if (!tick)
return false;
const win = tokens.find((x) => x.args[0] === tick.task_id);
const rest = tokens.filter((x) => x.args[0] !== tick.task_id);
if (tick.answer?.stdout)
ctrl.stdout(tick.answer.stdout);
if (tick.answer?.stderr)
ctrl.stderr(tick.answer.stderr);
if (!tick.answer || tick.answer.status === "failure")
return false;
if (tick.answer.status === "error")
throw tick.answer.error;
win.args[1] = tick.answer.goal;
goal.args[1] = win;
goal.args[2] = rest;
return goal;
}
);
var future_cancel_1 = new Predicate(
"future_cancel",
1,
function(pl, _subq, goal, _ctrl) {
const token = goal.args[0];
if (!isCompound(token, "$promise")) {
throw type_error("promise", token, goal.pi);
}
const id = token.args[0];
if (!isNumber(id)) {
throw type_error("integer", token, goal.pi);
}
const task = pl.tasks.get(id);
if (!task) {
return true;
}
if (task.cancel === null && task.promise === null) {
task.query.return();
return true;
}
if (typeof task.cancel === "function") {
task.cancel();
return true;
}
return true;
}
);
var sys_await_all_1 = new Predicate(
"$await_all",
1,
async function(pl, _subq, goal, ctrl) {
const tokens = goal.args[0];
if (!isList(tokens)) {
throw type_error("list", tokens, goal.pi);
}
for (const token of tokens) {
if (!isCompound(token, "$promise")) {
throw type_error("promise", token, goal.pi);
}
if (!isNumber(token.args[0])) {
throw type_error("integer", token.args[0], goal.pi);
}
}
const ps = tokens.map((token) => {
const id = token.args[0];
const task = pl.tasks.get(id);
if (!task) return;
return pl.tickTask(task);
});
const replies = await Promise.all(ps);
for (let i = 0; i < replies.length; i++) {
const reply = replies[i];
if (!reply)
return false;
if (reply.answer?.stdout)
ctrl.stdout(reply.answer.stdout);
if (reply.answer?.stderr)
ctrl.stderr(reply.answer.stderr);
if (!reply.answer || reply.answer.status === "failure")
return false;
if (reply.answer.status === "error")
throw reply.answer.error;
tokens[i].args[1] = reply.answer.goal;
}
return goal;
}
);
var sys_await_some_3 = new Predicate(
"$await_some",
3,
async function(pl, _subq, goal, ctrl) {
const tokens = goal.args[0];
if (!isList(tokens)) {
throw type_error("list", tokens, goal.pi);
}
for (const token of tokens) {
if (!isCompound(token, "$promise")) {
throw type_error("promise", token, goal.pi);
}
if (!isNumber(token.args[0])) {
throw type_error("integer", token.args[0], goal.pi);
}
}
const ps = tokens.map((token) => {
const id = token.args[0];
const task = pl.tasks.get(id);
if (!task) return;
return pl.tickTask(task);
});
const replies = await Promise.all(ps);
if (replies.length === 0)
return false;
const ok = [];
const done = [];
for (let i = 0; i < replies.length; i++) {
const reply = replies[i];
const result = replies[i]?.answer;
if (!reply) {
done.push(tokens[i]);
continue;
}
if (result?.status === "error") {
throw result.error;
} else if (!result || result?.status === "failure") {
done.push(tokens[i]);
} else if (result?.goal) {
tokens[i].args[1] = result.goal;
ok.push(tokens[i]);
}
if (reply.answer?.stdout)
ctrl.stdout(reply.answer.stdout);
if (reply.answer?.stderr)
ctrl.stderr(reply.answer.stderr);
}
if (ok.length === 0)
return false;
goal.args[1] = ok;
goal.args[2] = done;
return goal;
}
);
function sys_missing_n(_pl, _subq, goal) {
throw existence_error("procedure", goal.pi, piTerm("host_rpc", 1));
}
__name(sys_missing_n, "sys_missing_n");
function throwTerm(ball) {
return new Compound("throw", [ball]);
}
__name(throwTerm, "throwTerm");
function type_error(type, value, context) {
return new Compound("error", [new Compound("type_error", [type, value]), context]);
}
__name(type_error, "type_error");
function domain_error(type, value, context) {
return new Compound("error", [new Compound("domain_error", [type, value]), context]);
}
__name(domain_error, "domain_error");
function existence_error(type, value, context) {
return new Compound("error", [new Compound("existence_error", [type, value]), context]);
}
__name(existence_error, "existence_error");
function system_error(type, value, context) {
return new Compound("error", [new Compound("system_error", [type, value]), context]);
}
__name(system_error, "system_error");
var LIBRARY = [
sleep_1,
delay_1,
console_log_1,
js_eval_2,
js_eval_json_2,
sys_await_some_3,
future_2,
sys_await_1,
sys_await_all_1,
await_any_3,
future_cancel_1
];
var EVAL_BINDINGS = {
Atom,
Compound,
Variable,
Predicate,
Rational,
toProlog,
fromJSON,
piTerm
};
// src/buffer.ts
var ByteBuffer = class {
static {
__name(this, "ByteBuffer");
}
buf;
len = 0;
constructor(cap = 1024) {
this.buf = new Uint8Array(cap);
}
get cap() {
return this.buf.byteLength;
}
get data() {
return this.buf.slice(0, this.len);
}
toString() {
return this.len ? new TextDecoder().decode(this.data) : "";
}
write(data) {
this.grow(this.len + data.byteLength);
this.buf.set(data, this.len);
this.len += data.byteLength;
}
copyFrom(other) {
this.write(other.data);
}
grow(size) {
if (this.cap >= size)
return;
const cap2 = Math.max(size, this.cap * 2);
const buf2 = new Uint8Array(cap2);
buf2.set(this.buf, 0);
this.buf = buf2;
}
reset() {
this.len = 0;
}
};
// src/fs.ts
var FS = class {
static {
__name(this, "FS");
}
os;
wasi;
constructor(wasi, os) {
this.wasi = wasi;
this.os = os;
}
readDir(name) {
const { path } = Path.from(fixPath(name));
if (!path)
throw new Error("directory not found: " + name);
const { ret, entry } = this.os.root.dir.get_entry_for_path(path);
if (ret !== 0)
throw wasiError(ret, name);
if (!(entry instanceof Directory))
throw new Error(`not a directory: ${name}`);
const root = fixPath(path.to_path_string());
let prefix = root;
if (root && !root.endsWith("/")) {
prefix += "/";
}
return Array.from(entry.contents.entries()).map(toDirent(prefix)).sort(cmpDirent);
}
createDir(path) {
path = fixPath(path);
const { ret } = this.os.root.dir.create_entry_for_path(path, true);
if (ret !== 0) {
throw wasiError(ret, path);
}
}
removeDir(path) {
path = fixPath(path);
const ret = this.os.root.path_remove_directory(path);
if (ret !== 0) {
throw wasiError(ret, path);
}
}
removeFile(name) {
name = fixPath(name);
const { path } = Path.from(name);
if (path === null) {
throw new Error(`invalid path? ${name}`);
}
const { ret, parent_entry, filename } = this.os.root.dir.get_parent_dir_and_entry_for_path(path, false);
if (ret !== 0) {
throw wasiError(ret, name);
}
const parent = parent_entry ?? this.os.root.dir;
parent.contents.delete(filename ?? name);
}
rename(path, to) {
path = fixPath(path);
to = fixPath(to);
const fd = this.wasi.fds.indexOf(this.os.root);
const ret = this.os.root.path_rename(path, fd, to);
if (ret !== 0) {
throw wasiError(ret, `rename(${path}, ${to})`);
}
}
metadata(path) {
path = fixPath(path);
const { ret, filestat } = this.os.root.path_filestat_get(0, path);
if (ret !== 0) {
throw wasiError(ret, path);
}
return filestat;
}
open(path, options = { create: false, write: false }) {
path = fixPath(path);
const rights = BigInt(options.write ? wasi_defs_exports.RIGHTS_FD_WRITE : 0);
let oflags = (options.create ? wasi_defs_exports.OFLAGS_CREAT : 0) | (options.truncate ? wasi_defs_exports.OFLAGS_TRUNC : 0);
let fdflags = options.append ? wasi_defs_exports.FDFLAGS_APPEND : 0;
const { ret, fd_obj } = this.os.root.path_open(0, path, oflags, rights, rights, fdflags);
if (ret !== 0) throw wasiError(ret);
return new File2(fd_obj);
}
};
function toDirent(prefix) {
return function([path, inode]) {
const stat = inode.stat();
return {
path: prefix + path,
inode,
metadata: {
dev: stat.dev,
ino: stat.ino,
filetype: {
dir: stat.filetype === wasi_defs_exports.FILETYPE_DIRECTORY,
file: stat.filetype === wasi_defs_exports.FILETYPE_REGULAR_FILE,
symlink: stat.filetype === wasi_defs_exports.FILETYPE_SYMBOLIC_LINK,
type: stat.filetype
},
nlink: stat.nlink,
size: stat.size,
accessed: stat.atim,
modified: stat.mtim,
created: stat.ctim
}
};
};
}
__name(toDirent, "toDirent");
function cmpDirent(a, b) {
if (a.path === b.path) {
return 0;
}
return a.path < b.path ? -1 : 1;
}
__name(cmpDirent, "cmpDirent");
function fixPath(path) {
if (!path)
return "";
if (path[0] === "/")
return path.slice(1);
return path;
}
__name(fixPath, "fixPath");
var File2 = class {
static {
__name(this, "File");
}
openfile;
entity;
constructor(f) {
if (f instanceof OpenFile) {
this.openfile = f;
this.entity = this.openfile.file;
} else if (f instanceof File) {
this.entity = f;
} else {
throw new Error(`not a file: ${JSON.stringify(Object.entries(f))}`);
}
}
lastAccessed() {
return this.entity.stat().atim;
}
lastModified() {
return this.entity.stat().mtim;
}
createdTime() {
return this.entity.stat().ctim;
}
size() {
return this.entity.stat().size;
}
read(into) {
if (this.openfile) {
const size = into instanceof Uint8Array ? into.byteLength : this.openfile.file.data.byteLength - Number(this.openfile.file_pos);
const { ret, data } = this.openfile.fd_read(size);
if (ret !== 0)
throw wasiError(ret, `file read error`);
if (into) {
into.set(data);
return into;
}
return data;
}
return this.entity.data;
}
readString() {
const buf = this.read();
return new TextDecoder().decode(buf);
}
write(buf) {
if (this.entity.readonly)
throw wasiError(wasi_defs_exports.ERRNO_PERM, "write on readonly file");
this.entity.data = buf;
return buf.byteLength;
}
writeString(buf) {
this.entity.data = new TextEncoder().encode(buf);
return this.entity.data.byteLength;
}
flush() {
if (this.openfile) {
const ret = this.openfile.fd_sync();
if (ret !== 0) throw wasiError(ret, `file sync`);
}
}
seek(position) {
if (this.openfile) {
const { ret, offset } = this.openfile.fd_seek(position, wasi_defs_exports.WHENCE_SET);
if (ret !== 0) throw wasiError(ret, `file seek`);
return offset;
}
return BigInt(0);
}
};
function newOS() {
return {
stdout: new OutputStream(),
stderr: new OutputStream(),
//oob: new OutputStream(),
// tmp: new PreopenDirectory("/tmp", new Map()),
root: new PreopenDirectory(".", /* @__PURE__ */ new Map())
};
}
__name(newOS, "newOS");
var OutputStream = class {
static {
__name(this, "OutputStream");
}
buf = new ByteBuffer(256);
fd;
constructor() {
this.fd = new ConsoleStdout((buf) => {
if (buf.length > 0)
this.buf.write(buf);
});
}
reset() {
this.buf.reset();
}
};
// src/prolog.ts
import tpl_wasm from "./libtpl-QGJRSBRS.wasm";
var tpl;
var initPromise;
async function load() {
if (initPromise) return initPromise;
initPromise = async function() {
if (tpl_wasm instanceof WebAssembly.Module) {
tpl = tpl_wasm;
} else {
tpl = await WebAssembly.compile(tpl_wasm);
}
}();
return initPromise;
}
__name(load, "load");
var Prolog = class {
static {
__name(this, "Prolog");
}
wasi;
os = newOS();
fs;
instance;
ptr = 0;
// pointer to *prolog instance
n = 0;
taskcount = 0;
scratch = 0;
finalizers;
yielding = /* @__PURE__ */ new Map();
// *subq → maybe promise
procs = {};
// pi → predicate
tasks = /* @__PURE__ */ new Map();
// id → task
subqs = /* @__PURE__ */ new Map();
// *subq → ctrl
spawning = /* @__PURE__ */ new Map();
// **subq → ctrl
/** Create a new Prolog interpreter instance. */
constructor(options = {}) {
const {
library,
env,
quiet
} = options;
this.wasi = newWASI(this.os, library, env, quiet);
this.fs = new FS(this.wasi, this.os);
this.fs.createDir("/tmp");
if ("FinalizationRegistry" in globalThis) {
this.finalizers = new FinalizationRegistry((task) => {
if (task.alive) {
task.alive = false;
const pl_done = this.instance.exports.pl_done;
pl_done(task.subquery);
this.yielding.delete(task.subquery);
}
});
}
}
/** Instantiate this interpreter. Automatically called by other methods if necessary. */
async init() {
if (!tpl) {
await load();
}
const imports = {
// "wasi_snapshot_preview1": strace(this.wasi.wasiImport, ["clock_time_get"]),
"wasi_snapshot_preview1": this.wasi.wasiImport,
"trealla": {
"host-call": this._host_call.bind(this),
"host-resume": this._host_resume.bind(this),
"host-push-answer": this._host_push_answer.bind(this)
}
};
this.instance = await WebAssembly.instantiate(tpl, imports);
const exit = this.wasi.start(this.instance);
if (exit !== 0) {
throw new Error("trealla: could not initialize interpreter");
}
const pl_global = this.instance.exports.pl_global;
this.ptr = pl_global();
await this.registerPredicates(LIBRARY, "user");
}
/** Run a query. This is an asynchronous generator function.
* Use a `for await` loop to easily iterate through results.
* Exiting the loop will automatically destroy the query and reclaim memory.
* Call the `return()` method of the generator to kill it early if manually iterating with `next()`.
* Runtimes that support finalizers will make a best effort attempt to kill live but garbage-collected queries.
**/
async *query(goal, options = {}) {
if (!this.instance) await this.init();
const {
bind,
program,
// Prolog text to consult before running query
format = "json",
// Format (toplevel) selector
encode,
// Options passed to toplevel
autoyield = 20
// Yield interval, milliseconds. Set to 0 to disable.
} = options;
goal = goal.replaceAll("\n", " ").replaceAll(" ", " ");
const toplevel = typeof format === "string" ? FORMATS[format] : format;
if (!toplevel) {
throw new Error(`trealla: unknown format: ${format}`);
}
const _id = ++this.n;
const token = {};
const stdoutbuf = new ByteBuffer();
const stderrbuf = new ByteBuffer();
const readOutput = /* @__PURE__ */ __name(() => {
stdoutbuf.copyFrom(this.os.stdout.buf);
this.os.stdout.reset();
stderrbuf.copyFrom(this.os.stderr.buf);
this.os.stderr.reset();
}, "readOutput");
const realloc = this.instance.exports.canonical_abi_realloc;
const free = this.instance.exports.canonical_abi_free;
const pl_query = this.instance.exports.pl_query;
const pl_redo = this.instance.exports.pl_redo;
const pl_done = this.instance.exports.pl_done;
const get_status = this.instance.exports.get_status;
const get_error = this.instance.exports.get_error;
const pl_did_yield = this.instance.exports.pl_did_yield;
const pl_yield_at = this.instance.exports.pl_yield_at;
let subqptr = realloc(NULL, 0, ALIGN, PTRSIZE);
let readSubqPtr = /* @__PURE__ */ __name(() => {
const subq = subqptr ? indirect(this.instance, subqptr) : NULL;
if (subq !== NULL) {
this.subqs.set(subq, ctrl);
this.spawning.delete(subqptr);
}
return subq;
}, "readSubqPtr");
const os = this.os;
const ctrl = {
subq: NULL,
get subquery() {
if (this.subq === NULL)
this.subq = readSubqPtr();
return this.subq;
},
alive: true,
stdout: /* @__PURE__ */ __name(function(str) {
if (!str) return;
os.stdout.fd.write(new TextEncoder().encode(str));
}, "stdout"),
stderr: /* @__PURE__ */ __name(function(str) {
if (!str) return;
os.stderr.fd.write(new TextEncoder().encode(str));
}, "stderr"),
answers: []
};
this.spawning.set(subqptr, ctrl);
if (program) {
await this.consultText(program);
}
const goalstr = new CString(this.instance, toplevel.query(this, goal, bind, encode));
let finalizing = false;
let lastYield = 0;
try {
const ok = pl_query(this.ptr, goalstr.ptr, subqptr, autoyield);
goalstr.free();
const subq = readSubqPtr();
ctrl.subq = subq;
readSubqPtr = /* @__PURE__ */ __name(function() {
return subq;
}, "readSubqPtr");
free(subqptr, PTRSIZE, ALIGN);
subqptr = NULL;
do {
if (this.finalizers && ctrl.alive && !finalizing) {
this.finalizers.register(token, ctrl);
finalizing = true;
}
readOutput();
if (pl_did_yield(ctrl.subq) === TRUE) {
const thunk = this.yielding.get(ctrl.subq);
if (!thunk) {
let now;
if (autoyield > 0 && (now = Date.now()) - lastYield > autoyield) {
lastYield = now;
await new Promise((resolve) => setTimeout(resolve, 0));
pl_yield_at(ctrl.subq, autoyield);
readOutput();
}
continue;
}
try {
if (thunk.cont) {
const { value, done } = await thunk.cont.next();
readOutput();
thunk.value = value ?? void 0;
thunk.done = done ?? true;
} else {
thunk.value = void 0;
thunk.done = true;
}
} catch (error) {
console.error(error);
thunk.value = throwTerm(system_error("js_exception", `${error}`, piTerm("$host_resume", 1)));
}
lastYield = Date.now();
continue;
}
const status = get_status(this.ptr) === TRUE;
const usingJSON = toplevel === FORMATS.json;
const errored = !usingJSON ? get_error(this.ptr) : FALSE;
const stdout = stdoutbuf.data;
const stderr = stderrbuf.data;
stdoutbuf.reset();
stderrbuf.reset();
const queued = ctrl.answers.shift();
const empty = usingJSON ? !queued : stdout.byteLength === 0;
if (empty) {
const truth = toplevel.truth(this, status, stderr, encode);
if (truth === null) return;
yield truth;
} else {
const solution = toplevel.parse(this, status, stdout, stderr, encode, queued);
if (solution === null) return;
yield solution;
}
if (errored === TRUE) {
ctrl.alive = false;
return;
}
if (ok === FALSE) {
return;
}
} while (ctrl.alive = pl_redo(ctrl.subq) === TRUE);
} finally {
if (finalizing) {
this.finalizers.unregister(token);
}
if (ctrl.subq !== NULL) {
this.subqs.delete(ctrl.subq);
if (ctrl.alive) {
ctrl.alive = false;
pl_done(ctrl.subq);
this.yielding.delete(ctrl.subq);
}
}
}
}
/** Runs a query and returns a single solution, ignoring others. */
async queryOnce(goal, options) {
const q = this.query(goal, options);
try {
const answer = await q.next();
return answer.value;
} finally {
q.return(void 0);
}
}
/** Consult (load) a Prolog file with the given text content.
* Use fs to manipulate the filesystem. */
async consult(filename) {
if (!this.instance) await this.init();
if (filename === "user") {
throw new Error("trealla: consulting from 'user' unsupported");
}
const pl_consult = this.instance.exports.pl_consult;
const str = new CString(this.instance, filename);
let ret = FALSE;
try {
ret = pl_consult(this.ptr, str.ptr);
} finally {
str.free();
}
if (ret === FALSE) {
throw new Error(`trealla: failed to consult file: ${filename}`);
}
}
/** Consult (load) Prolog text. */
async consultText(code) {
if (!this.instance) {
await this.init();
}
const filename = await this.writeScratchFile(code);
await this.consult(filename);
}
async consultTextInto(code, module = "user") {
if (!this.instance) {
await this.init();
}
const goal = new Compound("load_text", [code, [new Compound("module", [new Atom(module)])]]);
const reply = await this.queryOnce(goal.toProlog());
if (reply.status !== "success") {
throw new Error("trealla: consult text failed");
}
}
async register(pred, module = "user") {
if (Array.isArray(pred))
return this.registerPredicates(pred, module);
if (!(pred instanceof Predicate))
throw new Error("trealla: predicate is not type Predicate");
this.procs[pred.pi.toString()] = pred;
const shim = pred.shim();
await this.consultTextInto(shim, module);
}
async registerPredicates(predicates, module = "user") {
let shim = "";
for (const pred of predicates) {
this.procs[pred.pi.toString()] = pred;
shim += pred.shim() + " ";
}
await this.consultTextInto(shim, module);
}
async writeScratchFile(code) {
const id = ++this.scratch;
const filename = `./tmp/scratch${id}.pl`;
const file = this.fs.open(filename, { create: true, write: true });
if (typeof code === "string") {
file.writeString(code);
} else if (code instanceof Uint8Array) {
file.write(code);
} else {
throw new Error("trealla: invalid parameter for consulting: " + code);
}
return filename;
}
addTask(query) {
const id = this.taskcount++;
const q = this.runTask(id, query);
this.tasks.set(id, {
id,
promise: null,
cancel: null,
query: q
});
return id;
}
async *runTask(id, query) {
let choice = 0;
try {
for await (const x of query) {
yield { task_id: id, answer: x, time: Date.now(), depth: choice++ };
}
} finally {
this.tasks.delete(id);
}
}
tickTask(task) {
if (!task.promise) {
task.promise = new Promise(async (resolve) => {
task.cancel = () => {
task.query.return();
resolve(Promise.resolve(void 0));
};
const { value } = await task.query.next();
resolve(value ?? void 0);
task.promise = null;
task.cancel = null;
});
}
return task.promise;
}
ctrl(subquery) {
const ctrl = this.subqs.get(subquery);
if (ctrl)
return ctrl;
for (const [_, ctrl2] of this.spawning) {
if (ctrl2.subquery === subquery)
return ctrl2;
}
throw new Error("trealla: internal error, couldn't find ctrl for subquery");
}
_host_call(subquery, ptr, msgsize, replyptrptr, replysizeptr) {
const raw = readString(this.instance, ptr, msgsize);
const goal = fromJSON(raw);
const ctrl = this.ctrl(subquery);
let result = "fail";
let cont;
try {
const pred = this.procs[goal.pi.toProlog()];
if (!pred) {
sys_missing_n(this, subquery, goal);
} else if (!pred.async) {
const value = pred.proc(this, subquery, goal, ctrl);
if (value instanceof Promise) {
cont = async function* () {
return await value;
}();
result = "true";
} else {
if (isTerm(value))
result = toProlog(value);
else
result = value;
}
} else {
cont = pred.eval(this, subquery, goal, ctrl);
result = "true";
}
} catch (error) {
console.error(error);
result = throwTerm(system_error("js_exception", `${error}`, goal.pi)).toProlog();
}
if (cont) {
this.yielding.set(subquery, {
cont,
done: false
});
}
let reply;
if (typeof result === "string") {
reply = new CString(this.instance, result);
} else {
console.warn("invalid return value from native predicate: " + goal.pi + " value: " + result);
return WASM_HOST_CALL_ERROR;
}
writeUint32(this.instance, replysizeptr, reply.size - 1);
writeUint32(this.instance, replyptrptr, reply.ptr);
if (!cont)
return WASM_HOST_CALL_OK;
return WASM_HOST_CALL_YIELD;
}
_host_resume(subquery, replyptrptr, replysizeptr) {
const task = this.yielding.get(subquery);
if (!task) {
return WASM_HOST_CALL_ERROR;
}
if (task.done)
this.yielding.delete(subquery);
let result;
try {
const x = task.value;
if (!x) {
result = "fail";
} else if (x === true) {
result = "true";
} else {
result = toProlog(x);
}
} catch (error) {
console.error(error);
result = throwTerm(system_error("js_exception", `${error}`, piTerm("host_rpc", 2))).toProlog();
}
const reply = new CString(this.instance, result);
writeUint32(this.instance, replysizeptr, reply.size - 1);
writeUint32(this.instance, replyptrptr, reply.ptr);
if (!task.done)
return WASM_HOST_CALL_CHOICE;
if (result === "fail")
return WASM_HOST_CALL_FAIL;
return WASM_HOST_CALL_OK;
}
_host_push_answer(subquery, ptr, msgsize) {
const raw = readString(this.instance, ptr, msgsize);
const ctrl = this.ctrl(subquery);
ctrl.answers.push(raw);
}
};
var WASM_HOST_CALL_ERROR = 0;
var WASM_HOST_CALL_OK = 1;
var WASM_HOST_CALL_YIELD = 2;
var WASM_HOST_CALL_CHOICE = 3;
var WASM_HOST_CALL_FAIL = 4;
function newWASI(os, library, env, quiet) {
const args = ["tpl", "--ns"];
if (library) args.push("--library", library);
if (quiet) args.push("-q");
const environ = env ? Object.entries(env).map(([k, v]) => `${k}=${v}`) : [];
let fds = [
/* 0: */
new OpenFile(new File([])),
// stdin
/* 1: */
os.stdout.fd,
/* 2: */
os.stderr.fd,
/* 3: */
os.root
];
const wasi = new WASI(args, environ, fds, { debug: false });
return wasi;
}
__name(newWASI, "newWASI");
export {
Atom,
Atomic,
Compound,
FORMATS,
FS,
File2 as File,
Float,
LIBRARY,
Literal,
Predicate,
Prolog,
Rational,
Variable,
atom,
await_any_3,
console_log_1,
delay_1,
domain_error,
escapeAtom,
escapeString,
existence_error,
fromJSON,
future_2,
future_cancel_1,
isAtom,
isCallable,
isCompound,
isList,
isNumber,
isRational,
isString,
isTerm,
isVariable,
js_eval_2,
js_eval_json_2,
load,
newOS,
piTerm,
prolog,
reviver,
sleep_1,
sys_await_1,
sys_await_all_1,
sys_await_some_3,
sys_missing_n,
system_error,
throwTerm,
toJSON,
toProlog,
type_error
};