UNPKG

@cpp.js/core-embind-jsi

Version:

The Embind JSI integration tool enables seamless C++ integration with React Native and Expo.

1,404 lines (1,225 loc) 176 kB
function warnOnce(msg) { console.warn(msg); } function callRuntimeCallbacks() {} // include: shell.js /** * @license * Copyright 2010 The Emscripten Authors * SPDX-License-Identifier: MIT */ // The Module object: Our interface to the outside world. We import // and export values on it. There are various ways Module can be used: // 1. Not defined. We create it here // 2. A function parameter, function(Module) { ..generated code.. } // 3. pre-run appended it, var Module = {}; ..generated code.. // 4. External script tag defines var Module. // We need to check if Module already exists (e.g. case 3 above). // Substitution will be replaced with actual code on later stage of the build, // this way Closure Compiler will not mangle it (e.g. case 4. above). // Note that if you want to run closure, and also to use Module // after the generated code, you will need to define var Module = {}; // before the code. Then that object will be used in the code, and you // can continue to use Module afterwards as well. globalThis.Module = typeof globalThis.Module != 'undefined' ? globalThis.Module : {}; // See https://caniuse.com/mdn-javascript_builtins_bigint64array // include: polyfill/bigint64array.js if (typeof globalThis.BigInt64Array === "undefined") { // BigInt64Array polyfill for Safari versions between v14.0 and v15.0. // All browsers other than Safari added BigInt and BigInt64Array at the same // time, but Safari introduced BigInt in v14.0 and introduced BigInt64Array in // v15.0 function partsToBigIntSigned(lower, upper) { return BigInt(lower) | (BigInt(upper + 2 * (upper & 0x80000000)) << 32n); } function partsToBigIntUnsigned(lower, upper) { return BigInt(lower) | (BigInt(upper) << 32n); } function bigIntToParts(value) { var lower = Number(BigInt(value) & BigInt(0xffffffff)) | 0; var upper = Number(BigInt(value) >> 32n) | 0; return [lower, upper]; } function createBigIntArrayShim(partsToBigInt) { function createBigInt64Array(array) { if (typeof array === "number") { array = new Uint32Array(2 * array); } var orig_array; if (!ArrayBuffer.isView(array)) { if (array.constructor && array.constructor.name === "ArrayBuffer") { array = new Uint32Array(array); } else { orig_array = array; array = new Uint32Array(array.length * 2); } } var proxy = new Proxy( { slice: function (min, max) { if (max === undefined) { max = array.length; } var new_buf = array.slice(min * 2, max * 2); return createBigInt64Array(new_buf); }, subarray: function (min, max) { var new_buf = array.subarray(min * 2, max * 2); return createBigInt64Array(new_buf); }, [Symbol.iterator]: function* () { for (var i = 0; i < array.length / 2; i++) { yield partsToBigInt(array[2 * i], array[2 * i + 1]); } }, BYTES_PER_ELEMENT: 2 * array.BYTES_PER_ELEMENT, buffer: array.buffer, byteLength: array.byteLength, byteOffset: array.byteOffset, length: array.length / 2, copyWithin: function (target, start, end) { array.copyWithin(target * 2, start * 2, end * 2); return proxy; }, set: function (source, targetOffset) { if (targetOffset === undefined) { targetOffset = 0; } if (2 * (source.length + targetOffset) > array.length) { // This is the Chrome error message // Firefox: "invalid or out-of-range index" throw new RangeError("offset is out of bounds"); } for (var i = 0; i < source.length; i++) { var value = source[i]; var pair = bigIntToParts(value); array.set(pair, 2 * (targetOffset + i)); } }, }, { get: function (target, idx, receiver) { if (typeof idx !== "string" || !/^\d+$/.test(idx)) { return Reflect.get(target, idx, receiver); } var lower = array[idx * 2]; var upper = array[idx * 2 + 1]; return partsToBigInt(lower, upper); }, set: function (target, idx, value, receiver) { if (typeof idx !== "string" || !/^\d+$/.test(idx)) { return Reflect.set(target, idx, value, receiver); } if (typeof value !== "bigint") { // Chrome error message, Firefox has no "a" in front if "BigInt". throw new TypeError(`Cannot convert ${value} to a BigInt`); } var pair = bigIntToParts(value); array.set(pair, 2 * idx); return true; }, } ); if (orig_array) { proxy.set(orig_array); } return proxy; } return createBigInt64Array; } globalThis.BigUint64Array = createBigIntArrayShim(partsToBigIntUnsigned); globalThis.BigInt64Array = createBigIntArrayShim(partsToBigIntSigned); } // end include: polyfill/bigint64array.js // --pre-jses are emitted after the Module integration code, so that they can // refer to Module (if they choose; they can also define Module) // Sometimes an existing Module object exists with properties // meant to overwrite the default module functionality. Here // we collect those properties and reapply _after_ we configure // the current environment's defaults to avoid having to be so // defensive during initialization. var moduleOverrides = Object.assign({}, Module); var arguments_ = []; var thisProgram = './this.program'; var quit_ = (status, toThrow) => { throw toThrow; }; // Determine the runtime environment we are in. You can customize this by // setting the ENVIRONMENT setting at compile time (see settings.js). // Attempt to auto-detect the environment var ENVIRONMENT_IS_WEB = typeof window == 'object'; var ENVIRONMENT_IS_WORKER = typeof importScripts == 'function'; // N.b. Electron.js environment is simultaneously a NODE-environment, but // also a web environment. 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; 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)'); } // `/` should be present at the end if `scriptDirectory` is not empty var scriptDirectory = ''; function locateFile(path) { return scriptDirectory + path; } // Hooks that are implemented differently in different runtime environments. var read_, readAsync, readBinary, setWindowTitle; 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?)'); if (typeof read != 'undefined') { read_ = (f) => { return read(f); }; } readBinary = (f) => { let data; if (typeof readbuffer == 'function') { return new Uint8Array(readbuffer(f)); } data = read(f, 'binary'); assert(typeof data == 'object'); return data; }; readAsync = (f, onload, onerror) => { setTimeout(() => onload(readBinary(f)), 0); }; if (typeof clearTimeout == 'undefined') { globalThis.clearTimeout = (id) => {}; } if (typeof scriptArgs != 'undefined') { arguments_ = scriptArgs; } else if (typeof arguments != 'undefined') { arguments_ = arguments; } if (typeof quit == 'function') { quit_ = (status, toThrow) => { // Unlike node which has process.exitCode, d8 has no such mechanism. So we // have no way to set the exit code and then let the program exit with // that code when it naturally stops running (say, when all setTimeouts // have completed). For that reason, we must call `quit` - the only way to // set the exit code - but quit also halts immediately. To increase // consistency with node (and the web) we schedule the actual quit call // using a setTimeout to give the current stack and any exception handlers // a chance to run. This enables features such as addOnPostRun (which // expected to be able to run code after main returns). setTimeout(() => { if (!(toThrow instanceof ExitStatus)) { let toLog = toThrow; if (toThrow && typeof toThrow == 'object' && toThrow.stack) { toLog = [toThrow, toThrow.stack]; } err('exiting due to exception: ' + toLog); } quit(status); }); throw toThrow; }; } if (typeof print != 'undefined') { // Prefer to use print/printErr where they exist, as they usually work better. if (typeof console == 'undefined') console = /** @type{!Console} */({}); console.log = /** @type{!function(this:Console, ...*): undefined} */ (print); console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */ (typeof printErr != 'undefined' ? printErr : print); } } else // Note that this includes Node.js workers when relevant (pthreads is enabled). // Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and // ENVIRONMENT_IS_NODE. if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled scriptDirectory = self.location.href; } else if (typeof document != 'undefined' && document.currentScript) { // web scriptDirectory = document.currentScript.src; } // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them. // otherwise, slice off the final part of the url to find the script directory. // if scriptDirectory does not contain a slash, lastIndexOf will return -1, // and scriptDirectory will correctly be replaced with an empty string. // If scriptDirectory contains a query (starting with ?) or a fragment (starting with #), // they are removed because they could contain a slash. if (scriptDirectory.indexOf('blob:') !== 0) { scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf('/')+1); } else { scriptDirectory = ''; } 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?)'); // Differentiate the Web Worker from the Node Worker case, as reading must // be done differently. { // include: web_or_worker_shell_read.js /** * @license * Copyright 2019 The Emscripten Authors * SPDX-License-Identifier: MIT */ 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(/** @type{!ArrayBuffer} */(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)) { // file URLs can return 0 onload(xhr.response); return; } onerror(); }; xhr.onerror = onerror; xhr.send(null); } // end include: web_or_worker_shell_read.js } setWindowTitle = (title) => document.title = title; } else { throw new Error('environment detection error'); } var out = console.log.bind(console); var err = console.warn.bind(console); // Merge back in the overrides Object.assign(Module, moduleOverrides); // Free the object hierarchy contained in the overrides, this lets the GC // reclaim data used e.g. in memoryInitializerRequest, which is a large typed array. moduleOverrides = null; // checkIncomingModuleAPI(); // Emit code to handle expected values on the Module object. This applies Module.x // to the proper local x. This has two benefits: first, we only emit it if it is // expected to arrive, and second, by using a local everywhere else that can be // minified. legacyModuleProp('arguments', 'arguments_'); legacyModuleProp('thisProgram', 'thisProgram'); legacyModuleProp('quit', 'quit_'); // perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message // Assertions on removed incoming Module JS APIs. 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 (modify read_ in JS)'); 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 setWindowTitle in JS)'); assert(typeof Module['TOTAL_MEMORY'] == 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY'); legacyModuleProp('read', 'read_'); 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 NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js'; // end include: shell.js // include: preamble.js /** * @license * Copyright 2010 The Emscripten Authors * SPDX-License-Identifier: MIT */ // === Preamble library stuff === // Documentation for the public APIs defined in this file must be updated in: // site/source/docs/api_reference/preamble.js.rst // A prebuilt local version of the documentation is available at: // site/build/text/docs/api_reference/preamble.js.txt // You can also build docs locally as HTML or other formats in site/ // An online HTML version (which may be of a different version of Emscripten) // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html var wasmBinary;legacyModuleProp('wasmBinary', 'wasmBinary'); var noExitRuntime = true;legacyModuleProp('noExitRuntime', 'noExitRuntime'); // Wasm globals var wasmMemory; //======================================== // Runtime essentials //======================================== // whether we are quitting the application. no code should run after this. // set in exit() and abort() var ABORT = false; // set by exit() and abort(). Passed to 'onExit' handler. // NOTE: This is also used as the process return code code in shell environments // but only when noExitRuntime is false. var EXITSTATUS; /** @type {function(*, string=)} */ function assert(condition, text) { if (!condition) { abort('Assertion failed' + (text ? ': ' + text : '')); } } // We used to include malloc/free by default in the past. Show a helpful error in // builds with assertions. function _malloc() { abort("malloc() called but not included in the build - add '_malloc' to EXPORTED_FUNCTIONS"); } function _free() { // Show a helpful error since we used to include free by default in the past. // console.warn("free() called but not included in the build - add '_free' to EXPORTED_FUNCTIONS"); } // Memory management var HEAP = [], /** @type {!Int8Array} */ HEAP8 = [], /** @type {!Uint8Array} */ HEAPU8 = [], /** @type {!Int16Array} */ HEAP16 = [], /** @type {!Uint16Array} */ HEAPU16 = [], /** @type {!Int32Array} */ HEAP32 = [], /** @type {!Uint32Array} */ HEAPU32 = [], /** @type {!Float32Array} */ HEAPF32 = [], /* BigInt64Array type is not correctly defined in closure /** not-@type {!BigInt64Array} */ HEAP64 = [], /* BigUInt64Array type is not correctly defined in closure /** not-t@type {!BigUint64Array} */ HEAPU64 = [], /** @type {!Float64Array} */ HEAPF64 = []; DATA_VIEW = []; var HEAP_OFFSET = []; function updateMemoryViews(offset, offset2, offset3, offset4) { // var b = wasmMemory.buffer; var b = globalThis.jsiArrayBuffer; var b2 = globalThis.jsiArrayBuffer2; var b3 = globalThis.jsiArrayBuffer3; var b4 = globalThis.jsiArrayBuffer4; // console.log('length: ' + b.byteLength + ', offset 1: ' + offset + ', offset 2: ' + offset2 + ', offset 3: ' + offset3 + ', offset 4: ' + offset4); HEAP_OFFSET = [offset, offset2, offset3, offset4]; HEAP8.push(new Int8Array(b)); HEAP8.push(new Int8Array(b2)); HEAP8.push(new Int8Array(b3)); HEAP8.push(new Int8Array(b4)); HEAPU8.push(new Uint8Array(b)); HEAPU8.push(new Uint8Array(b2)); HEAPU8.push(new Uint8Array(b3)); HEAPU8.push(new Uint8Array(b4)); DATA_VIEW.push(new DataView(b)); DATA_VIEW.push(new DataView(b2)); DATA_VIEW.push(new DataView(b3)); DATA_VIEW.push(new DataView(b4)); } function getHeapIndex(ptr) { let heapIndex = -1; if (ptr >= HEAP_OFFSET[1]) heapIndex = 1; else if (ptr >= HEAP_OFFSET[3]) heapIndex = 3; else if (ptr >= HEAP_OFFSET[0]) heapIndex = 0; else if (ptr >= HEAP_OFFSET[2]) heapIndex = 2; if (heapIndex === -1 || ptr - HEAP_OFFSET[heapIndex] > 4294967295) { throw(`Heap error !!! pointer: ${ptr}, heap index: ${heapIndex}, HEAPS: ${HEAP_OFFSET}`); } return heapIndex; } function writeToMemoryUsingShift(pointer, signed, shift, value) { // console.log(`writeToMemory, pointer: ${pointer}`); const pi = getHeapIndex(pointer); const offset = Number(pointer - HEAP_OFFSET[pi]); const shiftAsInt = Number(shift); // console.log(`writeToMemory, pi: ${pi}, shift: ${shiftAsInt}, signed: ${signed}, value: ${value}, pointer: ${pointer}`); switch (shiftAsInt) { case 0: result = signed ? DATA_VIEW[pi].setInt8(offset, value, true) : DATA_VIEW[pi].setUint8(offset, value, true); break; case 1: result = signed ? DATA_VIEW[pi].setInt16(offset, value, true) : DATA_VIEW[pi].setUint16(offset, value, true); break; case 2: result = signed ? DATA_VIEW[pi].setInt32(offset, value, true) : DATA_VIEW[pi].setUint32(offset, value, true); break; case 3: result = signed ? DATA_VIEW[pi].setBigInt64(offset, value, true) : DATA_VIEW[pi].setBigUint64(offset, value, true); break; default: throw new TypeError("Unknown heap type"); } } function readFromMemoryUsingShift(pointer, signed, shift, isFloat = false) { // console.log(`readFromMemory, pointer: ${pointer}`); const pi = getHeapIndex(pointer); const offset = Number(pointer - HEAP_OFFSET[pi]); // console.log(`readFromMemory, pi: ${pi}, shift: ${shift}, signed: ${signed}, pointer: ${pointer}, offset: ${offset}`); const shiftAsInt = Number(shift); let result = null; if (isFloat) { switch (shiftAsInt) { case 2: result = DATA_VIEW[pi].getFloat32(offset, true); break; case 3: result = DATA_VIEW[pi].getFloat64(offset, true); break; default: throw new TypeError("Unknown heap type"); } } else { switch (shiftAsInt) { case 0: result = signed ? DATA_VIEW[pi].getInt8(offset, true) : DATA_VIEW[pi].getUint8(offset, true); break; case 1: result = signed ? DATA_VIEW[pi].getInt16(offset, true) : DATA_VIEW[pi].getUint16(offset, true); break; case 2: result = signed ? DATA_VIEW[pi].getInt32(offset, true) : DATA_VIEW[pi].getUint32(offset, true); break; case 3: result = signed ? DATA_VIEW[pi].getBigInt64(offset, true) : DATA_VIEW[pi].getBigUint64(offset, true); break; default: throw new TypeError("Unknown heap type"); } } // console.log(`readFromMemory, result 1: ${result}`); return result; } function readFromMemoryUsingBit(pointer, signed, bit) { let shift = 0; switch (bit) { case 8: shift = 0; break; case 16: shift = 1; break; case 32: shift = 2; break; case 64: shift = 3; break; default: throw new TypeError("Unknown bit"); } return readFromMemoryUsingShift(pointer, signed, shift); } function readFromMemoryUsingSize(pointer, signed, bit) { let shift = 0; switch (bit) { case 1: shift = 0; break; case 2: shift = 1; break; case 4: shift = 2; break; default: throw new TypeError("Unknown size"); } return readFromMemoryUsingShift(pointer, signed, shift); } globalThis.updateMemoryViews = updateMemoryViews; 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 memory is defined in wasm, the user can't provide it, or set INITIAL_MEMORY assert(!Module['wasmMemory'], 'Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally'); assert(!Module['INITIAL_MEMORY'], 'Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically'); // include: runtime_init_table.js // In regular non-RELOCATABLE mode the table is exported // from the wasm module and this will be assigned once // the exports are available. var wasmTable; // end include: runtime_init_table.js // include: runtime_stack_check.js /** * @license * Copyright 2019 The Emscripten Authors * SPDX-License-Identifier: MIT */ // end include: runtime_stack_check.js // include: runtime_assertions.js /** * @license * Copyright 2019 The Emscripten Authors * SPDX-License-Identifier: MIT */ // Endianness check (function() { 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)'; })(); // end include: runtime_assertions.js var __ATPRERUN__ = []; // functions called before the runtime is initialized var __ATINIT__ = []; // functions called during startup var __ATEXIT__ = []; // functions called during shutdown var __ATPOSTRUN__ = []; // functions called after the main() is called var runtimeInitialized = false; var runtimeKeepaliveCounter = 0; function keepRuntimeAlive() { return noExitRuntime || runtimeKeepaliveCounter > 0; } function preRun() { callRuntimeCallbacks(__ATPRERUN__); } function initRuntime() { assert(!runtimeInitialized); runtimeInitialized = true; callRuntimeCallbacks(__ATINIT__); } function postRun() { callRuntimeCallbacks(__ATPOSTRUN__); } function addOnPreRun(cb) { __ATPRERUN__.unshift(cb); } function addOnInit(cb) { __ATINIT__.unshift(cb); } function addOnExit(cb) { } function addOnPostRun(cb) { __ATPOSTRUN__.unshift(cb); } // include: runtime_math.js /** * @license * Copyright 2019 The Emscripten Authors * SPDX-License-Identifier: MIT */ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc 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'); // end include: runtime_math.js // A counter of dependencies for calling run(). If we need to // do asynchronous work before running, increment this and // decrement it. Incrementing must happen in a place like // Module.preRun (used by emcc to add file preloading). // Note that you can add dependencies in preRun, even though // it happens right before run - run will be postponed until // the dependencies are met. var runDependencies = 0; var runDependencyWatcher = null; var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled var runDependencyTracking = {}; function getUniqueRunDependency(id) { var orig = id; while (1) { if (!runDependencyTracking[id]) return id; id = orig + Math.random(); } } function addRunDependency(id) { runDependencies++; if (id) { assert(!runDependencyTracking[id]); runDependencyTracking[id] = 1; if (runDependencyWatcher === null && typeof setInterval != 'undefined') { // Check for missing dependencies every few seconds 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--; 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(); // can add another dependenciesFulfilled } } } /** @param {string|number=} what */ function abort(what) { what = 'Aborted(' + what + ')'; // TODO(sbc): Should we remove printing and leave it up to whoever // catches the exception? err(what); ABORT = true; EXITSTATUS = 1; // Use a wasm runtime error, because a JS error might be seen as a foreign // exception, which means we'd run destructors on it. We need the error to // simply make the program stop. // FIXME This approach does not work in Wasm EH because it currently does not assume // all RuntimeErrors are from traps; it decides whether a RuntimeError is from // a trap or not based on a hidden field within the object. So at the moment // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that // allows this in the wasm spec. // Suppress closure compiler warning here. Closure compiler's builtin extern // defintion for WebAssembly.RuntimeError claims it takes no arguments even // though it can. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed. /** @suppress {checkTypes} */ var e = new WebAssembly.RuntimeError(what); // Throw the error whether or not MODULARIZE is set because abort is used // in code paths apart from instantiation where an exception is expected // to be thrown when abort is called. throw e; } // include: memoryprofiler.js /** * @license * Copyright 2015 The Emscripten Authors * SPDX-License-Identifier: MIT */ // end include: memoryprofiler.js // show errors on likely calls to FS when it was not included var FS = { error: function() { abort('Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -sFORCE_FILESYSTEM'); }, init: function() { FS.error() }, createDataFile: function() { FS.error() }, createPreloadedFile: function() { FS.error() }, createLazyFile: function() { FS.error() }, open: function() { FS.error() }, mkdev: function() { FS.error() }, registerDevice: function() { FS.error() }, analyzePath: function() { FS.error() }, ErrnoError: function ErrnoError() { FS.error() }, }; Module['FS_createDataFile'] = FS.createDataFile; Module['FS_createPreloadedFile'] = FS.createPreloadedFile; // include: URIUtils.js /** * @license * Copyright 2017 The Emscripten Authors * SPDX-License-Identifier: MIT */ // Prefix of data URIs emitted by SINGLE_FILE and related options. var dataURIPrefix = 'data:application/octet-stream;base64,'; // Indicates whether filename is a base64 data URI. function isDataURI(filename) { // Prefix of data URIs emitted by SINGLE_FILE and related options. return filename.startsWith(dataURIPrefix); } // Indicates whether filename is delivered via file protocol (as opposed to http/https) function isFileURI(filename) { return filename.startsWith('file://'); } // end include: URIUtils.js /** @param {boolean=} fixedasm */ function createExportWrapper(name, fixedasm) { return function() { var displayName = name; var asm = fixedasm; if (!fixedasm) { asm = Module['asm']; } assert(runtimeInitialized, 'native function `' + displayName + '` called before runtime initialization'); if (!asm[name]) { assert(asm[name], 'exported native function `' + displayName + '` not found'); } return asm[name].apply(null, arguments); }; } // include: runtime_exceptions.js /** * @license * Copyright 2023 The Emscripten Authors * SPDX-License-Identifier: MIT */ // end include: runtime_exceptions.js var wasmBinaryFile; wasmBinaryFile = ''; if (!isDataURI(wasmBinaryFile)) { wasmBinaryFile = locateFile(wasmBinaryFile); } 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(binaryFile) { // If we don't have the binary yet, try to load it asynchronously. // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url. // See https://github.com/github/fetch/pull/92#issuecomment-140665932 // Cordova or Electron apps are typically loaded from a file:// url. // So use fetch if it is available and the url is not a file, otherwise fall back to XHR. if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { if (typeof fetch == 'function' && !isFileURI(binaryFile) ) { return fetch(binaryFile, { credentials: 'same-origin' }).then((response) => { if (!response['ok']) { throw "failed to load wasm binary file at '" + binaryFile + "'"; } return response['arrayBuffer'](); }).catch(() => getBinary(binaryFile)); } else { if (readAsync) { // fetch is not available or url is file => try XHR (readAsync uses XHR internally) return new Promise((resolve, reject) => { readAsync(binaryFile, (response) => resolve(new Uint8Array(/** @type{!ArrayBuffer} */(response))), reject) }); } } } // Otherwise, getBinary should be able to get it synchronously return Promise.resolve().then(() => getBinary(binaryFile)); } function instantiateArrayBuffer(binaryFile, imports, receiver) { return getBinaryPromise(binaryFile).then((binary) => { return WebAssembly.instantiate(binary, imports); }).then((instance) => { return instance; }).then(receiver, (reason) => { err('failed to asynchronously prepare wasm: ' + reason); // Warn on some common problems. 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) && // Don't use streaming for file:// delivered objects in a webview, fetch them synchronously. !isFileURI(binaryFile) && // Avoid instantiateStreaming() on Node.js environment for now, as while // Node.js v18.1.0 implements it, it does not have a full fetch() // implementation yet. // // Reference: // https://github.com/emscripten-core/emscripten/pull/16917 !ENVIRONMENT_IS_NODE && typeof fetch == 'function') { return fetch(binaryFile, { credentials: 'same-origin' }).then((response) => { // Suppress closure warning here since the upstream definition for // instantiateStreaming only allows Promise<Repsponse> rather than // an actual Response. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure is fixed. /** @suppress {checkTypes} */ var result = WebAssembly.instantiateStreaming(response, imports); return result.then( callback, function(reason) { // We expect the most common failure cause to be a bad MIME type for the binary, // in which case falling back to ArrayBuffer instantiation should work. err('wasm streaming compile failed: ' + reason); err('falling back to ArrayBuffer instantiation'); return instantiateArrayBuffer(binaryFile, imports, callback); }); }); } else { return instantiateArrayBuffer(binaryFile, imports, callback); } } // Create the wasm instance. // Receives the wasm imports, returns the exports. function createWasm() { // prepare imports var info = { 'env': wasmImports, 'wasi_snapshot_preview1': wasmImports, }; // Load the wasm module and create an instance of using native support in the JS engine. // handle a generated wasm instance, receiving its exports and // performing other necessary setup /** @param {WebAssembly.Module=} module*/ function receiveInstance(instance, module) { var exports = instance.exports; exports = instrumentWasmExportsForMemory64(exports); Module['asm'] = exports; wasmMemory = Module['asm']['memory']; assert(wasmMemory, "memory not found in wasm exports"); // This assertion doesn't hold when emscripten is run in --post-link // mode. // TODO(sbc): Read INITIAL_MEMORY out of the wasm file in post-link mode. //assert(wasmMemory.buffer.byteLength === 16777216); updateMemoryViews(); wasmTable = Module['asm']['__indirect_function_table']; assert(wasmTable, "table not found in wasm exports"); removeRunDependency('wasm-instantiate'); return exports; } // wait for the pthread pool (if any) addRunDependency('wasm-instantiate'); // Prefer streaming instantiation if available. // Async compilation can be confusing when an error on the page overwrites Module // (for example, if the order of elements is wrong, and the one defining Module is // later), so we save Module and check it later. var trueModule = Module; function receiveInstantiationResult(result) { // 'result' is a ResultObject object which has both the module and instance. // receiveInstance() will swap in the exports (to Module.asm) so they can be called assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?'); trueModule = null; // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line. // When the regression is fixed, can restore the above PTHREADS-enabled path. receiveInstance(result['instance']); } instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult); return {}; // no exports yet; we'll fill them in later } // include: runtime_debug.js /** * @license * Copyright 2020 The Emscripten Authors * SPDX-License-Identifier: MIT */ function legacyModuleProp(prop, newName) { if (!Object.getOwnPropertyDescriptor(Module, prop)) { Object.defineProperty(Module, prop, { configurable: true, get: function() { abort('Module.' + prop + ' has been replaced with plain ' + newName + ' (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)'); } }); } } function ignoredModuleProp(prop) { if (Object.getOwnPropertyDescriptor(Module, prop)) { abort('`Module.' + prop + '` was supplied but `' + prop + '` not included in INCOMING_MODULE_JS_API'); } } // forcing the filesystem exports a few things by default function isExportedByForceFilesystem(name) { return name === 'FS_createPath' || name === 'FS_createDataFile' || name === 'FS_createPreloadedFile' || name === 'FS_unlink' || name === 'addRunDependency' || // The old FS has some functionality that WasmFS lacks. name === 'FS_createLazyFile' || name === 'FS_createDevice' || name === 'removeRunDependency'; } function missingGlobal(sym, msg) { if (typeof globalThis !== 'undefined') { Object.defineProperty(globalThis, sym, { configurable: true, get: function() { warnOnce('`' + sym + '` is not longer defined by emscripten. ' + msg); return undefined; } }); } } missingGlobal('buffer', 'Please use HEAP8.buffer or wasmMemory.buffer'); function missingLibrarySymbol(sym) { if (typeof globalThis !== 'undefined' && !Object.getOwnPropertyDescriptor(globalThis, sym)) { Object.defineProperty(globalThis, sym, { configurable: true, get: function() { // Can't `abort()` here because it would break code that does runtime // checks. e.g. `if (typeof SDL === 'undefined')`. 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'; // DEFAULT_LIBRARY_FUNCS_TO_INCLUDE requires the name as it appears in // library.js, which means $name for a JS name with no prefix, or name // for a JS name like _name. 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); return undefined; } }); } // Any symbol that is not included from the JS libary is also (by definition) // not exported on the Module object. unexportedRuntimeSymbol(sym); } function unexportedRuntimeSymbol(sym) { if (!Object.getOwnPropertyDescriptor(Module, sym)) { Object.defineProperty(Module, sym, { configurable: true, get: function() { var msg = "'" + sym + "' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)"; if (isExportedByForceFilesystem(sym)) { msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you'; } abort(msg); } }); } } // Used by XXXXX_DEBUG settings to output debug messages. function dbg(text) { // TODO(sbc): Make this configurable somehow. Its not always convenient for // logging to show up as errors. console.error.apply(console, arguments); } // end include: runtime_debug.js // === Body === // end include: preamble.js function embind_init_charCodes() { var codes = new Array(256); for (var i = 0; i < 256; ++i) { codes[i] = String.fromCharCode(i); } embind_charCodes = codes; } var embind_charCodes = undefined; function readLatin1String(ptr) { return ptr; /* var ret = ""; var c = ptr; while (HEAPU8[c]) { ret += embind_charCodes[HEAPU8[c++]]; } return ret; */ } var awaitingDependencies = {}; var registeredTypes = {}; var typeDependencies = {}; var char_0 = 48; var char_9 = 57; function makeLegalFunctionName(name) { if (undefined === name) { return '_unknown'; } name = name.replace(/[^a-zA-Z0-9_]/g, '$'); var f = name.charCodeAt(0); if (f >= char_0 && f <= char_9) { return '_' + name; } return name; } function createNamedFunction(name, body) { name = makeLegalFunctionName(name); // Use an abject with a computed property name to create a new function with // a name specified at runtime, but without using `new Function` or `eval`. return { [name]: function() { return body.apply(this, arguments); } }[name]; } function extendError(baseErrorType, errorName) { var errorClass = createNamedFunction(errorName, function(message) { this.name = errorName; this.message = message; var stack = (new Error(message)).stack; if (stack !== undefined) { this.stack = this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, ''); } }); errorClass.prototype = Object.create(baseErrorType.prototype); errorClass.prototype.constructor = errorClass; errorClass.prototype.toString = function() { if (this.message === undefined) { return this.name; } else { return this.name + ': ' + this.message; } }; return errorClass; } var BindingError = undefined; function throwBindingError(message) { console.log(message); throw new BindingError(message); } var InternalError = undefined; function throwInternalError(message) { throw new InternalError(message); } function whenDependentTypesAreResolved(myTypes, dependentTypes, getTypeConverters) { myTypes.forEach(function(type) { typeDependencies[type] = dependentTypes; }); function onComplete(typeConverters) { var myTypeConverters = getTypeConverters(typeConverters); if (myTypeConverters.length !== myTypes.length) { throwInternalError('Mismatched type converter count'); } for (var i = 0; i < myTypes.length; ++i) { registerType(myTypes[i], myTypeConverters[i]); } } var typeConverters = new Array(dependentTypes.length); var unregisteredTypes = []; var registered = 0; dependentTypes.forEach((dt, i) => { if (registeredTypes.hasOwnProperty(dt)) { typeConverters[i] = registeredTypes[dt]; } else { unregisteredTypes.push(dt); if (!awaitingDependencies.hasOwnProperty(dt)) { awaitingDependencies[dt] = []; } awaitingDependencies[dt].push(() => { typeConverters[i] = registeredTypes[dt]; ++registered; if (registered === unregisteredTypes.length) { onComplete(typeConverters); } }); } }); if (0 === unregisteredTypes.length) { onComplete(typeConverters); } } /** @param {Object=} options */ function registerType(rawType, registeredInstance, options = {}) { // console.log('1', rawType); if (!('argPackAdvance' in registeredInstance)) { throw new TypeError('registerType registeredInstance requires argPackAdvance'); } // console.log('2', rawType); var name = registeredInstance.name; if (!rawType) { throwBindingError(`type "${name}" must have a positive integer typeid pointer`); } // console.log('3', rawType); if (registeredTypes.hasOwnProperty(rawType)) { if (options.ignoreDuplicateRegistrations) { return; } else { throwBindingError(`Cannot register type '${name}' twice`); } } // console.log('4', rawType); registeredTypes[rawType] = registeredInstance; delete typeDependencies[rawType]; // console.log('5', rawType); if (awaitingDependencies.hasOwnProperty(rawType)) { var callbacks = awaitingDependencies[rawType]; delete awaitingDependencies[rawType]; callbacks.forEach((cb) => cb()); } // console.log('6', rawType); } function __embind_register_void(rawType, name) { name = readLatin1String(name); // console.log('__embind_register_void', name, rawType); registerType(rawType, { isVoid: true, // void return values can be optimized out sometimes name: name, 'argPackAdvance': 0n, 'fromWireType': function() { return undefined; }, 'toWireType': function(destructors, o) { // TODO: assert if anything else is given? return undefined; }, }); } globalThis.__embind_register_void = __embind_register_void; function __embind_register_jsiValue(rawType, name) { name = readLatin1String(name); // console.log('__embind_register_jsiValue', name, rawType); registerType(rawType, { isVoid: false, // void return values can be optimized out sometimes name: name, 'argPackAdvance': 0n, 'fromWireType': function(v) { return v; }, 'toWireType': function(destructors, o) { return o; }, }); } globalThis.__embind_register_jsiValue = __embind_register_jsiValue; function getShiftFromSize(size) { switch (size) { case 1: return 0; case 2: return 1; case 4: return 2; case 8: return 3; case 1n: return 0; case 2n: return 1; case 4n: return 2; case 8n: return 3; default: throw new TypeError('Unknown type size: ' + size); } } function __embind_register_bool(rawType, name, size, trueValue, falseValue) { // console.log('bool', name, rawType, size, trueValue, falseValue); var shift = getShiftFromSize(size); name = readLatin1String(name); registerType(rawType, { name: name, 'fromWireType': function(wt) { // ambiguous emscripten ABI: sometimes return values are // true or false, and sometimes integers (0 or 1) return !!wt; }, 'toWireType': function(destructors, o) { return o ? trueValue : falseValue; }, 'argPackAdvance': 8n, 'readValueFromPointer': function(pointer) { // console.log('__embind_register_bool readValueFromPointer', pointer); return this['fromWireType'](readFromMemoryUsingSize(pointer, true, size)); }, destructorFunction: null, // This type does not need a destructor }); } globalThis.__embind_register_bool = __embind_register_bool; function embindRepr(v) { if (v === null) { return 'null'; } var t = typeof v; if (t === 'object' || t === 'array' || t === 'function') { return v.toString(); } else { return '' + v; } } function integerReadValueFromPointer(name, shift, signed) { // integers are quite common, so generate very specialized functions switch (shift) { case 0: case 0n: return signed ? function readS8FromPointer(pointer) { return readFromMemoryUsingShift(pointer, true, 0); } : function readU8FromPointer(pointer) { return readFromMemoryUsingShift(pointer, false, 0); }; case 1: case 1n: return signed ? function readS16FromPointer(pointer) { return readFromMemoryUsingShift(pointer, true, 1); } : function readU16FromPointer(pointer) { return readFromMemoryUsingShift(pointer, false, 1); }; case 2: case 2n: return signed ? function readS32FromPointer(pointer) { return readFromMemoryUsingShift(pointer, true, 2); } : function readU32FromPointer(pointer) { return readFromMemoryUsingShi