UNPKG

@eliaspourquoi/sqlite-node-wasm

Version:

SQLite Wasm conveniently wrapped as an ES Module.

1,697 lines (1,542 loc) 481 kB
/* ** LICENSE for the sqlite3 WebAssembly/JavaScript APIs. ** ** This bundle (typically released as sqlite3.js or sqlite3.mjs) ** is an amalgamation of JavaScript source code from two projects: ** ** 1) https://emscripten.org: the Emscripten "glue code" is covered by ** the terms of the MIT license and University of Illinois/NCSA ** Open Source License, as described at: ** ** https://emscripten.org/docs/introducing_emscripten/emscripten_license.html ** ** 2) https://sqlite.org: all code and documentation labeled as being ** from this source are released under the same terms as the sqlite3 ** C library: ** ** 2022-10-16 ** ** The author disclaims copyright to this source code. In place of a ** legal notice, here is a blessing: ** ** * May you do good and not evil. ** * May you find forgiveness for yourself and forgive others. ** * May you share freely, never taking more than you give. */ /* ** This code was built from sqlite3 version... ** ** SQLITE_VERSION "3.46.0" ** SQLITE_VERSION_NUMBER 3046000 ** SQLITE_SOURCE_ID "2024-05-23 13:25:27 96c92aba00c8375bc32fafcdf12429c58bd8aabfcadab6683e35bbb9cdebf19e" ** ** Using the Emscripten SDK version 3.1.30. */ var sqlite3InitModule = (() => { var _scriptDir = import.meta.url; return function (config) { var sqlite3InitModule = config || {}; var Module = typeof sqlite3InitModule != 'undefined' ? sqlite3InitModule : {}; var readyPromiseResolve, readyPromiseReject; Module['ready'] = new Promise(function (resolve, reject) { readyPromiseResolve = resolve; readyPromiseReject = reject; }); const sqlite3InitModuleState = globalThis.sqlite3InitModuleState || Object.assign(Object.create(null), { debugModule: () => {}, }); delete globalThis.sqlite3InitModuleState; sqlite3InitModuleState.debugModule( 'globalThis.location =', globalThis.location, ); Module['locateFile'] = function (path, prefix) { return new URL(path, import.meta.url).href; }.bind(sqlite3InitModuleState); const xNameOfInstantiateWasm = false ? 'instantiateWasm' : 'emscripten-bug-17951'; Module[xNameOfInstantiateWasm] = function callee(imports, onSuccess) { imports.env.foo = function () {}; const uri = Module.locateFile( callee.uri, 'undefined' === typeof scriptDirectory ? '' : scriptDirectory, ); sqlite3InitModuleState.debugModule('instantiateWasm() uri =', uri); const wfetch = () => fetch(uri, { credentials: 'same-origin' }); const loadWasm = WebAssembly.instantiateStreaming ? async () => { return WebAssembly.instantiateStreaming(wfetch(), imports).then( (arg) => onSuccess(arg.instance, arg.module), ); } : async () => { return wfetch() .then((response) => response.arrayBuffer()) .then((bytes) => WebAssembly.instantiate(bytes, imports)) .then((arg) => onSuccess(arg.instance, arg.module)); }; loadWasm(); return {}; }; Module[xNameOfInstantiateWasm].uri = 'sqlite3.wasm'; var moduleOverrides = Object.assign({}, Module); var arguments_ = []; var thisProgram = './this.program'; var quit_ = (status, toThrow) => { throw toThrow; }; var ENVIRONMENT_IS_WEB = typeof window == 'object'; var ENVIRONMENT_IS_WORKER = typeof importScripts == 'function'; var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions == 'object' && typeof process.versions.node == 'string'; var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; var scriptDirectory = ''; function locateFile(path) { if (Module['locateFile']) { return Module['locateFile'](path, scriptDirectory); } return scriptDirectory + path; } var read_, readAsync, readBinary, setWindowTitle; if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { if (ENVIRONMENT_IS_WORKER) { scriptDirectory = self.location.href; } else if (typeof document != 'undefined' && document.currentScript) { scriptDirectory = document.currentScript.src; } if (_scriptDir) { scriptDirectory = _scriptDir; } if (scriptDirectory.indexOf('blob:') !== 0) { scriptDirectory = scriptDirectory.substr( 0, scriptDirectory.replace(/[?#].*/, '').lastIndexOf('/') + 1, ); } else { scriptDirectory = ''; } { read_ = (url) => { var xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.send(null); return xhr.responseText; }; if (ENVIRONMENT_IS_WORKER) { readBinary = (url) => { var xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.responseType = 'arraybuffer'; xhr.send(null); return new Uint8Array(xhr.response); }; } readAsync = (url, onload, onerror) => { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.onload = () => { if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { onload(xhr.response); return; } onerror(); }; xhr.onerror = onerror; xhr.send(null); }; } setWindowTitle = (title) => (document.title = title); } else { } var out = Module['print'] || console.log.bind(console); var err = Module['printErr'] || console.warn.bind(console); Object.assign(Module, moduleOverrides); moduleOverrides = null; if (Module['arguments']) arguments_ = Module['arguments']; if (Module['thisProgram']) thisProgram = Module['thisProgram']; if (Module['quit']) quit_ = Module['quit']; var STACK_ALIGN = 16; var POINTER_SIZE = 4; function getNativeTypeSize(type) { switch (type) { case 'i1': case 'i8': case 'u8': return 1; case 'i16': case 'u16': return 2; case 'i32': case 'u32': return 4; case 'i64': case 'u64': return 8; case 'float': return 4; case 'double': return 8; default: { if (type[type.length - 1] === '*') { return POINTER_SIZE; } if (type[0] === 'i') { const bits = Number(type.substr(1)); assert( bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type, ); return bits / 8; } return 0; } } } var wasmBinary; if (Module['wasmBinary']) wasmBinary = Module['wasmBinary']; var noExitRuntime = Module['noExitRuntime'] || true; if (typeof WebAssembly != 'object') { abort('no native wasm support detected'); } var wasmMemory; var ABORT = false; var EXITSTATUS; function assert(condition, text) { if (!condition) { abort(text); } } var UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf8') : undefined; function UTF8ArrayToString(heapOrArray, idx, maxBytesToRead) { var endIdx = idx + maxBytesToRead; var endPtr = idx; while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr; if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) { return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr)); } var str = ''; while (idx < endPtr) { var u0 = heapOrArray[idx++]; if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; } var u1 = heapOrArray[idx++] & 63; if ((u0 & 0xe0) == 0xc0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; } var u2 = heapOrArray[idx++] & 63; if ((u0 & 0xf0) == 0xe0) { u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; } else { u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63); } if (u0 < 0x10000) { str += String.fromCharCode(u0); } else { var ch = u0 - 0x10000; str += String.fromCharCode( 0xd800 | (ch >> 10), 0xdc00 | (ch & 0x3ff), ); } } return str; } function UTF8ToString(ptr, maxBytesToRead) { return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ''; } function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { if (!(maxBytesToWrite > 0)) return 0; var startIdx = outIdx; var endIdx = outIdx + maxBytesToWrite - 1; for (var i = 0; i < str.length; ++i) { var u = str.charCodeAt(i); if (u >= 0xd800 && u <= 0xdfff) { var u1 = str.charCodeAt(++i); u = (0x10000 + ((u & 0x3ff) << 10)) | (u1 & 0x3ff); } if (u <= 0x7f) { if (outIdx >= endIdx) break; heap[outIdx++] = u; } else if (u <= 0x7ff) { if (outIdx + 1 >= endIdx) break; heap[outIdx++] = 0xc0 | (u >> 6); heap[outIdx++] = 0x80 | (u & 63); } else if (u <= 0xffff) { if (outIdx + 2 >= endIdx) break; heap[outIdx++] = 0xe0 | (u >> 12); heap[outIdx++] = 0x80 | ((u >> 6) & 63); heap[outIdx++] = 0x80 | (u & 63); } else { if (outIdx + 3 >= endIdx) break; heap[outIdx++] = 0xf0 | (u >> 18); heap[outIdx++] = 0x80 | ((u >> 12) & 63); heap[outIdx++] = 0x80 | ((u >> 6) & 63); heap[outIdx++] = 0x80 | (u & 63); } } heap[outIdx] = 0; return outIdx - startIdx; } function stringToUTF8(str, outPtr, maxBytesToWrite) { return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite); } function lengthBytesUTF8(str) { var len = 0; for (var i = 0; i < str.length; ++i) { var c = str.charCodeAt(i); if (c <= 0x7f) { len++; } else if (c <= 0x7ff) { len += 2; } else if (c >= 0xd800 && c <= 0xdfff) { len += 4; ++i; } else { len += 3; } } return len; } var HEAP, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64, HEAPU64, HEAPF64; function updateMemoryViews() { var b = wasmMemory.buffer; Module['HEAP8'] = HEAP8 = new Int8Array(b); Module['HEAP16'] = HEAP16 = new Int16Array(b); Module['HEAP32'] = HEAP32 = new Int32Array(b); Module['HEAPU8'] = HEAPU8 = new Uint8Array(b); Module['HEAPU16'] = HEAPU16 = new Uint16Array(b); Module['HEAPU32'] = HEAPU32 = new Uint32Array(b); Module['HEAPF32'] = HEAPF32 = new Float32Array(b); Module['HEAPF64'] = HEAPF64 = new Float64Array(b); Module['HEAP64'] = HEAP64 = new BigInt64Array(b); Module['HEAPU64'] = HEAPU64 = new BigUint64Array(b); } var STACK_SIZE = 524288; var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216; if (Module['wasmMemory']) { wasmMemory = Module['wasmMemory']; } else { wasmMemory = new WebAssembly.Memory({ initial: INITIAL_MEMORY / 65536, maximum: 2147483648 / 65536, }); } updateMemoryViews(); INITIAL_MEMORY = wasmMemory.buffer.byteLength; var wasmTable; var __ATPRERUN__ = []; var __ATINIT__ = []; var __ATEXIT__ = []; var __ATPOSTRUN__ = []; var runtimeInitialized = false; function keepRuntimeAlive() { return noExitRuntime; } function preRun() { if (Module['preRun']) { if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']]; while (Module['preRun'].length) { addOnPreRun(Module['preRun'].shift()); } } callRuntimeCallbacks(__ATPRERUN__); } function initRuntime() { runtimeInitialized = true; if (!Module['noFSInit'] && !FS.init.initialized) FS.init(); FS.ignorePermissions = false; TTY.init(); callRuntimeCallbacks(__ATINIT__); } function postRun() { if (Module['postRun']) { if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']]; while (Module['postRun'].length) { addOnPostRun(Module['postRun'].shift()); } } callRuntimeCallbacks(__ATPOSTRUN__); } function addOnPreRun(cb) { __ATPRERUN__.unshift(cb); } function addOnInit(cb) { __ATINIT__.unshift(cb); } function addOnExit(cb) {} function addOnPostRun(cb) { __ATPOSTRUN__.unshift(cb); } var runDependencies = 0; var runDependencyWatcher = null; var dependenciesFulfilled = null; function getUniqueRunDependency(id) { return id; } function addRunDependency(id) { runDependencies++; if (Module['monitorRunDependencies']) { Module['monitorRunDependencies'](runDependencies); } } function removeRunDependency(id) { runDependencies--; if (Module['monitorRunDependencies']) { Module['monitorRunDependencies'](runDependencies); } if (runDependencies == 0) { if (runDependencyWatcher !== null) { clearInterval(runDependencyWatcher); runDependencyWatcher = null; } if (dependenciesFulfilled) { var callback = dependenciesFulfilled; dependenciesFulfilled = null; callback(); } } } function abort(what) { if (Module['onAbort']) { Module['onAbort'](what); } what = 'Aborted(' + what + ')'; err(what); ABORT = true; EXITSTATUS = 1; what += '. Build with -sASSERTIONS for more info.'; var e = new WebAssembly.RuntimeError(what); readyPromiseReject(e); throw e; } var dataURIPrefix = 'data:application/octet-stream;base64,'; function isDataURI(filename) { return filename.startsWith(dataURIPrefix); } function isFileURI(filename) { return filename.startsWith('file://'); } var wasmBinaryFile; if (Module['locateFile']) { wasmBinaryFile = 'sqlite3.wasm'; if (!isDataURI(wasmBinaryFile)) { wasmBinaryFile = locateFile(wasmBinaryFile); } } else { wasmBinaryFile = new URL('sqlite3.wasm', import.meta.url).href; } function getBinary(file) { try { if (file == wasmBinaryFile && wasmBinary) { return new Uint8Array(wasmBinary); } if (readBinary) { return readBinary(file); } throw 'both async and sync fetching of the wasm failed'; } catch (err) { abort(err); } } function getBinaryPromise() { if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { if (typeof fetch == 'function') { return fetch(wasmBinaryFile, { credentials: 'same-origin' }) .then(function (response) { if (!response['ok']) { throw ( "failed to load wasm binary file at '" + wasmBinaryFile + "'" ); } return response['arrayBuffer'](); }) .catch(function () { return getBinary(wasmBinaryFile); }); } } return Promise.resolve().then(function () { return getBinary(wasmBinaryFile); }); } function createWasm() { var info = { env: asmLibraryArg, wasi_snapshot_preview1: asmLibraryArg, }; function receiveInstance(instance, module) { var exports = instance.exports; Module['asm'] = exports; wasmTable = Module['asm']['__indirect_function_table']; addOnInit(Module['asm']['__wasm_call_ctors']); removeRunDependency('wasm-instantiate'); } addRunDependency('wasm-instantiate'); function receiveInstantiationResult(result) { receiveInstance(result['instance']); } function instantiateArrayBuffer(receiver) { return getBinaryPromise() .then(function (binary) { return WebAssembly.instantiate(binary, info); }) .then(function (instance) { return instance; }) .then(receiver, function (reason) { err('failed to asynchronously prepare wasm: ' + reason); abort(reason); }); } function instantiateAsync() { if ( !wasmBinary && typeof WebAssembly.instantiateStreaming == 'function' && !isDataURI(wasmBinaryFile) && typeof fetch == 'function' ) { return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then( function (response) { var result = WebAssembly.instantiateStreaming(response, info); return result.then(receiveInstantiationResult, function (reason) { err('wasm streaming compile failed: ' + reason); err('falling back to ArrayBuffer instantiation'); return instantiateArrayBuffer(receiveInstantiationResult); }); }, ); } else { return instantiateArrayBuffer(receiveInstantiationResult); } } if (Module['instantiateWasm']) { try { var exports = Module['instantiateWasm'](info, receiveInstance); return exports; } catch (e) { err('Module.instantiateWasm callback failed with error: ' + e); readyPromiseReject(e); } } instantiateAsync().catch(readyPromiseReject); return {}; } var tempDouble; var tempI64; var ASM_CONSTS = {}; function ExitStatus(status) { this.name = 'ExitStatus'; this.message = 'Program terminated with exit(' + status + ')'; this.status = status; } function callRuntimeCallbacks(callbacks) { while (callbacks.length > 0) { callbacks.shift()(Module); } } function getValue(ptr, type = 'i8') { if (type.endsWith('*')) type = '*'; switch (type) { case 'i1': return HEAP8[ptr >> 0]; case 'i8': return HEAP8[ptr >> 0]; case 'i16': return HEAP16[ptr >> 1]; case 'i32': return HEAP32[ptr >> 2]; case 'i64': return HEAP64[ptr >> 3]; case 'float': return HEAPF32[ptr >> 2]; case 'double': return HEAPF64[ptr >> 3]; case '*': return HEAPU32[ptr >> 2]; default: abort('invalid type for getValue: ' + type); } return null; } function setValue(ptr, value, type = 'i8') { if (type.endsWith('*')) type = '*'; switch (type) { case 'i1': HEAP8[ptr >> 0] = value; break; case 'i8': HEAP8[ptr >> 0] = value; break; case 'i16': HEAP16[ptr >> 1] = value; break; case 'i32': HEAP32[ptr >> 2] = value; break; case 'i64': (tempI64 = [ value >>> 0, ((tempDouble = value), +Math.abs(tempDouble) >= 1.0 ? tempDouble > 0.0 ? (Math.min( +Math.floor(tempDouble / 4294967296.0), 4294967295.0, ) | 0) >>> 0 : ~~+Math.ceil( (tempDouble - +(~~tempDouble >>> 0)) / 4294967296.0, ) >>> 0 : 0), ]), (HEAP32[ptr >> 2] = tempI64[0]), (HEAP32[(ptr + 4) >> 2] = tempI64[1]); break; case 'float': HEAPF32[ptr >> 2] = value; break; case 'double': HEAPF64[ptr >> 3] = value; break; case '*': HEAPU32[ptr >> 2] = value; break; default: abort('invalid type for setValue: ' + type); } } var PATH = { isAbs: (path) => path.charAt(0) === '/', splitPath: (filename) => { var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; return splitPathRe.exec(filename).slice(1); }, normalizeArray: (parts, allowAboveRoot) => { var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } if (allowAboveRoot) { for (; up; up--) { parts.unshift('..'); } } return parts; }, normalize: (path) => { var isAbsolute = PATH.isAbs(path), trailingSlash = path.substr(-1) === '/'; path = PATH.normalizeArray( path.split('/').filter((p) => !!p), !isAbsolute, ).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }, dirname: (path) => { var result = PATH.splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { return '.'; } if (dir) { dir = dir.substr(0, dir.length - 1); } return root + dir; }, basename: (path) => { if (path === '/') return '/'; path = PATH.normalize(path); path = path.replace(/\/$/, ''); var lastSlash = path.lastIndexOf('/'); if (lastSlash === -1) return path; return path.substr(lastSlash + 1); }, join: function () { var paths = Array.prototype.slice.call(arguments); return PATH.normalize(paths.join('/')); }, join2: (l, r) => { return PATH.normalize(l + '/' + r); }, }; function getRandomDevice() { if ( typeof crypto == 'object' && typeof crypto['getRandomValues'] == 'function' ) { var randomBuffer = new Uint8Array(1); return () => { crypto.getRandomValues(randomBuffer); return randomBuffer[0]; }; } else return () => abort('randomDevice'); } var PATH_FS = { resolve: function () { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = i >= 0 ? arguments[i] : FS.cwd(); if (typeof path != 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { return ''; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = PATH.isAbs(path); } resolvedPath = PATH.normalizeArray( resolvedPath.split('/').filter((p) => !!p), !resolvedAbsolute, ).join('/'); return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; }, relative: (from, to) => { from = PATH_FS.resolve(from).substr(1); to = PATH_FS.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }, }; function intArrayFromString(stringy, dontAddNull, length) { var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1; var u8array = new Array(len); var numBytesWritten = stringToUTF8Array( stringy, u8array, 0, u8array.length, ); if (dontAddNull) u8array.length = numBytesWritten; return u8array; } var TTY = { ttys: [], init: function () {}, shutdown: function () {}, register: function (dev, ops) { TTY.ttys[dev] = { input: [], output: [], ops: ops }; FS.registerDevice(dev, TTY.stream_ops); }, stream_ops: { open: function (stream) { var tty = TTY.ttys[stream.node.rdev]; if (!tty) { throw new FS.ErrnoError(43); } stream.tty = tty; stream.seekable = false; }, close: function (stream) { stream.tty.ops.fsync(stream.tty); }, fsync: function (stream) { stream.tty.ops.fsync(stream.tty); }, read: function (stream, buffer, offset, length, pos) { if (!stream.tty || !stream.tty.ops.get_char) { throw new FS.ErrnoError(60); } var bytesRead = 0; for (var i = 0; i < length; i++) { var result; try { result = stream.tty.ops.get_char(stream.tty); } catch (e) { throw new FS.ErrnoError(29); } if (result === undefined && bytesRead === 0) { throw new FS.ErrnoError(6); } if (result === null || result === undefined) break; bytesRead++; buffer[offset + i] = result; } if (bytesRead) { stream.node.timestamp = Date.now(); } return bytesRead; }, write: function (stream, buffer, offset, length, pos) { if (!stream.tty || !stream.tty.ops.put_char) { throw new FS.ErrnoError(60); } try { for (var i = 0; i < length; i++) { stream.tty.ops.put_char(stream.tty, buffer[offset + i]); } } catch (e) { throw new FS.ErrnoError(29); } if (length) { stream.node.timestamp = Date.now(); } return i; }, }, default_tty_ops: { get_char: function (tty) { if (!tty.input.length) { var result = null; if ( typeof window != 'undefined' && typeof window.prompt == 'function' ) { result = window.prompt('Input: '); if (result !== null) { result += '\n'; } } else if (typeof readline == 'function') { result = readline(); if (result !== null) { result += '\n'; } } if (!result) { return null; } tty.input = intArrayFromString(result, true); } return tty.input.shift(); }, put_char: function (tty, val) { if (val === null || val === 10) { out(UTF8ArrayToString(tty.output, 0)); tty.output = []; } else { if (val != 0) tty.output.push(val); } }, fsync: function (tty) { if (tty.output && tty.output.length > 0) { out(UTF8ArrayToString(tty.output, 0)); tty.output = []; } }, }, default_tty1_ops: { put_char: function (tty, val) { if (val === null || val === 10) { err(UTF8ArrayToString(tty.output, 0)); tty.output = []; } else { if (val != 0) tty.output.push(val); } }, fsync: function (tty) { if (tty.output && tty.output.length > 0) { err(UTF8ArrayToString(tty.output, 0)); tty.output = []; } }, }, }; function zeroMemory(address, size) { HEAPU8.fill(0, address, address + size); return address; } function alignMemory(size, alignment) { return Math.ceil(size / alignment) * alignment; } function mmapAlloc(size) { size = alignMemory(size, 65536); var ptr = _emscripten_builtin_memalign(65536, size); if (!ptr) return 0; return zeroMemory(ptr, size); } var MEMFS = { ops_table: null, mount: function (mount) { return MEMFS.createNode(null, '/', 16384 | 511, 0); }, createNode: function (parent, name, mode, dev) { if (FS.isBlkdev(mode) || FS.isFIFO(mode)) { throw new FS.ErrnoError(63); } if (!MEMFS.ops_table) { MEMFS.ops_table = { dir: { node: { getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr, lookup: MEMFS.node_ops.lookup, mknod: MEMFS.node_ops.mknod, rename: MEMFS.node_ops.rename, unlink: MEMFS.node_ops.unlink, rmdir: MEMFS.node_ops.rmdir, readdir: MEMFS.node_ops.readdir, symlink: MEMFS.node_ops.symlink, }, stream: { llseek: MEMFS.stream_ops.llseek, }, }, file: { node: { getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr, }, stream: { llseek: MEMFS.stream_ops.llseek, read: MEMFS.stream_ops.read, write: MEMFS.stream_ops.write, allocate: MEMFS.stream_ops.allocate, mmap: MEMFS.stream_ops.mmap, msync: MEMFS.stream_ops.msync, }, }, link: { node: { getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr, readlink: MEMFS.node_ops.readlink, }, stream: {}, }, chrdev: { node: { getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr, }, stream: FS.chrdev_stream_ops, }, }; } var node = FS.createNode(parent, name, mode, dev); if (FS.isDir(node.mode)) { node.node_ops = MEMFS.ops_table.dir.node; node.stream_ops = MEMFS.ops_table.dir.stream; node.contents = {}; } else if (FS.isFile(node.mode)) { node.node_ops = MEMFS.ops_table.file.node; node.stream_ops = MEMFS.ops_table.file.stream; node.usedBytes = 0; node.contents = null; } else if (FS.isLink(node.mode)) { node.node_ops = MEMFS.ops_table.link.node; node.stream_ops = MEMFS.ops_table.link.stream; } else if (FS.isChrdev(node.mode)) { node.node_ops = MEMFS.ops_table.chrdev.node; node.stream_ops = MEMFS.ops_table.chrdev.stream; } node.timestamp = Date.now(); if (parent) { parent.contents[name] = node; parent.timestamp = node.timestamp; } return node; }, getFileDataAsTypedArray: function (node) { if (!node.contents) return new Uint8Array(0); if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes); return new Uint8Array(node.contents); }, expandFileStorage: function (node, newCapacity) { var prevCapacity = node.contents ? node.contents.length : 0; if (prevCapacity >= newCapacity) return; var CAPACITY_DOUBLING_MAX = 1024 * 1024; newCapacity = Math.max( newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2.0 : 1.125)) >>> 0, ); if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256); var oldContents = node.contents; node.contents = new Uint8Array(newCapacity); if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0); }, resizeFileStorage: function (node, newSize) { if (node.usedBytes == newSize) return; if (newSize == 0) { node.contents = null; node.usedBytes = 0; } else { var oldContents = node.contents; node.contents = new Uint8Array(newSize); if (oldContents) { node.contents.set( oldContents.subarray(0, Math.min(newSize, node.usedBytes)), ); } node.usedBytes = newSize; } }, node_ops: { getattr: function (node) { var attr = {}; attr.dev = FS.isChrdev(node.mode) ? node.id : 1; attr.ino = node.id; attr.mode = node.mode; attr.nlink = 1; attr.uid = 0; attr.gid = 0; attr.rdev = node.rdev; if (FS.isDir(node.mode)) { attr.size = 4096; } else if (FS.isFile(node.mode)) { attr.size = node.usedBytes; } else if (FS.isLink(node.mode)) { attr.size = node.link.length; } else { attr.size = 0; } attr.atime = new Date(node.timestamp); attr.mtime = new Date(node.timestamp); attr.ctime = new Date(node.timestamp); attr.blksize = 4096; attr.blocks = Math.ceil(attr.size / attr.blksize); return attr; }, setattr: function (node, attr) { if (attr.mode !== undefined) { node.mode = attr.mode; } if (attr.timestamp !== undefined) { node.timestamp = attr.timestamp; } if (attr.size !== undefined) { MEMFS.resizeFileStorage(node, attr.size); } }, lookup: function (parent, name) { throw FS.genericErrors[44]; }, mknod: function (parent, name, mode, dev) { return MEMFS.createNode(parent, name, mode, dev); }, rename: function (old_node, new_dir, new_name) { if (FS.isDir(old_node.mode)) { var new_node; try { new_node = FS.lookupNode(new_dir, new_name); } catch (e) {} if (new_node) { for (var i in new_node.contents) { throw new FS.ErrnoError(55); } } } delete old_node.parent.contents[old_node.name]; old_node.parent.timestamp = Date.now(); old_node.name = new_name; new_dir.contents[new_name] = old_node; new_dir.timestamp = old_node.parent.timestamp; old_node.parent = new_dir; }, unlink: function (parent, name) { delete parent.contents[name]; parent.timestamp = Date.now(); }, rmdir: function (parent, name) { var node = FS.lookupNode(parent, name); for (var i in node.contents) { throw new FS.ErrnoError(55); } delete parent.contents[name]; parent.timestamp = Date.now(); }, readdir: function (node) { var entries = ['.', '..']; for (var key in node.contents) { if (!node.contents.hasOwnProperty(key)) { continue; } entries.push(key); } return entries; }, symlink: function (parent, newname, oldpath) { var node = MEMFS.createNode(parent, newname, 511 | 40960, 0); node.link = oldpath; return node; }, readlink: function (node) { if (!FS.isLink(node.mode)) { throw new FS.ErrnoError(28); } return node.link; }, }, stream_ops: { read: function (stream, buffer, offset, length, position) { var contents = stream.node.contents; if (position >= stream.node.usedBytes) return 0; var size = Math.min(stream.node.usedBytes - position, length); if (size > 8 && contents.subarray) { buffer.set(contents.subarray(position, position + size), offset); } else { for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i]; } return size; }, write: function (stream, buffer, offset, length, position, canOwn) { if (buffer.buffer === HEAP8.buffer) { canOwn = false; } if (!length) return 0; var node = stream.node; node.timestamp = Date.now(); if (buffer.subarray && (!node.contents || node.contents.subarray)) { if (canOwn) { node.contents = buffer.subarray(offset, offset + length); node.usedBytes = length; return length; } else if (node.usedBytes === 0 && position === 0) { node.contents = buffer.slice(offset, offset + length); node.usedBytes = length; return length; } else if (position + length <= node.usedBytes) { node.contents.set( buffer.subarray(offset, offset + length), position, ); return length; } } MEMFS.expandFileStorage(node, position + length); if (node.contents.subarray && buffer.subarray) { node.contents.set( buffer.subarray(offset, offset + length), position, ); } else { for (var i = 0; i < length; i++) { node.contents[position + i] = buffer[offset + i]; } } node.usedBytes = Math.max(node.usedBytes, position + length); return length; }, llseek: function (stream, offset, whence) { var position = offset; if (whence === 1) { position += stream.position; } else if (whence === 2) { if (FS.isFile(stream.node.mode)) { position += stream.node.usedBytes; } } if (position < 0) { throw new FS.ErrnoError(28); } return position; }, allocate: function (stream, offset, length) { MEMFS.expandFileStorage(stream.node, offset + length); stream.node.usedBytes = Math.max( stream.node.usedBytes, offset + length, ); }, mmap: function (stream, length, position, prot, flags) { if (!FS.isFile(stream.node.mode)) { throw new FS.ErrnoError(43); } var ptr; var allocated; var contents = stream.node.contents; if (!(flags & 2) && contents.buffer === HEAP8.buffer) { allocated = false; ptr = contents.byteOffset; } else { if (position > 0 || position + length < contents.length) { if (contents.subarray) { contents = contents.subarray(position, position + length); } else { contents = Array.prototype.slice.call( contents, position, position + length, ); } } allocated = true; ptr = mmapAlloc(length); if (!ptr) { throw new FS.ErrnoError(48); } HEAP8.set(contents, ptr); } return { ptr: ptr, allocated: allocated }; }, msync: function (stream, buffer, offset, length, mmapFlags) { MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false); return 0; }, }, }; function asyncLoad(url, onload, onerror, noRunDep) { var dep = !noRunDep ? getUniqueRunDependency('al ' + url) : ''; readAsync( url, (arrayBuffer) => { assert( arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).', ); onload(new Uint8Array(arrayBuffer)); if (dep) removeRunDependency(dep); }, (event) => { if (onerror) { onerror(); } else { throw 'Loading data file "' + url + '" failed.'; } }, ); if (dep) addRunDependency(dep); } var FS = { root: null, mounts: [], devices: {}, streams: [], nextInode: 1, nameTable: null, currentPath: '/', initialized: false, ignorePermissions: true, ErrnoError: null, genericErrors: {}, filesystems: null, syncFSRequests: 0, lookupPath: (path, opts = {}) => { path = PATH_FS.resolve(path); if (!path) return { path: '', node: null }; var defaults = { follow_mount: true, recurse_count: 0, }; opts = Object.assign(defaults, opts); if (opts.recurse_count > 8) { throw new FS.ErrnoError(32); } var parts = path.split('/').filter((p) => !!p); var current = FS.root; var current_path = '/'; for (var i = 0; i < parts.length; i++) { var islast = i === parts.length - 1; if (islast && opts.parent) { break; } current = FS.lookupNode(current, parts[i]); current_path = PATH.join2(current_path, parts[i]); if (FS.isMountpoint(current)) { if (!islast || (islast && opts.follow_mount)) { current = current.mounted.root; } } if (!islast || opts.follow) { var count = 0; while (FS.isLink(current.mode)) { var link = FS.readlink(current_path); current_path = PATH_FS.resolve(PATH.dirname(current_path), link); var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count + 1, }); current = lookup.node; if (count++ > 40) { throw new FS.ErrnoError(32); } } } } return { path: current_path, node: current }; }, getPath: (node) => { var path; while (true) { if (FS.isRoot(node)) { var mount = node.mount.mountpoint; if (!path) return mount; return mount[mount.length - 1] !== '/' ? mount + '/' + path : mount + path; } path = path ? node.name + '/' + path : node.name; node = node.parent; } }, hashName: (parentid, name) => { var hash = 0; for (var i = 0; i < name.length; i++) { hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0; } return ((parentid + hash) >>> 0) % FS.nameTable.length; }, hashAddNode: (node) => { var hash = FS.hashName(node.parent.id, node.name); node.name_next = FS.nameTable[hash]; FS.nameTable[hash] = node; }, hashRemoveNode: (node) => { var hash = FS.hashName(node.parent.id, node.name); if (FS.nameTable[hash] === node) { FS.nameTable[hash] = node.name_next; } else { var current = FS.nameTable[hash]; while (current) { if (current.name_next === node) { current.name_next = node.name_next; break; } current = current.name_next; } } }, lookupNode: (parent, name) => { var errCode = FS.mayLookup(parent); if (errCode) { throw new FS.ErrnoError(errCode, parent); } var hash = FS.hashName(parent.id, name); for (var node = FS.nameTable[hash]; node; node = node.name_next) { var nodeName = node.name; if (node.parent.id === parent.id && nodeName === name) { return node; } } return FS.lookup(parent, name); }, createNode: (parent, name, mode, rdev) => { var node = new FS.FSNode(parent, name, mode, rdev); FS.hashAddNode(node); return node; }, destroyNode: (node) => { FS.hashRemoveNode(node); }, isRoot: (node) => { return node === node.parent; }, isMountpoint: (node) => { return !!node.mounted; }, isFile: (mode) => { return (mode & 61440) === 32768; }, isDir: (mode) => { return (mode & 61440) === 16384; }, isLink: (mode) => { return (mode & 61440) === 40960; }, isChrdev: (mode) => { return (mode & 61440) === 8192; }, isBlkdev: (mode) => { return (mode & 61440) === 24576; }, isFIFO: (mode) => { return (mode & 61440) === 4096; }, isSocket: (mode) => { return (mode & 49152) === 49152; }, flagModes: { r: 0, 'r+': 2, w: 577, 'w+': 578, a: 1089, 'a+': 1090 }, modeStringToFlags: (str) => { var flags = FS.flagModes[str]; if (typeof flags == 'undefined') { throw new Error('Unknown file open mode: ' + str); } return flags; }, flagsToPermissionString: (flag) => { var perms = ['r', 'w', 'rw'][flag & 3]; if (flag & 512) { perms += 'w'; } return perms; }, nodePermissions: (node, perms) => { if (FS.ignorePermissions) { return 0; } if (perms.includes('r') && !(node.mode & 292)) { return 2; } else if (perms.includes('w') && !(node.mode & 146)) { return 2; } else if (perms.includes('x') && !(node.mode & 73)) { return 2; } return 0; }, mayLookup: (dir) => { var errCode = FS.nodePermissions(dir, 'x'); if (errCode) return errCode; if (!dir.node_ops.lookup) return 2; return 0; }, mayCreate: (dir, name) => { try { var node = FS.lookupNode(dir, name); return 20; } catch (e) {} return FS.nodePermissions(dir, 'wx'); }, mayDelete: (dir, name, isdir) => { var node; try { node = FS.lookupNode(dir, name); } catch (e) { return e.errno; } var errCode = FS.nodePermissions(dir, 'wx'); if (errCode) { return errCode; } if (isdir) { if (!FS.isDir(node.mode)) { return 54; } if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) { return 10; } } else { if (FS.isDir(node.mode)) { return 31; } } return 0; }, mayOpen: (node, flags) => { if (!node) { return 44; } if (FS.isLink(node.mode)) { return 32; } else if (FS.isDir(node.mode)) { if (FS.flagsToPermissionString(flags) !== 'r' || flags & 512) { return 31; } } return FS.nodePermissions(node, FS.flagsToPermissionString(flags)); }, MAX_OPEN_FDS: 4096, nextfd: (fd_start = 0, fd_end = FS.MAX_OPEN_FDS) => { for (var fd = fd_start; fd <= fd_end; fd++) { if (!FS.streams[fd]) { return fd; } } throw new FS.ErrnoError(33); }, getStream: (fd) => FS.streams[fd], createStream: (stream, fd_start, fd_end) => { if (!FS.FSStream) { FS.FSStream = function () { this.shared = {}; }; FS.FSStream.prototype = {}; Object.defineProperties(FS.FSStream.prototype, { object: { get: function () { return this.node; }, set: function (val) { this.node = val; }, }, isRead: { get: function () { return (this.flags & 2097155) !== 1; }, }, isWrite: { get: function () { return (this.flags & 2097155) !== 0; }, }, isAppend: { get: function () { return this.flags & 1024; }, }, flags: { get: function () { return this.shared.flags; }, set: function (val) { this.shared.flags = val; }, }, position: { get: function () { return this.shared.positio