web-tree-sitter
Version:
Tree-sitter bindings for the web
4 lines • 271 kB
Source Map (JSON)
{
"version": 3,
"sources": ["lib/tree-sitter.cjs", "src/index.ts", "src/constants.ts", "src/lookahead_iterator.ts", "src/tree.ts", "src/tree_cursor.ts", "src/node.ts", "src/marshal.ts", "src/query.ts", "src/language.ts", "src/bindings.ts", "src/parser.ts"],
"sourcesContent": ["var Module = (() => {\n var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;\n if (typeof __filename != 'undefined') _scriptName = _scriptName || __filename;\n return (\nasync function(moduleArg = {}) {\n var moduleRtn;\n\n// include: shell.js\n// The Module object: Our interface to the outside world. We import\n// and export values on it. There are various ways Module can be used:\n// 1. Not defined. We create it here\n// 2. A function parameter, function(moduleArg) => Promise<Module>\n// 3. pre-run appended it, var Module = {}; ..generated code..\n// 4. External script tag defines var Module.\n// We need to check if Module already exists (e.g. case 3 above).\n// Substitution will be replaced with actual code on later stage of the build,\n// this way Closure Compiler will not mangle it (e.g. case 4. above).\n// Note that if you want to run closure, and also to use Module\n// after the generated code, you will need to define var Module = {};\n// before the code. Then that object will be used in the code, and you\n// can continue to use Module afterwards as well.\nvar Module = moduleArg;\n\n// Set up the promise that indicates the Module is initialized\nvar readyPromiseResolve, readyPromiseReject;\n\nvar readyPromise = new Promise((resolve, reject) => {\n readyPromiseResolve = resolve;\n readyPromiseReject = reject;\n});\n\n// Determine the runtime environment we are in. You can customize this by\n// setting the ENVIRONMENT setting at compile time (see settings.js).\n// Attempt to auto-detect the environment\nvar ENVIRONMENT_IS_WEB = typeof window == \"object\";\n\nvar ENVIRONMENT_IS_WORKER = typeof WorkerGlobalScope != \"undefined\";\n\n// N.b. Electron.js environment is simultaneously a NODE-environment, but\n// also a web environment.\nvar ENVIRONMENT_IS_NODE = typeof process == \"object\" && typeof process.versions == \"object\" && typeof process.versions.node == \"string\" && process.type != \"renderer\";\n\nvar ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;\n\nif (ENVIRONMENT_IS_NODE) {}\n\n// --pre-jses are emitted after the Module integration code, so that they can\n// refer to Module (if they choose; they can also define Module)\n// include: lib/binding_web/lib/prefix.js\nModule.currentQueryProgressCallback = null;\n\nModule.currentProgressCallback = null;\n\nModule.currentLogCallback = null;\n\nModule.currentParseCallback = null;\n\n// end include: lib/binding_web/lib/prefix.js\n// Sometimes an existing Module object exists with properties\n// meant to overwrite the default module functionality. Here\n// we collect those properties and reapply _after_ we configure\n// the current environment's defaults to avoid having to be so\n// defensive during initialization.\nvar moduleOverrides = Object.assign({}, Module);\n\nvar arguments_ = [];\n\nvar thisProgram = \"./this.program\";\n\nvar quit_ = (status, toThrow) => {\n throw toThrow;\n};\n\n// `/` should be present at the end if `scriptDirectory` is not empty\nvar scriptDirectory = \"\";\n\nfunction locateFile(path) {\n if (Module[\"locateFile\"]) {\n return Module[\"locateFile\"](path, scriptDirectory);\n }\n return scriptDirectory + path;\n}\n\n// Hooks that are implemented differently in different runtime environments.\nvar readAsync, readBinary;\n\nif (ENVIRONMENT_IS_NODE) {\n // These modules will usually be used on Node.js. Load them eagerly to avoid\n // the complexity of lazy-loading.\n var fs = require(\"fs\");\n var nodePath = require(\"path\");\n scriptDirectory = __dirname + \"/\";\n // include: node_shell_read.js\n readBinary = filename => {\n // We need to re-wrap `file://` strings to URLs.\n filename = isFileURI(filename) ? new URL(filename) : filename;\n var ret = fs.readFileSync(filename);\n return ret;\n };\n readAsync = async (filename, binary = true) => {\n // See the comment in the `readBinary` function.\n filename = isFileURI(filename) ? new URL(filename) : filename;\n var ret = fs.readFileSync(filename, binary ? undefined : \"utf8\");\n return ret;\n };\n // end include: node_shell_read.js\n if (!Module[\"thisProgram\"] && process.argv.length > 1) {\n thisProgram = process.argv[1].replace(/\\\\/g, \"/\");\n }\n arguments_ = process.argv.slice(2);\n // MODULARIZE will export the module in the proper place outside, we don't need to export here\n quit_ = (status, toThrow) => {\n process.exitCode = status;\n throw toThrow;\n };\n} else // Note that this includes Node.js workers when relevant (pthreads is enabled).\n// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and\n// ENVIRONMENT_IS_NODE.\nif (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {\n if (ENVIRONMENT_IS_WORKER) {\n // Check worker, not web, since window could be polyfilled\n scriptDirectory = self.location.href;\n } else if (typeof document != \"undefined\" && document.currentScript) {\n // web\n scriptDirectory = document.currentScript.src;\n }\n // When MODULARIZE, this JS may be executed later, after document.currentScript\n // is gone, so we saved it, and we use it here instead of any other info.\n if (_scriptName) {\n scriptDirectory = _scriptName;\n }\n // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.\n // otherwise, slice off the final part of the url to find the script directory.\n // if scriptDirectory does not contain a slash, lastIndexOf will return -1,\n // and scriptDirectory will correctly be replaced with an empty string.\n // If scriptDirectory contains a query (starting with ?) or a fragment (starting with #),\n // they are removed because they could contain a slash.\n if (scriptDirectory.startsWith(\"blob:\")) {\n scriptDirectory = \"\";\n } else {\n scriptDirectory = scriptDirectory.slice(0, scriptDirectory.replace(/[?#].*/, \"\").lastIndexOf(\"/\") + 1);\n }\n {\n // include: web_or_worker_shell_read.js\n if (ENVIRONMENT_IS_WORKER) {\n readBinary = url => {\n var xhr = new XMLHttpRequest;\n xhr.open(\"GET\", url, false);\n xhr.responseType = \"arraybuffer\";\n xhr.send(null);\n return new Uint8Array(/** @type{!ArrayBuffer} */ (xhr.response));\n };\n }\n readAsync = async url => {\n // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.\n // See https://github.com/github/fetch/pull/92#issuecomment-140665932\n // Cordova or Electron apps are typically loaded from a file:// url.\n // So use XHR on webview if URL is a file URL.\n if (isFileURI(url)) {\n return new Promise((resolve, reject) => {\n var xhr = new XMLHttpRequest;\n xhr.open(\"GET\", url, true);\n xhr.responseType = \"arraybuffer\";\n xhr.onload = () => {\n if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) {\n // file URLs can return 0\n resolve(xhr.response);\n return;\n }\n reject(xhr.status);\n };\n xhr.onerror = reject;\n xhr.send(null);\n });\n }\n var response = await fetch(url, {\n credentials: \"same-origin\"\n });\n if (response.ok) {\n return response.arrayBuffer();\n }\n throw new Error(response.status + \" : \" + response.url);\n };\n }\n} else {}\n\nvar out = Module[\"print\"] || console.log.bind(console);\n\nvar err = Module[\"printErr\"] || console.error.bind(console);\n\n// Merge back in the overrides\nObject.assign(Module, moduleOverrides);\n\n// Free the object hierarchy contained in the overrides, this lets the GC\n// reclaim data used.\nmoduleOverrides = null;\n\n// Emit code to handle expected values on the Module object. This applies Module.x\n// to the proper local x. This has two benefits: first, we only emit it if it is\n// expected to arrive, and second, by using a local everywhere else that can be\n// minified.\nif (Module[\"arguments\"]) arguments_ = Module[\"arguments\"];\n\nif (Module[\"thisProgram\"]) thisProgram = Module[\"thisProgram\"];\n\n// perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message\n// end include: shell.js\n// include: preamble.js\n// === Preamble library stuff ===\n// Documentation for the public APIs defined in this file must be updated in:\n// site/source/docs/api_reference/preamble.js.rst\n// A prebuilt local version of the documentation is available at:\n// site/build/text/docs/api_reference/preamble.js.txt\n// You can also build docs locally as HTML or other formats in site/\n// An online HTML version (which may be of a different version of Emscripten)\n// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html\nvar dynamicLibraries = Module[\"dynamicLibraries\"] || [];\n\nvar wasmBinary = Module[\"wasmBinary\"];\n\n// Wasm globals\nvar wasmMemory;\n\n//========================================\n// Runtime essentials\n//========================================\n// whether we are quitting the application. no code should run after this.\n// set in exit() and abort()\nvar ABORT = false;\n\n// set by exit() and abort(). Passed to 'onExit' handler.\n// NOTE: This is also used as the process return code code in shell environments\n// but only when noExitRuntime is false.\nvar EXITSTATUS;\n\n// In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we\n// don't define it at all in release modes. This matches the behaviour of\n// MINIMAL_RUNTIME.\n// TODO(sbc): Make this the default even without STRICT enabled.\n/** @type {function(*, string=)} */ function assert(condition, text) {\n if (!condition) {\n // This build was created without ASSERTIONS defined. `assert()` should not\n // ever be called in this configuration but in case there are callers in\n // the wild leave this simple abort() implementation here for now.\n abort(text);\n }\n}\n\n// Memory management\nvar 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\n/** not-@type {!BigInt64Array} */ HEAP64, /* BigUint64Array type is not correctly defined in closure\n/** not-t@type {!BigUint64Array} */ HEAPU64, /** @type {!Float64Array} */ HEAPF64;\n\nvar HEAP_DATA_VIEW;\n\nvar runtimeInitialized = false;\n\n/**\n * Indicates whether filename is delivered via file protocol (as opposed to http/https)\n * @noinline\n */ var isFileURI = filename => filename.startsWith(\"file://\");\n\n// include: runtime_shared.js\n// include: runtime_stack_check.js\n// end include: runtime_stack_check.js\n// include: runtime_exceptions.js\n// end include: runtime_exceptions.js\n// include: runtime_debug.js\n// end include: runtime_debug.js\n// include: memoryprofiler.js\n// end include: memoryprofiler.js\nfunction updateMemoryViews() {\n var b = wasmMemory.buffer;\n Module[\"HEAP_DATA_VIEW\"] = HEAP_DATA_VIEW = new DataView(b);\n Module[\"HEAP8\"] = HEAP8 = new Int8Array(b);\n Module[\"HEAP16\"] = HEAP16 = new Int16Array(b);\n Module[\"HEAPU8\"] = HEAPU8 = new Uint8Array(b);\n Module[\"HEAPU16\"] = HEAPU16 = new Uint16Array(b);\n Module[\"HEAP32\"] = HEAP32 = new Int32Array(b);\n Module[\"HEAPU32\"] = HEAPU32 = new Uint32Array(b);\n Module[\"HEAPF32\"] = HEAPF32 = new Float32Array(b);\n Module[\"HEAPF64\"] = HEAPF64 = new Float64Array(b);\n Module[\"HEAP64\"] = HEAP64 = new BigInt64Array(b);\n Module[\"HEAPU64\"] = HEAPU64 = new BigUint64Array(b);\n}\n\n// end include: runtime_shared.js\n// In non-standalone/normal mode, we create the memory here.\n// include: runtime_init_memory.js\n// Create the wasm memory. (Note: this only applies if IMPORTED_MEMORY is defined)\n// check for full engine support (use string 'subarray' to avoid closure compiler confusion)\nif (Module[\"wasmMemory\"]) {\n wasmMemory = Module[\"wasmMemory\"];\n} else {\n var INITIAL_MEMORY = Module[\"INITIAL_MEMORY\"] || 33554432;\n /** @suppress {checkTypes} */ wasmMemory = new WebAssembly.Memory({\n \"initial\": INITIAL_MEMORY / 65536,\n // In theory we should not need to emit the maximum if we want \"unlimited\"\n // or 4GB of memory, but VMs error on that atm, see\n // https://github.com/emscripten-core/emscripten/issues/14130\n // And in the pthreads case we definitely need to emit a maximum. So\n // always emit one.\n \"maximum\": 32768\n });\n}\n\nupdateMemoryViews();\n\n// end include: runtime_init_memory.js\nvar __RELOC_FUNCS__ = [];\n\nfunction preRun() {\n if (Module[\"preRun\"]) {\n if (typeof Module[\"preRun\"] == \"function\") Module[\"preRun\"] = [ Module[\"preRun\"] ];\n while (Module[\"preRun\"].length) {\n addOnPreRun(Module[\"preRun\"].shift());\n }\n }\n callRuntimeCallbacks(onPreRuns);\n}\n\nfunction initRuntime() {\n runtimeInitialized = true;\n callRuntimeCallbacks(__RELOC_FUNCS__);\n wasmExports[\"__wasm_call_ctors\"]();\n callRuntimeCallbacks(onPostCtors);\n}\n\nfunction preMain() {}\n\nfunction postRun() {\n if (Module[\"postRun\"]) {\n if (typeof Module[\"postRun\"] == \"function\") Module[\"postRun\"] = [ Module[\"postRun\"] ];\n while (Module[\"postRun\"].length) {\n addOnPostRun(Module[\"postRun\"].shift());\n }\n }\n callRuntimeCallbacks(onPostRuns);\n}\n\n// A counter of dependencies for calling run(). If we need to\n// do asynchronous work before running, increment this and\n// decrement it. Incrementing must happen in a place like\n// Module.preRun (used by emcc to add file preloading).\n// Note that you can add dependencies in preRun, even though\n// it happens right before run - run will be postponed until\n// the dependencies are met.\nvar runDependencies = 0;\n\nvar dependenciesFulfilled = null;\n\n// overridden to take different actions when all run dependencies are fulfilled\nfunction getUniqueRunDependency(id) {\n return id;\n}\n\nfunction addRunDependency(id) {\n runDependencies++;\n Module[\"monitorRunDependencies\"]?.(runDependencies);\n}\n\nfunction removeRunDependency(id) {\n runDependencies--;\n Module[\"monitorRunDependencies\"]?.(runDependencies);\n if (runDependencies == 0) {\n if (dependenciesFulfilled) {\n var callback = dependenciesFulfilled;\n dependenciesFulfilled = null;\n callback();\n }\n }\n}\n\n/** @param {string|number=} what */ function abort(what) {\n Module[\"onAbort\"]?.(what);\n what = \"Aborted(\" + what + \")\";\n // TODO(sbc): Should we remove printing and leave it up to whoever\n // catches the exception?\n err(what);\n ABORT = true;\n what += \". Build with -sASSERTIONS for more info.\";\n // Use a wasm runtime error, because a JS error might be seen as a foreign\n // exception, which means we'd run destructors on it. We need the error to\n // simply make the program stop.\n // FIXME This approach does not work in Wasm EH because it currently does not assume\n // all RuntimeErrors are from traps; it decides whether a RuntimeError is from\n // a trap or not based on a hidden field within the object. So at the moment\n // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that\n // allows this in the wasm spec.\n // Suppress closure compiler warning here. Closure compiler's builtin extern\n // definition for WebAssembly.RuntimeError claims it takes no arguments even\n // though it can.\n // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.\n /** @suppress {checkTypes} */ var e = new WebAssembly.RuntimeError(what);\n readyPromiseReject(e);\n // Throw the error whether or not MODULARIZE is set because abort is used\n // in code paths apart from instantiation where an exception is expected\n // to be thrown when abort is called.\n throw e;\n}\n\nvar wasmBinaryFile;\n\nfunction findWasmBinary() {\n return locateFile(\"tree-sitter.wasm\");\n}\n\nfunction getBinarySync(file) {\n if (file == wasmBinaryFile && wasmBinary) {\n return new Uint8Array(wasmBinary);\n }\n if (readBinary) {\n return readBinary(file);\n }\n throw \"both async and sync fetching of the wasm failed\";\n}\n\nasync function getWasmBinary(binaryFile) {\n // If we don't have the binary yet, load it asynchronously using readAsync.\n if (!wasmBinary) {\n // Fetch the binary using readAsync\n try {\n var response = await readAsync(binaryFile);\n return new Uint8Array(response);\n } catch {}\n }\n // Otherwise, getBinarySync should be able to get it synchronously\n return getBinarySync(binaryFile);\n}\n\nasync function instantiateArrayBuffer(binaryFile, imports) {\n try {\n var binary = await getWasmBinary(binaryFile);\n var instance = await WebAssembly.instantiate(binary, imports);\n return instance;\n } catch (reason) {\n err(`failed to asynchronously prepare wasm: ${reason}`);\n abort(reason);\n }\n}\n\nasync function instantiateAsync(binary, binaryFile, imports) {\n if (!binary && typeof WebAssembly.instantiateStreaming == \"function\" && !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE) {\n try {\n var response = fetch(binaryFile, {\n credentials: \"same-origin\"\n });\n var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);\n return instantiationResult;\n } catch (reason) {\n // We expect the most common failure cause to be a bad MIME type for the binary,\n // in which case falling back to ArrayBuffer instantiation should work.\n err(`wasm streaming compile failed: ${reason}`);\n err(\"falling back to ArrayBuffer instantiation\");\n }\n }\n return instantiateArrayBuffer(binaryFile, imports);\n}\n\nfunction getWasmImports() {\n // prepare imports\n return {\n \"env\": wasmImports,\n \"wasi_snapshot_preview1\": wasmImports,\n \"GOT.mem\": new Proxy(wasmImports, GOTHandler),\n \"GOT.func\": new Proxy(wasmImports, GOTHandler)\n };\n}\n\n// Create the wasm instance.\n// Receives the wasm imports, returns the exports.\nasync function createWasm() {\n // Load the wasm module and create an instance of using native support in the JS engine.\n // handle a generated wasm instance, receiving its exports and\n // performing other necessary setup\n /** @param {WebAssembly.Module=} module*/ function receiveInstance(instance, module) {\n wasmExports = instance.exports;\n wasmExports = relocateExports(wasmExports, 1024);\n var metadata = getDylinkMetadata(module);\n if (metadata.neededDynlibs) {\n dynamicLibraries = metadata.neededDynlibs.concat(dynamicLibraries);\n }\n mergeLibSymbols(wasmExports, \"main\");\n LDSO.init();\n loadDylibs();\n __RELOC_FUNCS__.push(wasmExports[\"__wasm_apply_data_relocs\"]);\n removeRunDependency(\"wasm-instantiate\");\n return wasmExports;\n }\n // wait for the pthread pool (if any)\n addRunDependency(\"wasm-instantiate\");\n // Prefer streaming instantiation if available.\n function receiveInstantiationResult(result) {\n // 'result' is a ResultObject object which has both the module and instance.\n // receiveInstance() will swap in the exports (to Module.asm) so they can be called\n return receiveInstance(result[\"instance\"], result[\"module\"]);\n }\n var info = getWasmImports();\n // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback\n // to manually instantiate the Wasm module themselves. This allows pages to\n // run the instantiation parallel to any other async startup actions they are\n // performing.\n // Also pthreads and wasm workers initialize the wasm instance through this\n // path.\n if (Module[\"instantiateWasm\"]) {\n return new Promise((resolve, reject) => {\n Module[\"instantiateWasm\"](info, (mod, inst) => {\n receiveInstance(mod, inst);\n resolve(mod.exports);\n });\n });\n }\n wasmBinaryFile ??= findWasmBinary();\n try {\n var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);\n var exports = receiveInstantiationResult(result);\n return exports;\n } catch (e) {\n // If instantiation fails, reject the module ready promise.\n readyPromiseReject(e);\n return Promise.reject(e);\n }\n}\n\n// === Body ===\nvar ASM_CONSTS = {};\n\n// end include: preamble.js\nclass ExitStatus {\n name=\"ExitStatus\";\n constructor(status) {\n this.message = `Program terminated with exit(${status})`;\n this.status = status;\n }\n}\n\nvar GOT = {};\n\nvar currentModuleWeakSymbols = new Set([]);\n\nvar GOTHandler = {\n get(obj, symName) {\n var rtn = GOT[symName];\n if (!rtn) {\n rtn = GOT[symName] = new WebAssembly.Global({\n \"value\": \"i32\",\n \"mutable\": true\n });\n }\n if (!currentModuleWeakSymbols.has(symName)) {\n // Any non-weak reference to a symbol marks it as `required`, which\n // enabled `reportUndefinedSymbols` to report undefined symbol errors\n // correctly.\n rtn.required = true;\n }\n return rtn;\n }\n};\n\nvar LE_HEAP_LOAD_F32 = byteOffset => HEAP_DATA_VIEW.getFloat32(byteOffset, true);\n\nvar LE_HEAP_LOAD_F64 = byteOffset => HEAP_DATA_VIEW.getFloat64(byteOffset, true);\n\nvar LE_HEAP_LOAD_I16 = byteOffset => HEAP_DATA_VIEW.getInt16(byteOffset, true);\n\nvar LE_HEAP_LOAD_I32 = byteOffset => HEAP_DATA_VIEW.getInt32(byteOffset, true);\n\nvar LE_HEAP_LOAD_U16 = byteOffset => HEAP_DATA_VIEW.getUint16(byteOffset, true);\n\nvar LE_HEAP_LOAD_U32 = byteOffset => HEAP_DATA_VIEW.getUint32(byteOffset, true);\n\nvar LE_HEAP_STORE_F32 = (byteOffset, value) => HEAP_DATA_VIEW.setFloat32(byteOffset, value, true);\n\nvar LE_HEAP_STORE_F64 = (byteOffset, value) => HEAP_DATA_VIEW.setFloat64(byteOffset, value, true);\n\nvar LE_HEAP_STORE_I16 = (byteOffset, value) => HEAP_DATA_VIEW.setInt16(byteOffset, value, true);\n\nvar LE_HEAP_STORE_I32 = (byteOffset, value) => HEAP_DATA_VIEW.setInt32(byteOffset, value, true);\n\nvar LE_HEAP_STORE_U16 = (byteOffset, value) => HEAP_DATA_VIEW.setUint16(byteOffset, value, true);\n\nvar LE_HEAP_STORE_U32 = (byteOffset, value) => HEAP_DATA_VIEW.setUint32(byteOffset, value, true);\n\nvar callRuntimeCallbacks = callbacks => {\n while (callbacks.length > 0) {\n // Pass the module as the first argument.\n callbacks.shift()(Module);\n }\n};\n\nvar onPostRuns = [];\n\nvar addOnPostRun = cb => onPostRuns.unshift(cb);\n\nvar onPreRuns = [];\n\nvar addOnPreRun = cb => onPreRuns.unshift(cb);\n\nvar UTF8Decoder = typeof TextDecoder != \"undefined\" ? new TextDecoder : undefined;\n\n/**\n * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given\n * array that contains uint8 values, returns a copy of that string as a\n * Javascript String object.\n * heapOrArray is either a regular array, or a JavaScript typed array view.\n * @param {number=} idx\n * @param {number=} maxBytesToRead\n * @return {string}\n */ var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead = NaN) => {\n var endIdx = idx + maxBytesToRead;\n var endPtr = idx;\n // TextDecoder needs to know the byte length in advance, it doesn't stop on\n // null terminator by itself. Also, use the length info to avoid running tiny\n // strings through TextDecoder, since .subarray() allocates garbage.\n // (As a tiny code save trick, compare endPtr against endIdx using a negation,\n // so that undefined/NaN means Infinity)\n while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;\n if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {\n return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));\n }\n var str = \"\";\n // If building with TextDecoder, we have already computed the string length\n // above, so test loop end condition against that\n while (idx < endPtr) {\n // For UTF8 byte structure, see:\n // http://en.wikipedia.org/wiki/UTF-8#Description\n // https://www.ietf.org/rfc/rfc2279.txt\n // https://tools.ietf.org/html/rfc3629\n var u0 = heapOrArray[idx++];\n if (!(u0 & 128)) {\n str += String.fromCharCode(u0);\n continue;\n }\n var u1 = heapOrArray[idx++] & 63;\n if ((u0 & 224) == 192) {\n str += String.fromCharCode(((u0 & 31) << 6) | u1);\n continue;\n }\n var u2 = heapOrArray[idx++] & 63;\n if ((u0 & 240) == 224) {\n u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;\n } else {\n u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63);\n }\n if (u0 < 65536) {\n str += String.fromCharCode(u0);\n } else {\n var ch = u0 - 65536;\n str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023));\n }\n }\n return str;\n};\n\nvar getDylinkMetadata = binary => {\n var offset = 0;\n var end = 0;\n function getU8() {\n return binary[offset++];\n }\n function getLEB() {\n var ret = 0;\n var mul = 1;\n while (1) {\n var byte = binary[offset++];\n ret += ((byte & 127) * mul);\n mul *= 128;\n if (!(byte & 128)) break;\n }\n return ret;\n }\n function getString() {\n var len = getLEB();\n offset += len;\n return UTF8ArrayToString(binary, offset - len, len);\n }\n /** @param {string=} message */ function failIf(condition, message) {\n if (condition) throw new Error(message);\n }\n var name = \"dylink.0\";\n if (binary instanceof WebAssembly.Module) {\n var dylinkSection = WebAssembly.Module.customSections(binary, name);\n if (dylinkSection.length === 0) {\n name = \"dylink\";\n dylinkSection = WebAssembly.Module.customSections(binary, name);\n }\n failIf(dylinkSection.length === 0, \"need dylink section\");\n binary = new Uint8Array(dylinkSection[0]);\n end = binary.length;\n } else {\n var int32View = new Uint32Array(new Uint8Array(binary.subarray(0, 24)).buffer);\n var magicNumberFound = int32View[0] == 1836278016 || int32View[0] == 6386541;\n failIf(!magicNumberFound, \"need to see wasm magic number\");\n // \\0asm\n // we should see the dylink custom section right after the magic number and wasm version\n failIf(binary[8] !== 0, \"need the dylink section to be first\");\n offset = 9;\n var section_size = getLEB();\n //section size\n end = offset + section_size;\n name = getString();\n }\n var customSection = {\n neededDynlibs: [],\n tlsExports: new Set,\n weakImports: new Set\n };\n if (name == \"dylink\") {\n customSection.memorySize = getLEB();\n customSection.memoryAlign = getLEB();\n customSection.tableSize = getLEB();\n customSection.tableAlign = getLEB();\n // shared libraries this module needs. We need to load them first, so that\n // current module could resolve its imports. (see tools/shared.py\n // WebAssembly.make_shared_library() for \"dylink\" section extension format)\n var neededDynlibsCount = getLEB();\n for (var i = 0; i < neededDynlibsCount; ++i) {\n var libname = getString();\n customSection.neededDynlibs.push(libname);\n }\n } else {\n failIf(name !== \"dylink.0\");\n var WASM_DYLINK_MEM_INFO = 1;\n var WASM_DYLINK_NEEDED = 2;\n var WASM_DYLINK_EXPORT_INFO = 3;\n var WASM_DYLINK_IMPORT_INFO = 4;\n var WASM_SYMBOL_TLS = 256;\n var WASM_SYMBOL_BINDING_MASK = 3;\n var WASM_SYMBOL_BINDING_WEAK = 1;\n while (offset < end) {\n var subsectionType = getU8();\n var subsectionSize = getLEB();\n if (subsectionType === WASM_DYLINK_MEM_INFO) {\n customSection.memorySize = getLEB();\n customSection.memoryAlign = getLEB();\n customSection.tableSize = getLEB();\n customSection.tableAlign = getLEB();\n } else if (subsectionType === WASM_DYLINK_NEEDED) {\n var neededDynlibsCount = getLEB();\n for (var i = 0; i < neededDynlibsCount; ++i) {\n libname = getString();\n customSection.neededDynlibs.push(libname);\n }\n } else if (subsectionType === WASM_DYLINK_EXPORT_INFO) {\n var count = getLEB();\n while (count--) {\n var symname = getString();\n var flags = getLEB();\n if (flags & WASM_SYMBOL_TLS) {\n customSection.tlsExports.add(symname);\n }\n }\n } else if (subsectionType === WASM_DYLINK_IMPORT_INFO) {\n var count = getLEB();\n while (count--) {\n var modname = getString();\n var symname = getString();\n var flags = getLEB();\n if ((flags & WASM_SYMBOL_BINDING_MASK) == WASM_SYMBOL_BINDING_WEAK) {\n customSection.weakImports.add(symname);\n }\n }\n } else {\n // unknown subsection\n offset += subsectionSize;\n }\n }\n }\n return customSection;\n};\n\n/**\n * @param {number} ptr\n * @param {string} type\n */ function getValue(ptr, type = \"i8\") {\n if (type.endsWith(\"*\")) type = \"*\";\n switch (type) {\n case \"i1\":\n return HEAP8[ptr];\n\n case \"i8\":\n return HEAP8[ptr];\n\n case \"i16\":\n return LE_HEAP_LOAD_I16(((ptr) >> 1) * 2);\n\n case \"i32\":\n return LE_HEAP_LOAD_I32(((ptr) >> 2) * 4);\n\n case \"i64\":\n return HEAP64[((ptr) >> 3)];\n\n case \"float\":\n return LE_HEAP_LOAD_F32(((ptr) >> 2) * 4);\n\n case \"double\":\n return LE_HEAP_LOAD_F64(((ptr) >> 3) * 8);\n\n case \"*\":\n return LE_HEAP_LOAD_U32(((ptr) >> 2) * 4);\n\n default:\n abort(`invalid type for getValue: ${type}`);\n }\n}\n\nvar newDSO = (name, handle, syms) => {\n var dso = {\n refcount: Infinity,\n name,\n exports: syms,\n global: true\n };\n LDSO.loadedLibsByName[name] = dso;\n if (handle != undefined) {\n LDSO.loadedLibsByHandle[handle] = dso;\n }\n return dso;\n};\n\nvar LDSO = {\n loadedLibsByName: {},\n loadedLibsByHandle: {},\n init() {\n newDSO(\"__main__\", 0, wasmImports);\n }\n};\n\nvar ___heap_base = 78224;\n\nvar alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment;\n\nvar getMemory = size => {\n // After the runtime is initialized, we must only use sbrk() normally.\n if (runtimeInitialized) {\n // Currently we don't support freeing of static data when modules are\n // unloaded via dlclose. This function is tagged as `noleakcheck` to\n // avoid having this reported as leak.\n return _calloc(size, 1);\n }\n var ret = ___heap_base;\n // Keep __heap_base stack aligned.\n var end = ret + alignMemory(size, 16);\n ___heap_base = end;\n GOT[\"__heap_base\"].value = end;\n return ret;\n};\n\nvar isInternalSym = symName => [ \"__cpp_exception\", \"__c_longjmp\", \"__wasm_apply_data_relocs\", \"__dso_handle\", \"__tls_size\", \"__tls_align\", \"__set_stack_limits\", \"_emscripten_tls_init\", \"__wasm_init_tls\", \"__wasm_call_ctors\", \"__start_em_asm\", \"__stop_em_asm\", \"__start_em_js\", \"__stop_em_js\" ].includes(symName) || symName.startsWith(\"__em_js__\");\n\nvar uleb128Encode = (n, target) => {\n if (n < 128) {\n target.push(n);\n } else {\n target.push((n % 128) | 128, n >> 7);\n }\n};\n\nvar sigToWasmTypes = sig => {\n var typeNames = {\n \"i\": \"i32\",\n \"j\": \"i64\",\n \"f\": \"f32\",\n \"d\": \"f64\",\n \"e\": \"externref\",\n \"p\": \"i32\"\n };\n var type = {\n parameters: [],\n results: sig[0] == \"v\" ? [] : [ typeNames[sig[0]] ]\n };\n for (var i = 1; i < sig.length; ++i) {\n type.parameters.push(typeNames[sig[i]]);\n }\n return type;\n};\n\nvar generateFuncType = (sig, target) => {\n var sigRet = sig.slice(0, 1);\n var sigParam = sig.slice(1);\n var typeCodes = {\n \"i\": 127,\n // i32\n \"p\": 127,\n // i32\n \"j\": 126,\n // i64\n \"f\": 125,\n // f32\n \"d\": 124,\n // f64\n \"e\": 111\n };\n // Parameters, length + signatures\n target.push(96);\n uleb128Encode(sigParam.length, target);\n for (var i = 0; i < sigParam.length; ++i) {\n target.push(typeCodes[sigParam[i]]);\n }\n // Return values, length + signatures\n // With no multi-return in MVP, either 0 (void) or 1 (anything else)\n if (sigRet == \"v\") {\n target.push(0);\n } else {\n target.push(1, typeCodes[sigRet]);\n }\n};\n\nvar convertJsFunctionToWasm = (func, sig) => {\n // If the type reflection proposal is available, use the new\n // \"WebAssembly.Function\" constructor.\n // Otherwise, construct a minimal wasm module importing the JS function and\n // re-exporting it.\n if (typeof WebAssembly.Function == \"function\") {\n return new WebAssembly.Function(sigToWasmTypes(sig), func);\n }\n // The module is static, with the exception of the type section, which is\n // generated based on the signature passed in.\n var typeSectionBody = [ 1 ];\n generateFuncType(sig, typeSectionBody);\n // Rest of the module is static\n var bytes = [ 0, 97, 115, 109, // magic (\"\\0asm\")\n 1, 0, 0, 0, // version: 1\n 1 ];\n // Write the overall length of the type section followed by the body\n uleb128Encode(typeSectionBody.length, bytes);\n bytes.push(...typeSectionBody);\n // The rest of the module is static\n bytes.push(2, 7, // import section\n // (import \"e\" \"f\" (func 0 (type 0)))\n 1, 1, 101, 1, 102, 0, 0, 7, 5, // export section\n // (export \"f\" (func 0 (type 0)))\n 1, 1, 102, 0, 0);\n // We can compile this wasm module synchronously because it is very small.\n // This accepts an import (at \"e.f\"), that it reroutes to an export (at \"f\")\n var module = new WebAssembly.Module(new Uint8Array(bytes));\n var instance = new WebAssembly.Instance(module, {\n \"e\": {\n \"f\": func\n }\n });\n var wrappedFunc = instance.exports[\"f\"];\n return wrappedFunc;\n};\n\nvar wasmTableMirror = [];\n\n/** @type {WebAssembly.Table} */ var wasmTable = new WebAssembly.Table({\n \"initial\": 31,\n \"element\": \"anyfunc\"\n});\n\nvar getWasmTableEntry = funcPtr => {\n var func = wasmTableMirror[funcPtr];\n if (!func) {\n if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1;\n /** @suppress {checkTypes} */ wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);\n }\n return func;\n};\n\nvar updateTableMap = (offset, count) => {\n if (functionsInTableMap) {\n for (var i = offset; i < offset + count; i++) {\n var item = getWasmTableEntry(i);\n // Ignore null values.\n if (item) {\n functionsInTableMap.set(item, i);\n }\n }\n }\n};\n\nvar functionsInTableMap;\n\nvar getFunctionAddress = func => {\n // First, create the map if this is the first use.\n if (!functionsInTableMap) {\n functionsInTableMap = new WeakMap;\n updateTableMap(0, wasmTable.length);\n }\n return functionsInTableMap.get(func) || 0;\n};\n\nvar freeTableIndexes = [];\n\nvar getEmptyTableSlot = () => {\n // Reuse a free index if there is one, otherwise grow.\n if (freeTableIndexes.length) {\n return freeTableIndexes.pop();\n }\n // Grow the table\n try {\n /** @suppress {checkTypes} */ wasmTable.grow(1);\n } catch (err) {\n if (!(err instanceof RangeError)) {\n throw err;\n }\n throw \"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.\";\n }\n return wasmTable.length - 1;\n};\n\nvar setWasmTableEntry = (idx, func) => {\n /** @suppress {checkTypes} */ wasmTable.set(idx, func);\n // With ABORT_ON_WASM_EXCEPTIONS wasmTable.get is overridden to return wrapped\n // functions so we need to call it here to retrieve the potential wrapper correctly\n // instead of just storing 'func' directly into wasmTableMirror\n /** @suppress {checkTypes} */ wasmTableMirror[idx] = wasmTable.get(idx);\n};\n\n/** @param {string=} sig */ var addFunction = (func, sig) => {\n // Check if the function is already in the table, to ensure each function\n // gets a unique index.\n var rtn = getFunctionAddress(func);\n if (rtn) {\n return rtn;\n }\n // It's not in the table, add it now.\n var ret = getEmptyTableSlot();\n // Set the new value.\n try {\n // Attempting to call this with JS function will cause of table.set() to fail\n setWasmTableEntry(ret, func);\n } catch (err) {\n if (!(err instanceof TypeError)) {\n throw err;\n }\n var wrapped = convertJsFunctionToWasm(func, sig);\n setWasmTableEntry(ret, wrapped);\n }\n functionsInTableMap.set(func, ret);\n return ret;\n};\n\nvar updateGOT = (exports, replace) => {\n for (var symName in exports) {\n if (isInternalSym(symName)) {\n continue;\n }\n var value = exports[symName];\n GOT[symName] ||= new WebAssembly.Global({\n \"value\": \"i32\",\n \"mutable\": true\n });\n if (replace || GOT[symName].value == 0) {\n if (typeof value == \"function\") {\n GOT[symName].value = addFunction(value);\n } else if (typeof value == \"number\") {\n GOT[symName].value = value;\n } else {\n err(`unhandled export type for '${symName}': ${typeof value}`);\n }\n }\n }\n};\n\n/** @param {boolean=} replace */ var relocateExports = (exports, memoryBase, replace) => {\n var relocated = {};\n for (var e in exports) {\n var value = exports[e];\n if (typeof value == \"object\") {\n // a breaking change in the wasm spec, globals are now objects\n // https://github.com/WebAssembly/mutable-global/issues/1\n value = value.value;\n }\n if (typeof value == \"number\") {\n value += memoryBase;\n }\n relocated[e] = value;\n }\n updateGOT(relocated, replace);\n return relocated;\n};\n\nvar isSymbolDefined = symName => {\n // Ignore 'stub' symbols that are auto-generated as part of the original\n // `wasmImports` used to instantiate the main module.\n var existing = wasmImports[symName];\n if (!existing || existing.stub) {\n return false;\n }\n return true;\n};\n\nvar dynCall = (sig, ptr, args = []) => {\n var rtn = getWasmTableEntry(ptr)(...args);\n return rtn;\n};\n\nvar stackSave = () => _emscripten_stack_get_current();\n\nvar stackRestore = val => __emscripten_stack_restore(val);\n\nvar createInvokeFunction = sig => (ptr, ...args) => {\n var sp = stackSave();\n try {\n return dynCall(sig, ptr, args);\n } catch (e) {\n stackRestore(sp);\n // Create a try-catch guard that rethrows the Emscripten EH exception.\n // Exceptions thrown from C++ will be a pointer (number) and longjmp\n // will throw the number Infinity. Use the compact and fast \"e !== e+0\"\n // test to check if e was not a Number.\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n // In theory this if statement could be done on\n // creating the function, but I just added this to\n // save wasting code space as it only happens on exception.\n if (sig[0] == \"j\") return 0n;\n }\n};\n\nvar resolveGlobalSymbol = (symName, direct = false) => {\n var sym;\n if (isSymbolDefined(symName)) {\n sym = wasmImports[symName];\n } else if (symName.startsWith(\"invoke_\")) {\n // Create (and cache) new invoke_ functions on demand.\n sym = wasmImports[symName] = createInvokeFunction(symName.split(\"_\")[1]);\n }\n return {\n sym,\n name: symName\n };\n};\n\nvar onPostCtors = [];\n\nvar addOnPostCtor = cb => onPostCtors.unshift(cb);\n\n/**\n * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the\n * emscripten HEAP, returns a copy of that string as a Javascript String object.\n *\n * @param {number} ptr\n * @param {number=} maxBytesToRead - An optional length that specifies the\n * maximum number of bytes to read. You can omit this parameter to scan the\n * string until the first 0 byte. If maxBytesToRead is passed, and the string\n * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the\n * string will cut short at that byte index (i.e. maxBytesToRead will not\n * produce a string of exact length [ptr, ptr+maxBytesToRead[) N.B. mixing\n * frequent uses of UTF8ToString() with and without maxBytesToRead may throw\n * JS JIT optimizations off, so it is worth to consider consistently using one\n * @return {string}\n */ var UTF8ToString = (ptr, maxBytesToRead) => ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : \"\";\n\n/**\n * @param {string=} libName\n * @param {Object=} localScope\n * @param {number=} handle\n */ var loadWebAssemblyModule = (binary, flags, libName, localScope, handle) => {\n var metadata = getDylinkMetadata(binary);\n currentModuleWeakSymbols = metadata.weakImports;\n // loadModule loads the wasm module after all its dependencies have been loaded.\n // can be called both sync/async.\n function loadModule() {\n // alignments are powers of 2\n var memAlign = Math.pow(2, metadata.memoryAlign);\n // prepare memory\n var memoryBase = metadata.memorySize ? alignMemory(getMemory(metadata.memorySize + memAlign), memAlign) : 0;\n // TODO: add to cleanups\n var tableBase = metadata.tableSize ? wasmTable.length : 0;\n if (handle) {\n HEAP8[(handle) + (8)] = 1;\n LE_HEAP_STORE_U32((((handle) + (12)) >> 2) * 4, memoryBase);\n LE_HEAP_STORE_I32((((handle) + (16)) >> 2) * 4, metadata.memorySize);\n LE_HEAP_STORE_U32((((handle) + (20)) >> 2) * 4, tableBase);\n LE_HEAP_STORE_I32((((handle) + (24)) >> 2) * 4, metadata.tableSize);\n }\n if (metadata.tableSize) {\n wasmTable.grow(metadata.tableSize);\n }\n // This is the export map that we ultimately return. We declare it here\n // so it can be used within resolveSymbol. We resolve symbols against\n // this local symbol map in the case there they are not present on the\n // global Module object. We need this fallback because Modules sometime\n // need to import their own symbols\n var moduleExports;\n function resolveSymbol(sym) {\n var resolved = resolveGlobalSymbol(sym).sym;\n if (!resolved && localScope) {\n resolved = localScope[sym];\n }\n if (!resolved) {\n resolved = moduleExports[sym];\n }\n return resolved;\n }\n // TODO kill \u2193\u2193\u2193 (except \"symbols local to this module\", it will likely be\n // not needed if we require that if A wants symbols from B it has to link\n // to B explicitly: similarly to -Wl,--no-undefined)\n // wasm dynamic libraries are pure wasm, so they cannot assist in\n // their own loading. When side module A wants to import something\n // provided by a side module B that is loaded later, we need to\n // add a layer of indirection, but worse, we can't even tell what\n // to add the indirection for, without inspecting what A's imports\n // are. To do that here, we use a JS proxy (another option would\n // be to inspect the binary directly).\n var proxyHandler = {\n get(stubs, prop) {\n // symbols that should be local to this module\n switch (prop) {\n case \"__memory_base\":\n return memoryBase;\n\n case \"__table_base\":\n return tableBase;\n }\n if (prop in wasmImports && !wasmImports[prop].stub) {\n // No stub needed, symbol already exists in symbol table\n var res = wasmImports[prop];\n return res;\n }\n // Return a stub function that will resolve the symbol\n // when first called.\n if (!(prop in stubs)) {\n var resolved;\n stubs[prop] = (...args) => {\n resolved ||= resolveSymbol(prop);\n return resolved(...args);\n };\n }\n return stubs[prop];\n }\n };\n var proxy = new Proxy({}, proxyHandler);\n var info = {\n \"GOT.mem\": new Proxy({}, GOTHandler),\n \"GOT.func\": new Proxy({}, GOTHandler),\n \"env\": proxy,\n \"wasi_snapshot_preview1\": proxy\n };\n function postInstantiation(module, instance) {\n // add new entries to functionsInTableMap\n updateTableMap(tableBase, metadata.tableSize);\n moduleExports = relocateExports(instance.exports, memoryBase);\n if (!flags.allowUndefined) {\n reportUndefinedSymbols();\n }\n function addEmAsm(addr, body) {\n var args = [];\n var arity = 0;\n for (;arity < 16; arity++) {\n if (body.indexOf(\"$\" + arity) != -1) {\n args.push(\"$\" + arity);\n } else {\n break;\n }\n }\n args = args.join(\",\");\n var func = `(${args}) => { ${body} };`;\n ASM_CONSTS[start] = eval(func);\n }\n // Add any EM_ASM function that exist in the side module\n if (\"__start_em_asm\" in moduleExports) {\n var start = moduleExports[\"__start_em_asm\"];\n var stop = moduleExports[\"__stop_em_asm\"];\n while (start < stop) {\n var jsString = UTF8ToString(start);\n addEmAsm(start, jsString);\n start = HEAPU8.indexOf(0, start) + 1;\n }\n }\n function addEmJs(name, cSig, body) {\n // The signature here is a C signature (e.g. \"(int foo, char* bar)\").\n // See `create_em_js` in emcc.py` for the build-time version of this\n // code.\n var jsArgs = [];\n cSig = cSig.slice(1, -1);\n if (cSig != \"void\") {\n cSig = cSig.split(\",\");\n for (var i in cSig) {\n var jsArg = cSig[i].split(\" \").pop();\n jsArgs.push(jsArg.replace(\"*\", \"\"));\n }\n }\n var func = `(${jsArgs}) => ${body};`;\n moduleExports[name] = eval(func);\n }\n for (var name in moduleExports) {\n if (name.startsWith(\"__em_js__\")) {\n var start = moduleExports[name];\n var jsString = UTF8ToString(start);\n // EM_JS strings are stored in the data section in the form\n // SIG<::>BODY.\n var parts = jsString.split(\"<::>\");\n addEmJs(name.replace(\"__em_js__\", \"\"), parts[0], parts[1]);\n delete moduleExports[name];\n }\n }\n // initialize the module\n var applyRelocs = moduleExports[\"__wasm_apply_data_relocs\"];\n if (applyRelocs) {\n if (runtimeInitialized) {\n applyRelocs();\n } else {\n __RELOC_FUNCS__.push(applyRelocs);\n }\n }\n var init = moduleExports[\"__wasm_call_ctors\"];\n if (init) {\n if (runtimeInitialized) {\n init();\n } else {\n // we aren't ready to run compiled code yet\n addOnPostCtor(init);\n }\n }\n return moduleExports;\n }\n if (flags.loadAsync) {\n if (binary instanceof WebAssembly.Module) {\n var instance = new WebAssembly.Instance(binary, info);\n return Promise.resolve(postInstantiation(binary, instance));\n }\n return WebAssembly.instantiate(binary, info).then(result => postInstantiation(result.module, result.instance));\n }\n var module = binary instanceof WebAssembly.Module ? binary : new WebAssembly.Module(binary);\n var instance = new WebAssembly.Instance(module, info);\n return postInstantiation(module, instance);\n }\n // now load needed libraries and the module itself.\n if (flags.loadAsync) {\n return metadata.neededDynlibs.reduce((chain, dynNeeded) => chain.then(() => loadDynamicLibrary(dynNeeded, flags, localScope)), Promise.resolve()).then(loadModule);\n }\n metadata.neededDynlibs.forEach(needed => loadDynamicLibrary(needed, flags, localScope));\n return loadModule();\n};\n\nvar mergeLibSymbols = (exports, libName) => {\n // add symbols into global namespace TODO: weak linking etc.\n for (var [sym, exp] of Object.entries(exports)) {\n // When RTLD_GLOBAL is enabled, the symbols defined by this shared object\n // will be made available for symbol resolution of subsequently loaded\n // shared objects.\n // We should copy the symbols (which include methods and variables) from\n // SIDE_MODULE to MAIN_MODULE.\n const setImport = target => {\n if (!isSymbolDefined(target)) {\n wasmImports[target] = exp;\n }\n };\n setImport(sym);\n // Special case for handling of main symbol: If a side module exports\n // `main` that also acts a definition for `__main_argc_argv` and vice\n // versa.\n const main_alias = \"__main_argc_argv\";\n if (sym == \"main\") {\n setImport(main_alias);\n }\n if (sym == main_alias) {\n setImport(\"main\");\n }\n }\n};\n\nvar asyncLoad = async url => {\n var arrayBuffer = await readAsync(url);\n return new Uint8Array(arrayBuffer);\n};\n\n/**\n * @param {number=} handle\n * @param {Object=} localScope\n */ function loadDynamicLibrary(libName, flags = {\n global: true,\n nodelete: true\n}, localScope, handle) {\n // when loadDynamicLibrary did not have flags, libraries were loaded\n // globally & permanently\n var dso = LDSO.loadedLibsByName[libName];\n if (dso) {\n // the library is being loaded or has been loaded already.\n if (!flags.global) {\n if (localScope) {\n Object.assign(localScope, dso.exports);\n }\n } else if (!dso.global) {\n // The library was previously loaded only locally but not\n // we have a request with global=true.\n dso.global = true;\n mergeLibSymbols(dso.exports, libNam