blob: 626ff70b309987069599a56555d88572c2871b7d [file] [log] [blame]
swissChiliab615d82024-03-08 17:15:13 -05001var createMyModule = (() => {
swissChili281af442024-11-14 23:30:29 -05002 var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;
3 if (typeof __filename != 'undefined') _scriptName ||= __filename;
swissChiliab615d82024-03-08 17:15:13 -05004 return (
5 function(moduleArg = {}) {
swissChili281af442024-11-14 23:30:29 -05006 var moduleRtn;
7
swissChiliab615d82024-03-08 17:15:13 -05008 var Module = moduleArg;
9 var readyPromiseResolve, readyPromiseReject;
swissChili281af442024-11-14 23:30:29 -050010 var readyPromise = new Promise((resolve, reject) => {
swissChiliab615d82024-03-08 17:15:13 -050011 readyPromiseResolve = resolve;
12 readyPromiseReject = reject
13 });
swissChili281af442024-11-14 23:30:29 -050014 ["_test_int", "_do_a_conversion", "_memory", "___indirect_function_table", "onRuntimeInitialized"].forEach(prop => {
15 if (!Object.getOwnPropertyDescriptor(readyPromise, prop)) {
16 Object.defineProperty(readyPromise, prop, {
17 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"),
18 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")
19 })
20 }
21 });
22 var ENVIRONMENT_IS_WEB = typeof window == "object";
23 var ENVIRONMENT_IS_WORKER = typeof importScripts == "function";
24 var ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string";
25 var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
26 if (Module["ENVIRONMENT"]) {
27 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)")
swissChiliab615d82024-03-08 17:15:13 -050028 }
swissChili281af442024-11-14 23:30:29 -050029 if (ENVIRONMENT_IS_NODE) {}
30 if (!Module["expectedDataFileDownloads"]) {
31 Module["expectedDataFileDownloads"] = 0
32 }
33 Module["expectedDataFileDownloads"]++;
34 (() => {
35 var isPthread = typeof ENVIRONMENT_IS_PTHREAD != "undefined" && ENVIRONMENT_IS_PTHREAD;
36 var isWasmWorker = typeof ENVIRONMENT_IS_WASM_WORKER != "undefined" && ENVIRONMENT_IS_WASM_WORKER;
37 if (isPthread || isWasmWorker) return;
38
39 function loadPackage(metadata) {
swissChiliab615d82024-03-08 17:15:13 -050040 var PACKAGE_PATH = "";
41 if (typeof window === "object") {
42 PACKAGE_PATH = window["encodeURIComponent"](window.location.pathname.toString().substring(0, window.location.pathname.toString().lastIndexOf("/")) + "/")
43 } else if (typeof process === "undefined" && typeof location !== "undefined") {
44 PACKAGE_PATH = encodeURIComponent(location.pathname.toString().substring(0, location.pathname.toString().lastIndexOf("/")) + "/")
45 }
46 var PACKAGE_NAME = "units.lib.data";
47 var REMOTE_PACKAGE_BASE = "units.lib.data";
48 if (typeof Module["locateFilePackage"] === "function" && !Module["locateFile"]) {
49 Module["locateFile"] = Module["locateFilePackage"];
50 err("warning: you defined Module.locateFilePackage, that has been renamed to Module.locateFile (using your locateFilePackage for now)")
51 }
52 var REMOTE_PACKAGE_NAME = Module["locateFile"] ? Module["locateFile"](REMOTE_PACKAGE_BASE, "") : REMOTE_PACKAGE_BASE;
53 var REMOTE_PACKAGE_SIZE = metadata["remote_package_size"];
54
55 function fetchRemotePackage(packageName, packageSize, callback, errback) {
56 if (typeof process === "object" && typeof process.versions === "object" && typeof process.versions.node === "string") {
swissChili281af442024-11-14 23:30:29 -050057 require("fs").readFile(packageName, (err, contents) => {
swissChiliab615d82024-03-08 17:15:13 -050058 if (err) {
59 errback(err)
60 } else {
61 callback(contents.buffer)
62 }
63 });
64 return
65 }
66 var xhr = new XMLHttpRequest;
67 xhr.open("GET", packageName, true);
68 xhr.responseType = "arraybuffer";
swissChili281af442024-11-14 23:30:29 -050069 xhr.onprogress = event => {
swissChiliab615d82024-03-08 17:15:13 -050070 var url = packageName;
71 var size = packageSize;
72 if (event.total) size = event.total;
73 if (event.loaded) {
74 if (!xhr.addedTotal) {
75 xhr.addedTotal = true;
swissChili281af442024-11-14 23:30:29 -050076 if (!Module["dataFileDownloads"]) Module["dataFileDownloads"] = {};
77 Module["dataFileDownloads"][url] = {
swissChiliab615d82024-03-08 17:15:13 -050078 loaded: event.loaded,
79 total: size
80 }
81 } else {
swissChili281af442024-11-14 23:30:29 -050082 Module["dataFileDownloads"][url].loaded = event.loaded
swissChiliab615d82024-03-08 17:15:13 -050083 }
84 var total = 0;
85 var loaded = 0;
86 var num = 0;
swissChili281af442024-11-14 23:30:29 -050087 for (var download in Module["dataFileDownloads"]) {
88 var data = Module["dataFileDownloads"][download];
swissChiliab615d82024-03-08 17:15:13 -050089 total += data.total;
90 loaded += data.loaded;
91 num++
92 }
swissChili281af442024-11-14 23:30:29 -050093 total = Math.ceil(total * Module["expectedDataFileDownloads"] / num);
94 Module["setStatus"]?.(`Downloading data... (${loaded}/${total})`)
95 } else if (!Module["dataFileDownloads"]) {
96 Module["setStatus"]?.("Downloading data...")
swissChiliab615d82024-03-08 17:15:13 -050097 }
98 };
swissChili281af442024-11-14 23:30:29 -050099 xhr.onerror = event => {
swissChiliab615d82024-03-08 17:15:13 -0500100 throw new Error("NetworkError for: " + packageName)
101 };
swissChili281af442024-11-14 23:30:29 -0500102 xhr.onload = event => {
swissChiliab615d82024-03-08 17:15:13 -0500103 if (xhr.status == 200 || xhr.status == 304 || xhr.status == 206 || xhr.status == 0 && xhr.response) {
104 var packageData = xhr.response;
105 callback(packageData)
106 } else {
107 throw new Error(xhr.statusText + " : " + xhr.responseURL)
108 }
109 };
110 xhr.send(null)
111 }
112
113 function handleError(error) {
114 console.error("package error:", error)
115 }
116 var fetchedCallback = null;
117 var fetched = Module["getPreloadedPackage"] ? Module["getPreloadedPackage"](REMOTE_PACKAGE_NAME, REMOTE_PACKAGE_SIZE) : null;
swissChili281af442024-11-14 23:30:29 -0500118 if (!fetched) fetchRemotePackage(REMOTE_PACKAGE_NAME, REMOTE_PACKAGE_SIZE, data => {
swissChiliab615d82024-03-08 17:15:13 -0500119 if (fetchedCallback) {
120 fetchedCallback(data);
121 fetchedCallback = null
122 } else {
123 fetched = data
124 }
125 }, handleError);
126
swissChili281af442024-11-14 23:30:29 -0500127 function runWithFS(Module) {
swissChiliab615d82024-03-08 17:15:13 -0500128 function assert(check, msg) {
129 if (!check) throw msg + (new Error).stack
130 }
131
132 function DataRequest(start, end, audio) {
133 this.start = start;
134 this.end = end;
135 this.audio = audio
136 }
137 DataRequest.prototype = {
138 requests: {},
139 open: function(mode, name) {
140 this.name = name;
141 this.requests[name] = this;
142 Module["addRunDependency"](`fp ${this.name}`)
143 },
144 send: function() {},
145 onload: function() {
146 var byteArray = this.byteArray.subarray(this.start, this.end);
147 this.finish(byteArray)
148 },
149 finish: function(byteArray) {
150 var that = this;
151 Module["FS_createDataFile"](this.name, null, byteArray, true, true, true);
152 Module["removeRunDependency"](`fp ${that.name}`);
153 this.requests[this.name] = null
154 }
155 };
156 var files = metadata["files"];
157 for (var i = 0; i < files.length; ++i) {
158 new DataRequest(files[i]["start"], files[i]["end"], files[i]["audio"] || 0).open("GET", files[i]["filename"])
159 }
160
161 function processPackageData(arrayBuffer) {
162 assert(arrayBuffer, "Loading data file failed.");
163 assert(arrayBuffer.constructor.name === ArrayBuffer.name, "bad input to processPackageData");
164 var byteArray = new Uint8Array(arrayBuffer);
165 DataRequest.prototype.byteArray = byteArray;
166 var files = metadata["files"];
167 for (var i = 0; i < files.length; ++i) {
168 DataRequest.prototype.requests[files[i].filename].onload()
169 }
170 Module["removeRunDependency"]("datafile_units.lib.data")
171 }
172 Module["addRunDependency"]("datafile_units.lib.data");
swissChili281af442024-11-14 23:30:29 -0500173 if (!Module["preloadResults"]) Module["preloadResults"] = {};
174 Module["preloadResults"][PACKAGE_NAME] = {
swissChiliab615d82024-03-08 17:15:13 -0500175 fromCache: false
176 };
177 if (fetched) {
178 processPackageData(fetched);
179 fetched = null
180 } else {
181 fetchedCallback = processPackageData
182 }
183 }
184 if (Module["calledRun"]) {
swissChili281af442024-11-14 23:30:29 -0500185 runWithFS(Module)
swissChiliab615d82024-03-08 17:15:13 -0500186 } else {
187 if (!Module["preRun"]) Module["preRun"] = [];
188 Module["preRun"].push(runWithFS)
189 }
swissChili281af442024-11-14 23:30:29 -0500190 }
swissChiliab615d82024-03-08 17:15:13 -0500191 loadPackage({
swissChili281af442024-11-14 23:30:29 -0500192 files: [{
193 filename: "/cpi.units",
194 start: 0,
195 end: 44458
swissChiliab615d82024-03-08 17:15:13 -0500196 }, {
swissChili281af442024-11-14 23:30:29 -0500197 filename: "/currency.units",
198 start: 44458,
199 end: 59060
swissChiliab615d82024-03-08 17:15:13 -0500200 }, {
swissChili281af442024-11-14 23:30:29 -0500201 filename: "/definitions.units",
202 start: 59060,
203 end: 419653
swissChiliab615d82024-03-08 17:15:13 -0500204 }, {
swissChili281af442024-11-14 23:30:29 -0500205 filename: "/elements.units",
206 start: 419653,
207 end: 571034
swissChiliab615d82024-03-08 17:15:13 -0500208 }],
swissChili281af442024-11-14 23:30:29 -0500209 remote_package_size: 571034
swissChiliab615d82024-03-08 17:15:13 -0500210 })
211 })();
swissChili281af442024-11-14 23:30:29 -0500212 if (Module["$ww"] || typeof ENVIRONMENT_IS_PTHREAD != "undefined" && ENVIRONMENT_IS_PTHREAD) Module["preRun"] = [];
213 var necessaryPreJSTasks = Module["preRun"].slice();
214 if (!Module["preRun"]) throw "Module.preRun should exist because file support used it; did a pre-js delete it?";
215 necessaryPreJSTasks.forEach(task => {
216 if (Module["preRun"].indexOf(task) < 0) throw "All preRun tasks that exist before user pre-js code should remain after; did you replace Module or modify Module.preRun?"
217 });
swissChiliab615d82024-03-08 17:15:13 -0500218 var moduleOverrides = Object.assign({}, Module);
219 var arguments_ = [];
220 var thisProgram = "./this.program";
221 var quit_ = (status, toThrow) => {
222 throw toThrow
223 };
swissChiliab615d82024-03-08 17:15:13 -0500224 var scriptDirectory = "";
225
226 function locateFile(path) {
227 if (Module["locateFile"]) {
228 return Module["locateFile"](path, scriptDirectory)
229 }
230 return scriptDirectory + path
231 }
swissChili281af442024-11-14 23:30:29 -0500232 var readAsync, readBinary;
swissChiliab615d82024-03-08 17:15:13 -0500233 if (ENVIRONMENT_IS_NODE) {
swissChili281af442024-11-14 23:30:29 -0500234 if (typeof process == "undefined" || !process.release || process.release.name !== "node") 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?)");
235 var nodeVersion = process.versions.node;
236 var numericVersion = nodeVersion.split(".").slice(0, 3);
237 numericVersion = numericVersion[0] * 1e4 + numericVersion[1] * 100 + numericVersion[2].split("-")[0] * 1;
238 if (numericVersion < 16e4) {
239 throw new Error("This emscripten-generated code requires node v16.0.0 (detected v" + nodeVersion + ")")
240 }
swissChiliab615d82024-03-08 17:15:13 -0500241 var fs = require("fs");
242 var nodePath = require("path");
swissChili281af442024-11-14 23:30:29 -0500243 scriptDirectory = __dirname + "/";
swissChiliab615d82024-03-08 17:15:13 -0500244 readBinary = filename => {
swissChili281af442024-11-14 23:30:29 -0500245 filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
246 var ret = fs.readFileSync(filename);
247 assert(ret.buffer);
swissChiliab615d82024-03-08 17:15:13 -0500248 return ret
249 };
swissChili281af442024-11-14 23:30:29 -0500250 readAsync = (filename, binary = true) => {
swissChiliab615d82024-03-08 17:15:13 -0500251 filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
swissChili281af442024-11-14 23:30:29 -0500252 return new Promise((resolve, reject) => {
253 fs.readFile(filename, binary ? undefined : "utf8", (err, data) => {
254 if (err) reject(err);
255 else resolve(binary ? data.buffer : data)
256 })
swissChiliab615d82024-03-08 17:15:13 -0500257 })
258 };
259 if (!Module["thisProgram"] && process.argv.length > 1) {
260 thisProgram = process.argv[1].replace(/\\/g, "/")
261 }
262 arguments_ = process.argv.slice(2);
263 quit_ = (status, toThrow) => {
264 process.exitCode = status;
265 throw toThrow
266 }
swissChili281af442024-11-14 23:30:29 -0500267 } else if (ENVIRONMENT_IS_SHELL) {
268 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?)")
swissChiliab615d82024-03-08 17:15:13 -0500269 } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
270 if (ENVIRONMENT_IS_WORKER) {
271 scriptDirectory = self.location.href
272 } else if (typeof document != "undefined" && document.currentScript) {
273 scriptDirectory = document.currentScript.src
274 }
swissChili281af442024-11-14 23:30:29 -0500275 if (_scriptName) {
276 scriptDirectory = _scriptName
swissChiliab615d82024-03-08 17:15:13 -0500277 }
278 if (scriptDirectory.startsWith("blob:")) {
279 scriptDirectory = ""
280 } else {
281 scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1)
swissChili281af442024-11-14 23:30:29 -0500282 }
283 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?)");
284 {
swissChiliab615d82024-03-08 17:15:13 -0500285 if (ENVIRONMENT_IS_WORKER) {
286 readBinary = url => {
287 var xhr = new XMLHttpRequest;
288 xhr.open("GET", url, false);
289 xhr.responseType = "arraybuffer";
290 xhr.send(null);
291 return new Uint8Array(xhr.response)
292 }
293 }
swissChili281af442024-11-14 23:30:29 -0500294 readAsync = url => {
295 if (isFileURI(url)) {
296 return new Promise((resolve, reject) => {
297 var xhr = new XMLHttpRequest;
298 xhr.open("GET", url, true);
299 xhr.responseType = "arraybuffer";
300 xhr.onload = () => {
301 if (xhr.status == 200 || xhr.status == 0 && xhr.response) {
302 resolve(xhr.response);
303 return
304 }
305 reject(xhr.status)
306 };
307 xhr.onerror = reject;
308 xhr.send(null)
309 })
310 }
311 return fetch(url, {
312 credentials: "same-origin"
313 }).then(response => {
314 if (response.ok) {
315 return response.arrayBuffer()
swissChiliab615d82024-03-08 17:15:13 -0500316 }
swissChili281af442024-11-14 23:30:29 -0500317 return Promise.reject(new Error(response.status + " : " + response.url))
318 })
swissChiliab615d82024-03-08 17:15:13 -0500319 }
320 }
swissChili281af442024-11-14 23:30:29 -0500321 } else {
322 throw new Error("environment detection error")
323 }
swissChiliab615d82024-03-08 17:15:13 -0500324 var out = Module["print"] || console.log.bind(console);
325 var err = Module["printErr"] || console.error.bind(console);
326 Object.assign(Module, moduleOverrides);
327 moduleOverrides = null;
swissChili281af442024-11-14 23:30:29 -0500328 checkIncomingModuleAPI();
swissChiliab615d82024-03-08 17:15:13 -0500329 if (Module["arguments"]) arguments_ = Module["arguments"];
swissChili281af442024-11-14 23:30:29 -0500330 legacyModuleProp("arguments", "arguments_");
swissChiliab615d82024-03-08 17:15:13 -0500331 if (Module["thisProgram"]) thisProgram = Module["thisProgram"];
swissChili281af442024-11-14 23:30:29 -0500332 legacyModuleProp("thisProgram", "thisProgram");
333 assert(typeof Module["memoryInitializerPrefixURL"] == "undefined", "Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead");
334 assert(typeof Module["pthreadMainPrefixURL"] == "undefined", "Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead");
335 assert(typeof Module["cdInitializerPrefixURL"] == "undefined", "Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead");
336 assert(typeof Module["filePackagePrefixURL"] == "undefined", "Module.filePackagePrefixURL option was removed, use Module.locateFile instead");
337 assert(typeof Module["read"] == "undefined", "Module.read option was removed");
338 assert(typeof Module["readAsync"] == "undefined", "Module.readAsync option was removed (modify readAsync in JS)");
339 assert(typeof Module["readBinary"] == "undefined", "Module.readBinary option was removed (modify readBinary in JS)");
340 assert(typeof Module["setWindowTitle"] == "undefined", "Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)");
341 assert(typeof Module["TOTAL_MEMORY"] == "undefined", "Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY");
342 legacyModuleProp("asm", "wasmExports");
343 legacyModuleProp("readAsync", "readAsync");
344 legacyModuleProp("readBinary", "readBinary");
345 legacyModuleProp("setWindowTitle", "setWindowTitle");
346 assert(!ENVIRONMENT_IS_SHELL, "shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.");
347 var wasmBinary = Module["wasmBinary"];
348 legacyModuleProp("wasmBinary", "wasmBinary");
swissChiliab615d82024-03-08 17:15:13 -0500349 if (typeof WebAssembly != "object") {
swissChili281af442024-11-14 23:30:29 -0500350 err("no native wasm support detected")
351 }
352
353 function intArrayFromBase64(s) {
354 if (typeof ENVIRONMENT_IS_NODE != "undefined" && ENVIRONMENT_IS_NODE) {
355 var buf = Buffer.from(s, "base64");
356 return new Uint8Array(buf.buffer, buf.byteOffset, buf.length)
357 }
358 var decoded = atob(s);
359 var bytes = new Uint8Array(decoded.length);
360 for (var i = 0; i < decoded.length; ++i) {
361 bytes[i] = decoded.charCodeAt(i)
362 }
363 return bytes
swissChiliab615d82024-03-08 17:15:13 -0500364 }
365 var wasmMemory;
366 var ABORT = false;
367 var EXITSTATUS;
swissChili281af442024-11-14 23:30:29 -0500368
369 function assert(condition, text) {
370 if (!condition) {
371 abort("Assertion failed" + (text ? ": " + text : ""))
372 }
373 }
swissChiliab615d82024-03-08 17:15:13 -0500374 var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
375
376 function updateMemoryViews() {
377 var b = wasmMemory.buffer;
378 Module["HEAP8"] = HEAP8 = new Int8Array(b);
379 Module["HEAP16"] = HEAP16 = new Int16Array(b);
380 Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);
381 Module["HEAPU16"] = HEAPU16 = new Uint16Array(b);
382 Module["HEAP32"] = HEAP32 = new Int32Array(b);
383 Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);
384 Module["HEAPF32"] = HEAPF32 = new Float32Array(b);
385 Module["HEAPF64"] = HEAPF64 = new Float64Array(b)
386 }
swissChili281af442024-11-14 23:30:29 -0500387 assert(!Module["STACK_SIZE"], "STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time");
388 assert(typeof Int32Array != "undefined" && typeof Float64Array !== "undefined" && Int32Array.prototype.subarray != undefined && Int32Array.prototype.set != undefined, "JS engine does not provide full typed array support");
389 assert(!Module["wasmMemory"], "Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally");
390 assert(!Module["INITIAL_MEMORY"], "Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically");
391
392 function writeStackCookie() {
393 var max = _emscripten_stack_get_end();
394 assert((max & 3) == 0);
395 if (max == 0) {
396 max += 4
397 }
398 HEAPU32[max >> 2] = 34821223;
399 HEAPU32[max + 4 >> 2] = 2310721022;
400 HEAPU32[0 >> 2] = 1668509029
401 }
402
403 function checkStackCookie() {
404 if (ABORT) return;
405 var max = _emscripten_stack_get_end();
406 if (max == 0) {
407 max += 4
408 }
409 var cookie1 = HEAPU32[max >> 2];
410 var cookie2 = HEAPU32[max + 4 >> 2];
411 if (cookie1 != 34821223 || cookie2 != 2310721022) {
412 abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`)
413 }
414 if (HEAPU32[0 >> 2] != 1668509029) {
415 abort("Runtime error: The application has corrupted its heap memory area (address zero)!")
416 }
417 }
swissChiliab615d82024-03-08 17:15:13 -0500418 var __ATPRERUN__ = [];
419 var __ATINIT__ = [];
420 var __ATPOSTRUN__ = [];
421 var runtimeInitialized = false;
422
423 function preRun() {
424 if (Module["preRun"]) {
425 if (typeof Module["preRun"] == "function") Module["preRun"] = [Module["preRun"]];
426 while (Module["preRun"].length) {
427 addOnPreRun(Module["preRun"].shift())
428 }
429 }
430 callRuntimeCallbacks(__ATPRERUN__)
431 }
432
433 function initRuntime() {
swissChili281af442024-11-14 23:30:29 -0500434 assert(!runtimeInitialized);
swissChiliab615d82024-03-08 17:15:13 -0500435 runtimeInitialized = true;
swissChili281af442024-11-14 23:30:29 -0500436 checkStackCookie();
437 if (!Module["noFSInit"] && !FS.initialized) FS.init();
swissChiliab615d82024-03-08 17:15:13 -0500438 FS.ignorePermissions = false;
439 TTY.init();
440 callRuntimeCallbacks(__ATINIT__)
441 }
442
443 function postRun() {
swissChili281af442024-11-14 23:30:29 -0500444 checkStackCookie();
swissChiliab615d82024-03-08 17:15:13 -0500445 if (Module["postRun"]) {
446 if (typeof Module["postRun"] == "function") Module["postRun"] = [Module["postRun"]];
447 while (Module["postRun"].length) {
448 addOnPostRun(Module["postRun"].shift())
449 }
450 }
451 callRuntimeCallbacks(__ATPOSTRUN__)
452 }
453
454 function addOnPreRun(cb) {
455 __ATPRERUN__.unshift(cb)
456 }
457
458 function addOnInit(cb) {
459 __ATINIT__.unshift(cb)
460 }
461
462 function addOnPostRun(cb) {
463 __ATPOSTRUN__.unshift(cb)
464 }
swissChili281af442024-11-14 23:30:29 -0500465 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");
466 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");
467 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");
468 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");
swissChiliab615d82024-03-08 17:15:13 -0500469 var runDependencies = 0;
470 var runDependencyWatcher = null;
471 var dependenciesFulfilled = null;
swissChili281af442024-11-14 23:30:29 -0500472 var runDependencyTracking = {};
swissChiliab615d82024-03-08 17:15:13 -0500473
474 function getUniqueRunDependency(id) {
swissChili281af442024-11-14 23:30:29 -0500475 var orig = id;
476 while (1) {
477 if (!runDependencyTracking[id]) return id;
478 id = orig + Math.random()
479 }
swissChiliab615d82024-03-08 17:15:13 -0500480 }
481
482 function addRunDependency(id) {
483 runDependencies++;
swissChili281af442024-11-14 23:30:29 -0500484 Module["monitorRunDependencies"]?.(runDependencies);
485 if (id) {
486 assert(!runDependencyTracking[id]);
487 runDependencyTracking[id] = 1;
488 if (runDependencyWatcher === null && typeof setInterval != "undefined") {
489 runDependencyWatcher = setInterval(() => {
490 if (ABORT) {
491 clearInterval(runDependencyWatcher);
492 runDependencyWatcher = null;
493 return
494 }
495 var shown = false;
496 for (var dep in runDependencyTracking) {
497 if (!shown) {
498 shown = true;
499 err("still waiting on run dependencies:")
500 }
501 err(`dependency: ${dep}`)
502 }
503 if (shown) {
504 err("(end of list)")
505 }
506 }, 1e4)
507 }
508 } else {
509 err("warning: run dependency added without ID")
510 }
swissChiliab615d82024-03-08 17:15:13 -0500511 }
512
513 function removeRunDependency(id) {
514 runDependencies--;
515 Module["monitorRunDependencies"]?.(runDependencies);
swissChili281af442024-11-14 23:30:29 -0500516 if (id) {
517 assert(runDependencyTracking[id]);
518 delete runDependencyTracking[id]
519 } else {
520 err("warning: run dependency removed without ID")
521 }
swissChiliab615d82024-03-08 17:15:13 -0500522 if (runDependencies == 0) {
523 if (runDependencyWatcher !== null) {
524 clearInterval(runDependencyWatcher);
525 runDependencyWatcher = null
526 }
527 if (dependenciesFulfilled) {
528 var callback = dependenciesFulfilled;
529 dependenciesFulfilled = null;
530 callback()
531 }
532 }
533 }
534
535 function abort(what) {
536 Module["onAbort"]?.(what);
537 what = "Aborted(" + what + ")";
538 err(what);
539 ABORT = true;
540 EXITSTATUS = 1;
swissChili281af442024-11-14 23:30:29 -0500541 if (what.indexOf("RuntimeError: unreachable") >= 0) {
542 what += '. "unreachable" may be due to ASYNCIFY_STACK_SIZE not being large enough (try increasing it)'
543 }
swissChiliab615d82024-03-08 17:15:13 -0500544 var e = new WebAssembly.RuntimeError(what);
545 readyPromiseReject(e);
546 throw e
547 }
548 var dataURIPrefix = "data:application/octet-stream;base64,";
549 var isDataURI = filename => filename.startsWith(dataURIPrefix);
550 var isFileURI = filename => filename.startsWith("file://");
swissChili281af442024-11-14 23:30:29 -0500551
552 function createExportWrapper(name, nargs) {
553 return (...args) => {
554 assert(runtimeInitialized, `native function \`${name}\` called before runtime initialization`);
555 var f = wasmExports[name];
556 assert(f, `exported native function \`${name}\` not found`);
557 assert(args.length <= nargs, `native function \`${name}\` called with ${args.length} args but expects ${nargs}`);
558 return f(...args)
559 }
swissChiliab615d82024-03-08 17:15:13 -0500560 }
561
swissChili281af442024-11-14 23:30:29 -0500562 function findWasmBinary() {
563 var f = "units.lib.wasm";
564 if (!isDataURI(f)) {
565 return locateFile(f)
566 }
567 return f
568 }
569 var wasmBinaryFile;
570
swissChiliab615d82024-03-08 17:15:13 -0500571 function getBinarySync(file) {
572 if (file == wasmBinaryFile && wasmBinary) {
573 return new Uint8Array(wasmBinary)
574 }
575 if (readBinary) {
576 return readBinary(file)
577 }
578 throw "both async and sync fetching of the wasm failed"
579 }
580
581 function getBinaryPromise(binaryFile) {
swissChili281af442024-11-14 23:30:29 -0500582 if (!wasmBinary) {
583 return readAsync(binaryFile).then(response => new Uint8Array(response), () => getBinarySync(binaryFile))
swissChiliab615d82024-03-08 17:15:13 -0500584 }
585 return Promise.resolve().then(() => getBinarySync(binaryFile))
586 }
587
588 function instantiateArrayBuffer(binaryFile, imports, receiver) {
589 return getBinaryPromise(binaryFile).then(binary => WebAssembly.instantiate(binary, imports)).then(receiver, reason => {
590 err(`failed to asynchronously prepare wasm: ${reason}`);
swissChili281af442024-11-14 23:30:29 -0500591 if (isFileURI(wasmBinaryFile)) {
592 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`)
593 }
swissChiliab615d82024-03-08 17:15:13 -0500594 abort(reason)
595 })
596 }
597
598 function instantiateAsync(binary, binaryFile, imports, callback) {
599 if (!binary && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(binaryFile) && !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE && typeof fetch == "function") {
600 return fetch(binaryFile, {
601 credentials: "same-origin"
602 }).then(response => {
603 var result = WebAssembly.instantiateStreaming(response, imports);
604 return result.then(callback, function(reason) {
605 err(`wasm streaming compile failed: ${reason}`);
606 err("falling back to ArrayBuffer instantiation");
607 return instantiateArrayBuffer(binaryFile, imports, callback)
608 })
609 })
610 }
611 return instantiateArrayBuffer(binaryFile, imports, callback)
612 }
613
swissChili281af442024-11-14 23:30:29 -0500614 function getWasmImports() {
615 Asyncify.instrumentWasmImports(wasmImports);
616 return {
617 env: wasmImports,
618 wasi_snapshot_preview1: wasmImports
619 }
620 }
621
swissChiliab615d82024-03-08 17:15:13 -0500622 function createWasm() {
swissChili281af442024-11-14 23:30:29 -0500623 var info = getWasmImports();
swissChiliab615d82024-03-08 17:15:13 -0500624
625 function receiveInstance(instance, module) {
626 wasmExports = instance.exports;
627 wasmExports = Asyncify.instrumentWasmExports(wasmExports);
swissChili281af442024-11-14 23:30:29 -0500628 wasmMemory = wasmExports["memory"];
629 assert(wasmMemory, "memory not found in wasm exports");
swissChiliab615d82024-03-08 17:15:13 -0500630 updateMemoryViews();
swissChili281af442024-11-14 23:30:29 -0500631 addOnInit(wasmExports["__wasm_call_ctors"]);
swissChiliab615d82024-03-08 17:15:13 -0500632 removeRunDependency("wasm-instantiate");
633 return wasmExports
634 }
635 addRunDependency("wasm-instantiate");
swissChili281af442024-11-14 23:30:29 -0500636 var trueModule = Module;
swissChiliab615d82024-03-08 17:15:13 -0500637
638 function receiveInstantiationResult(result) {
swissChili281af442024-11-14 23:30:29 -0500639 assert(Module === trueModule, "the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?");
640 trueModule = null;
swissChiliab615d82024-03-08 17:15:13 -0500641 receiveInstance(result["instance"])
642 }
643 if (Module["instantiateWasm"]) {
644 try {
645 return Module["instantiateWasm"](info, receiveInstance)
646 } catch (e) {
647 err(`Module.instantiateWasm callback failed with error: ${e}`);
648 readyPromiseReject(e)
649 }
650 }
swissChili281af442024-11-14 23:30:29 -0500651 if (!wasmBinaryFile) wasmBinaryFile = findWasmBinary();
swissChiliab615d82024-03-08 17:15:13 -0500652 instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult).catch(readyPromiseReject);
653 return {}
654 }
655 var tempDouble;
656 var tempI64;
swissChili281af442024-11-14 23:30:29 -0500657 (function() {
658 var h16 = new Int16Array(1);
659 var h8 = new Int8Array(h16.buffer);
660 h16[0] = 25459;
661 if (h8[0] !== 115 || h8[1] !== 99) throw "Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"
662 })();
663
664 function legacyModuleProp(prop, newName, incoming = true) {
665 if (!Object.getOwnPropertyDescriptor(Module, prop)) {
666 Object.defineProperty(Module, prop, {
667 configurable: true,
668 get() {
669 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)" : "";
670 abort(`\`Module.${prop}\` has been replaced by \`${newName}\`` + extra)
671 }
672 })
673 }
674 }
675
676 function ignoredModuleProp(prop) {
677 if (Object.getOwnPropertyDescriptor(Module, prop)) {
678 abort(`\`Module.${prop}\` was supplied but \`${prop}\` not included in INCOMING_MODULE_JS_API`)
679 }
680 }
681
682 function isExportedByForceFilesystem(name) {
683 return name === "FS_createPath" || name === "FS_createDataFile" || name === "FS_createPreloadedFile" || name === "FS_unlink" || name === "addRunDependency" || name === "FS_createLazyFile" || name === "FS_createDevice" || name === "removeRunDependency"
684 }
685
686 function missingGlobal(sym, msg) {
687 if (typeof globalThis != "undefined") {
688 Object.defineProperty(globalThis, sym, {
689 configurable: true,
690 get() {
691 warnOnce(`\`${sym}\` is not longer defined by emscripten. ${msg}`);
692 return undefined
693 }
694 })
695 }
696 }
697 missingGlobal("buffer", "Please use HEAP8.buffer or wasmMemory.buffer");
698 missingGlobal("asm", "Please use wasmExports instead");
699
700 function missingLibrarySymbol(sym) {
701 if (typeof globalThis != "undefined" && !Object.getOwnPropertyDescriptor(globalThis, sym)) {
702 Object.defineProperty(globalThis, sym, {
703 configurable: true,
704 get() {
705 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`;
706 var librarySymbol = sym;
707 if (!librarySymbol.startsWith("_")) {
708 librarySymbol = "$" + sym
709 }
710 msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${librarySymbol}')`;
711 if (isExportedByForceFilesystem(sym)) {
712 msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"
713 }
714 warnOnce(msg);
715 return undefined
716 }
717 })
718 }
719 unexportedRuntimeSymbol(sym)
720 }
721
722 function unexportedRuntimeSymbol(sym) {
723 if (!Object.getOwnPropertyDescriptor(Module, sym)) {
724 Object.defineProperty(Module, sym, {
725 configurable: true,
726 get() {
727 var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;
728 if (isExportedByForceFilesystem(sym)) {
729 msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"
730 }
731 abort(msg)
732 }
733 })
734 }
735 }
swissChiliab615d82024-03-08 17:15:13 -0500736
737 function ExitStatus(status) {
738 this.name = "ExitStatus";
739 this.message = `Program terminated with exit(${status})`;
740 this.status = status
741 }
742 var callRuntimeCallbacks = callbacks => {
743 while (callbacks.length > 0) {
744 callbacks.shift()(Module)
745 }
746 };
747 var noExitRuntime = Module["noExitRuntime"] || true;
swissChili281af442024-11-14 23:30:29 -0500748 var ptrToString = ptr => {
749 assert(typeof ptr === "number");
750 ptr >>>= 0;
751 return "0x" + ptr.toString(16).padStart(8, "0")
752 };
753 var stackRestore = val => __emscripten_stack_restore(val);
754 var stackSave = () => _emscripten_stack_get_current();
755 var warnOnce = text => {
756 warnOnce.shown ||= {};
757 if (!warnOnce.shown[text]) {
758 warnOnce.shown[text] = 1;
759 if (ENVIRONMENT_IS_NODE) text = "warning: " + text;
760 err(text)
761 }
762 };
763
764 function syscallGetVarargI() {
765 assert(SYSCALLS.varargs != undefined);
766 var ret = HEAP32[+SYSCALLS.varargs >> 2];
767 SYSCALLS.varargs += 4;
768 return ret
769 }
770 var syscallGetVarargP = syscallGetVarargI;
swissChiliab615d82024-03-08 17:15:13 -0500771 var PATH = {
772 isAbs: path => path.charAt(0) === "/",
773 splitPath: filename => {
774 var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
775 return splitPathRe.exec(filename).slice(1)
776 },
777 normalizeArray: (parts, allowAboveRoot) => {
778 var up = 0;
779 for (var i = parts.length - 1; i >= 0; i--) {
780 var last = parts[i];
781 if (last === ".") {
782 parts.splice(i, 1)
783 } else if (last === "..") {
784 parts.splice(i, 1);
785 up++
786 } else if (up) {
787 parts.splice(i, 1);
788 up--
789 }
790 }
791 if (allowAboveRoot) {
792 for (; up; up--) {
793 parts.unshift("..")
794 }
795 }
796 return parts
797 },
798 normalize: path => {
799 var isAbsolute = PATH.isAbs(path),
800 trailingSlash = path.substr(-1) === "/";
801 path = PATH.normalizeArray(path.split("/").filter(p => !!p), !isAbsolute).join("/");
802 if (!path && !isAbsolute) {
803 path = "."
804 }
805 if (path && trailingSlash) {
806 path += "/"
807 }
808 return (isAbsolute ? "/" : "") + path
809 },
810 dirname: path => {
811 var result = PATH.splitPath(path),
812 root = result[0],
813 dir = result[1];
814 if (!root && !dir) {
815 return "."
816 }
817 if (dir) {
818 dir = dir.substr(0, dir.length - 1)
819 }
820 return root + dir
821 },
822 basename: path => {
823 if (path === "/") return "/";
824 path = PATH.normalize(path);
825 path = path.replace(/\/$/, "");
826 var lastSlash = path.lastIndexOf("/");
827 if (lastSlash === -1) return path;
828 return path.substr(lastSlash + 1)
829 },
830 join: (...paths) => PATH.normalize(paths.join("/")),
831 join2: (l, r) => PATH.normalize(l + "/" + r)
832 };
833 var initRandomFill = () => {
834 if (typeof crypto == "object" && typeof crypto["getRandomValues"] == "function") {
835 return view => crypto.getRandomValues(view)
836 } else if (ENVIRONMENT_IS_NODE) {
837 try {
838 var crypto_module = require("crypto");
839 var randomFillSync = crypto_module["randomFillSync"];
840 if (randomFillSync) {
841 return view => crypto_module["randomFillSync"](view)
842 }
843 var randomBytes = crypto_module["randomBytes"];
844 return view => (view.set(randomBytes(view.byteLength)), view)
845 } catch (e) {}
846 }
swissChili281af442024-11-14 23:30:29 -0500847 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 } };")
swissChiliab615d82024-03-08 17:15:13 -0500848 };
849 var randomFill = view => (randomFill = initRandomFill())(view);
850 var PATH_FS = {
851 resolve: (...args) => {
852 var resolvedPath = "",
853 resolvedAbsolute = false;
854 for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
855 var path = i >= 0 ? args[i] : FS.cwd();
856 if (typeof path != "string") {
857 throw new TypeError("Arguments to path.resolve must be strings")
858 } else if (!path) {
859 return ""
860 }
861 resolvedPath = path + "/" + resolvedPath;
862 resolvedAbsolute = PATH.isAbs(path)
863 }
864 resolvedPath = PATH.normalizeArray(resolvedPath.split("/").filter(p => !!p), !resolvedAbsolute).join("/");
865 return (resolvedAbsolute ? "/" : "") + resolvedPath || "."
866 },
867 relative: (from, to) => {
868 from = PATH_FS.resolve(from).substr(1);
869 to = PATH_FS.resolve(to).substr(1);
870
871 function trim(arr) {
872 var start = 0;
873 for (; start < arr.length; start++) {
874 if (arr[start] !== "") break
875 }
876 var end = arr.length - 1;
877 for (; end >= 0; end--) {
878 if (arr[end] !== "") break
879 }
880 if (start > end) return [];
881 return arr.slice(start, end - start + 1)
882 }
883 var fromParts = trim(from.split("/"));
884 var toParts = trim(to.split("/"));
885 var length = Math.min(fromParts.length, toParts.length);
886 var samePartsLength = length;
887 for (var i = 0; i < length; i++) {
888 if (fromParts[i] !== toParts[i]) {
889 samePartsLength = i;
890 break
891 }
892 }
893 var outputParts = [];
894 for (var i = samePartsLength; i < fromParts.length; i++) {
895 outputParts.push("..")
896 }
897 outputParts = outputParts.concat(toParts.slice(samePartsLength));
898 return outputParts.join("/")
899 }
900 };
swissChili281af442024-11-14 23:30:29 -0500901 var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder : undefined;
swissChiliab615d82024-03-08 17:15:13 -0500902 var UTF8ArrayToString = (heapOrArray, idx, maxBytesToRead) => {
903 var endIdx = idx + maxBytesToRead;
904 var endPtr = idx;
905 while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
906 if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
907 return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr))
908 }
909 var str = "";
910 while (idx < endPtr) {
911 var u0 = heapOrArray[idx++];
912 if (!(u0 & 128)) {
913 str += String.fromCharCode(u0);
914 continue
915 }
916 var u1 = heapOrArray[idx++] & 63;
917 if ((u0 & 224) == 192) {
918 str += String.fromCharCode((u0 & 31) << 6 | u1);
919 continue
920 }
921 var u2 = heapOrArray[idx++] & 63;
922 if ((u0 & 240) == 224) {
923 u0 = (u0 & 15) << 12 | u1 << 6 | u2
924 } else {
swissChili281af442024-11-14 23:30:29 -0500925 if ((u0 & 248) != 240) warnOnce("Invalid UTF-8 leading byte " + ptrToString(u0) + " encountered when deserializing a UTF-8 string in wasm memory to a JS string!");
swissChiliab615d82024-03-08 17:15:13 -0500926 u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63
927 }
928 if (u0 < 65536) {
929 str += String.fromCharCode(u0)
930 } else {
931 var ch = u0 - 65536;
932 str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023)
933 }
934 }
935 return str
936 };
937 var FS_stdin_getChar_buffer = [];
938 var lengthBytesUTF8 = str => {
939 var len = 0;
940 for (var i = 0; i < str.length; ++i) {
941 var c = str.charCodeAt(i);
942 if (c <= 127) {
943 len++
944 } else if (c <= 2047) {
945 len += 2
946 } else if (c >= 55296 && c <= 57343) {
947 len += 4;
948 ++i
949 } else {
950 len += 3
951 }
952 }
953 return len
954 };
955 var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
swissChili281af442024-11-14 23:30:29 -0500956 assert(typeof str === "string", `stringToUTF8Array expects a string (got ${typeof str})`);
swissChiliab615d82024-03-08 17:15:13 -0500957 if (!(maxBytesToWrite > 0)) return 0;
958 var startIdx = outIdx;
959 var endIdx = outIdx + maxBytesToWrite - 1;
960 for (var i = 0; i < str.length; ++i) {
961 var u = str.charCodeAt(i);
962 if (u >= 55296 && u <= 57343) {
963 var u1 = str.charCodeAt(++i);
964 u = 65536 + ((u & 1023) << 10) | u1 & 1023
965 }
966 if (u <= 127) {
967 if (outIdx >= endIdx) break;
968 heap[outIdx++] = u
969 } else if (u <= 2047) {
970 if (outIdx + 1 >= endIdx) break;
971 heap[outIdx++] = 192 | u >> 6;
972 heap[outIdx++] = 128 | u & 63
973 } else if (u <= 65535) {
974 if (outIdx + 2 >= endIdx) break;
975 heap[outIdx++] = 224 | u >> 12;
976 heap[outIdx++] = 128 | u >> 6 & 63;
977 heap[outIdx++] = 128 | u & 63
978 } else {
979 if (outIdx + 3 >= endIdx) break;
swissChili281af442024-11-14 23:30:29 -0500980 if (u > 1114111) 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).");
swissChiliab615d82024-03-08 17:15:13 -0500981 heap[outIdx++] = 240 | u >> 18;
982 heap[outIdx++] = 128 | u >> 12 & 63;
983 heap[outIdx++] = 128 | u >> 6 & 63;
984 heap[outIdx++] = 128 | u & 63
985 }
986 }
987 heap[outIdx] = 0;
988 return outIdx - startIdx
989 };
990
991 function intArrayFromString(stringy, dontAddNull, length) {
992 var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;
993 var u8array = new Array(len);
994 var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
995 if (dontAddNull) u8array.length = numBytesWritten;
996 return u8array
997 }
998 var FS_stdin_getChar = () => {
999 if (!FS_stdin_getChar_buffer.length) {
1000 var result = null;
1001 if (ENVIRONMENT_IS_NODE) {
1002 var BUFSIZE = 256;
1003 var buf = Buffer.alloc(BUFSIZE);
1004 var bytesRead = 0;
1005 var fd = process.stdin.fd;
1006 try {
swissChili281af442024-11-14 23:30:29 -05001007 bytesRead = fs.readSync(fd, buf, 0, BUFSIZE)
swissChiliab615d82024-03-08 17:15:13 -05001008 } catch (e) {
1009 if (e.toString().includes("EOF")) bytesRead = 0;
1010 else throw e
1011 }
1012 if (bytesRead > 0) {
1013 result = buf.slice(0, bytesRead).toString("utf-8")
swissChiliab615d82024-03-08 17:15:13 -05001014 }
1015 } else if (typeof window != "undefined" && typeof window.prompt == "function") {
1016 result = window.prompt("Input: ");
1017 if (result !== null) {
1018 result += "\n"
1019 }
swissChili281af442024-11-14 23:30:29 -05001020 } else {}
swissChiliab615d82024-03-08 17:15:13 -05001021 if (!result) {
1022 return null
1023 }
1024 FS_stdin_getChar_buffer = intArrayFromString(result, true)
1025 }
1026 return FS_stdin_getChar_buffer.shift()
1027 };
1028 var TTY = {
1029 ttys: [],
1030 init() {},
1031 shutdown() {},
1032 register(dev, ops) {
1033 TTY.ttys[dev] = {
1034 input: [],
1035 output: [],
1036 ops: ops
1037 };
1038 FS.registerDevice(dev, TTY.stream_ops)
1039 },
1040 stream_ops: {
1041 open(stream) {
1042 var tty = TTY.ttys[stream.node.rdev];
1043 if (!tty) {
1044 throw new FS.ErrnoError(43)
1045 }
1046 stream.tty = tty;
1047 stream.seekable = false
1048 },
1049 close(stream) {
1050 stream.tty.ops.fsync(stream.tty)
1051 },
1052 fsync(stream) {
1053 stream.tty.ops.fsync(stream.tty)
1054 },
1055 read(stream, buffer, offset, length, pos) {
1056 if (!stream.tty || !stream.tty.ops.get_char) {
1057 throw new FS.ErrnoError(60)
1058 }
1059 var bytesRead = 0;
1060 for (var i = 0; i < length; i++) {
1061 var result;
1062 try {
1063 result = stream.tty.ops.get_char(stream.tty)
1064 } catch (e) {
1065 throw new FS.ErrnoError(29)
1066 }
1067 if (result === undefined && bytesRead === 0) {
1068 throw new FS.ErrnoError(6)
1069 }
1070 if (result === null || result === undefined) break;
1071 bytesRead++;
1072 buffer[offset + i] = result
1073 }
1074 if (bytesRead) {
1075 stream.node.timestamp = Date.now()
1076 }
1077 return bytesRead
1078 },
1079 write(stream, buffer, offset, length, pos) {
1080 if (!stream.tty || !stream.tty.ops.put_char) {
1081 throw new FS.ErrnoError(60)
1082 }
1083 try {
1084 for (var i = 0; i < length; i++) {
1085 stream.tty.ops.put_char(stream.tty, buffer[offset + i])
1086 }
1087 } catch (e) {
1088 throw new FS.ErrnoError(29)
1089 }
1090 if (length) {
1091 stream.node.timestamp = Date.now()
1092 }
1093 return i
1094 }
1095 },
1096 default_tty_ops: {
1097 get_char(tty) {
1098 return FS_stdin_getChar()
1099 },
1100 put_char(tty, val) {
1101 if (val === null || val === 10) {
1102 out(UTF8ArrayToString(tty.output, 0));
1103 tty.output = []
1104 } else {
1105 if (val != 0) tty.output.push(val)
1106 }
1107 },
1108 fsync(tty) {
1109 if (tty.output && tty.output.length > 0) {
1110 out(UTF8ArrayToString(tty.output, 0));
1111 tty.output = []
1112 }
1113 },
1114 ioctl_tcgets(tty) {
1115 return {
1116 c_iflag: 25856,
1117 c_oflag: 5,
1118 c_cflag: 191,
1119 c_lflag: 35387,
1120 c_cc: [3, 28, 127, 21, 4, 0, 1, 0, 17, 19, 26, 0, 18, 15, 23, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1121 }
1122 },
1123 ioctl_tcsets(tty, optional_actions, data) {
1124 return 0
1125 },
1126 ioctl_tiocgwinsz(tty) {
1127 return [24, 80]
1128 }
1129 },
1130 default_tty1_ops: {
1131 put_char(tty, val) {
1132 if (val === null || val === 10) {
1133 err(UTF8ArrayToString(tty.output, 0));
1134 tty.output = []
1135 } else {
1136 if (val != 0) tty.output.push(val)
1137 }
1138 },
1139 fsync(tty) {
1140 if (tty.output && tty.output.length > 0) {
1141 err(UTF8ArrayToString(tty.output, 0));
1142 tty.output = []
1143 }
1144 }
1145 }
1146 };
1147 var mmapAlloc = size => {
swissChili281af442024-11-14 23:30:29 -05001148 abort("internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported")
swissChiliab615d82024-03-08 17:15:13 -05001149 };
1150 var MEMFS = {
1151 ops_table: null,
1152 mount(mount) {
1153 return MEMFS.createNode(null, "/", 16384 | 511, 0)
1154 },
1155 createNode(parent, name, mode, dev) {
1156 if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
1157 throw new FS.ErrnoError(63)
1158 }
1159 MEMFS.ops_table ||= {
1160 dir: {
1161 node: {
1162 getattr: MEMFS.node_ops.getattr,
1163 setattr: MEMFS.node_ops.setattr,
1164 lookup: MEMFS.node_ops.lookup,
1165 mknod: MEMFS.node_ops.mknod,
1166 rename: MEMFS.node_ops.rename,
1167 unlink: MEMFS.node_ops.unlink,
1168 rmdir: MEMFS.node_ops.rmdir,
1169 readdir: MEMFS.node_ops.readdir,
1170 symlink: MEMFS.node_ops.symlink
1171 },
1172 stream: {
1173 llseek: MEMFS.stream_ops.llseek
1174 }
1175 },
1176 file: {
1177 node: {
1178 getattr: MEMFS.node_ops.getattr,
1179 setattr: MEMFS.node_ops.setattr
1180 },
1181 stream: {
1182 llseek: MEMFS.stream_ops.llseek,
1183 read: MEMFS.stream_ops.read,
1184 write: MEMFS.stream_ops.write,
1185 allocate: MEMFS.stream_ops.allocate,
1186 mmap: MEMFS.stream_ops.mmap,
1187 msync: MEMFS.stream_ops.msync
1188 }
1189 },
1190 link: {
1191 node: {
1192 getattr: MEMFS.node_ops.getattr,
1193 setattr: MEMFS.node_ops.setattr,
1194 readlink: MEMFS.node_ops.readlink
1195 },
1196 stream: {}
1197 },
1198 chrdev: {
1199 node: {
1200 getattr: MEMFS.node_ops.getattr,
1201 setattr: MEMFS.node_ops.setattr
1202 },
1203 stream: FS.chrdev_stream_ops
1204 }
1205 };
1206 var node = FS.createNode(parent, name, mode, dev);
1207 if (FS.isDir(node.mode)) {
1208 node.node_ops = MEMFS.ops_table.dir.node;
1209 node.stream_ops = MEMFS.ops_table.dir.stream;
1210 node.contents = {}
1211 } else if (FS.isFile(node.mode)) {
1212 node.node_ops = MEMFS.ops_table.file.node;
1213 node.stream_ops = MEMFS.ops_table.file.stream;
1214 node.usedBytes = 0;
1215 node.contents = null
1216 } else if (FS.isLink(node.mode)) {
1217 node.node_ops = MEMFS.ops_table.link.node;
1218 node.stream_ops = MEMFS.ops_table.link.stream
1219 } else if (FS.isChrdev(node.mode)) {
1220 node.node_ops = MEMFS.ops_table.chrdev.node;
1221 node.stream_ops = MEMFS.ops_table.chrdev.stream
1222 }
1223 node.timestamp = Date.now();
1224 if (parent) {
1225 parent.contents[name] = node;
1226 parent.timestamp = node.timestamp
1227 }
1228 return node
1229 },
1230 getFileDataAsTypedArray(node) {
1231 if (!node.contents) return new Uint8Array(0);
1232 if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes);
1233 return new Uint8Array(node.contents)
1234 },
1235 expandFileStorage(node, newCapacity) {
1236 var prevCapacity = node.contents ? node.contents.length : 0;
1237 if (prevCapacity >= newCapacity) return;
1238 var CAPACITY_DOUBLING_MAX = 1024 * 1024;
1239 newCapacity = Math.max(newCapacity, prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125) >>> 0);
1240 if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256);
1241 var oldContents = node.contents;
1242 node.contents = new Uint8Array(newCapacity);
1243 if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0)
1244 },
1245 resizeFileStorage(node, newSize) {
1246 if (node.usedBytes == newSize) return;
1247 if (newSize == 0) {
1248 node.contents = null;
1249 node.usedBytes = 0
1250 } else {
1251 var oldContents = node.contents;
1252 node.contents = new Uint8Array(newSize);
1253 if (oldContents) {
1254 node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)))
1255 }
1256 node.usedBytes = newSize
1257 }
1258 },
1259 node_ops: {
1260 getattr(node) {
1261 var attr = {};
1262 attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
1263 attr.ino = node.id;
1264 attr.mode = node.mode;
1265 attr.nlink = 1;
1266 attr.uid = 0;
1267 attr.gid = 0;
1268 attr.rdev = node.rdev;
1269 if (FS.isDir(node.mode)) {
1270 attr.size = 4096
1271 } else if (FS.isFile(node.mode)) {
1272 attr.size = node.usedBytes
1273 } else if (FS.isLink(node.mode)) {
1274 attr.size = node.link.length
1275 } else {
1276 attr.size = 0
1277 }
1278 attr.atime = new Date(node.timestamp);
1279 attr.mtime = new Date(node.timestamp);
1280 attr.ctime = new Date(node.timestamp);
1281 attr.blksize = 4096;
1282 attr.blocks = Math.ceil(attr.size / attr.blksize);
1283 return attr
1284 },
1285 setattr(node, attr) {
1286 if (attr.mode !== undefined) {
1287 node.mode = attr.mode
1288 }
1289 if (attr.timestamp !== undefined) {
1290 node.timestamp = attr.timestamp
1291 }
1292 if (attr.size !== undefined) {
1293 MEMFS.resizeFileStorage(node, attr.size)
1294 }
1295 },
1296 lookup(parent, name) {
1297 throw FS.genericErrors[44]
1298 },
1299 mknod(parent, name, mode, dev) {
1300 return MEMFS.createNode(parent, name, mode, dev)
1301 },
1302 rename(old_node, new_dir, new_name) {
1303 if (FS.isDir(old_node.mode)) {
1304 var new_node;
1305 try {
1306 new_node = FS.lookupNode(new_dir, new_name)
1307 } catch (e) {}
1308 if (new_node) {
1309 for (var i in new_node.contents) {
1310 throw new FS.ErrnoError(55)
1311 }
1312 }
1313 }
1314 delete old_node.parent.contents[old_node.name];
1315 old_node.parent.timestamp = Date.now();
1316 old_node.name = new_name;
1317 new_dir.contents[new_name] = old_node;
swissChili281af442024-11-14 23:30:29 -05001318 new_dir.timestamp = old_node.parent.timestamp
swissChiliab615d82024-03-08 17:15:13 -05001319 },
1320 unlink(parent, name) {
1321 delete parent.contents[name];
1322 parent.timestamp = Date.now()
1323 },
1324 rmdir(parent, name) {
1325 var node = FS.lookupNode(parent, name);
1326 for (var i in node.contents) {
1327 throw new FS.ErrnoError(55)
1328 }
1329 delete parent.contents[name];
1330 parent.timestamp = Date.now()
1331 },
1332 readdir(node) {
1333 var entries = [".", ".."];
1334 for (var key of Object.keys(node.contents)) {
1335 entries.push(key)
1336 }
1337 return entries
1338 },
1339 symlink(parent, newname, oldpath) {
1340 var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);
1341 node.link = oldpath;
1342 return node
1343 },
1344 readlink(node) {
1345 if (!FS.isLink(node.mode)) {
1346 throw new FS.ErrnoError(28)
1347 }
1348 return node.link
1349 }
1350 },
1351 stream_ops: {
1352 read(stream, buffer, offset, length, position) {
1353 var contents = stream.node.contents;
1354 if (position >= stream.node.usedBytes) return 0;
1355 var size = Math.min(stream.node.usedBytes - position, length);
swissChili281af442024-11-14 23:30:29 -05001356 assert(size >= 0);
swissChiliab615d82024-03-08 17:15:13 -05001357 if (size > 8 && contents.subarray) {
1358 buffer.set(contents.subarray(position, position + size), offset)
1359 } else {
1360 for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i]
1361 }
1362 return size
1363 },
1364 write(stream, buffer, offset, length, position, canOwn) {
swissChili281af442024-11-14 23:30:29 -05001365 assert(!(buffer instanceof ArrayBuffer));
swissChiliab615d82024-03-08 17:15:13 -05001366 if (!length) return 0;
1367 var node = stream.node;
1368 node.timestamp = Date.now();
1369 if (buffer.subarray && (!node.contents || node.contents.subarray)) {
1370 if (canOwn) {
swissChili281af442024-11-14 23:30:29 -05001371 assert(position === 0, "canOwn must imply no weird position inside the file");
swissChiliab615d82024-03-08 17:15:13 -05001372 node.contents = buffer.subarray(offset, offset + length);
1373 node.usedBytes = length;
1374 return length
1375 } else if (node.usedBytes === 0 && position === 0) {
1376 node.contents = buffer.slice(offset, offset + length);
1377 node.usedBytes = length;
1378 return length
1379 } else if (position + length <= node.usedBytes) {
1380 node.contents.set(buffer.subarray(offset, offset + length), position);
1381 return length
1382 }
1383 }
1384 MEMFS.expandFileStorage(node, position + length);
1385 if (node.contents.subarray && buffer.subarray) {
1386 node.contents.set(buffer.subarray(offset, offset + length), position)
1387 } else {
1388 for (var i = 0; i < length; i++) {
1389 node.contents[position + i] = buffer[offset + i]
1390 }
1391 }
1392 node.usedBytes = Math.max(node.usedBytes, position + length);
1393 return length
1394 },
1395 llseek(stream, offset, whence) {
1396 var position = offset;
1397 if (whence === 1) {
1398 position += stream.position
1399 } else if (whence === 2) {
1400 if (FS.isFile(stream.node.mode)) {
1401 position += stream.node.usedBytes
1402 }
1403 }
1404 if (position < 0) {
1405 throw new FS.ErrnoError(28)
1406 }
1407 return position
1408 },
1409 allocate(stream, offset, length) {
1410 MEMFS.expandFileStorage(stream.node, offset + length);
1411 stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length)
1412 },
1413 mmap(stream, length, position, prot, flags) {
1414 if (!FS.isFile(stream.node.mode)) {
1415 throw new FS.ErrnoError(43)
1416 }
1417 var ptr;
1418 var allocated;
1419 var contents = stream.node.contents;
swissChili281af442024-11-14 23:30:29 -05001420 if (!(flags & 2) && contents && contents.buffer === HEAP8.buffer) {
swissChiliab615d82024-03-08 17:15:13 -05001421 allocated = false;
1422 ptr = contents.byteOffset
1423 } else {
swissChiliab615d82024-03-08 17:15:13 -05001424 allocated = true;
1425 ptr = mmapAlloc(length);
1426 if (!ptr) {
1427 throw new FS.ErrnoError(48)
1428 }
swissChili281af442024-11-14 23:30:29 -05001429 if (contents) {
1430 if (position > 0 || position + length < contents.length) {
1431 if (contents.subarray) {
1432 contents = contents.subarray(position, position + length)
1433 } else {
1434 contents = Array.prototype.slice.call(contents, position, position + length)
1435 }
1436 }
1437 HEAP8.set(contents, ptr)
1438 }
swissChiliab615d82024-03-08 17:15:13 -05001439 }
1440 return {
1441 ptr: ptr,
1442 allocated: allocated
1443 }
1444 },
1445 msync(stream, buffer, offset, length, mmapFlags) {
1446 MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
1447 return 0
1448 }
1449 }
1450 };
1451 var asyncLoad = (url, onload, onerror, noRunDep) => {
1452 var dep = !noRunDep ? getUniqueRunDependency(`al ${url}`) : "";
swissChili281af442024-11-14 23:30:29 -05001453 readAsync(url).then(arrayBuffer => {
1454 assert(arrayBuffer, `Loading data file "${url}" failed (no arrayBuffer).`);
swissChiliab615d82024-03-08 17:15:13 -05001455 onload(new Uint8Array(arrayBuffer));
1456 if (dep) removeRunDependency(dep)
swissChili281af442024-11-14 23:30:29 -05001457 }, err => {
swissChiliab615d82024-03-08 17:15:13 -05001458 if (onerror) {
1459 onerror()
1460 } else {
1461 throw `Loading data file "${url}" failed.`
1462 }
1463 });
1464 if (dep) addRunDependency(dep)
1465 };
1466 var FS_createDataFile = (parent, name, fileData, canRead, canWrite, canOwn) => {
1467 FS.createDataFile(parent, name, fileData, canRead, canWrite, canOwn)
1468 };
1469 var preloadPlugins = Module["preloadPlugins"] || [];
1470 var FS_handledByPreloadPlugin = (byteArray, fullname, finish, onerror) => {
1471 if (typeof Browser != "undefined") Browser.init();
1472 var handled = false;
1473 preloadPlugins.forEach(plugin => {
1474 if (handled) return;
1475 if (plugin["canHandle"](fullname)) {
1476 plugin["handle"](byteArray, fullname, finish, onerror);
1477 handled = true
1478 }
1479 });
1480 return handled
1481 };
1482 var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {
1483 var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
1484 var dep = getUniqueRunDependency(`cp ${fullname}`);
1485
1486 function processData(byteArray) {
1487 function finish(byteArray) {
1488 preFinish?.();
1489 if (!dontCreateFile) {
1490 FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn)
1491 }
1492 onload?.();
1493 removeRunDependency(dep)
1494 }
1495 if (FS_handledByPreloadPlugin(byteArray, fullname, finish, () => {
1496 onerror?.();
1497 removeRunDependency(dep)
1498 })) {
1499 return
1500 }
1501 finish(byteArray)
1502 }
1503 addRunDependency(dep);
1504 if (typeof url == "string") {
1505 asyncLoad(url, processData, onerror)
1506 } else {
1507 processData(url)
1508 }
1509 };
1510 var FS_modeStringToFlags = str => {
1511 var flagModes = {
swissChili281af442024-11-14 23:30:29 -05001512 r: 0,
swissChiliab615d82024-03-08 17:15:13 -05001513 "r+": 2,
swissChili281af442024-11-14 23:30:29 -05001514 w: 512 | 64 | 1,
swissChiliab615d82024-03-08 17:15:13 -05001515 "w+": 512 | 64 | 2,
swissChili281af442024-11-14 23:30:29 -05001516 a: 1024 | 64 | 1,
swissChiliab615d82024-03-08 17:15:13 -05001517 "a+": 1024 | 64 | 2
1518 };
1519 var flags = flagModes[str];
1520 if (typeof flags == "undefined") {
1521 throw new Error(`Unknown file open mode: ${str}`)
1522 }
1523 return flags
1524 };
1525 var FS_getMode = (canRead, canWrite) => {
1526 var mode = 0;
1527 if (canRead) mode |= 292 | 73;
1528 if (canWrite) mode |= 146;
1529 return mode
1530 };
swissChili281af442024-11-14 23:30:29 -05001531 var UTF8ToString = (ptr, maxBytesToRead) => {
1532 assert(typeof ptr == "number", `UTF8ToString expects a number (got ${typeof ptr})`);
1533 return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ""
1534 };
1535 var strError = errno => UTF8ToString(_strerror(errno));
1536 var ERRNO_CODES = {
1537 EPERM: 63,
1538 ENOENT: 44,
1539 ESRCH: 71,
1540 EINTR: 27,
1541 EIO: 29,
1542 ENXIO: 60,
1543 E2BIG: 1,
1544 ENOEXEC: 45,
1545 EBADF: 8,
1546 ECHILD: 12,
1547 EAGAIN: 6,
1548 EWOULDBLOCK: 6,
1549 ENOMEM: 48,
1550 EACCES: 2,
1551 EFAULT: 21,
1552 ENOTBLK: 105,
1553 EBUSY: 10,
1554 EEXIST: 20,
1555 EXDEV: 75,
1556 ENODEV: 43,
1557 ENOTDIR: 54,
1558 EISDIR: 31,
1559 EINVAL: 28,
1560 ENFILE: 41,
1561 EMFILE: 33,
1562 ENOTTY: 59,
1563 ETXTBSY: 74,
1564 EFBIG: 22,
1565 ENOSPC: 51,
1566 ESPIPE: 70,
1567 EROFS: 69,
1568 EMLINK: 34,
1569 EPIPE: 64,
1570 EDOM: 18,
1571 ERANGE: 68,
1572 ENOMSG: 49,
1573 EIDRM: 24,
1574 ECHRNG: 106,
1575 EL2NSYNC: 156,
1576 EL3HLT: 107,
1577 EL3RST: 108,
1578 ELNRNG: 109,
1579 EUNATCH: 110,
1580 ENOCSI: 111,
1581 EL2HLT: 112,
1582 EDEADLK: 16,
1583 ENOLCK: 46,
1584 EBADE: 113,
1585 EBADR: 114,
1586 EXFULL: 115,
1587 ENOANO: 104,
1588 EBADRQC: 103,
1589 EBADSLT: 102,
1590 EDEADLOCK: 16,
1591 EBFONT: 101,
1592 ENOSTR: 100,
1593 ENODATA: 116,
1594 ETIME: 117,
1595 ENOSR: 118,
1596 ENONET: 119,
1597 ENOPKG: 120,
1598 EREMOTE: 121,
1599 ENOLINK: 47,
1600 EADV: 122,
1601 ESRMNT: 123,
1602 ECOMM: 124,
1603 EPROTO: 65,
1604 EMULTIHOP: 36,
1605 EDOTDOT: 125,
1606 EBADMSG: 9,
1607 ENOTUNIQ: 126,
1608 EBADFD: 127,
1609 EREMCHG: 128,
1610 ELIBACC: 129,
1611 ELIBBAD: 130,
1612 ELIBSCN: 131,
1613 ELIBMAX: 132,
1614 ELIBEXEC: 133,
1615 ENOSYS: 52,
1616 ENOTEMPTY: 55,
1617 ENAMETOOLONG: 37,
1618 ELOOP: 32,
1619 EOPNOTSUPP: 138,
1620 EPFNOSUPPORT: 139,
1621 ECONNRESET: 15,
1622 ENOBUFS: 42,
1623 EAFNOSUPPORT: 5,
1624 EPROTOTYPE: 67,
1625 ENOTSOCK: 57,
1626 ENOPROTOOPT: 50,
1627 ESHUTDOWN: 140,
1628 ECONNREFUSED: 14,
1629 EADDRINUSE: 3,
1630 ECONNABORTED: 13,
1631 ENETUNREACH: 40,
1632 ENETDOWN: 38,
1633 ETIMEDOUT: 73,
1634 EHOSTDOWN: 142,
1635 EHOSTUNREACH: 23,
1636 EINPROGRESS: 26,
1637 EALREADY: 7,
1638 EDESTADDRREQ: 17,
1639 EMSGSIZE: 35,
1640 EPROTONOSUPPORT: 66,
1641 ESOCKTNOSUPPORT: 137,
1642 EADDRNOTAVAIL: 4,
1643 ENETRESET: 39,
1644 EISCONN: 30,
1645 ENOTCONN: 53,
1646 ETOOMANYREFS: 141,
1647 EUSERS: 136,
1648 EDQUOT: 19,
1649 ESTALE: 72,
1650 ENOTSUP: 138,
1651 ENOMEDIUM: 148,
1652 EILSEQ: 25,
1653 EOVERFLOW: 61,
1654 ECANCELED: 11,
1655 ENOTRECOVERABLE: 56,
1656 EOWNERDEAD: 62,
1657 ESTRPIPE: 135
1658 };
swissChiliab615d82024-03-08 17:15:13 -05001659 var FS = {
1660 root: null,
1661 mounts: [],
1662 devices: {},
1663 streams: [],
1664 nextInode: 1,
1665 nameTable: null,
1666 currentPath: "/",
1667 initialized: false,
1668 ignorePermissions: true,
swissChili281af442024-11-14 23:30:29 -05001669 ErrnoError: class extends Error {
swissChiliab615d82024-03-08 17:15:13 -05001670 constructor(errno) {
swissChili281af442024-11-14 23:30:29 -05001671 super(runtimeInitialized ? strError(errno) : "");
swissChiliab615d82024-03-08 17:15:13 -05001672 this.name = "ErrnoError";
swissChili281af442024-11-14 23:30:29 -05001673 this.errno = errno;
1674 for (var key in ERRNO_CODES) {
1675 if (ERRNO_CODES[key] === errno) {
1676 this.code = key;
1677 break
1678 }
1679 }
swissChiliab615d82024-03-08 17:15:13 -05001680 }
1681 },
1682 genericErrors: {},
1683 filesystems: null,
1684 syncFSRequests: 0,
swissChili281af442024-11-14 23:30:29 -05001685 FSStream: class {
1686 constructor() {
1687 this.shared = {}
1688 }
1689 get object() {
1690 return this.node
1691 }
1692 set object(val) {
1693 this.node = val
1694 }
1695 get isRead() {
1696 return (this.flags & 2097155) !== 1
1697 }
1698 get isWrite() {
1699 return (this.flags & 2097155) !== 0
1700 }
1701 get isAppend() {
1702 return this.flags & 1024
1703 }
1704 get flags() {
1705 return this.shared.flags
1706 }
1707 set flags(val) {
1708 this.shared.flags = val
1709 }
1710 get position() {
1711 return this.shared.position
1712 }
1713 set position(val) {
1714 this.shared.position = val
1715 }
1716 },
1717 FSNode: class {
1718 constructor(parent, name, mode, rdev) {
1719 if (!parent) {
1720 parent = this
1721 }
1722 this.parent = parent;
1723 this.mount = parent.mount;
1724 this.mounted = null;
1725 this.id = FS.nextInode++;
1726 this.name = name;
1727 this.mode = mode;
1728 this.node_ops = {};
1729 this.stream_ops = {};
1730 this.rdev = rdev;
1731 this.readMode = 292 | 73;
1732 this.writeMode = 146
1733 }
1734 get read() {
1735 return (this.mode & this.readMode) === this.readMode
1736 }
1737 set read(val) {
1738 val ? this.mode |= this.readMode : this.mode &= ~this.readMode
1739 }
1740 get write() {
1741 return (this.mode & this.writeMode) === this.writeMode
1742 }
1743 set write(val) {
1744 val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode
1745 }
1746 get isFolder() {
1747 return FS.isDir(this.mode)
1748 }
1749 get isDevice() {
1750 return FS.isChrdev(this.mode)
1751 }
1752 },
swissChiliab615d82024-03-08 17:15:13 -05001753 lookupPath(path, opts = {}) {
1754 path = PATH_FS.resolve(path);
1755 if (!path) return {
1756 path: "",
1757 node: null
1758 };
1759 var defaults = {
1760 follow_mount: true,
1761 recurse_count: 0
1762 };
1763 opts = Object.assign(defaults, opts);
1764 if (opts.recurse_count > 8) {
1765 throw new FS.ErrnoError(32)
1766 }
1767 var parts = path.split("/").filter(p => !!p);
1768 var current = FS.root;
1769 var current_path = "/";
1770 for (var i = 0; i < parts.length; i++) {
1771 var islast = i === parts.length - 1;
1772 if (islast && opts.parent) {
1773 break
1774 }
1775 current = FS.lookupNode(current, parts[i]);
1776 current_path = PATH.join2(current_path, parts[i]);
1777 if (FS.isMountpoint(current)) {
1778 if (!islast || islast && opts.follow_mount) {
1779 current = current.mounted.root
1780 }
1781 }
1782 if (!islast || opts.follow) {
1783 var count = 0;
1784 while (FS.isLink(current.mode)) {
1785 var link = FS.readlink(current_path);
1786 current_path = PATH_FS.resolve(PATH.dirname(current_path), link);
1787 var lookup = FS.lookupPath(current_path, {
1788 recurse_count: opts.recurse_count + 1
1789 });
1790 current = lookup.node;
1791 if (count++ > 40) {
1792 throw new FS.ErrnoError(32)
1793 }
1794 }
1795 }
1796 }
1797 return {
1798 path: current_path,
1799 node: current
1800 }
1801 },
1802 getPath(node) {
1803 var path;
1804 while (true) {
1805 if (FS.isRoot(node)) {
1806 var mount = node.mount.mountpoint;
1807 if (!path) return mount;
1808 return mount[mount.length - 1] !== "/" ? `${mount}/${path}` : mount + path
1809 }
1810 path = path ? `${node.name}/${path}` : node.name;
1811 node = node.parent
1812 }
1813 },
1814 hashName(parentid, name) {
1815 var hash = 0;
1816 for (var i = 0; i < name.length; i++) {
1817 hash = (hash << 5) - hash + name.charCodeAt(i) | 0
1818 }
1819 return (parentid + hash >>> 0) % FS.nameTable.length
1820 },
1821 hashAddNode(node) {
1822 var hash = FS.hashName(node.parent.id, node.name);
1823 node.name_next = FS.nameTable[hash];
1824 FS.nameTable[hash] = node
1825 },
1826 hashRemoveNode(node) {
1827 var hash = FS.hashName(node.parent.id, node.name);
1828 if (FS.nameTable[hash] === node) {
1829 FS.nameTable[hash] = node.name_next
1830 } else {
1831 var current = FS.nameTable[hash];
1832 while (current) {
1833 if (current.name_next === node) {
1834 current.name_next = node.name_next;
1835 break
1836 }
1837 current = current.name_next
1838 }
1839 }
1840 },
1841 lookupNode(parent, name) {
1842 var errCode = FS.mayLookup(parent);
1843 if (errCode) {
1844 throw new FS.ErrnoError(errCode)
1845 }
1846 var hash = FS.hashName(parent.id, name);
1847 for (var node = FS.nameTable[hash]; node; node = node.name_next) {
1848 var nodeName = node.name;
1849 if (node.parent.id === parent.id && nodeName === name) {
1850 return node
1851 }
1852 }
1853 return FS.lookup(parent, name)
1854 },
1855 createNode(parent, name, mode, rdev) {
swissChili281af442024-11-14 23:30:29 -05001856 assert(typeof parent == "object");
swissChiliab615d82024-03-08 17:15:13 -05001857 var node = new FS.FSNode(parent, name, mode, rdev);
1858 FS.hashAddNode(node);
1859 return node
1860 },
1861 destroyNode(node) {
1862 FS.hashRemoveNode(node)
1863 },
1864 isRoot(node) {
1865 return node === node.parent
1866 },
1867 isMountpoint(node) {
1868 return !!node.mounted
1869 },
1870 isFile(mode) {
1871 return (mode & 61440) === 32768
1872 },
1873 isDir(mode) {
1874 return (mode & 61440) === 16384
1875 },
1876 isLink(mode) {
1877 return (mode & 61440) === 40960
1878 },
1879 isChrdev(mode) {
1880 return (mode & 61440) === 8192
1881 },
1882 isBlkdev(mode) {
1883 return (mode & 61440) === 24576
1884 },
1885 isFIFO(mode) {
1886 return (mode & 61440) === 4096
1887 },
1888 isSocket(mode) {
1889 return (mode & 49152) === 49152
1890 },
1891 flagsToPermissionString(flag) {
1892 var perms = ["r", "w", "rw"][flag & 3];
1893 if (flag & 512) {
1894 perms += "w"
1895 }
1896 return perms
1897 },
1898 nodePermissions(node, perms) {
1899 if (FS.ignorePermissions) {
1900 return 0
1901 }
1902 if (perms.includes("r") && !(node.mode & 292)) {
1903 return 2
1904 } else if (perms.includes("w") && !(node.mode & 146)) {
1905 return 2
1906 } else if (perms.includes("x") && !(node.mode & 73)) {
1907 return 2
1908 }
1909 return 0
1910 },
1911 mayLookup(dir) {
1912 if (!FS.isDir(dir.mode)) return 54;
1913 var errCode = FS.nodePermissions(dir, "x");
1914 if (errCode) return errCode;
1915 if (!dir.node_ops.lookup) return 2;
1916 return 0
1917 },
1918 mayCreate(dir, name) {
1919 try {
1920 var node = FS.lookupNode(dir, name);
1921 return 20
1922 } catch (e) {}
1923 return FS.nodePermissions(dir, "wx")
1924 },
1925 mayDelete(dir, name, isdir) {
1926 var node;
1927 try {
1928 node = FS.lookupNode(dir, name)
1929 } catch (e) {
1930 return e.errno
1931 }
1932 var errCode = FS.nodePermissions(dir, "wx");
1933 if (errCode) {
1934 return errCode
1935 }
1936 if (isdir) {
1937 if (!FS.isDir(node.mode)) {
1938 return 54
1939 }
1940 if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
1941 return 10
1942 }
1943 } else {
1944 if (FS.isDir(node.mode)) {
1945 return 31
1946 }
1947 }
1948 return 0
1949 },
1950 mayOpen(node, flags) {
1951 if (!node) {
1952 return 44
1953 }
1954 if (FS.isLink(node.mode)) {
1955 return 32
1956 } else if (FS.isDir(node.mode)) {
1957 if (FS.flagsToPermissionString(flags) !== "r" || flags & 512) {
1958 return 31
1959 }
1960 }
1961 return FS.nodePermissions(node, FS.flagsToPermissionString(flags))
1962 },
1963 MAX_OPEN_FDS: 4096,
1964 nextfd() {
1965 for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {
1966 if (!FS.streams[fd]) {
1967 return fd
1968 }
1969 }
1970 throw new FS.ErrnoError(33)
1971 },
1972 getStreamChecked(fd) {
1973 var stream = FS.getStream(fd);
1974 if (!stream) {
1975 throw new FS.ErrnoError(8)
1976 }
1977 return stream
1978 },
1979 getStream: fd => FS.streams[fd],
1980 createStream(stream, fd = -1) {
swissChili281af442024-11-14 23:30:29 -05001981 assert(fd >= -1);
swissChiliab615d82024-03-08 17:15:13 -05001982 stream = Object.assign(new FS.FSStream, stream);
1983 if (fd == -1) {
1984 fd = FS.nextfd()
1985 }
1986 stream.fd = fd;
1987 FS.streams[fd] = stream;
1988 return stream
1989 },
1990 closeStream(fd) {
1991 FS.streams[fd] = null
1992 },
swissChili281af442024-11-14 23:30:29 -05001993 dupStream(origStream, fd = -1) {
1994 var stream = FS.createStream(origStream, fd);
1995 stream.stream_ops?.dup?.(stream);
1996 return stream
1997 },
swissChiliab615d82024-03-08 17:15:13 -05001998 chrdev_stream_ops: {
1999 open(stream) {
2000 var device = FS.getDevice(stream.node.rdev);
2001 stream.stream_ops = device.stream_ops;
2002 stream.stream_ops.open?.(stream)
2003 },
2004 llseek() {
2005 throw new FS.ErrnoError(70)
2006 }
2007 },
2008 major: dev => dev >> 8,
2009 minor: dev => dev & 255,
2010 makedev: (ma, mi) => ma << 8 | mi,
2011 registerDevice(dev, ops) {
2012 FS.devices[dev] = {
2013 stream_ops: ops
2014 }
2015 },
2016 getDevice: dev => FS.devices[dev],
2017 getMounts(mount) {
2018 var mounts = [];
2019 var check = [mount];
2020 while (check.length) {
2021 var m = check.pop();
2022 mounts.push(m);
2023 check.push(...m.mounts)
2024 }
2025 return mounts
2026 },
2027 syncfs(populate, callback) {
2028 if (typeof populate == "function") {
2029 callback = populate;
2030 populate = false
2031 }
2032 FS.syncFSRequests++;
2033 if (FS.syncFSRequests > 1) {
2034 err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)
2035 }
2036 var mounts = FS.getMounts(FS.root.mount);
2037 var completed = 0;
2038
2039 function doCallback(errCode) {
swissChili281af442024-11-14 23:30:29 -05002040 assert(FS.syncFSRequests > 0);
swissChiliab615d82024-03-08 17:15:13 -05002041 FS.syncFSRequests--;
2042 return callback(errCode)
2043 }
2044
2045 function done(errCode) {
2046 if (errCode) {
2047 if (!done.errored) {
2048 done.errored = true;
2049 return doCallback(errCode)
2050 }
2051 return
2052 }
2053 if (++completed >= mounts.length) {
2054 doCallback(null)
2055 }
2056 }
2057 mounts.forEach(mount => {
2058 if (!mount.type.syncfs) {
2059 return done(null)
2060 }
2061 mount.type.syncfs(mount, populate, done)
2062 })
2063 },
2064 mount(type, opts, mountpoint) {
swissChili281af442024-11-14 23:30:29 -05002065 if (typeof type == "string") {
2066 throw type
2067 }
swissChiliab615d82024-03-08 17:15:13 -05002068 var root = mountpoint === "/";
2069 var pseudo = !mountpoint;
2070 var node;
2071 if (root && FS.root) {
2072 throw new FS.ErrnoError(10)
2073 } else if (!root && !pseudo) {
2074 var lookup = FS.lookupPath(mountpoint, {
2075 follow_mount: false
2076 });
2077 mountpoint = lookup.path;
2078 node = lookup.node;
2079 if (FS.isMountpoint(node)) {
2080 throw new FS.ErrnoError(10)
2081 }
2082 if (!FS.isDir(node.mode)) {
2083 throw new FS.ErrnoError(54)
2084 }
2085 }
2086 var mount = {
2087 type: type,
2088 opts: opts,
2089 mountpoint: mountpoint,
2090 mounts: []
2091 };
2092 var mountRoot = type.mount(mount);
2093 mountRoot.mount = mount;
2094 mount.root = mountRoot;
2095 if (root) {
2096 FS.root = mountRoot
2097 } else if (node) {
2098 node.mounted = mount;
2099 if (node.mount) {
2100 node.mount.mounts.push(mount)
2101 }
2102 }
2103 return mountRoot
2104 },
2105 unmount(mountpoint) {
2106 var lookup = FS.lookupPath(mountpoint, {
2107 follow_mount: false
2108 });
2109 if (!FS.isMountpoint(lookup.node)) {
2110 throw new FS.ErrnoError(28)
2111 }
2112 var node = lookup.node;
2113 var mount = node.mounted;
2114 var mounts = FS.getMounts(mount);
2115 Object.keys(FS.nameTable).forEach(hash => {
2116 var current = FS.nameTable[hash];
2117 while (current) {
2118 var next = current.name_next;
2119 if (mounts.includes(current.mount)) {
2120 FS.destroyNode(current)
2121 }
2122 current = next
2123 }
2124 });
2125 node.mounted = null;
2126 var idx = node.mount.mounts.indexOf(mount);
swissChili281af442024-11-14 23:30:29 -05002127 assert(idx !== -1);
swissChiliab615d82024-03-08 17:15:13 -05002128 node.mount.mounts.splice(idx, 1)
2129 },
2130 lookup(parent, name) {
2131 return parent.node_ops.lookup(parent, name)
2132 },
2133 mknod(path, mode, dev) {
2134 var lookup = FS.lookupPath(path, {
2135 parent: true
2136 });
2137 var parent = lookup.node;
2138 var name = PATH.basename(path);
2139 if (!name || name === "." || name === "..") {
2140 throw new FS.ErrnoError(28)
2141 }
2142 var errCode = FS.mayCreate(parent, name);
2143 if (errCode) {
2144 throw new FS.ErrnoError(errCode)
2145 }
2146 if (!parent.node_ops.mknod) {
2147 throw new FS.ErrnoError(63)
2148 }
2149 return parent.node_ops.mknod(parent, name, mode, dev)
2150 },
2151 create(path, mode) {
2152 mode = mode !== undefined ? mode : 438;
2153 mode &= 4095;
2154 mode |= 32768;
2155 return FS.mknod(path, mode, 0)
2156 },
2157 mkdir(path, mode) {
2158 mode = mode !== undefined ? mode : 511;
2159 mode &= 511 | 512;
2160 mode |= 16384;
2161 return FS.mknod(path, mode, 0)
2162 },
2163 mkdirTree(path, mode) {
2164 var dirs = path.split("/");
2165 var d = "";
2166 for (var i = 0; i < dirs.length; ++i) {
2167 if (!dirs[i]) continue;
2168 d += "/" + dirs[i];
2169 try {
2170 FS.mkdir(d, mode)
2171 } catch (e) {
2172 if (e.errno != 20) throw e
2173 }
2174 }
2175 },
2176 mkdev(path, mode, dev) {
2177 if (typeof dev == "undefined") {
2178 dev = mode;
2179 mode = 438
2180 }
2181 mode |= 8192;
2182 return FS.mknod(path, mode, dev)
2183 },
2184 symlink(oldpath, newpath) {
2185 if (!PATH_FS.resolve(oldpath)) {
2186 throw new FS.ErrnoError(44)
2187 }
2188 var lookup = FS.lookupPath(newpath, {
2189 parent: true
2190 });
2191 var parent = lookup.node;
2192 if (!parent) {
2193 throw new FS.ErrnoError(44)
2194 }
2195 var newname = PATH.basename(newpath);
2196 var errCode = FS.mayCreate(parent, newname);
2197 if (errCode) {
2198 throw new FS.ErrnoError(errCode)
2199 }
2200 if (!parent.node_ops.symlink) {
2201 throw new FS.ErrnoError(63)
2202 }
2203 return parent.node_ops.symlink(parent, newname, oldpath)
2204 },
2205 rename(old_path, new_path) {
2206 var old_dirname = PATH.dirname(old_path);
2207 var new_dirname = PATH.dirname(new_path);
2208 var old_name = PATH.basename(old_path);
2209 var new_name = PATH.basename(new_path);
2210 var lookup, old_dir, new_dir;
2211 lookup = FS.lookupPath(old_path, {
2212 parent: true
2213 });
2214 old_dir = lookup.node;
2215 lookup = FS.lookupPath(new_path, {
2216 parent: true
2217 });
2218 new_dir = lookup.node;
2219 if (!old_dir || !new_dir) throw new FS.ErrnoError(44);
2220 if (old_dir.mount !== new_dir.mount) {
2221 throw new FS.ErrnoError(75)
2222 }
2223 var old_node = FS.lookupNode(old_dir, old_name);
2224 var relative = PATH_FS.relative(old_path, new_dirname);
2225 if (relative.charAt(0) !== ".") {
2226 throw new FS.ErrnoError(28)
2227 }
2228 relative = PATH_FS.relative(new_path, old_dirname);
2229 if (relative.charAt(0) !== ".") {
2230 throw new FS.ErrnoError(55)
2231 }
2232 var new_node;
2233 try {
2234 new_node = FS.lookupNode(new_dir, new_name)
2235 } catch (e) {}
2236 if (old_node === new_node) {
2237 return
2238 }
2239 var isdir = FS.isDir(old_node.mode);
2240 var errCode = FS.mayDelete(old_dir, old_name, isdir);
2241 if (errCode) {
2242 throw new FS.ErrnoError(errCode)
2243 }
2244 errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);
2245 if (errCode) {
2246 throw new FS.ErrnoError(errCode)
2247 }
2248 if (!old_dir.node_ops.rename) {
2249 throw new FS.ErrnoError(63)
2250 }
2251 if (FS.isMountpoint(old_node) || new_node && FS.isMountpoint(new_node)) {
2252 throw new FS.ErrnoError(10)
2253 }
2254 if (new_dir !== old_dir) {
2255 errCode = FS.nodePermissions(old_dir, "w");
2256 if (errCode) {
2257 throw new FS.ErrnoError(errCode)
2258 }
2259 }
2260 FS.hashRemoveNode(old_node);
2261 try {
swissChili281af442024-11-14 23:30:29 -05002262 old_dir.node_ops.rename(old_node, new_dir, new_name);
2263 old_node.parent = new_dir
swissChiliab615d82024-03-08 17:15:13 -05002264 } catch (e) {
2265 throw e
2266 } finally {
2267 FS.hashAddNode(old_node)
2268 }
2269 },
2270 rmdir(path) {
2271 var lookup = FS.lookupPath(path, {
2272 parent: true
2273 });
2274 var parent = lookup.node;
2275 var name = PATH.basename(path);
2276 var node = FS.lookupNode(parent, name);
2277 var errCode = FS.mayDelete(parent, name, true);
2278 if (errCode) {
2279 throw new FS.ErrnoError(errCode)
2280 }
2281 if (!parent.node_ops.rmdir) {
2282 throw new FS.ErrnoError(63)
2283 }
2284 if (FS.isMountpoint(node)) {
2285 throw new FS.ErrnoError(10)
2286 }
2287 parent.node_ops.rmdir(parent, name);
2288 FS.destroyNode(node)
2289 },
2290 readdir(path) {
2291 var lookup = FS.lookupPath(path, {
2292 follow: true
2293 });
2294 var node = lookup.node;
2295 if (!node.node_ops.readdir) {
2296 throw new FS.ErrnoError(54)
2297 }
2298 return node.node_ops.readdir(node)
2299 },
2300 unlink(path) {
2301 var lookup = FS.lookupPath(path, {
2302 parent: true
2303 });
2304 var parent = lookup.node;
2305 if (!parent) {
2306 throw new FS.ErrnoError(44)
2307 }
2308 var name = PATH.basename(path);
2309 var node = FS.lookupNode(parent, name);
2310 var errCode = FS.mayDelete(parent, name, false);
2311 if (errCode) {
2312 throw new FS.ErrnoError(errCode)
2313 }
2314 if (!parent.node_ops.unlink) {
2315 throw new FS.ErrnoError(63)
2316 }
2317 if (FS.isMountpoint(node)) {
2318 throw new FS.ErrnoError(10)
2319 }
2320 parent.node_ops.unlink(parent, name);
2321 FS.destroyNode(node)
2322 },
2323 readlink(path) {
2324 var lookup = FS.lookupPath(path);
2325 var link = lookup.node;
2326 if (!link) {
2327 throw new FS.ErrnoError(44)
2328 }
2329 if (!link.node_ops.readlink) {
2330 throw new FS.ErrnoError(28)
2331 }
2332 return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link))
2333 },
2334 stat(path, dontFollow) {
2335 var lookup = FS.lookupPath(path, {
2336 follow: !dontFollow
2337 });
2338 var node = lookup.node;
2339 if (!node) {
2340 throw new FS.ErrnoError(44)
2341 }
2342 if (!node.node_ops.getattr) {
2343 throw new FS.ErrnoError(63)
2344 }
2345 return node.node_ops.getattr(node)
2346 },
2347 lstat(path) {
2348 return FS.stat(path, true)
2349 },
2350 chmod(path, mode, dontFollow) {
2351 var node;
2352 if (typeof path == "string") {
2353 var lookup = FS.lookupPath(path, {
2354 follow: !dontFollow
2355 });
2356 node = lookup.node
2357 } else {
2358 node = path
2359 }
2360 if (!node.node_ops.setattr) {
2361 throw new FS.ErrnoError(63)
2362 }
2363 node.node_ops.setattr(node, {
2364 mode: mode & 4095 | node.mode & ~4095,
2365 timestamp: Date.now()
2366 })
2367 },
2368 lchmod(path, mode) {
2369 FS.chmod(path, mode, true)
2370 },
2371 fchmod(fd, mode) {
2372 var stream = FS.getStreamChecked(fd);
2373 FS.chmod(stream.node, mode)
2374 },
2375 chown(path, uid, gid, dontFollow) {
2376 var node;
2377 if (typeof path == "string") {
2378 var lookup = FS.lookupPath(path, {
2379 follow: !dontFollow
2380 });
2381 node = lookup.node
2382 } else {
2383 node = path
2384 }
2385 if (!node.node_ops.setattr) {
2386 throw new FS.ErrnoError(63)
2387 }
2388 node.node_ops.setattr(node, {
2389 timestamp: Date.now()
2390 })
2391 },
2392 lchown(path, uid, gid) {
2393 FS.chown(path, uid, gid, true)
2394 },
2395 fchown(fd, uid, gid) {
2396 var stream = FS.getStreamChecked(fd);
2397 FS.chown(stream.node, uid, gid)
2398 },
2399 truncate(path, len) {
2400 if (len < 0) {
2401 throw new FS.ErrnoError(28)
2402 }
2403 var node;
2404 if (typeof path == "string") {
2405 var lookup = FS.lookupPath(path, {
2406 follow: true
2407 });
2408 node = lookup.node
2409 } else {
2410 node = path
2411 }
2412 if (!node.node_ops.setattr) {
2413 throw new FS.ErrnoError(63)
2414 }
2415 if (FS.isDir(node.mode)) {
2416 throw new FS.ErrnoError(31)
2417 }
2418 if (!FS.isFile(node.mode)) {
2419 throw new FS.ErrnoError(28)
2420 }
2421 var errCode = FS.nodePermissions(node, "w");
2422 if (errCode) {
2423 throw new FS.ErrnoError(errCode)
2424 }
2425 node.node_ops.setattr(node, {
2426 size: len,
2427 timestamp: Date.now()
2428 })
2429 },
2430 ftruncate(fd, len) {
2431 var stream = FS.getStreamChecked(fd);
2432 if ((stream.flags & 2097155) === 0) {
2433 throw new FS.ErrnoError(28)
2434 }
2435 FS.truncate(stream.node, len)
2436 },
2437 utime(path, atime, mtime) {
2438 var lookup = FS.lookupPath(path, {
2439 follow: true
2440 });
2441 var node = lookup.node;
2442 node.node_ops.setattr(node, {
2443 timestamp: Math.max(atime, mtime)
2444 })
2445 },
2446 open(path, flags, mode) {
2447 if (path === "") {
2448 throw new FS.ErrnoError(44)
2449 }
2450 flags = typeof flags == "string" ? FS_modeStringToFlags(flags) : flags;
swissChiliab615d82024-03-08 17:15:13 -05002451 if (flags & 64) {
swissChili281af442024-11-14 23:30:29 -05002452 mode = typeof mode == "undefined" ? 438 : mode;
swissChiliab615d82024-03-08 17:15:13 -05002453 mode = mode & 4095 | 32768
2454 } else {
2455 mode = 0
2456 }
2457 var node;
2458 if (typeof path == "object") {
2459 node = path
2460 } else {
2461 path = PATH.normalize(path);
2462 try {
2463 var lookup = FS.lookupPath(path, {
2464 follow: !(flags & 131072)
2465 });
2466 node = lookup.node
2467 } catch (e) {}
2468 }
2469 var created = false;
2470 if (flags & 64) {
2471 if (node) {
2472 if (flags & 128) {
2473 throw new FS.ErrnoError(20)
2474 }
2475 } else {
2476 node = FS.mknod(path, mode, 0);
2477 created = true
2478 }
2479 }
2480 if (!node) {
2481 throw new FS.ErrnoError(44)
2482 }
2483 if (FS.isChrdev(node.mode)) {
2484 flags &= ~512
2485 }
2486 if (flags & 65536 && !FS.isDir(node.mode)) {
2487 throw new FS.ErrnoError(54)
2488 }
2489 if (!created) {
2490 var errCode = FS.mayOpen(node, flags);
2491 if (errCode) {
2492 throw new FS.ErrnoError(errCode)
2493 }
2494 }
2495 if (flags & 512 && !created) {
2496 FS.truncate(node, 0)
2497 }
2498 flags &= ~(128 | 512 | 131072);
2499 var stream = FS.createStream({
2500 node: node,
2501 path: FS.getPath(node),
2502 flags: flags,
2503 seekable: true,
2504 position: 0,
2505 stream_ops: node.stream_ops,
2506 ungotten: [],
2507 error: false
2508 });
2509 if (stream.stream_ops.open) {
2510 stream.stream_ops.open(stream)
2511 }
2512 if (Module["logReadFiles"] && !(flags & 1)) {
2513 if (!FS.readFiles) FS.readFiles = {};
2514 if (!(path in FS.readFiles)) {
2515 FS.readFiles[path] = 1
2516 }
2517 }
2518 return stream
2519 },
2520 close(stream) {
2521 if (FS.isClosed(stream)) {
2522 throw new FS.ErrnoError(8)
2523 }
2524 if (stream.getdents) stream.getdents = null;
2525 try {
2526 if (stream.stream_ops.close) {
2527 stream.stream_ops.close(stream)
2528 }
2529 } catch (e) {
2530 throw e
2531 } finally {
2532 FS.closeStream(stream.fd)
2533 }
2534 stream.fd = null
2535 },
2536 isClosed(stream) {
2537 return stream.fd === null
2538 },
2539 llseek(stream, offset, whence) {
2540 if (FS.isClosed(stream)) {
2541 throw new FS.ErrnoError(8)
2542 }
2543 if (!stream.seekable || !stream.stream_ops.llseek) {
2544 throw new FS.ErrnoError(70)
2545 }
2546 if (whence != 0 && whence != 1 && whence != 2) {
2547 throw new FS.ErrnoError(28)
2548 }
2549 stream.position = stream.stream_ops.llseek(stream, offset, whence);
2550 stream.ungotten = [];
2551 return stream.position
2552 },
2553 read(stream, buffer, offset, length, position) {
swissChili281af442024-11-14 23:30:29 -05002554 assert(offset >= 0);
swissChiliab615d82024-03-08 17:15:13 -05002555 if (length < 0 || position < 0) {
2556 throw new FS.ErrnoError(28)
2557 }
2558 if (FS.isClosed(stream)) {
2559 throw new FS.ErrnoError(8)
2560 }
2561 if ((stream.flags & 2097155) === 1) {
2562 throw new FS.ErrnoError(8)
2563 }
2564 if (FS.isDir(stream.node.mode)) {
2565 throw new FS.ErrnoError(31)
2566 }
2567 if (!stream.stream_ops.read) {
2568 throw new FS.ErrnoError(28)
2569 }
2570 var seeking = typeof position != "undefined";
2571 if (!seeking) {
2572 position = stream.position
2573 } else if (!stream.seekable) {
2574 throw new FS.ErrnoError(70)
2575 }
2576 var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
2577 if (!seeking) stream.position += bytesRead;
2578 return bytesRead
2579 },
2580 write(stream, buffer, offset, length, position, canOwn) {
swissChili281af442024-11-14 23:30:29 -05002581 assert(offset >= 0);
swissChiliab615d82024-03-08 17:15:13 -05002582 if (length < 0 || position < 0) {
2583 throw new FS.ErrnoError(28)
2584 }
2585 if (FS.isClosed(stream)) {
2586 throw new FS.ErrnoError(8)
2587 }
2588 if ((stream.flags & 2097155) === 0) {
2589 throw new FS.ErrnoError(8)
2590 }
2591 if (FS.isDir(stream.node.mode)) {
2592 throw new FS.ErrnoError(31)
2593 }
2594 if (!stream.stream_ops.write) {
2595 throw new FS.ErrnoError(28)
2596 }
2597 if (stream.seekable && stream.flags & 1024) {
2598 FS.llseek(stream, 0, 2)
2599 }
2600 var seeking = typeof position != "undefined";
2601 if (!seeking) {
2602 position = stream.position
2603 } else if (!stream.seekable) {
2604 throw new FS.ErrnoError(70)
2605 }
2606 var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
2607 if (!seeking) stream.position += bytesWritten;
2608 return bytesWritten
2609 },
2610 allocate(stream, offset, length) {
2611 if (FS.isClosed(stream)) {
2612 throw new FS.ErrnoError(8)
2613 }
2614 if (offset < 0 || length <= 0) {
2615 throw new FS.ErrnoError(28)
2616 }
2617 if ((stream.flags & 2097155) === 0) {
2618 throw new FS.ErrnoError(8)
2619 }
2620 if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
2621 throw new FS.ErrnoError(43)
2622 }
2623 if (!stream.stream_ops.allocate) {
2624 throw new FS.ErrnoError(138)
2625 }
2626 stream.stream_ops.allocate(stream, offset, length)
2627 },
2628 mmap(stream, length, position, prot, flags) {
2629 if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {
2630 throw new FS.ErrnoError(2)
2631 }
2632 if ((stream.flags & 2097155) === 1) {
2633 throw new FS.ErrnoError(2)
2634 }
2635 if (!stream.stream_ops.mmap) {
2636 throw new FS.ErrnoError(43)
2637 }
swissChili281af442024-11-14 23:30:29 -05002638 if (!length) {
2639 throw new FS.ErrnoError(28)
2640 }
swissChiliab615d82024-03-08 17:15:13 -05002641 return stream.stream_ops.mmap(stream, length, position, prot, flags)
2642 },
2643 msync(stream, buffer, offset, length, mmapFlags) {
swissChili281af442024-11-14 23:30:29 -05002644 assert(offset >= 0);
swissChiliab615d82024-03-08 17:15:13 -05002645 if (!stream.stream_ops.msync) {
2646 return 0
2647 }
2648 return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags)
2649 },
swissChiliab615d82024-03-08 17:15:13 -05002650 ioctl(stream, cmd, arg) {
2651 if (!stream.stream_ops.ioctl) {
2652 throw new FS.ErrnoError(59)
2653 }
2654 return stream.stream_ops.ioctl(stream, cmd, arg)
2655 },
2656 readFile(path, opts = {}) {
2657 opts.flags = opts.flags || 0;
2658 opts.encoding = opts.encoding || "binary";
2659 if (opts.encoding !== "utf8" && opts.encoding !== "binary") {
2660 throw new Error(`Invalid encoding type "${opts.encoding}"`)
2661 }
2662 var ret;
2663 var stream = FS.open(path, opts.flags);
2664 var stat = FS.stat(path);
2665 var length = stat.size;
2666 var buf = new Uint8Array(length);
2667 FS.read(stream, buf, 0, length, 0);
2668 if (opts.encoding === "utf8") {
2669 ret = UTF8ArrayToString(buf, 0)
2670 } else if (opts.encoding === "binary") {
2671 ret = buf
2672 }
2673 FS.close(stream);
2674 return ret
2675 },
2676 writeFile(path, data, opts = {}) {
2677 opts.flags = opts.flags || 577;
2678 var stream = FS.open(path, opts.flags, opts.mode);
2679 if (typeof data == "string") {
2680 var buf = new Uint8Array(lengthBytesUTF8(data) + 1);
2681 var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
2682 FS.write(stream, buf, 0, actualNumBytes, undefined, opts.canOwn)
2683 } else if (ArrayBuffer.isView(data)) {
2684 FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn)
2685 } else {
2686 throw new Error("Unsupported data type")
2687 }
2688 FS.close(stream)
2689 },
2690 cwd: () => FS.currentPath,
2691 chdir(path) {
2692 var lookup = FS.lookupPath(path, {
2693 follow: true
2694 });
2695 if (lookup.node === null) {
2696 throw new FS.ErrnoError(44)
2697 }
2698 if (!FS.isDir(lookup.node.mode)) {
2699 throw new FS.ErrnoError(54)
2700 }
2701 var errCode = FS.nodePermissions(lookup.node, "x");
2702 if (errCode) {
2703 throw new FS.ErrnoError(errCode)
2704 }
2705 FS.currentPath = lookup.path
2706 },
2707 createDefaultDirectories() {
2708 FS.mkdir("/tmp");
2709 FS.mkdir("/home");
2710 FS.mkdir("/home/web_user")
2711 },
2712 createDefaultDevices() {
2713 FS.mkdir("/dev");
2714 FS.registerDevice(FS.makedev(1, 3), {
2715 read: () => 0,
2716 write: (stream, buffer, offset, length, pos) => length
2717 });
2718 FS.mkdev("/dev/null", FS.makedev(1, 3));
2719 TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
2720 TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
2721 FS.mkdev("/dev/tty", FS.makedev(5, 0));
2722 FS.mkdev("/dev/tty1", FS.makedev(6, 0));
2723 var randomBuffer = new Uint8Array(1024),
2724 randomLeft = 0;
2725 var randomByte = () => {
2726 if (randomLeft === 0) {
2727 randomLeft = randomFill(randomBuffer).byteLength
2728 }
2729 return randomBuffer[--randomLeft]
2730 };
2731 FS.createDevice("/dev", "random", randomByte);
2732 FS.createDevice("/dev", "urandom", randomByte);
2733 FS.mkdir("/dev/shm");
2734 FS.mkdir("/dev/shm/tmp")
2735 },
2736 createSpecialDirectories() {
2737 FS.mkdir("/proc");
2738 var proc_self = FS.mkdir("/proc/self");
2739 FS.mkdir("/proc/self/fd");
2740 FS.mount({
2741 mount() {
2742 var node = FS.createNode(proc_self, "fd", 16384 | 511, 73);
2743 node.node_ops = {
2744 lookup(parent, name) {
2745 var fd = +name;
2746 var stream = FS.getStreamChecked(fd);
2747 var ret = {
2748 parent: null,
2749 mount: {
2750 mountpoint: "fake"
2751 },
2752 node_ops: {
2753 readlink: () => stream.path
2754 }
2755 };
2756 ret.parent = ret;
2757 return ret
2758 }
2759 };
2760 return node
2761 }
2762 }, {}, "/proc/self/fd")
2763 },
swissChili281af442024-11-14 23:30:29 -05002764 createStandardStreams(input, output, error) {
2765 if (input) {
2766 FS.createDevice("/dev", "stdin", input)
swissChiliab615d82024-03-08 17:15:13 -05002767 } else {
2768 FS.symlink("/dev/tty", "/dev/stdin")
2769 }
swissChili281af442024-11-14 23:30:29 -05002770 if (output) {
2771 FS.createDevice("/dev", "stdout", null, output)
swissChiliab615d82024-03-08 17:15:13 -05002772 } else {
2773 FS.symlink("/dev/tty", "/dev/stdout")
2774 }
swissChili281af442024-11-14 23:30:29 -05002775 if (error) {
2776 FS.createDevice("/dev", "stderr", null, error)
swissChiliab615d82024-03-08 17:15:13 -05002777 } else {
2778 FS.symlink("/dev/tty1", "/dev/stderr")
2779 }
2780 var stdin = FS.open("/dev/stdin", 0);
2781 var stdout = FS.open("/dev/stdout", 1);
swissChili281af442024-11-14 23:30:29 -05002782 var stderr = FS.open("/dev/stderr", 1);
2783 assert(stdin.fd === 0, `invalid handle for stdin (${stdin.fd})`);
2784 assert(stdout.fd === 1, `invalid handle for stdout (${stdout.fd})`);
2785 assert(stderr.fd === 2, `invalid handle for stderr (${stderr.fd})`)
swissChiliab615d82024-03-08 17:15:13 -05002786 },
2787 staticInit() {
2788 [44].forEach(code => {
2789 FS.genericErrors[code] = new FS.ErrnoError(code);
2790 FS.genericErrors[code].stack = "<generic error, no stack>"
2791 });
2792 FS.nameTable = new Array(4096);
2793 FS.mount(MEMFS, {}, "/");
2794 FS.createDefaultDirectories();
2795 FS.createDefaultDevices();
2796 FS.createSpecialDirectories();
2797 FS.filesystems = {
swissChili281af442024-11-14 23:30:29 -05002798 MEMFS: MEMFS
swissChiliab615d82024-03-08 17:15:13 -05002799 }
2800 },
2801 init(input, output, error) {
swissChili281af442024-11-14 23:30:29 -05002802 assert(!FS.initialized, "FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)");
2803 FS.initialized = true;
2804 input ??= Module["stdin"];
2805 output ??= Module["stdout"];
2806 error ??= Module["stderr"];
2807 FS.createStandardStreams(input, output, error)
swissChiliab615d82024-03-08 17:15:13 -05002808 },
2809 quit() {
swissChili281af442024-11-14 23:30:29 -05002810 FS.initialized = false;
2811 _fflush(0);
swissChiliab615d82024-03-08 17:15:13 -05002812 for (var i = 0; i < FS.streams.length; i++) {
2813 var stream = FS.streams[i];
2814 if (!stream) {
2815 continue
2816 }
2817 FS.close(stream)
2818 }
2819 },
2820 findObject(path, dontResolveLastLink) {
2821 var ret = FS.analyzePath(path, dontResolveLastLink);
2822 if (!ret.exists) {
2823 return null
2824 }
2825 return ret.object
2826 },
2827 analyzePath(path, dontResolveLastLink) {
2828 try {
2829 var lookup = FS.lookupPath(path, {
2830 follow: !dontResolveLastLink
2831 });
2832 path = lookup.path
2833 } catch (e) {}
2834 var ret = {
2835 isRoot: false,
2836 exists: false,
2837 error: 0,
2838 name: null,
2839 path: null,
2840 object: null,
2841 parentExists: false,
2842 parentPath: null,
2843 parentObject: null
2844 };
2845 try {
2846 var lookup = FS.lookupPath(path, {
2847 parent: true
2848 });
2849 ret.parentExists = true;
2850 ret.parentPath = lookup.path;
2851 ret.parentObject = lookup.node;
2852 ret.name = PATH.basename(path);
2853 lookup = FS.lookupPath(path, {
2854 follow: !dontResolveLastLink
2855 });
2856 ret.exists = true;
2857 ret.path = lookup.path;
2858 ret.object = lookup.node;
2859 ret.name = lookup.node.name;
2860 ret.isRoot = lookup.path === "/"
2861 } catch (e) {
2862 ret.error = e.errno
2863 }
2864 return ret
2865 },
2866 createPath(parent, path, canRead, canWrite) {
2867 parent = typeof parent == "string" ? parent : FS.getPath(parent);
2868 var parts = path.split("/").reverse();
2869 while (parts.length) {
2870 var part = parts.pop();
2871 if (!part) continue;
2872 var current = PATH.join2(parent, part);
2873 try {
2874 FS.mkdir(current)
2875 } catch (e) {}
2876 parent = current
2877 }
2878 return current
2879 },
2880 createFile(parent, name, properties, canRead, canWrite) {
2881 var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);
2882 var mode = FS_getMode(canRead, canWrite);
2883 return FS.create(path, mode)
2884 },
2885 createDataFile(parent, name, data, canRead, canWrite, canOwn) {
2886 var path = name;
2887 if (parent) {
2888 parent = typeof parent == "string" ? parent : FS.getPath(parent);
2889 path = name ? PATH.join2(parent, name) : parent
2890 }
2891 var mode = FS_getMode(canRead, canWrite);
2892 var node = FS.create(path, mode);
2893 if (data) {
2894 if (typeof data == "string") {
2895 var arr = new Array(data.length);
2896 for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
2897 data = arr
2898 }
2899 FS.chmod(node, mode | 146);
2900 var stream = FS.open(node, 577);
2901 FS.write(stream, data, 0, data.length, 0, canOwn);
2902 FS.close(stream);
2903 FS.chmod(node, mode)
2904 }
2905 },
2906 createDevice(parent, name, input, output) {
2907 var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);
2908 var mode = FS_getMode(!!input, !!output);
2909 if (!FS.createDevice.major) FS.createDevice.major = 64;
2910 var dev = FS.makedev(FS.createDevice.major++, 0);
2911 FS.registerDevice(dev, {
2912 open(stream) {
2913 stream.seekable = false
2914 },
2915 close(stream) {
2916 if (output?.buffer?.length) {
2917 output(10)
2918 }
2919 },
2920 read(stream, buffer, offset, length, pos) {
2921 var bytesRead = 0;
2922 for (var i = 0; i < length; i++) {
2923 var result;
2924 try {
2925 result = input()
2926 } catch (e) {
2927 throw new FS.ErrnoError(29)
2928 }
2929 if (result === undefined && bytesRead === 0) {
2930 throw new FS.ErrnoError(6)
2931 }
2932 if (result === null || result === undefined) break;
2933 bytesRead++;
2934 buffer[offset + i] = result
2935 }
2936 if (bytesRead) {
2937 stream.node.timestamp = Date.now()
2938 }
2939 return bytesRead
2940 },
2941 write(stream, buffer, offset, length, pos) {
2942 for (var i = 0; i < length; i++) {
2943 try {
2944 output(buffer[offset + i])
2945 } catch (e) {
2946 throw new FS.ErrnoError(29)
2947 }
2948 }
2949 if (length) {
2950 stream.node.timestamp = Date.now()
2951 }
2952 return i
2953 }
2954 });
2955 return FS.mkdev(path, mode, dev)
2956 },
2957 forceLoadFile(obj) {
2958 if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
2959 if (typeof XMLHttpRequest != "undefined") {
2960 throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")
swissChili281af442024-11-14 23:30:29 -05002961 } else {
swissChiliab615d82024-03-08 17:15:13 -05002962 try {
swissChili281af442024-11-14 23:30:29 -05002963 obj.contents = readBinary(obj.url);
swissChiliab615d82024-03-08 17:15:13 -05002964 obj.usedBytes = obj.contents.length
2965 } catch (e) {
2966 throw new FS.ErrnoError(29)
2967 }
swissChiliab615d82024-03-08 17:15:13 -05002968 }
2969 },
2970 createLazyFile(parent, name, url, canRead, canWrite) {
swissChili281af442024-11-14 23:30:29 -05002971 class LazyUint8Array {
2972 constructor() {
2973 this.lengthKnown = false;
2974 this.chunks = []
swissChiliab615d82024-03-08 17:15:13 -05002975 }
swissChili281af442024-11-14 23:30:29 -05002976 get(idx) {
2977 if (idx > this.length - 1 || idx < 0) {
2978 return undefined
swissChiliab615d82024-03-08 17:15:13 -05002979 }
swissChili281af442024-11-14 23:30:29 -05002980 var chunkOffset = idx % this.chunkSize;
2981 var chunkNum = idx / this.chunkSize | 0;
2982 return this.getter(chunkNum)[chunkOffset]
2983 }
2984 setDataGetter(getter) {
2985 this.getter = getter
2986 }
2987 cacheLength() {
2988 var xhr = new XMLHttpRequest;
2989 xhr.open("HEAD", url, false);
swissChiliab615d82024-03-08 17:15:13 -05002990 xhr.send(null);
2991 if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
swissChili281af442024-11-14 23:30:29 -05002992 var datalength = Number(xhr.getResponseHeader("Content-length"));
2993 var header;
2994 var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
2995 var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
2996 var chunkSize = 1024 * 1024;
2997 if (!hasByteServing) chunkSize = datalength;
2998 var doXHR = (from, to) => {
2999 if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
3000 if (to > datalength - 1) throw new Error("only " + datalength + " bytes available! programmer error!");
3001 var xhr = new XMLHttpRequest;
3002 xhr.open("GET", url, false);
3003 if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
3004 xhr.responseType = "arraybuffer";
3005 if (xhr.overrideMimeType) {
3006 xhr.overrideMimeType("text/plain; charset=x-user-defined")
3007 }
3008 xhr.send(null);
3009 if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
3010 if (xhr.response !== undefined) {
3011 return new Uint8Array(xhr.response || [])
3012 }
3013 return intArrayFromString(xhr.responseText || "", true)
3014 };
3015 var lazyArray = this;
3016 lazyArray.setDataGetter(chunkNum => {
3017 var start = chunkNum * chunkSize;
3018 var end = (chunkNum + 1) * chunkSize - 1;
3019 end = Math.min(end, datalength - 1);
3020 if (typeof lazyArray.chunks[chunkNum] == "undefined") {
3021 lazyArray.chunks[chunkNum] = doXHR(start, end)
3022 }
3023 if (typeof lazyArray.chunks[chunkNum] == "undefined") throw new Error("doXHR failed!");
3024 return lazyArray.chunks[chunkNum]
3025 });
3026 if (usesGzip || !datalength) {
3027 chunkSize = datalength = 1;
3028 datalength = this.getter(0).length;
3029 chunkSize = datalength;
3030 out("LazyFiles on gzip forces download of the whole file when length is accessed")
swissChiliab615d82024-03-08 17:15:13 -05003031 }
swissChili281af442024-11-14 23:30:29 -05003032 this._length = datalength;
3033 this._chunkSize = chunkSize;
3034 this.lengthKnown = true
swissChiliab615d82024-03-08 17:15:13 -05003035 }
swissChili281af442024-11-14 23:30:29 -05003036 get length() {
3037 if (!this.lengthKnown) {
3038 this.cacheLength()
3039 }
3040 return this._length
3041 }
3042 get chunkSize() {
3043 if (!this.lengthKnown) {
3044 this.cacheLength()
3045 }
3046 return this._chunkSize
3047 }
3048 }
swissChiliab615d82024-03-08 17:15:13 -05003049 if (typeof XMLHttpRequest != "undefined") {
3050 if (!ENVIRONMENT_IS_WORKER) throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";
3051 var lazyArray = new LazyUint8Array;
swissChiliab615d82024-03-08 17:15:13 -05003052 var properties = {
3053 isDevice: false,
3054 contents: lazyArray
3055 }
3056 } else {
3057 var properties = {
3058 isDevice: false,
3059 url: url
3060 }
3061 }
3062 var node = FS.createFile(parent, name, properties, canRead, canWrite);
3063 if (properties.contents) {
3064 node.contents = properties.contents
3065 } else if (properties.url) {
3066 node.contents = null;
3067 node.url = properties.url
3068 }
3069 Object.defineProperties(node, {
3070 usedBytes: {
3071 get: function() {
3072 return this.contents.length
3073 }
3074 }
3075 });
3076 var stream_ops = {};
3077 var keys = Object.keys(node.stream_ops);
3078 keys.forEach(key => {
3079 var fn = node.stream_ops[key];
3080 stream_ops[key] = (...args) => {
3081 FS.forceLoadFile(node);
3082 return fn(...args)
3083 }
3084 });
3085
3086 function writeChunks(stream, buffer, offset, length, position) {
3087 var contents = stream.node.contents;
3088 if (position >= contents.length) return 0;
3089 var size = Math.min(contents.length - position, length);
swissChili281af442024-11-14 23:30:29 -05003090 assert(size >= 0);
swissChiliab615d82024-03-08 17:15:13 -05003091 if (contents.slice) {
3092 for (var i = 0; i < size; i++) {
3093 buffer[offset + i] = contents[position + i]
3094 }
3095 } else {
3096 for (var i = 0; i < size; i++) {
3097 buffer[offset + i] = contents.get(position + i)
3098 }
3099 }
3100 return size
3101 }
3102 stream_ops.read = (stream, buffer, offset, length, position) => {
3103 FS.forceLoadFile(node);
3104 return writeChunks(stream, buffer, offset, length, position)
3105 };
3106 stream_ops.mmap = (stream, length, position, prot, flags) => {
3107 FS.forceLoadFile(node);
3108 var ptr = mmapAlloc(length);
3109 if (!ptr) {
3110 throw new FS.ErrnoError(48)
3111 }
3112 writeChunks(stream, HEAP8, ptr, length, position);
3113 return {
3114 ptr: ptr,
3115 allocated: true
3116 }
3117 };
3118 node.stream_ops = stream_ops;
3119 return node
swissChili281af442024-11-14 23:30:29 -05003120 },
3121 absolutePath() {
3122 abort("FS.absolutePath has been removed; use PATH_FS.resolve instead")
3123 },
3124 createFolder() {
3125 abort("FS.createFolder has been removed; use FS.mkdir instead")
3126 },
3127 createLink() {
3128 abort("FS.createLink has been removed; use FS.symlink instead")
3129 },
3130 joinPath() {
3131 abort("FS.joinPath has been removed; use PATH.join instead")
3132 },
3133 mmapAlloc() {
3134 abort("FS.mmapAlloc has been replaced by the top level function mmapAlloc")
3135 },
3136 standardizePath() {
3137 abort("FS.standardizePath has been removed; use PATH.normalize instead")
swissChiliab615d82024-03-08 17:15:13 -05003138 }
3139 };
swissChiliab615d82024-03-08 17:15:13 -05003140 var SYSCALLS = {
3141 DEFAULT_POLLMASK: 5,
3142 calculateAt(dirfd, path, allowEmpty) {
3143 if (PATH.isAbs(path)) {
3144 return path
3145 }
3146 var dir;
3147 if (dirfd === -100) {
3148 dir = FS.cwd()
3149 } else {
3150 var dirstream = SYSCALLS.getStreamFromFD(dirfd);
3151 dir = dirstream.path
3152 }
3153 if (path.length == 0) {
3154 if (!allowEmpty) {
3155 throw new FS.ErrnoError(44)
3156 }
3157 return dir
3158 }
3159 return PATH.join2(dir, path)
3160 },
3161 doStat(func, path, buf) {
3162 var stat = func(path);
3163 HEAP32[buf >> 2] = stat.dev;
3164 HEAP32[buf + 4 >> 2] = stat.mode;
3165 HEAPU32[buf + 8 >> 2] = stat.nlink;
3166 HEAP32[buf + 12 >> 2] = stat.uid;
3167 HEAP32[buf + 16 >> 2] = stat.gid;
3168 HEAP32[buf + 20 >> 2] = stat.rdev;
3169 tempI64 = [stat.size >>> 0, (tempDouble = stat.size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[buf + 24 >> 2] = tempI64[0], HEAP32[buf + 28 >> 2] = tempI64[1];
3170 HEAP32[buf + 32 >> 2] = 4096;
3171 HEAP32[buf + 36 >> 2] = stat.blocks;
3172 var atime = stat.atime.getTime();
3173 var mtime = stat.mtime.getTime();
3174 var ctime = stat.ctime.getTime();
3175 tempI64 = [Math.floor(atime / 1e3) >>> 0, (tempDouble = Math.floor(atime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[buf + 40 >> 2] = tempI64[0], HEAP32[buf + 44 >> 2] = tempI64[1];
3176 HEAPU32[buf + 48 >> 2] = atime % 1e3 * 1e3;
3177 tempI64 = [Math.floor(mtime / 1e3) >>> 0, (tempDouble = Math.floor(mtime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[buf + 56 >> 2] = tempI64[0], HEAP32[buf + 60 >> 2] = tempI64[1];
3178 HEAPU32[buf + 64 >> 2] = mtime % 1e3 * 1e3;
3179 tempI64 = [Math.floor(ctime / 1e3) >>> 0, (tempDouble = Math.floor(ctime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[buf + 72 >> 2] = tempI64[0], HEAP32[buf + 76 >> 2] = tempI64[1];
3180 HEAPU32[buf + 80 >> 2] = ctime % 1e3 * 1e3;
3181 tempI64 = [stat.ino >>> 0, (tempDouble = stat.ino, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[buf + 88 >> 2] = tempI64[0], HEAP32[buf + 92 >> 2] = tempI64[1];
3182 return 0
3183 },
3184 doMsync(addr, stream, len, flags, offset) {
3185 if (!FS.isFile(stream.node.mode)) {
3186 throw new FS.ErrnoError(43)
3187 }
3188 if (flags & 2) {
3189 return 0
3190 }
3191 var buffer = HEAPU8.slice(addr, addr + len);
3192 FS.msync(stream, buffer, offset, len, flags)
3193 },
swissChiliab615d82024-03-08 17:15:13 -05003194 getStreamFromFD(fd) {
3195 var stream = FS.getStreamChecked(fd);
3196 return stream
swissChili281af442024-11-14 23:30:29 -05003197 },
3198 varargs: undefined,
3199 getStr(ptr) {
3200 var ret = UTF8ToString(ptr);
3201 return ret
swissChiliab615d82024-03-08 17:15:13 -05003202 }
3203 };
3204
3205 function ___syscall_fcntl64(fd, cmd, varargs) {
3206 SYSCALLS.varargs = varargs;
3207 try {
3208 var stream = SYSCALLS.getStreamFromFD(fd);
3209 switch (cmd) {
3210 case 0: {
swissChili281af442024-11-14 23:30:29 -05003211 var arg = syscallGetVarargI();
swissChiliab615d82024-03-08 17:15:13 -05003212 if (arg < 0) {
3213 return -28
3214 }
3215 while (FS.streams[arg]) {
3216 arg++
3217 }
3218 var newStream;
swissChili281af442024-11-14 23:30:29 -05003219 newStream = FS.dupStream(stream, arg);
swissChiliab615d82024-03-08 17:15:13 -05003220 return newStream.fd
3221 }
3222 case 1:
3223 case 2:
3224 return 0;
3225 case 3:
3226 return stream.flags;
3227 case 4: {
swissChili281af442024-11-14 23:30:29 -05003228 var arg = syscallGetVarargI();
swissChiliab615d82024-03-08 17:15:13 -05003229 stream.flags |= arg;
3230 return 0
3231 }
3232 case 12: {
swissChili281af442024-11-14 23:30:29 -05003233 var arg = syscallGetVarargP();
swissChiliab615d82024-03-08 17:15:13 -05003234 var offset = 0;
3235 HEAP16[arg + offset >> 1] = 2;
3236 return 0
3237 }
3238 case 13:
3239 case 14:
3240 return 0
3241 }
3242 return -28
3243 } catch (e) {
3244 if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
3245 return -e.errno
3246 }
3247 }
3248
swissChili281af442024-11-14 23:30:29 -05003249 function ___syscall_fstat64(fd, buf) {
3250 try {
3251 var stream = SYSCALLS.getStreamFromFD(fd);
3252 return SYSCALLS.doStat(FS.stat, stream.path, buf)
3253 } catch (e) {
3254 if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
3255 return -e.errno
3256 }
3257 }
3258
swissChiliab615d82024-03-08 17:15:13 -05003259 function ___syscall_ioctl(fd, op, varargs) {
3260 SYSCALLS.varargs = varargs;
3261 try {
3262 var stream = SYSCALLS.getStreamFromFD(fd);
3263 switch (op) {
3264 case 21509: {
3265 if (!stream.tty) return -59;
3266 return 0
3267 }
3268 case 21505: {
3269 if (!stream.tty) return -59;
3270 if (stream.tty.ops.ioctl_tcgets) {
3271 var termios = stream.tty.ops.ioctl_tcgets(stream);
swissChili281af442024-11-14 23:30:29 -05003272 var argp = syscallGetVarargP();
swissChiliab615d82024-03-08 17:15:13 -05003273 HEAP32[argp >> 2] = termios.c_iflag || 0;
3274 HEAP32[argp + 4 >> 2] = termios.c_oflag || 0;
3275 HEAP32[argp + 8 >> 2] = termios.c_cflag || 0;
3276 HEAP32[argp + 12 >> 2] = termios.c_lflag || 0;
3277 for (var i = 0; i < 32; i++) {
3278 HEAP8[argp + i + 17] = termios.c_cc[i] || 0
3279 }
3280 return 0
3281 }
3282 return 0
3283 }
3284 case 21510:
3285 case 21511:
3286 case 21512: {
3287 if (!stream.tty) return -59;
3288 return 0
3289 }
3290 case 21506:
3291 case 21507:
3292 case 21508: {
3293 if (!stream.tty) return -59;
3294 if (stream.tty.ops.ioctl_tcsets) {
swissChili281af442024-11-14 23:30:29 -05003295 var argp = syscallGetVarargP();
swissChiliab615d82024-03-08 17:15:13 -05003296 var c_iflag = HEAP32[argp >> 2];
3297 var c_oflag = HEAP32[argp + 4 >> 2];
3298 var c_cflag = HEAP32[argp + 8 >> 2];
3299 var c_lflag = HEAP32[argp + 12 >> 2];
3300 var c_cc = [];
3301 for (var i = 0; i < 32; i++) {
3302 c_cc.push(HEAP8[argp + i + 17])
3303 }
3304 return stream.tty.ops.ioctl_tcsets(stream.tty, op, {
3305 c_iflag: c_iflag,
3306 c_oflag: c_oflag,
3307 c_cflag: c_cflag,
3308 c_lflag: c_lflag,
3309 c_cc: c_cc
3310 })
3311 }
3312 return 0
3313 }
3314 case 21519: {
3315 if (!stream.tty) return -59;
swissChili281af442024-11-14 23:30:29 -05003316 var argp = syscallGetVarargP();
swissChiliab615d82024-03-08 17:15:13 -05003317 HEAP32[argp >> 2] = 0;
3318 return 0
3319 }
3320 case 21520: {
3321 if (!stream.tty) return -59;
3322 return -28
3323 }
3324 case 21531: {
swissChili281af442024-11-14 23:30:29 -05003325 var argp = syscallGetVarargP();
swissChiliab615d82024-03-08 17:15:13 -05003326 return FS.ioctl(stream, op, argp)
3327 }
3328 case 21523: {
3329 if (!stream.tty) return -59;
3330 if (stream.tty.ops.ioctl_tiocgwinsz) {
3331 var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);
swissChili281af442024-11-14 23:30:29 -05003332 var argp = syscallGetVarargP();
swissChiliab615d82024-03-08 17:15:13 -05003333 HEAP16[argp >> 1] = winsize[0];
3334 HEAP16[argp + 2 >> 1] = winsize[1]
3335 }
3336 return 0
3337 }
3338 case 21524: {
3339 if (!stream.tty) return -59;
3340 return 0
3341 }
3342 case 21515: {
3343 if (!stream.tty) return -59;
3344 return 0
3345 }
3346 default:
3347 return -28
3348 }
3349 } catch (e) {
3350 if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
3351 return -e.errno
3352 }
3353 }
3354
swissChili281af442024-11-14 23:30:29 -05003355 function ___syscall_lstat64(path, buf) {
3356 try {
3357 path = SYSCALLS.getStr(path);
3358 return SYSCALLS.doStat(FS.lstat, path, buf)
3359 } catch (e) {
3360 if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
3361 return -e.errno
3362 }
3363 }
3364
3365 function ___syscall_newfstatat(dirfd, path, buf, flags) {
3366 try {
3367 path = SYSCALLS.getStr(path);
3368 var nofollow = flags & 256;
3369 var allowEmpty = flags & 4096;
3370 flags = flags & ~6400;
3371 assert(!flags, `unknown flags in __syscall_newfstatat: ${flags}`);
3372 path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);
3373 return SYSCALLS.doStat(nofollow ? FS.lstat : FS.stat, path, buf)
3374 } catch (e) {
3375 if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
3376 return -e.errno
3377 }
3378 }
3379
swissChiliab615d82024-03-08 17:15:13 -05003380 function ___syscall_openat(dirfd, path, flags, varargs) {
3381 SYSCALLS.varargs = varargs;
3382 try {
3383 path = SYSCALLS.getStr(path);
3384 path = SYSCALLS.calculateAt(dirfd, path);
swissChili281af442024-11-14 23:30:29 -05003385 var mode = varargs ? syscallGetVarargI() : 0;
swissChiliab615d82024-03-08 17:15:13 -05003386 return FS.open(path, flags, mode).fd
3387 } catch (e) {
3388 if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
3389 return -e.errno
3390 }
3391 }
3392
3393 function ___syscall_stat64(path, buf) {
3394 try {
3395 path = SYSCALLS.getStr(path);
3396 return SYSCALLS.doStat(FS.stat, path, buf)
3397 } catch (e) {
3398 if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
3399 return -e.errno
3400 }
3401 }
swissChili281af442024-11-14 23:30:29 -05003402 var __abort_js = () => {
3403 abort("native code called abort()")
3404 };
3405 var __emscripten_memcpy_js = (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num);
3406 var __emscripten_runtime_keepalive_clear = () => {
3407 noExitRuntime = false;
3408 runtimeKeepaliveCounter = 0
3409 };
3410 var timers = {};
3411 var handleException = e => {
3412 if (e instanceof ExitStatus || e == "unwind") {
3413 return EXITSTATUS
3414 }
3415 checkStackCookie();
3416 if (e instanceof WebAssembly.RuntimeError) {
3417 if (_emscripten_stack_get_current() <= 0) {
3418 err("Stack overflow detected. You can try increasing -sSTACK_SIZE (currently set to 65536)")
3419 }
3420 }
3421 quit_(1, e)
3422 };
3423 var runtimeKeepaliveCounter = 0;
3424 var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0;
3425 var _proc_exit = code => {
3426 EXITSTATUS = code;
3427 if (!keepRuntimeAlive()) {
3428 Module["onExit"]?.(code);
3429 ABORT = true
3430 }
3431 quit_(code, new ExitStatus(code))
3432 };
3433 var exitJS = (status, implicit) => {
3434 EXITSTATUS = status;
3435 checkUnflushedContent();
3436 if (keepRuntimeAlive() && !implicit) {
3437 var msg = `program exited (with status: ${status}), but keepRuntimeAlive() is set (counter=${runtimeKeepaliveCounter}) due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)`;
3438 readyPromiseReject(msg);
3439 err(msg)
3440 }
3441 _proc_exit(status)
3442 };
3443 var _exit = exitJS;
3444 var maybeExit = () => {
3445 if (!keepRuntimeAlive()) {
3446 try {
3447 _exit(EXITSTATUS)
3448 } catch (e) {
3449 handleException(e)
3450 }
3451 }
3452 };
3453 var callUserCallback = func => {
3454 if (ABORT) {
3455 err("user callback triggered after runtime exited or application aborted. Ignoring.");
3456 return
3457 }
3458 try {
3459 func();
3460 maybeExit()
3461 } catch (e) {
3462 handleException(e)
3463 }
3464 };
3465 var _emscripten_get_now;
3466 _emscripten_get_now = () => performance.now();
3467 var __setitimer_js = (which, timeout_ms) => {
3468 if (timers[which]) {
3469 clearTimeout(timers[which].id);
3470 delete timers[which]
3471 }
3472 if (!timeout_ms) return 0;
3473 var id = setTimeout(() => {
3474 assert(which in timers);
3475 delete timers[which];
3476 callUserCallback(() => __emscripten_timeout(which, _emscripten_get_now()))
3477 }, timeout_ms);
3478 timers[which] = {
3479 id: id,
3480 timeout_ms: timeout_ms
3481 };
3482 return 0
3483 };
swissChiliab615d82024-03-08 17:15:13 -05003484 var abortOnCannotGrowMemory = requestedSize => {
swissChili281af442024-11-14 23:30:29 -05003485 abort(`Cannot enlarge memory arrays to size ${requestedSize} bytes (OOM). Either (1) compile with -sINITIAL_MEMORY=X with X higher than the current value ${HEAP8.length}, (2) compile with -sALLOW_MEMORY_GROWTH which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -sABORTING_MALLOC=0`)
swissChiliab615d82024-03-08 17:15:13 -05003486 };
3487 var _emscripten_resize_heap = requestedSize => {
3488 var oldSize = HEAPU8.length;
3489 requestedSize >>>= 0;
3490 abortOnCannotGrowMemory(requestedSize)
3491 };
3492 var ENV = {};
3493 var getExecutableName = () => thisProgram || "./this.program";
3494 var getEnvStrings = () => {
3495 if (!getEnvStrings.strings) {
3496 var lang = (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8";
3497 var env = {
swissChili281af442024-11-14 23:30:29 -05003498 USER: "web_user",
3499 LOGNAME: "web_user",
3500 PATH: "/",
3501 PWD: "/",
3502 HOME: "/home/web_user",
3503 LANG: lang,
3504 _: getExecutableName()
swissChiliab615d82024-03-08 17:15:13 -05003505 };
3506 for (var x in ENV) {
3507 if (ENV[x] === undefined) delete env[x];
3508 else env[x] = ENV[x]
3509 }
3510 var strings = [];
3511 for (var x in env) {
3512 strings.push(`${x}=${env[x]}`)
3513 }
3514 getEnvStrings.strings = strings
3515 }
3516 return getEnvStrings.strings
3517 };
3518 var stringToAscii = (str, buffer) => {
3519 for (var i = 0; i < str.length; ++i) {
swissChili281af442024-11-14 23:30:29 -05003520 assert(str.charCodeAt(i) === (str.charCodeAt(i) & 255));
swissChiliab615d82024-03-08 17:15:13 -05003521 HEAP8[buffer++] = str.charCodeAt(i)
3522 }
3523 HEAP8[buffer] = 0
3524 };
3525 var _environ_get = (__environ, environ_buf) => {
3526 var bufSize = 0;
3527 getEnvStrings().forEach((string, i) => {
3528 var ptr = environ_buf + bufSize;
3529 HEAPU32[__environ + i * 4 >> 2] = ptr;
3530 stringToAscii(string, ptr);
3531 bufSize += string.length + 1
3532 });
3533 return 0
3534 };
3535 var _environ_sizes_get = (penviron_count, penviron_buf_size) => {
3536 var strings = getEnvStrings();
3537 HEAPU32[penviron_count >> 2] = strings.length;
3538 var bufSize = 0;
3539 strings.forEach(string => bufSize += string.length + 1);
3540 HEAPU32[penviron_buf_size >> 2] = bufSize;
3541 return 0
3542 };
swissChiliab615d82024-03-08 17:15:13 -05003543
3544 function _fd_close(fd) {
3545 try {
3546 var stream = SYSCALLS.getStreamFromFD(fd);
3547 FS.close(stream);
3548 return 0
3549 } catch (e) {
3550 if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
3551 return e.errno
3552 }
3553 }
swissChiliab615d82024-03-08 17:15:13 -05003554 var doReadv = (stream, iov, iovcnt, offset) => {
3555 var ret = 0;
3556 for (var i = 0; i < iovcnt; i++) {
3557 var ptr = HEAPU32[iov >> 2];
3558 var len = HEAPU32[iov + 4 >> 2];
3559 iov += 8;
3560 var curr = FS.read(stream, HEAP8, ptr, len, offset);
3561 if (curr < 0) return -1;
3562 ret += curr;
3563 if (curr < len) break;
swissChili281af442024-11-14 23:30:29 -05003564 if (typeof offset != "undefined") {
swissChiliab615d82024-03-08 17:15:13 -05003565 offset += curr
3566 }
3567 }
3568 return ret
3569 };
3570
3571 function _fd_read(fd, iov, iovcnt, pnum) {
3572 try {
3573 var stream = SYSCALLS.getStreamFromFD(fd);
3574 var num = doReadv(stream, iov, iovcnt);
3575 HEAPU32[pnum >> 2] = num;
3576 return 0
3577 } catch (e) {
3578 if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
3579 return e.errno
3580 }
3581 }
swissChili281af442024-11-14 23:30:29 -05003582 var convertI32PairToI53Checked = (lo, hi) => {
3583 assert(lo == lo >>> 0 || lo == (lo | 0));
3584 assert(hi === (hi | 0));
3585 return hi + 2097152 >>> 0 < 4194305 - !!lo ? (lo >>> 0) + hi * 4294967296 : NaN
3586 };
swissChiliab615d82024-03-08 17:15:13 -05003587
3588 function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
3589 var offset = convertI32PairToI53Checked(offset_low, offset_high);
3590 try {
3591 if (isNaN(offset)) return 61;
3592 var stream = SYSCALLS.getStreamFromFD(fd);
3593 FS.llseek(stream, offset, whence);
3594 tempI64 = [stream.position >>> 0, (tempDouble = stream.position, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[newOffset >> 2] = tempI64[0], HEAP32[newOffset + 4 >> 2] = tempI64[1];
3595 if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null;
3596 return 0
3597 } catch (e) {
3598 if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
3599 return e.errno
3600 }
3601 }
3602 var doWritev = (stream, iov, iovcnt, offset) => {
3603 var ret = 0;
3604 for (var i = 0; i < iovcnt; i++) {
3605 var ptr = HEAPU32[iov >> 2];
3606 var len = HEAPU32[iov + 4 >> 2];
3607 iov += 8;
3608 var curr = FS.write(stream, HEAP8, ptr, len, offset);
3609 if (curr < 0) return -1;
3610 ret += curr;
swissChili281af442024-11-14 23:30:29 -05003611 if (curr < len) {
3612 break
3613 }
3614 if (typeof offset != "undefined") {
swissChiliab615d82024-03-08 17:15:13 -05003615 offset += curr
3616 }
3617 }
3618 return ret
3619 };
3620
3621 function _fd_write(fd, iov, iovcnt, pnum) {
3622 try {
3623 var stream = SYSCALLS.getStreamFromFD(fd);
3624 var num = doWritev(stream, iov, iovcnt);
3625 HEAPU32[pnum >> 2] = num;
3626 return 0
3627 } catch (e) {
3628 if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
3629 return e.errno
3630 }
3631 }
3632 var runAndAbortIfError = func => {
3633 try {
3634 return func()
3635 } catch (e) {
3636 abort(e)
3637 }
3638 };
swissChiliab615d82024-03-08 17:15:13 -05003639 var runtimeKeepalivePush = () => {
3640 runtimeKeepaliveCounter += 1
3641 };
3642 var runtimeKeepalivePop = () => {
swissChili281af442024-11-14 23:30:29 -05003643 assert(runtimeKeepaliveCounter > 0);
swissChiliab615d82024-03-08 17:15:13 -05003644 runtimeKeepaliveCounter -= 1
3645 };
3646 var Asyncify = {
3647 instrumentWasmImports(imports) {
3648 var importPattern = /^(invoke_.*|__asyncjs__.*)$/;
3649 for (let [x, original] of Object.entries(imports)) {
swissChiliab615d82024-03-08 17:15:13 -05003650 if (typeof original == "function") {
swissChili281af442024-11-14 23:30:29 -05003651 let isAsyncifyImport = original.isAsync || importPattern.test(x);
3652 imports[x] = (...args) => {
3653 var originalAsyncifyState = Asyncify.state;
3654 try {
3655 return original(...args)
3656 } finally {
3657 var changedToDisabled = originalAsyncifyState === Asyncify.State.Normal && Asyncify.state === Asyncify.State.Disabled;
3658 var ignoredInvoke = x.startsWith("invoke_") && true;
3659 if (Asyncify.state !== originalAsyncifyState && !isAsyncifyImport && !changedToDisabled && !ignoredInvoke) {
3660 throw new Error(`import ${x} was not in ASYNCIFY_IMPORTS, but changed the state`)
3661 }
3662 }
3663 }
swissChiliab615d82024-03-08 17:15:13 -05003664 }
3665 }
3666 },
3667 instrumentWasmExports(exports) {
3668 var ret = {};
3669 for (let [x, original] of Object.entries(exports)) {
3670 if (typeof original == "function") {
3671 ret[x] = (...args) => {
3672 Asyncify.exportCallStack.push(x);
3673 try {
3674 return original(...args)
3675 } finally {
3676 if (!ABORT) {
3677 var y = Asyncify.exportCallStack.pop();
swissChili281af442024-11-14 23:30:29 -05003678 assert(y === x);
swissChiliab615d82024-03-08 17:15:13 -05003679 Asyncify.maybeStopUnwind()
3680 }
3681 }
3682 }
3683 } else {
3684 ret[x] = original
3685 }
3686 }
3687 return ret
3688 },
3689 State: {
3690 Normal: 0,
3691 Unwinding: 1,
3692 Rewinding: 2,
3693 Disabled: 3
3694 },
3695 state: 0,
3696 StackSize: 4096,
3697 currData: null,
3698 handleSleepReturnValue: 0,
3699 exportCallStack: [],
3700 callStackNameToId: {},
3701 callStackIdToName: {},
3702 callStackId: 0,
3703 asyncPromiseHandlers: null,
3704 sleepCallbacks: [],
3705 getCallStackId(funcName) {
3706 var id = Asyncify.callStackNameToId[funcName];
3707 if (id === undefined) {
3708 id = Asyncify.callStackId++;
3709 Asyncify.callStackNameToId[funcName] = id;
3710 Asyncify.callStackIdToName[id] = funcName
3711 }
3712 return id
3713 },
3714 maybeStopUnwind() {
3715 if (Asyncify.currData && Asyncify.state === Asyncify.State.Unwinding && Asyncify.exportCallStack.length === 0) {
3716 Asyncify.state = Asyncify.State.Normal;
3717 runAndAbortIfError(_asyncify_stop_unwind);
3718 if (typeof Fibers != "undefined") {
3719 Fibers.trampoline()
3720 }
3721 }
3722 },
3723 whenDone() {
swissChili281af442024-11-14 23:30:29 -05003724 assert(Asyncify.currData, "Tried to wait for an async operation when none is in progress.");
3725 assert(!Asyncify.asyncPromiseHandlers, "Cannot have multiple async operations in flight at once");
swissChiliab615d82024-03-08 17:15:13 -05003726 return new Promise((resolve, reject) => {
3727 Asyncify.asyncPromiseHandlers = {
3728 resolve: resolve,
3729 reject: reject
3730 }
3731 })
3732 },
3733 allocateData() {
3734 var ptr = _malloc(12 + Asyncify.StackSize);
3735 Asyncify.setDataHeader(ptr, ptr + 12, Asyncify.StackSize);
3736 Asyncify.setDataRewindFunc(ptr);
3737 return ptr
3738 },
3739 setDataHeader(ptr, stack, stackSize) {
3740 HEAPU32[ptr >> 2] = stack;
3741 HEAPU32[ptr + 4 >> 2] = stack + stackSize
3742 },
3743 setDataRewindFunc(ptr) {
3744 var bottomOfCallStack = Asyncify.exportCallStack[0];
3745 var rewindId = Asyncify.getCallStackId(bottomOfCallStack);
3746 HEAP32[ptr + 8 >> 2] = rewindId
3747 },
swissChili281af442024-11-14 23:30:29 -05003748 getDataRewindFuncName(ptr) {
swissChiliab615d82024-03-08 17:15:13 -05003749 var id = HEAP32[ptr + 8 >> 2];
3750 var name = Asyncify.callStackIdToName[id];
swissChili281af442024-11-14 23:30:29 -05003751 return name
3752 },
3753 getDataRewindFunc(name) {
swissChiliab615d82024-03-08 17:15:13 -05003754 var func = wasmExports[name];
3755 return func
3756 },
3757 doRewind(ptr) {
swissChili281af442024-11-14 23:30:29 -05003758 var name = Asyncify.getDataRewindFuncName(ptr);
3759 var func = Asyncify.getDataRewindFunc(name);
3760 return func()
swissChiliab615d82024-03-08 17:15:13 -05003761 },
3762 handleSleep(startAsync) {
swissChili281af442024-11-14 23:30:29 -05003763 assert(Asyncify.state !== Asyncify.State.Disabled, "Asyncify cannot be done during or after the runtime exits");
swissChiliab615d82024-03-08 17:15:13 -05003764 if (ABORT) return;
3765 if (Asyncify.state === Asyncify.State.Normal) {
3766 var reachedCallback = false;
3767 var reachedAfterCallback = false;
3768 startAsync((handleSleepReturnValue = 0) => {
swissChili281af442024-11-14 23:30:29 -05003769 assert(!handleSleepReturnValue || typeof handleSleepReturnValue == "number" || typeof handleSleepReturnValue == "boolean");
swissChiliab615d82024-03-08 17:15:13 -05003770 if (ABORT) return;
3771 Asyncify.handleSleepReturnValue = handleSleepReturnValue;
3772 reachedCallback = true;
3773 if (!reachedAfterCallback) {
3774 return
3775 }
swissChili281af442024-11-14 23:30:29 -05003776 assert(!Asyncify.exportCallStack.length, "Waking up (starting to rewind) must be done from JS, without compiled code on the stack.");
swissChiliab615d82024-03-08 17:15:13 -05003777 Asyncify.state = Asyncify.State.Rewinding;
3778 runAndAbortIfError(() => _asyncify_start_rewind(Asyncify.currData));
3779 if (typeof Browser != "undefined" && Browser.mainLoop.func) {
3780 Browser.mainLoop.resume()
3781 }
3782 var asyncWasmReturnValue, isError = false;
3783 try {
3784 asyncWasmReturnValue = Asyncify.doRewind(Asyncify.currData)
3785 } catch (err) {
3786 asyncWasmReturnValue = err;
3787 isError = true
3788 }
3789 var handled = false;
3790 if (!Asyncify.currData) {
3791 var asyncPromiseHandlers = Asyncify.asyncPromiseHandlers;
3792 if (asyncPromiseHandlers) {
3793 Asyncify.asyncPromiseHandlers = null;
3794 (isError ? asyncPromiseHandlers.reject : asyncPromiseHandlers.resolve)(asyncWasmReturnValue);
3795 handled = true
3796 }
3797 }
3798 if (isError && !handled) {
3799 throw asyncWasmReturnValue
3800 }
3801 });
3802 reachedAfterCallback = true;
3803 if (!reachedCallback) {
3804 Asyncify.state = Asyncify.State.Unwinding;
3805 Asyncify.currData = Asyncify.allocateData();
3806 if (typeof Browser != "undefined" && Browser.mainLoop.func) {
3807 Browser.mainLoop.pause()
3808 }
3809 runAndAbortIfError(() => _asyncify_start_unwind(Asyncify.currData))
3810 }
3811 } else if (Asyncify.state === Asyncify.State.Rewinding) {
3812 Asyncify.state = Asyncify.State.Normal;
3813 runAndAbortIfError(_asyncify_stop_rewind);
3814 _free(Asyncify.currData);
3815 Asyncify.currData = null;
3816 Asyncify.sleepCallbacks.forEach(callUserCallback)
3817 } else {
3818 abort(`invalid state: ${Asyncify.state}`)
3819 }
3820 return Asyncify.handleSleepReturnValue
3821 },
3822 handleAsync(startAsync) {
3823 return Asyncify.handleSleep(wakeUp => {
3824 startAsync().then(wakeUp)
3825 })
3826 }
3827 };
3828 var getCFunc = ident => {
3829 var func = Module["_" + ident];
swissChili281af442024-11-14 23:30:29 -05003830 assert(func, "Cannot call unknown function " + ident + ", make sure it is exported");
swissChiliab615d82024-03-08 17:15:13 -05003831 return func
3832 };
3833 var writeArrayToMemory = (array, buffer) => {
swissChili281af442024-11-14 23:30:29 -05003834 assert(array.length >= 0, "writeArrayToMemory array must have a length (should be an array or typed array)");
swissChiliab615d82024-03-08 17:15:13 -05003835 HEAP8.set(array, buffer)
3836 };
swissChili281af442024-11-14 23:30:29 -05003837 var stringToUTF8 = (str, outPtr, maxBytesToWrite) => {
3838 assert(typeof maxBytesToWrite == "number", "stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!");
3839 return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite)
3840 };
3841 var stackAlloc = sz => __emscripten_stack_alloc(sz);
swissChiliab615d82024-03-08 17:15:13 -05003842 var stringToUTF8OnStack = str => {
3843 var size = lengthBytesUTF8(str) + 1;
3844 var ret = stackAlloc(size);
3845 stringToUTF8(str, ret, size);
3846 return ret
3847 };
3848 var ccall = (ident, returnType, argTypes, args, opts) => {
3849 var toC = {
swissChili281af442024-11-14 23:30:29 -05003850 string: str => {
swissChiliab615d82024-03-08 17:15:13 -05003851 var ret = 0;
3852 if (str !== null && str !== undefined && str !== 0) {
3853 ret = stringToUTF8OnStack(str)
3854 }
3855 return ret
3856 },
swissChili281af442024-11-14 23:30:29 -05003857 array: arr => {
swissChiliab615d82024-03-08 17:15:13 -05003858 var ret = stackAlloc(arr.length);
3859 writeArrayToMemory(arr, ret);
3860 return ret
3861 }
3862 };
3863
3864 function convertReturnValue(ret) {
3865 if (returnType === "string") {
3866 return UTF8ToString(ret)
3867 }
3868 if (returnType === "boolean") return Boolean(ret);
3869 return ret
3870 }
3871 var func = getCFunc(ident);
3872 var cArgs = [];
3873 var stack = 0;
swissChili281af442024-11-14 23:30:29 -05003874 assert(returnType !== "array", 'Return type should not be "array".');
swissChiliab615d82024-03-08 17:15:13 -05003875 if (args) {
3876 for (var i = 0; i < args.length; i++) {
3877 var converter = toC[argTypes[i]];
3878 if (converter) {
3879 if (stack === 0) stack = stackSave();
3880 cArgs[i] = converter(args[i])
3881 } else {
3882 cArgs[i] = args[i]
3883 }
3884 }
3885 }
3886 var previousAsync = Asyncify.currData;
3887 var ret = func(...cArgs);
3888
3889 function onDone(ret) {
3890 runtimeKeepalivePop();
3891 if (stack !== 0) stackRestore(stack);
3892 return convertReturnValue(ret)
3893 }
3894 var asyncMode = opts?.async;
3895 runtimeKeepalivePush();
3896 if (Asyncify.currData != previousAsync) {
swissChili281af442024-11-14 23:30:29 -05003897 assert(!(previousAsync && Asyncify.currData), "We cannot start an async operation when one is already flight");
3898 assert(!(previousAsync && !Asyncify.currData), "We cannot stop an async operation in flight");
3899 assert(asyncMode, "The call to " + ident + " is running asynchronously. If this was intended, add the async option to the ccall/cwrap call.");
swissChiliab615d82024-03-08 17:15:13 -05003900 return Asyncify.whenDone().then(onDone)
3901 }
3902 ret = onDone(ret);
3903 if (asyncMode) return Promise.resolve(ret);
3904 return ret
3905 };
swissChili281af442024-11-14 23:30:29 -05003906 var cwrap = (ident, returnType, argTypes, opts) => (...args) => ccall(ident, returnType, argTypes, args, opts);
swissChiliab615d82024-03-08 17:15:13 -05003907 var stringToNewUTF8 = str => {
3908 var size = lengthBytesUTF8(str) + 1;
3909 var ret = _malloc(size);
3910 if (ret) stringToUTF8(str, ret, size);
3911 return ret
3912 };
swissChili281af442024-11-14 23:30:29 -05003913 var FS_createPath = FS.createPath;
3914 var FS_unlink = path => FS.unlink(path);
3915 var FS_createLazyFile = FS.createLazyFile;
3916 var FS_createDevice = FS.createDevice;
swissChiliab615d82024-03-08 17:15:13 -05003917 FS.createPreloadedFile = FS_createPreloadedFile;
3918 FS.staticInit();
3919 Module["FS_createPath"] = FS.createPath;
3920 Module["FS_createDataFile"] = FS.createDataFile;
3921 Module["FS_createPreloadedFile"] = FS.createPreloadedFile;
3922 Module["FS_unlink"] = FS.unlink;
3923 Module["FS_createLazyFile"] = FS.createLazyFile;
3924 Module["FS_createDevice"] = FS.createDevice;
swissChili281af442024-11-14 23:30:29 -05003925
3926 function checkIncomingModuleAPI() {
3927 ignoredModuleProp("fetchSettings")
3928 }
swissChiliab615d82024-03-08 17:15:13 -05003929 var wasmImports = {
swissChili281af442024-11-14 23:30:29 -05003930 __syscall_fcntl64: ___syscall_fcntl64,
3931 __syscall_fstat64: ___syscall_fstat64,
3932 __syscall_ioctl: ___syscall_ioctl,
3933 __syscall_lstat64: ___syscall_lstat64,
3934 __syscall_newfstatat: ___syscall_newfstatat,
3935 __syscall_openat: ___syscall_openat,
3936 __syscall_stat64: ___syscall_stat64,
3937 _abort_js: __abort_js,
3938 _emscripten_memcpy_js: __emscripten_memcpy_js,
3939 _emscripten_runtime_keepalive_clear: __emscripten_runtime_keepalive_clear,
3940 _setitimer_js: __setitimer_js,
3941 emscripten_resize_heap: _emscripten_resize_heap,
3942 environ_get: _environ_get,
3943 environ_sizes_get: _environ_sizes_get,
3944 exit: _exit,
3945 fd_close: _fd_close,
3946 fd_read: _fd_read,
3947 fd_seek: _fd_seek,
3948 fd_write: _fd_write,
3949 proc_exit: _proc_exit
swissChiliab615d82024-03-08 17:15:13 -05003950 };
3951 var wasmExports = createWasm();
swissChili281af442024-11-14 23:30:29 -05003952 var ___wasm_call_ctors = createExportWrapper("__wasm_call_ctors", 0);
3953 var _free = createExportWrapper("free", 1);
3954 var _malloc = createExportWrapper("malloc", 1);
3955 var _strerror = createExportWrapper("strerror", 1);
3956 var _test_int = Module["_test_int"] = createExportWrapper("test_int", 2);
3957 var _do_a_conversion = Module["_do_a_conversion"] = createExportWrapper("do_a_conversion", 3);
3958 var _fflush = createExportWrapper("fflush", 1);
3959 var __emscripten_timeout = createExportWrapper("_emscripten_timeout", 2);
3960 var __emscripten_tempret_set = createExportWrapper("_emscripten_tempret_set", 1);
3961 var _emscripten_stack_init = () => (_emscripten_stack_init = wasmExports["emscripten_stack_init"])();
3962 var _emscripten_stack_get_free = () => (_emscripten_stack_get_free = wasmExports["emscripten_stack_get_free"])();
3963 var _emscripten_stack_get_base = () => (_emscripten_stack_get_base = wasmExports["emscripten_stack_get_base"])();
3964 var _emscripten_stack_get_end = () => (_emscripten_stack_get_end = wasmExports["emscripten_stack_get_end"])();
3965 var __emscripten_stack_restore = a0 => (__emscripten_stack_restore = wasmExports["_emscripten_stack_restore"])(a0);
3966 var __emscripten_stack_alloc = a0 => (__emscripten_stack_alloc = wasmExports["_emscripten_stack_alloc"])(a0);
3967 var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports["emscripten_stack_get_current"])();
3968 var ___cxa_increment_exception_refcount = createExportWrapper("__cxa_increment_exception_refcount", 1);
3969 var dynCall_ii = Module["dynCall_ii"] = createExportWrapper("dynCall_ii", 2);
3970 var dynCall_iiii = Module["dynCall_iiii"] = createExportWrapper("dynCall_iiii", 4);
3971 var dynCall_iii = Module["dynCall_iii"] = createExportWrapper("dynCall_iii", 3);
3972 var dynCall_jiji = Module["dynCall_jiji"] = createExportWrapper("dynCall_jiji", 5);
3973 var dynCall_iidiiii = Module["dynCall_iidiiii"] = createExportWrapper("dynCall_iidiiii", 7);
3974 var dynCall_vii = Module["dynCall_vii"] = createExportWrapper("dynCall_vii", 3);
3975 var dynCall_v = Module["dynCall_v"] = createExportWrapper("dynCall_v", 1);
3976 var dynCall_dd = Module["dynCall_dd"] = createExportWrapper("dynCall_dd", 2);
3977 var dynCall_vi = Module["dynCall_vi"] = createExportWrapper("dynCall_vi", 2);
3978 var _asyncify_start_unwind = createExportWrapper("asyncify_start_unwind", 1);
3979 var _asyncify_stop_unwind = createExportWrapper("asyncify_stop_unwind", 0);
3980 var _asyncify_start_rewind = createExportWrapper("asyncify_start_rewind", 1);
3981 var _asyncify_stop_rewind = createExportWrapper("asyncify_stop_rewind", 0);
swissChiliab615d82024-03-08 17:15:13 -05003982 Module["addRunDependency"] = addRunDependency;
3983 Module["removeRunDependency"] = removeRunDependency;
swissChiliab615d82024-03-08 17:15:13 -05003984 Module["ccall"] = ccall;
3985 Module["cwrap"] = cwrap;
3986 Module["stringToNewUTF8"] = stringToNewUTF8;
swissChili281af442024-11-14 23:30:29 -05003987 Module["FS_createPreloadedFile"] = FS_createPreloadedFile;
3988 Module["FS_unlink"] = FS_unlink;
3989 Module["FS_createPath"] = FS_createPath;
3990 Module["FS_createDevice"] = FS_createDevice;
3991 Module["FS_createDataFile"] = FS_createDataFile;
3992 Module["FS_createLazyFile"] = FS_createLazyFile;
3993 var missingLibrarySymbols = ["writeI53ToI64", "writeI53ToI64Clamped", "writeI53ToI64Signaling", "writeI53ToU64Clamped", "writeI53ToU64Signaling", "readI53FromI64", "readI53FromU64", "convertI32PairToI53", "convertU32PairToI53", "getTempRet0", "setTempRet0", "growMemory", "inetPton4", "inetNtop4", "inetPton6", "inetNtop6", "readSockaddr", "writeSockaddr", "emscriptenLog", "readEmAsmArgs", "jstoi_q", "listenOnce", "autoResumeAudioContext", "dynCallLegacy", "getDynCaller", "dynCall", "setWasmTableEntry", "getWasmTableEntry", "asmjsMangle", "HandleAllocator", "getNativeTypeSize", "STACK_SIZE", "STACK_ALIGN", "POINTER_SIZE", "ASSERTIONS", "uleb128Encode", "generateFuncType", "convertJsFunctionToWasm", "getEmptyTableSlot", "updateTableMap", "getFunctionAddress", "addFunction", "removeFunction", "reallyNegative", "unSign", "strLen", "reSign", "formatString", "intArrayToString", "AsciiToString", "UTF16ToString", "stringToUTF16", "lengthBytesUTF16", "UTF32ToString", "stringToUTF32", "lengthBytesUTF32", "registerKeyEventCallback", "maybeCStringToJsString", "findEventTarget", "getBoundingClientRect", "fillMouseEventData", "registerMouseEventCallback", "registerWheelEventCallback", "registerUiEventCallback", "registerFocusEventCallback", "fillDeviceOrientationEventData", "registerDeviceOrientationEventCallback", "fillDeviceMotionEventData", "registerDeviceMotionEventCallback", "screenOrientation", "fillOrientationChangeEventData", "registerOrientationChangeEventCallback", "fillFullscreenChangeEventData", "registerFullscreenChangeEventCallback", "JSEvents_requestFullscreen", "JSEvents_resizeCanvasForFullscreen", "registerRestoreOldStyle", "hideEverythingExceptGivenElement", "restoreHiddenElements", "setLetterbox", "softFullscreenResizeWebGLRenderTarget", "doRequestFullscreen", "fillPointerlockChangeEventData", "registerPointerlockChangeEventCallback", "registerPointerlockErrorEventCallback", "requestPointerLock", "fillVisibilityChangeEventData", "registerVisibilityChangeEventCallback", "registerTouchEventCallback", "fillGamepadEventData", "registerGamepadEventCallback", "registerBeforeUnloadEventCallback", "fillBatteryEventData", "battery", "registerBatteryEventCallback", "setCanvasElementSize", "getCanvasElementSize", "jsStackTrace", "getCallstack", "convertPCtoSourceLocation", "checkWasiClock", "wasiRightsToMuslOFlags", "wasiOFlagsToMuslOFlags", "createDyncallWrapper", "safeSetTimeout", "setImmediateWrapped", "clearImmediateWrapped", "polyfillSetImmediate", "getPromise", "makePromise", "idsToPromises", "makePromiseCallback", "ExceptionInfo", "findMatchingCatch", "Browser_asyncPrepareDataCounter", "setMainLoop", "isLeapYear", "ydayFromDate", "arraySum", "addDays", "getSocketFromFD", "getSocketAddress", "FS_mkdirTree", "_setNetworkCallback", "heapObjectForWebGLType", "toTypedArrayIndex", "webgl_enable_ANGLE_instanced_arrays", "webgl_enable_OES_vertex_array_object", "webgl_enable_WEBGL_draw_buffers", "webgl_enable_WEBGL_multi_draw", "emscriptenWebGLGet", "computeUnpackAlignedImageSize", "colorChannelsInGlTextureFormat", "emscriptenWebGLGetTexPixelData", "emscriptenWebGLGetUniform", "webglGetUniformLocation", "webglPrepareUniformLocationsBeforeFirstUse", "webglGetLeftBracePos", "emscriptenWebGLGetVertexAttrib", "__glGetActiveAttribOrUniform", "writeGLArray", "registerWebGlEventCallback", "ALLOC_NORMAL", "ALLOC_STACK", "allocate", "writeStringToMemory", "writeAsciiToMemory", "setErrNo", "demangle", "stackTrace"];
3994 missingLibrarySymbols.forEach(missingLibrarySymbol);
3995 var unexportedSymbols = ["run", "addOnPreRun", "addOnInit", "addOnPreMain", "addOnExit", "addOnPostRun", "out", "err", "callMain", "abort", "wasmMemory", "wasmExports", "writeStackCookie", "checkStackCookie", "convertI32PairToI53Checked", "stackSave", "stackRestore", "stackAlloc", "ptrToString", "zeroMemory", "exitJS", "getHeapMax", "abortOnCannotGrowMemory", "ENV", "ERRNO_CODES", "strError", "DNS", "Protocols", "Sockets", "initRandomFill", "randomFill", "timers", "warnOnce", "readEmAsmArgsArray", "jstoi_s", "getExecutableName", "handleException", "keepRuntimeAlive", "runtimeKeepalivePush", "runtimeKeepalivePop", "callUserCallback", "maybeExit", "asyncLoad", "alignMemory", "mmapAlloc", "wasmTable", "noExitRuntime", "getCFunc", "sigToWasmTypes", "freeTableIndexes", "functionsInTableMap", "setValue", "getValue", "PATH", "PATH_FS", "UTF8Decoder", "UTF8ArrayToString", "UTF8ToString", "stringToUTF8Array", "stringToUTF8", "lengthBytesUTF8", "intArrayFromString", "stringToAscii", "UTF16Decoder", "stringToUTF8OnStack", "writeArrayToMemory", "JSEvents", "specialHTMLTargets", "findCanvasEventTarget", "currentFullscreenStrategy", "restoreOldWindowedStyle", "UNWIND_CACHE", "ExitStatus", "getEnvStrings", "doReadv", "doWritev", "promiseMap", "uncaughtExceptionCount", "exceptionLast", "exceptionCaught", "Browser", "getPreloadedImageData__data", "wget", "MONTH_DAYS_REGULAR", "MONTH_DAYS_LEAP", "MONTH_DAYS_REGULAR_CUMULATIVE", "MONTH_DAYS_LEAP_CUMULATIVE", "SYSCALLS", "preloadPlugins", "FS_modeStringToFlags", "FS_getMode", "FS_stdin_getChar_buffer", "FS_stdin_getChar", "FS_readFile", "FS", "MEMFS", "TTY", "PIPEFS", "SOCKFS", "tempFixedLengthArray", "miniTempWebGLFloatBuffers", "miniTempWebGLIntBuffers", "GL", "AL", "GLUT", "EGL", "GLEW", "IDBStore", "runAndAbortIfError", "Asyncify", "Fibers", "SDL", "SDL_gfx", "allocateUTF8", "allocateUTF8OnStack", "print", "printErr"];
3996 unexportedSymbols.forEach(unexportedRuntimeSymbol);
swissChiliab615d82024-03-08 17:15:13 -05003997 var calledRun;
3998 dependenciesFulfilled = function runCaller() {
3999 if (!calledRun) run();
4000 if (!calledRun) dependenciesFulfilled = runCaller
4001 };
4002
swissChili281af442024-11-14 23:30:29 -05004003 function stackCheckInit() {
4004 _emscripten_stack_init();
4005 writeStackCookie()
4006 }
4007
swissChiliab615d82024-03-08 17:15:13 -05004008 function run() {
4009 if (runDependencies > 0) {
4010 return
4011 }
swissChili281af442024-11-14 23:30:29 -05004012 stackCheckInit();
swissChiliab615d82024-03-08 17:15:13 -05004013 preRun();
4014 if (runDependencies > 0) {
4015 return
4016 }
4017
4018 function doRun() {
4019 if (calledRun) return;
4020 calledRun = true;
4021 Module["calledRun"] = true;
4022 if (ABORT) return;
4023 initRuntime();
4024 readyPromiseResolve(Module);
swissChili281af442024-11-14 23:30:29 -05004025 Module["onRuntimeInitialized"]?.();
4026 assert(!Module["_main"], 'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]');
swissChiliab615d82024-03-08 17:15:13 -05004027 postRun()
4028 }
4029 if (Module["setStatus"]) {
4030 Module["setStatus"]("Running...");
4031 setTimeout(function() {
4032 setTimeout(function() {
4033 Module["setStatus"]("")
4034 }, 1);
4035 doRun()
4036 }, 1)
4037 } else {
4038 doRun()
4039 }
swissChili281af442024-11-14 23:30:29 -05004040 checkStackCookie()
4041 }
4042
4043 function checkUnflushedContent() {
4044 var oldOut = out;
4045 var oldErr = err;
4046 var has = false;
4047 out = err = x => {
4048 has = true
4049 };
4050 try {
4051 _fflush(0);
4052 ["stdout", "stderr"].forEach(function(name) {
4053 var info = FS.analyzePath("/dev/" + name);
4054 if (!info) return;
4055 var stream = info.object;
4056 var rdev = stream.rdev;
4057 var tty = TTY.ttys[rdev];
4058 if (tty?.output?.length) {
4059 has = true
4060 }
4061 })
4062 } catch (e) {}
4063 out = oldOut;
4064 err = oldErr;
4065 if (has) {
4066 warnOnce("stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the Emscripten FAQ), or make sure to emit a newline when you printf etc.")
4067 }
swissChiliab615d82024-03-08 17:15:13 -05004068 }
4069 if (Module["preInit"]) {
4070 if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]];
4071 while (Module["preInit"].length > 0) {
4072 Module["preInit"].pop()()
4073 }
4074 }
4075 run();
swissChili281af442024-11-14 23:30:29 -05004076 moduleRtn = readyPromise;
4077 for (const prop of Object.keys(Module)) {
4078 if (!(prop in moduleArg)) {
4079 Object.defineProperty(moduleArg, prop, {
4080 configurable: true,
4081 get() {
4082 abort(`Access to module property ('${prop}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`)
4083 }
4084 })
4085 }
4086 }
4087
4088
4089 return moduleRtn;
swissChiliab615d82024-03-08 17:15:13 -05004090 }
4091 );
4092})();
4093if (typeof exports === 'object' && typeof module === 'object')
4094 module.exports = createMyModule;
4095else if (typeof define === 'function' && define['amd'])
4096 define([], () => createMyModule);