UNPKG

@libsql/libsql-wasm-experimental

Version:
1,609 lines (1,162 loc) 402 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.45.1" ** SQLITE_VERSION_NUMBER 3045001 ** SQLITE_SOURCE_ID "2024-01-30 16:01:20 e876e51a0ed5c5b3126f52e532044363a014bc594cfefa87ffb5b82257ccalt1" ** ** Using the Emscripten SDK version 3.1.70. */ var sqlite3InitModule = (() => { var _scriptName = import.meta.url; return ( function(moduleArg = {}) { var moduleRtn; var Module = moduleArg; var readyPromiseResolve, readyPromiseReject; var readyPromise = new Promise((resolve, reject) => { readyPromiseResolve = resolve; readyPromiseReject = reject; }); ["_malloc","_free","_realloc","_sqlite3_aggregate_context","_sqlite3_auto_extension","_sqlite3_bind_blob","_sqlite3_bind_double","_sqlite3_bind_int","_sqlite3_bind_int64","_sqlite3_bind_null","_sqlite3_bind_parameter_count","_sqlite3_bind_parameter_index","_sqlite3_bind_pointer","_sqlite3_bind_text","_sqlite3_busy_handler","_sqlite3_busy_timeout","_sqlite3_cancel_auto_extension","_sqlite3_changes","_sqlite3_changes64","_sqlite3_clear_bindings","_sqlite3_close_v2","_sqlite3_collation_needed","_sqlite3_column_blob","_sqlite3_column_bytes","_sqlite3_column_count","_sqlite3_column_double","_sqlite3_column_int","_sqlite3_column_int64","_sqlite3_column_name","_sqlite3_column_text","_sqlite3_column_type","_sqlite3_column_value","_sqlite3_commit_hook","_sqlite3_compileoption_get","_sqlite3_compileoption_used","_sqlite3_complete","_sqlite3_context_db_handle","_sqlite3_create_collation","_sqlite3_create_collation_v2","_sqlite3_create_function","_sqlite3_create_function_v2","_sqlite3_create_module","_sqlite3_create_module_v2","_sqlite3_create_window_function","_sqlite3_data_count","_sqlite3_db_filename","_sqlite3_db_handle","_sqlite3_db_name","_sqlite3_db_status","_sqlite3_declare_vtab","_sqlite3_deserialize","_sqlite3_drop_modules","_sqlite3_errcode","_sqlite3_errmsg","_sqlite3_error_offset","_sqlite3_errstr","_sqlite3_exec","_sqlite3_expanded_sql","_sqlite3_extended_errcode","_sqlite3_extended_result_codes","_sqlite3_file_control","_sqlite3_finalize","_sqlite3_free","_sqlite3_get_autocommit","_sqlite3_get_auxdata","_sqlite3_initialize","_sqlite3_keyword_count","_sqlite3_keyword_name","_sqlite3_keyword_check","_sqlite3_last_insert_rowid","_sqlite3_libversion","_sqlite3_libversion_number","_sqlite3_limit","_sqlite3_malloc","_sqlite3_malloc64","_sqlite3_msize","_sqlite3_open","_sqlite3_open_v2","_sqlite3_overload_function","_sqlite3_prepare_v2","_sqlite3_prepare_v3","_sqlite3_preupdate_blobwrite","_sqlite3_preupdate_count","_sqlite3_preupdate_depth","_sqlite3_preupdate_hook","_sqlite3_preupdate_new","_sqlite3_preupdate_old","_sqlite3_progress_handler","_sqlite3_randomness","_sqlite3_realloc","_sqlite3_realloc64","_sqlite3_reset","_sqlite3_reset_auto_extension","_sqlite3_result_blob","_sqlite3_result_double","_sqlite3_result_error","_sqlite3_result_error_code","_sqlite3_result_error_nomem","_sqlite3_result_error_toobig","_sqlite3_result_int","_sqlite3_result_int64","_sqlite3_result_null","_sqlite3_result_pointer","_sqlite3_result_subtype","_sqlite3_result_text","_sqlite3_result_zeroblob","_sqlite3_result_zeroblob64","_sqlite3_rollback_hook","_sqlite3_serialize","_sqlite3_set_authorizer","_sqlite3_set_auxdata","_sqlite3_set_last_insert_rowid","_sqlite3_shutdown","_sqlite3_sourceid","_sqlite3_sql","_sqlite3_status","_sqlite3_status64","_sqlite3_step","_sqlite3_stmt_isexplain","_sqlite3_stmt_readonly","_sqlite3_stmt_status","_sqlite3_strglob","_sqlite3_stricmp","_sqlite3_strlike","_sqlite3_strnicmp","_sqlite3_table_column_metadata","_sqlite3_total_changes","_sqlite3_total_changes64","_sqlite3_trace_v2","_sqlite3_txn_state","_sqlite3_update_hook","_sqlite3_uri_boolean","_sqlite3_uri_int64","_sqlite3_uri_key","_sqlite3_uri_parameter","_sqlite3_user_data","_sqlite3_value_blob","_sqlite3_value_bytes","_sqlite3_value_double","_sqlite3_value_dup","_sqlite3_value_free","_sqlite3_value_frombind","_sqlite3_value_int","_sqlite3_value_int64","_sqlite3_value_nochange","_sqlite3_value_numeric_type","_sqlite3_value_pointer","_sqlite3_value_subtype","_sqlite3_value_text","_sqlite3_value_type","_sqlite3_vfs_find","_sqlite3_vfs_register","_sqlite3_vfs_unregister","_sqlite3_vtab_collation","_sqlite3_vtab_distinct","_sqlite3_vtab_in","_sqlite3_vtab_in_first","_sqlite3_vtab_in_next","_sqlite3_vtab_nochange","_sqlite3_vtab_on_conflict","_sqlite3_vtab_rhs_value","_sqlite3changegroup_add","_sqlite3changegroup_add_strm","_sqlite3changegroup_delete","_sqlite3changegroup_new","_sqlite3changegroup_output","_sqlite3changegroup_output_strm","_sqlite3changeset_apply","_sqlite3changeset_apply_strm","_sqlite3changeset_apply_v2","_sqlite3changeset_apply_v2_strm","_sqlite3changeset_concat","_sqlite3changeset_concat_strm","_sqlite3changeset_conflict","_sqlite3changeset_finalize","_sqlite3changeset_fk_conflicts","_sqlite3changeset_invert","_sqlite3changeset_invert_strm","_sqlite3changeset_new","_sqlite3changeset_next","_sqlite3changeset_old","_sqlite3changeset_op","_sqlite3changeset_pk","_sqlite3changeset_start","_sqlite3changeset_start_strm","_sqlite3changeset_start_v2","_sqlite3changeset_start_v2_strm","_sqlite3session_attach","_sqlite3session_changeset","_sqlite3session_changeset_size","_sqlite3session_changeset_strm","_sqlite3session_config","_sqlite3session_create","_sqlite3session_delete","_sqlite3session_diff","_sqlite3session_enable","_sqlite3session_indirect","_sqlite3session_isempty","_sqlite3session_memory_used","_sqlite3session_object_config","_sqlite3session_patchset","_sqlite3session_patchset_strm","_sqlite3session_table_filter","___indirect_function_table","_sqlite3_wasm_pstack_ptr","_sqlite3_wasm_pstack_restore","_sqlite3_wasm_pstack_alloc","_sqlite3_wasm_pstack_remaining","_sqlite3_wasm_pstack_quota","_sqlite3_wasm_db_error","_sqlite3_wasm_test_struct","_sqlite3_wasm_enum_json","_sqlite3_wasm_vfs_unlink","_sqlite3_wasm_db_vfs","_sqlite3_wasm_db_reset","_sqlite3_wasm_db_export_chunked","_sqlite3_wasm_db_serialize","_sqlite3_wasm_vfs_create_file","_sqlite3_wasm_posix_create_file","_sqlite3_wasm_kvvfsMakeKeyOnPstack","_sqlite3_wasm_kvvfs_methods","_sqlite3_wasm_vtab_config","_sqlite3_wasm_db_config_ip","_sqlite3_wasm_db_config_pii","_sqlite3_wasm_db_config_s","_sqlite3_wasm_config_i","_sqlite3_wasm_config_ii","_sqlite3_wasm_config_j","_sqlite3_wasm_init_wasmfs","_sqlite3_wasm_test_intptr","_sqlite3_wasm_test_voidptr","_sqlite3_wasm_test_int64_max","_sqlite3_wasm_test_int64_min","_sqlite3_wasm_test_int64_times2","_sqlite3_wasm_test_int64_minmax","_sqlite3_wasm_test_int64ptr","_sqlite3_wasm_test_stack_overflow","_sqlite3_wasm_test_str_hello","_sqlite3_wasm_SQLTester_strglob","onRuntimeInitialized"].forEach((prop) => { if (!Object.getOwnPropertyDescriptor(readyPromise, prop)) { Object.defineProperty(readyPromise, prop, { get: () => abort('You are getting ' + prop + ' on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js'), set: () => abort('You are setting ' + prop + ' on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js'), }); } }); 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' && process.type != 'renderer'; var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; const sqlite3InitModuleState = globalThis.sqlite3InitModuleState || Object.assign(Object.create(null),{ debugModule: ()=>{} }); delete globalThis.sqlite3InitModuleState; sqlite3InitModuleState.debugModule('globalThis.location =',globalThis.location); 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 scriptDirectory = ''; function locateFile(path) { if (Module['locateFile']) { return Module['locateFile'](path, scriptDirectory); } return scriptDirectory + path; } var readAsync, readBinary; if (ENVIRONMENT_IS_SHELL) { if ((typeof process == 'object' && typeof require === 'function') || typeof window == 'object' || typeof importScripts == 'function') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); } else 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 (_scriptName) { scriptDirectory = _scriptName; } if (scriptDirectory.startsWith('blob:')) { scriptDirectory = ''; } else { scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, '').lastIndexOf('/')+1); } if (!(typeof window == 'object' || typeof importScripts == 'function')) throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); { 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) => { assert(!isFileURI(url), "readAsync does not work with file:// URLs"); return fetch(url, { credentials: 'same-origin' }) .then((response) => { if (response.ok) { return response.arrayBuffer(); } return Promise.reject(new Error(response.status + ' : ' + response.url)); }) }; } } else { throw new Error('environment detection error'); } var out = Module['print'] || console.log.bind(console); var err = Module['printErr'] || console.error.bind(console); Object.assign(Module, moduleOverrides); moduleOverrides = null; checkIncomingModuleAPI(); if (Module['arguments']) arguments_ = Module['arguments'];legacyModuleProp('arguments', 'arguments_'); if (Module['thisProgram']) thisProgram = Module['thisProgram'];legacyModuleProp('thisProgram', 'thisProgram'); assert(typeof Module['memoryInitializerPrefixURL'] == 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead'); assert(typeof Module['pthreadMainPrefixURL'] == 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead'); assert(typeof Module['cdInitializerPrefixURL'] == 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead'); assert(typeof Module['filePackagePrefixURL'] == 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead'); assert(typeof Module['read'] == 'undefined', 'Module.read option was removed'); assert(typeof Module['readAsync'] == 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)'); assert(typeof Module['readBinary'] == 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)'); assert(typeof Module['setWindowTitle'] == 'undefined', 'Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)'); assert(typeof Module['TOTAL_MEMORY'] == 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY'); legacyModuleProp('asm', 'wasmExports'); legacyModuleProp('readAsync', 'readAsync'); legacyModuleProp('readBinary', 'readBinary'); legacyModuleProp('setWindowTitle', 'setWindowTitle'); var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js'; var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js'; var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js'; var FETCHFS = 'FETCHFS is no longer included by default; build with -lfetchfs.js'; var ICASEFS = 'ICASEFS is no longer included by default; build with -licasefs.js'; var JSFILEFS = 'JSFILEFS is no longer included by default; build with -ljsfilefs.js'; var OPFS = 'OPFS is no longer included by default; build with -lopfs.js'; var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js'; assert(!ENVIRONMENT_IS_NODE, 'node environment detected but not enabled at build time. Add `node` to `-sENVIRONMENT` to enable.'); assert(!ENVIRONMENT_IS_SHELL, 'shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.'); var wasmBinary = Module['wasmBinary'];legacyModuleProp('wasmBinary', 'wasmBinary'); if (typeof WebAssembly != 'object') { err('no native wasm support detected'); } var wasmMemory; var ABORT = false; var EXITSTATUS; function assert(condition, text) { if (!condition) { abort('Assertion failed' + (text ? ': ' + text : '')); } } 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['HEAPU8'] = HEAPU8 = new Uint8Array(b); Module['HEAPU16'] = HEAPU16 = new Uint16Array(b); Module['HEAP32'] = HEAP32 = new Int32Array(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); } assert(!Module['STACK_SIZE'], 'STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time') assert(typeof Int32Array != 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray != undefined && Int32Array.prototype.set != undefined, 'JS engine does not provide full typed array support'); if (Module['wasmMemory']) { wasmMemory = Module['wasmMemory']; } else { var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216;legacyModuleProp('INITIAL_MEMORY', 'INITIAL_MEMORY'); assert(INITIAL_MEMORY >= 524288, 'INITIAL_MEMORY should be larger than STACK_SIZE, was ' + INITIAL_MEMORY + '! (STACK_SIZE=' + 524288 + ')'); wasmMemory = new WebAssembly.Memory({ 'initial': INITIAL_MEMORY / 65536, 'maximum': 32768, }); } updateMemoryViews(); function writeStackCookie() { var max = _emscripten_stack_get_end(); assert((max & 3) == 0); if (max == 0) { max += 4; } HEAPU32[((max)>>2)] = 0x02135467; HEAPU32[(((max)+(4))>>2)] = 0x89BACDFE; HEAPU32[((0)>>2)] = 1668509029; } function checkStackCookie() { if (ABORT) return; var max = _emscripten_stack_get_end(); if (max == 0) { max += 4; } var cookie1 = HEAPU32[((max)>>2)]; var cookie2 = HEAPU32[(((max)+(4))>>2)]; if (cookie1 != 0x02135467 || cookie2 != 0x89BACDFE) { abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`); } if (HEAPU32[((0)>>2)] != 0x63736d65 ) { abort('Runtime error: The application has corrupted its heap memory area (address zero)!'); } } var __ATPRERUN__ = []; var __ATINIT__ = []; var __ATEXIT__ = []; var __ATPOSTRUN__ = []; var runtimeInitialized = false; function preRun() { var preRuns = Module['preRun']; if (preRuns) { if (typeof preRuns == 'function') preRuns = [preRuns]; preRuns.forEach(addOnPreRun); } callRuntimeCallbacks(__ATPRERUN__); } function initRuntime() { assert(!runtimeInitialized); runtimeInitialized = true; checkStackCookie(); if (!Module['noFSInit'] && !FS.initialized) FS.init(); FS.ignorePermissions = false; TTY.init(); callRuntimeCallbacks(__ATINIT__); } function postRun() { checkStackCookie(); var postRuns = Module['postRun']; if (postRuns) { if (typeof postRuns == 'function') postRuns = [postRuns]; postRuns.forEach(addOnPostRun); } callRuntimeCallbacks(__ATPOSTRUN__); } function addOnPreRun(cb) { __ATPRERUN__.unshift(cb); } function addOnInit(cb) { __ATINIT__.unshift(cb); } function addOnExit(cb) { } function addOnPostRun(cb) { __ATPOSTRUN__.unshift(cb); } assert(Math.imul, 'This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill'); assert(Math.fround, 'This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill'); assert(Math.clz32, 'This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill'); assert(Math.trunc, 'This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill'); var runDependencies = 0; var runDependencyWatcher = null; var dependenciesFulfilled = null; var runDependencyTracking = {}; function getUniqueRunDependency(id) { var orig = id; while (1) { if (!runDependencyTracking[id]) return id; id = orig + Math.random(); } } function addRunDependency(id) { runDependencies++; Module['monitorRunDependencies']?.(runDependencies); if (id) { assert(!runDependencyTracking[id]); runDependencyTracking[id] = 1; if (runDependencyWatcher === null && typeof setInterval != 'undefined') { runDependencyWatcher = setInterval(() => { if (ABORT) { clearInterval(runDependencyWatcher); runDependencyWatcher = null; return; } var shown = false; for (var dep in runDependencyTracking) { if (!shown) { shown = true; err('still waiting on run dependencies:'); } err(`dependency: ${dep}`); } if (shown) { err('(end of list)'); } }, 10000); } } else { err('warning: run dependency added without ID'); } } function removeRunDependency(id) { runDependencies--; Module['monitorRunDependencies']?.(runDependencies); if (id) { assert(runDependencyTracking[id]); delete runDependencyTracking[id]; } else { err('warning: run dependency removed without ID'); } if (runDependencies == 0) { if (runDependencyWatcher !== null) { clearInterval(runDependencyWatcher); runDependencyWatcher = null; } if (dependenciesFulfilled) { var callback = dependenciesFulfilled; dependenciesFulfilled = null; callback(); } } } function abort(what) { Module['onAbort']?.(what); what = 'Aborted(' + what + ')'; err(what); ABORT = true; var e = new WebAssembly.RuntimeError(what); readyPromiseReject(e); throw e; } var dataURIPrefix = 'data:application/octet-stream;base64,'; var isDataURI = (filename) => filename.startsWith(dataURIPrefix); var isFileURI = (filename) => filename.startsWith('file://'); function createExportWrapper(name, nargs) { return (...args) => { assert(runtimeInitialized, `native function \`${name}\` called before runtime initialization`); var f = wasmExports[name]; assert(f, `exported native function \`${name}\` not found`); assert(args.length <= nargs, `native function \`${name}\` called with ${args.length} args but expects ${nargs}`); return f(...args); }; } function findWasmBinary() { if (Module['locateFile']) { var f = 'sqlite3.wasm'; if (!isDataURI(f)) { return locateFile(f); } return f; } return new URL('sqlite3.wasm', import.meta.url).href; } var wasmBinaryFile; function getBinarySync(file) { if (file == wasmBinaryFile && wasmBinary) { return new Uint8Array(wasmBinary); } if (readBinary) { return readBinary(file); } throw 'both async and sync fetching of the wasm failed'; } function getBinaryPromise(binaryFile) { if (!wasmBinary ) { return readAsync(binaryFile).then( (response) => new Uint8Array((response)), () => getBinarySync(binaryFile) ); } return Promise.resolve().then(() => getBinarySync(binaryFile)); } function instantiateArrayBuffer(binaryFile, imports, receiver) { return getBinaryPromise(binaryFile).then((binary) => { return WebAssembly.instantiate(binary, imports); }).then(receiver, (reason) => { err(`failed to asynchronously prepare wasm: ${reason}`); if (isFileURI(wasmBinaryFile)) { err(`warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`); } abort(reason); }); } function instantiateAsync(binary, binaryFile, imports, callback) { if (!binary && typeof WebAssembly.instantiateStreaming == 'function' && !isDataURI(binaryFile) && typeof fetch == 'function') { return fetch(binaryFile, { credentials: 'same-origin' }).then((response) => { var result = WebAssembly.instantiateStreaming(response, imports); return result.then( callback, function(reason) { err(`wasm streaming compile failed: ${reason}`); err('falling back to ArrayBuffer instantiation'); return instantiateArrayBuffer(binaryFile, imports, callback); }); }); } return instantiateArrayBuffer(binaryFile, imports, callback); } function getWasmImports() { return { 'env': wasmImports, 'wasi_snapshot_preview1': wasmImports, } } function createWasm() { var info = getWasmImports(); function receiveInstance(instance, module) { wasmExports = instance.exports; addOnInit(wasmExports['__wasm_call_ctors']); removeRunDependency('wasm-instantiate'); return wasmExports; } addRunDependency('wasm-instantiate'); var trueModule = Module; function receiveInstantiationResult(result) { assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?'); trueModule = null; receiveInstance(result['instance']); } if (Module['instantiateWasm']) { try { return Module['instantiateWasm'](info, receiveInstance); } catch(e) { err(`Module.instantiateWasm callback failed with error: ${e}`); readyPromiseReject(e); } } wasmBinaryFile ??= findWasmBinary(); instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult).catch(readyPromiseReject); return {}; } (() => { var h16 = new Int16Array(1); var h8 = new Int8Array(h16.buffer); h16[0] = 0x6373; if (h8[0] !== 0x73 || h8[1] !== 0x63) throw 'Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)'; })(); if (Module['ENVIRONMENT']) { throw new Error('Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)'); } function legacyModuleProp(prop, newName, incoming=true) { if (!Object.getOwnPropertyDescriptor(Module, prop)) { Object.defineProperty(Module, prop, { configurable: true, get() { let extra = incoming ? ' (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)' : ''; abort(`\`Module.${prop}\` has been replaced by \`${newName}\`` + extra); } }); } } function ignoredModuleProp(prop) { if (Object.getOwnPropertyDescriptor(Module, prop)) { abort(`\`Module.${prop}\` was supplied but \`${prop}\` not included in INCOMING_MODULE_JS_API`); } } function isExportedByForceFilesystem(name) { return name === 'FS_createPath' || name === 'FS_createDataFile' || name === 'FS_createPreloadedFile' || name === 'FS_unlink' || name === 'addRunDependency' || name === 'FS_createLazyFile' || name === 'FS_createDevice' || name === 'removeRunDependency'; } function hookGlobalSymbolAccess(sym, func) { if (typeof globalThis != 'undefined' && !Object.getOwnPropertyDescriptor(globalThis, sym)) { Object.defineProperty(globalThis, sym, { configurable: true, get() { func(); return undefined; } }); } } function missingGlobal(sym, msg) { hookGlobalSymbolAccess(sym, () => { warnOnce(`\`${sym}\` is not longer defined by emscripten. ${msg}`); }); } missingGlobal('buffer', 'Please use HEAP8.buffer or wasmMemory.buffer'); missingGlobal('asm', 'Please use wasmExports instead'); function missingLibrarySymbol(sym) { hookGlobalSymbolAccess(sym, () => { var msg = `\`${sym}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`; var librarySymbol = sym; if (!librarySymbol.startsWith('_')) { librarySymbol = '$' + sym; } msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${librarySymbol}')`; if (isExportedByForceFilesystem(sym)) { msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you'; } warnOnce(msg); }); unexportedRuntimeSymbol(sym); } function unexportedRuntimeSymbol(sym) { if (!Object.getOwnPropertyDescriptor(Module, sym)) { Object.defineProperty(Module, sym, { configurable: true, get() { var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`; if (isExportedByForceFilesystem(sym)) { msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you'; } abort(msg); } }); } } function dbg(...args) { console.warn(...args); } function ExitStatus(status) { this.name = 'ExitStatus'; this.message = `Program terminated with exit(${status})`; this.status = status; } var callRuntimeCallbacks = (callbacks) => { callbacks.forEach((f) => f(Module)); }; function getValue(ptr, type = 'i8') { if (type.endsWith('*')) type = '*'; switch (type) { case 'i1': return HEAP8[ptr]; case 'i8': return HEAP8[ptr]; 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}`); } } var noExitRuntime = Module['noExitRuntime'] || true; var ptrToString = (ptr) => { assert(typeof ptr === 'number'); ptr >>>= 0; return '0x' + ptr.toString(16).padStart(8, '0'); }; function setValue(ptr, value, type = 'i8') { if (type.endsWith('*')) type = '*'; switch (type) { case 'i1': HEAP8[ptr] = value; break; case 'i8': HEAP8[ptr] = value; break; case 'i16': HEAP16[((ptr)>>1)] = value; break; case 'i32': HEAP32[((ptr)>>2)] = value; break; case 'i64': HEAP64[((ptr)>>3)] = BigInt(value); 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 stackRestore = (val) => __emscripten_stack_restore(val); var stackSave = () => _emscripten_stack_get_current(); var warnOnce = (text) => { warnOnce.shown ||= {}; if (!warnOnce.shown[text]) { warnOnce.shown[text] = 1; err(text); } }; 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:(...paths) => PATH.normalize(paths.join('/')), join2:(l, r) => PATH.normalize(l + '/' + r), }; var initRandomFill = () => { if (typeof crypto == 'object' && typeof crypto['getRandomValues'] == 'function') { return (view) => crypto.getRandomValues(view); } else abort('no cryptographic support found for randomDevice. consider polyfilling it if you want to use something insecure like Math.random(), e.g. put this in a --pre-js: var crypto = { getRandomValues: (array) => { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };'); }; var randomFill = (view) => { return (randomFill = initRandomFill())(view); }; var PATH_FS = { resolve:(...args) => { var resolvedPath = '', resolvedAbsolute = false; for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? args[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('/'); }, }; var UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder() : undefined; var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead = NaN) => { 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 { if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte ' + ptrToString(u0) + ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!'); 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; }; var FS_stdin_getChar_buffer = []; var 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 stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => { assert(typeof str === 'string', `stringToUTF8Array expects a string (got ${typeof str})`); 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; if (u > 0x10FFFF) warnOnce('Invalid Unicode code point ' + ptrToString(u) + ' encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF).'); 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 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 FS_stdin_getChar = () => { if (!FS_stdin_getChar_buffer.length) { var result = null; if (typeof window != 'undefined' && typeof window.prompt == 'function') { result = window.prompt('Input: '); if (result !== null) { result += '\n'; } } else {} if (!result) { return null; } FS_stdin_getChar_buffer = intArrayFromString(result, true); } return FS_stdin_getChar_buffer.shift(); }; var TTY = { ttys:[], init() { }, shutdown() { }, register(dev, ops) { TTY.ttys[dev] = { input: [], output: [], ops: ops }; FS.registerDevice(dev, TTY.stream_ops); }, stream_ops:{ open(stream) { var tty = TTY.ttys[stream.node.rdev]; if (!tty) { throw new FS.ErrnoError(43); } stream.tty = tty; stream.seekable = false; }, close(stream) { stream.tty.ops.fsync(stream.tty); }, fsync(stream) { stream.tty.ops.fsync(stream.tty); }, read(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(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(tty) { return FS_stdin_getChar(); }, put_char(tty, val) { if (val === null || val === 10) { out(UTF8ArrayToString(tty.output)); tty.output = []; } else { if (val != 0) tty.output.push(val); } }, fsync(tty) { if (tty.output && tty.output.length > 0) { out(UTF8ArrayToString(tty.output)); tty.output = []; } }, ioctl_tcgets(tty) { return { c_iflag: 25856, c_oflag: 5, c_cflag: 191, c_lflag: 35387, c_cc: [ 0x03, 0x1c, 0x7f, 0x15, 0x04, 0x00, 0x01, 0x00, 0x11, 0x13, 0x1a, 0x00, 0x12, 0x0f, 0x17, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ] }; }, ioctl_tcsets(tty, optional_actions, data) { return 0; }, ioctl_tiocgwinsz(tty) { return [24, 80]; }, }, default_tty1_ops:{ put_char(tty, val) { if (val === null || val === 10) { err(UTF8ArrayToString(tty.output)); tty.output = []; } else { if (val != 0) tty.output.push(val); } }, fsync(tty) { if (tty.output && tty.output.length > 0) { err(UTF8ArrayToString(tty.output)); tty.output = []; } }, }, }; var zeroMemory = (address, size) => { HEAPU8.fill(0, address, address + size); }; var alignMemory = (size, alignment) => { assert(alignment, "alignment argument is required"); return Math.ceil(size / alignment) * alignment; }; var mmapAlloc = (size) => { size = alignMemory(size, 65536); var ptr = _emscripten_builtin_memalign(65536, size); if (ptr) zeroMemory(ptr, size); return ptr; }; var MEMFS = { ops_table:null, mount(mount) { return MEMFS.createNode(null, '/', 16384 | 511 , 0); }, createNode(parent, name, mode, dev) { if (FS.isBlkdev(mode) || FS.isFIFO(mode)) { throw new FS.ErrnoError(63); } 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(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(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(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(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(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(parent, name) { throw FS.genericErrors[44]; }, mknod(parent, name, mode, dev) { return MEMFS.createNode(parent, name, mode, dev); }, rename(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; }, unlink(parent, name) { delete parent.contents[name]; parent.timestamp = Date.now(); }, rmdir(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(node) { var entries = ['.', '..']; for (var key of