funicular 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +56 -1
- data/README.md +58 -20
- data/Rakefile +74 -2
- data/demo/keymap_editor.html +582 -0
- data/demo/test_cable.html +179 -0
- data/demo/test_chartjs.html +235 -0
- data/demo/test_component.html +201 -0
- data/demo/test_diff_patch.html +146 -0
- data/demo/test_error_boundary.html +284 -0
- data/demo/test_router.html +257 -0
- data/demo/test_vdom.html +100 -0
- data/demo/tic-tac-toe.html +201 -0
- data/docs/README.md +419 -0
- data/docs/advanced-features.md +632 -0
- data/docs/architecture.md +409 -0
- data/docs/components-and-state.md +539 -0
- data/docs/data-fetching.md +528 -0
- data/docs/forms.md +446 -0
- data/docs/rails-integration.md +426 -0
- data/docs/realtime.md +543 -0
- data/docs/routing-and-navigation.md +427 -0
- data/docs/styling.md +285 -0
- data/exe/funicular +32 -0
- data/lib/funicular/assets/funicular.rb +21 -0
- data/lib/funicular/assets/funicular_debug.css +73 -0
- data/lib/funicular/assets/funicular_debug.js +183 -0
- data/lib/funicular/commands/routes.rb +69 -0
- data/lib/funicular/compiler.rb +135 -0
- data/lib/funicular/configuration.rb +76 -0
- data/lib/funicular/helpers/picoruby_helper.rb +50 -0
- data/lib/funicular/middleware.rb +98 -0
- data/lib/funicular/railtie.rb +26 -0
- data/lib/funicular/route_parser.rb +137 -0
- data/lib/funicular/vendor/picorbc/VERSION +1 -0
- data/lib/funicular/vendor/picorbc/picorbc.js +5283 -0
- data/lib/funicular/vendor/picorbc/picorbc.wasm +0 -0
- data/lib/funicular/vendor/picoruby/VERSION +1 -0
- data/lib/funicular/vendor/picoruby/debug/init.iife.js +130 -0
- data/lib/funicular/vendor/picoruby/debug/picoruby.js +6404 -0
- data/lib/funicular/vendor/picoruby/debug/picoruby.wasm +0 -0
- data/lib/funicular/vendor/picoruby/dist/init.iife.js +130 -0
- data/lib/funicular/vendor/picoruby/dist/picoruby.js +2 -0
- data/lib/funicular/vendor/picoruby/dist/picoruby.wasm +0 -0
- data/lib/funicular/version.rb +1 -1
- data/lib/funicular.rb +29 -1
- data/lib/tasks/funicular.rake +135 -0
- data/minitest/funicular_test.rb +13 -0
- data/minitest/test_helper.rb +7 -0
- data/mrbgem.rake +15 -0
- data/mrblib/cable.rb +417 -0
- data/mrblib/component.rb +911 -0
- data/mrblib/debug.rb +205 -0
- data/mrblib/differ.rb +244 -0
- data/mrblib/environment_inquirer.rb +34 -0
- data/mrblib/error_boundary.rb +125 -0
- data/mrblib/file_upload.rb +184 -0
- data/mrblib/form_builder.rb +284 -0
- data/mrblib/funicular.rb +156 -0
- data/mrblib/http.rb +89 -0
- data/mrblib/model.rb +146 -0
- data/mrblib/patcher.rb +203 -0
- data/mrblib/router.rb +229 -0
- data/mrblib/styles.rb +83 -0
- data/mrblib/vdom.rb +273 -0
- data/sig/cable.rbs +65 -0
- data/sig/component.rbs +141 -0
- data/sig/debug.rbs +28 -0
- data/sig/differ.rbs +18 -0
- data/sig/environment_iquirer.rbs +10 -0
- data/sig/error_boundary.rbs +14 -0
- data/sig/file_upload.rbs +18 -0
- data/sig/form_builder.rbs +29 -0
- data/sig/funicular.rbs +11 -1
- data/sig/http.rbs +22 -0
- data/sig/model.rbs +23 -0
- data/sig/patcher.rbs +15 -0
- data/sig/router.rbs +43 -0
- data/sig/styles.rbs +25 -0
- data/sig/vdom.rbs +59 -0
- metadata +119 -8
|
Binary file
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
(async function(global) {
|
|
2
|
+
async function initPicoRuby() {
|
|
3
|
+
// Import the factory function
|
|
4
|
+
const baseURL = document.currentScript?.src ? new URL('.', document.currentScript.src).href : '';
|
|
5
|
+
const { default: createModule } = await import(baseURL + 'picoruby.js');
|
|
6
|
+
|
|
7
|
+
async function collectRubyScripts() {
|
|
8
|
+
const rubyScripts = document.querySelectorAll('script[type="text/ruby"]');
|
|
9
|
+
const taskPromises = Array.from(rubyScripts).map(async script => {
|
|
10
|
+
if (script.src) {
|
|
11
|
+
const response = await fetch(script.src);
|
|
12
|
+
if (!response.ok) {
|
|
13
|
+
throw new Error(`Failed to load ${script.src}: ${response.statusText}`);
|
|
14
|
+
}
|
|
15
|
+
const code = await response.text();
|
|
16
|
+
const filename = script.src.split('/').pop() || script.src;
|
|
17
|
+
return { code, filename };
|
|
18
|
+
}
|
|
19
|
+
return { code: script.textContent.trim(), filename: null };
|
|
20
|
+
});
|
|
21
|
+
return Promise.all(taskPromises);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function collectMrbVMCode() {
|
|
25
|
+
const mrbScripts = document.querySelectorAll('script[type="application/x-mrb"]');
|
|
26
|
+
const taskPromises = Array.from(mrbScripts).map(async script => {
|
|
27
|
+
const src = script.src;
|
|
28
|
+
if (src) {
|
|
29
|
+
const response = await fetch(src);
|
|
30
|
+
if (!response.ok) {
|
|
31
|
+
throw new Error(`Failed to load ${src}: ${response.statusText}`);
|
|
32
|
+
}
|
|
33
|
+
return await response.arrayBuffer();
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
});
|
|
37
|
+
const results = await Promise.all(taskPromises);
|
|
38
|
+
return results.filter(Boolean);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Create and initialize the module
|
|
42
|
+
const Module = await createModule();
|
|
43
|
+
|
|
44
|
+
// Expose Module for debugging (used by PicoRuby DevTools extension)
|
|
45
|
+
window.picorubyModule = Module;
|
|
46
|
+
|
|
47
|
+
Module.picorubyRun = function() {
|
|
48
|
+
const MRB_TICK_UNIT = 4; // Must match the value in build_config/picoruby-wasm.rb
|
|
49
|
+
const BATCH_DURATION = 16; // ~1 frame (16.67ms)
|
|
50
|
+
const MAX_CATCHUP_TICKS = 10; // Cap to avoid freeze when tab returns from background
|
|
51
|
+
let lastTick = performance.now();
|
|
52
|
+
function run() {
|
|
53
|
+
const now = performance.now();
|
|
54
|
+
let tickCount = 0;
|
|
55
|
+
while (now - lastTick >= MRB_TICK_UNIT && tickCount < MAX_CATCHUP_TICKS) {
|
|
56
|
+
Module._mrb_tick_wasm();
|
|
57
|
+
lastTick += MRB_TICK_UNIT;
|
|
58
|
+
tickCount++;
|
|
59
|
+
}
|
|
60
|
+
if (now - lastTick >= MRB_TICK_UNIT) {
|
|
61
|
+
lastTick = now;
|
|
62
|
+
}
|
|
63
|
+
const sliceStart = performance.now();
|
|
64
|
+
while (performance.now() - sliceStart < BATCH_DURATION) {
|
|
65
|
+
const result = Module._mrb_run_step();
|
|
66
|
+
if (result < 0) {
|
|
67
|
+
console.error('mrb_run_step returned', result, '- scheduler continues');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
setTimeout(run, 0);
|
|
71
|
+
}
|
|
72
|
+
run();
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// Initialize WASM and start tasks
|
|
76
|
+
Module.ccall('picorb_init', 'number', [], []);
|
|
77
|
+
|
|
78
|
+
// Collect and create tasks from Ruby script tags
|
|
79
|
+
try {
|
|
80
|
+
const rubyTasks = await collectRubyScripts();
|
|
81
|
+
rubyTasks.forEach(function(task) {
|
|
82
|
+
if (task.filename) {
|
|
83
|
+
Module.ccall('picorb_create_task_with_filename', 'number',
|
|
84
|
+
['string', 'string'], [task.code, task.filename]);
|
|
85
|
+
} else {
|
|
86
|
+
Module.ccall('picorb_create_task', 'number', ['string'], [task.code]);
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
} catch (error) {
|
|
90
|
+
console.error('Error loading Ruby tasks:', error);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Collect and create tasks from MRB data tags
|
|
94
|
+
try {
|
|
95
|
+
const mrbTasks = await collectMrbVMCode();
|
|
96
|
+
mrbTasks.forEach(function(buffer) {
|
|
97
|
+
const ptr = Module._malloc(buffer.byteLength);
|
|
98
|
+
if (ptr === 0) {
|
|
99
|
+
throw new Error('Failed to allocate memory in Wasm heap.');
|
|
100
|
+
}
|
|
101
|
+
try {
|
|
102
|
+
Module.HEAPU8.set(new Uint8Array(buffer), ptr);
|
|
103
|
+
const result = Module.ccall('picorb_create_task_from_mrb', 'number', ['number', 'number'], [ptr, buffer.byteLength]);
|
|
104
|
+
if (result !== 0) {
|
|
105
|
+
console.error('Failed to create task from mrb.');
|
|
106
|
+
}
|
|
107
|
+
} finally {
|
|
108
|
+
Module._free(ptr);
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
} catch (error) {
|
|
112
|
+
console.error('Error loading MRB tasks:', error);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Also support window.userTasks if present (for backward compatibility)
|
|
116
|
+
if (window.userTasks) {
|
|
117
|
+
window.userTasks.forEach(function(task) {
|
|
118
|
+
Module.ccall('picorb_create_task', 'number', ['string'],
|
|
119
|
+
[typeof task === 'string' ? task : task.code]);
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Start PicoRuby execution
|
|
124
|
+
Module.picorubyRun();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
global.initPicoRuby = initPicoRuby;
|
|
128
|
+
|
|
129
|
+
await initPicoRuby();
|
|
130
|
+
})(typeof window !== 'undefined' ? window : this).catch(console.error);
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
async function Module(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();PIPEFS.root=FS.mount(PIPEFS,{},null);wasmExports["__wasm_call_ctors"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("picoruby.wasm")}return new URL("picoruby.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={env:wasmImports,wasi_snapshot_preview1:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>view=>crypto.getRandomValues(view);var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[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]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var zeroMemory=(ptr,size)=>HEAPU8.fill(0,ptr,ptr+size);var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var mmapAlloc=size=>{size=alignMemory(size,65536);var ptr=_emscripten_builtin_memalign(65536,size);if(ptr)zeroMemory(ptr,size);return ptr};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}if(perms.includes("w")&&!(node.mode&146)){return 2}if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else if(FS.isDir(node.mode)){return 31}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}var mode=FS.flagsToPermissionString(flags);if(FS.isDir(node.mode)){if(mode!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,mode)},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){data=new Uint8Array(intArrayFromString(data,true))}if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{abort("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("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.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var SYSCALLS={calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_chdir(path){try{path=SYSCALLS.getStr(path);FS.chdir(path);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_chmod(path,mode){try{path=SYSCALLS.getStr(path);FS.chmod(path,mode);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_dup(fd){try{var old=SYSCALLS.getStreamFromFD(fd);return FS.dupStream(old).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_dup3(fd,newfd,flags){try{var old=SYSCALLS.getStreamFromFD(fd);if(old.fd===newfd)return-28;if(newfd<0||newfd>=FS.MAX_OPEN_FDS)return-8;var existing=FS.getStream(newfd);if(existing)FS.close(existing);return FS.dupStream(old,newfd).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fstat64(fd,buf){try{return SYSCALLS.writeStat(buf,FS.fstat(fd))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function ___syscall_ftruncate64(fd,length){length=bigintToI53Checked(length);try{if(isNaN(length))return-61;FS.ftruncate(fd,length);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);function ___syscall_getcwd(buf,size){try{if(size===0)return-28;var cwd=FS.cwd();var cwdLengthInBytes=lengthBytesUTF8(cwd)+1;if(size<cwdLengthInBytes)return-68;stringToUTF8(cwd,buf,size);return cwdLengthInBytes}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_getdents64(fd,dirp,count){try{var stream=SYSCALLS.getStreamFromFD(fd);stream.getdents||=FS.readdir(stream.path);var struct_size=280;var pos=0;var off=FS.llseek(stream,0,1);var startIdx=Math.floor(off/struct_size);var endIdx=Math.min(stream.getdents.length,startIdx+Math.floor(count/struct_size));for(var idx=startIdx;idx<endIdx;idx++){var id;var type;var name=stream.getdents[idx];if(name==="."){id=stream.node.id;type=4}else if(name===".."){var lookup=FS.lookupPath(stream.path,{parent:true});id=lookup.node.id;type=4}else{var child;try{child=FS.lookupNode(stream.node,name)}catch(e){if(e?.errno===28){continue}throw e}id=child.id;type=FS.isChrdev(child.mode)?2:FS.isDir(child.mode)?4:FS.isLink(child.mode)?10:8}HEAP64[dirp+pos>>3]=BigInt(id);HEAP64[dirp+pos+8>>3]=BigInt((idx+1)*struct_size);HEAP16[dirp+pos+16>>1]=280;HEAP8[dirp+pos+18]=type;stringToUTF8(name,dirp+pos+19,256);pos+=struct_size}FS.llseek(stream,idx*struct_size,0);return pos}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_lstat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.lstat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_mkdirat(dirfd,path,mode){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);FS.mkdir(path,mode,0);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_newfstatat(dirfd,path,buf,flags){try{path=SYSCALLS.getStr(path);var nofollow=flags&256;var allowEmpty=flags&4096;flags=flags&~6400;path=SYSCALLS.calculateAt(dirfd,path,allowEmpty);return SYSCALLS.writeStat(buf,nofollow?FS.lstat(path):FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var PIPEFS={BUCKET_BUFFER_SIZE:8192,mount(mount){return FS.createNode(null,"/",16384|511,0)},createPipe(){var pipe={buckets:[],refcnt:2,timestamp:new Date};pipe.buckets.push({buffer:new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE),offset:0,roffset:0});var rName=PIPEFS.nextname();var wName=PIPEFS.nextname();var rNode=FS.createNode(PIPEFS.root,rName,4096,0);var wNode=FS.createNode(PIPEFS.root,wName,4096,0);rNode.pipe=pipe;wNode.pipe=pipe;var readableStream=FS.createStream({path:rName,node:rNode,flags:0,seekable:false,stream_ops:PIPEFS.stream_ops});rNode.stream=readableStream;var writableStream=FS.createStream({path:wName,node:wNode,flags:1,seekable:false,stream_ops:PIPEFS.stream_ops});wNode.stream=writableStream;return{readable_fd:readableStream.fd,writable_fd:writableStream.fd}},stream_ops:{getattr(stream){var node=stream.node;var timestamp=node.pipe.timestamp;return{dev:14,ino:node.id,mode:4480,nlink:1,uid:0,gid:0,rdev:0,size:0,atime:timestamp,mtime:timestamp,ctime:timestamp,blksize:4096,blocks:0}},poll(stream,timeout,notifyCallback){var pipe=stream.node.pipe;if((stream.flags&2097155)===1){return 256|4}for(var bucket of pipe.buckets){if(bucket.offset-bucket.roffset>0){return 64|1}}return 0},dup(stream){stream.node.pipe.refcnt++},ioctl(stream,request,varargs){return 28},fsync(stream){return 28},read(stream,buffer,offset,length,position){var pipe=stream.node.pipe;var currentLength=0;for(var bucket of pipe.buckets){currentLength+=bucket.offset-bucket.roffset}var data=buffer.subarray(offset,offset+length);if(length<=0){return 0}if(currentLength==0){throw new FS.ErrnoError(6)}var toRead=Math.min(currentLength,length);var totalRead=toRead;var toRemove=0;for(var bucket of pipe.buckets){var bucketSize=bucket.offset-bucket.roffset;if(toRead<=bucketSize){var tmpSlice=bucket.buffer.subarray(bucket.roffset,bucket.offset);if(toRead<bucketSize){tmpSlice=tmpSlice.subarray(0,toRead);bucket.roffset+=toRead}else{toRemove++}data.set(tmpSlice);break}else{var tmpSlice=bucket.buffer.subarray(bucket.roffset,bucket.offset);data.set(tmpSlice);data=data.subarray(tmpSlice.byteLength);toRead-=tmpSlice.byteLength;toRemove++}}if(toRemove&&toRemove==pipe.buckets.length){toRemove--;pipe.buckets[toRemove].offset=0;pipe.buckets[toRemove].roffset=0}pipe.buckets.splice(0,toRemove);return totalRead},write(stream,buffer,offset,length,position){var pipe=stream.node.pipe;var data=buffer.subarray(offset,offset+length);var dataLen=data.byteLength;if(dataLen<=0){return 0}var currBucket=null;if(pipe.buckets.length==0){currBucket={buffer:new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE),offset:0,roffset:0};pipe.buckets.push(currBucket)}else{currBucket=pipe.buckets[pipe.buckets.length-1]}var freeBytesInCurrBuffer=PIPEFS.BUCKET_BUFFER_SIZE-currBucket.offset;if(freeBytesInCurrBuffer>=dataLen){currBucket.buffer.set(data,currBucket.offset);currBucket.offset+=dataLen;return dataLen}else if(freeBytesInCurrBuffer>0){currBucket.buffer.set(data.subarray(0,freeBytesInCurrBuffer),currBucket.offset);currBucket.offset+=freeBytesInCurrBuffer;data=data.subarray(freeBytesInCurrBuffer,data.byteLength)}var numBuckets=data.byteLength/PIPEFS.BUCKET_BUFFER_SIZE|0;var remElements=data.byteLength%PIPEFS.BUCKET_BUFFER_SIZE;for(var i=0;i<numBuckets;i++){var newBucket={buffer:new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE),offset:PIPEFS.BUCKET_BUFFER_SIZE,roffset:0};pipe.buckets.push(newBucket);newBucket.buffer.set(data.subarray(0,PIPEFS.BUCKET_BUFFER_SIZE));data=data.subarray(PIPEFS.BUCKET_BUFFER_SIZE,data.byteLength)}if(remElements>0){var newBucket={buffer:new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE),offset:data.byteLength,roffset:0};pipe.buckets.push(newBucket);newBucket.buffer.set(data)}return dataLen},close(stream){var pipe=stream.node.pipe;pipe.refcnt--;if(pipe.refcnt===0){pipe.buckets=null}}},nextname(){if(!PIPEFS.nextname.current){PIPEFS.nextname.current=0}return"pipe["+PIPEFS.nextname.current+++"]"}};function ___syscall_pipe(fdPtr){try{if(fdPtr==0){throw new FS.ErrnoError(21)}var res=PIPEFS.createPipe();HEAP32[fdPtr>>2]=res.readable_fd;HEAP32[fdPtr+4>>2]=res.writable_fd;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_poll(fds,nfds,timeout){try{var count=0;for(var i=0;i<nfds;i++){var pollfd=fds+8*i;var fd=HEAP32[pollfd>>2];var events=HEAP16[pollfd+4>>1];var flags=32;var stream=FS.getStream(fd);if(stream){if(stream.stream_ops.poll){flags=stream.stream_ops.poll(stream,-1)}else{flags=5}}flags&=events|8|16;if(flags)count++;HEAP16[pollfd+6>>1]=flags}return count}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_readlinkat(dirfd,path,buf,bufsize){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(bufsize<=0)return-28;var ret=FS.readlink(path);var len=Math.min(bufsize,lengthBytesUTF8(ret));var endChar=HEAP8[buf+len];stringToUTF8(ret,buf,bufsize+1);HEAP8[buf+len]=endChar;return len}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_renameat(olddirfd,oldpath,newdirfd,newpath){try{oldpath=SYSCALLS.getStr(oldpath);newpath=SYSCALLS.getStr(newpath);oldpath=SYSCALLS.calculateAt(olddirfd,oldpath);newpath=SYSCALLS.calculateAt(newdirfd,newpath);FS.rename(oldpath,newpath);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_rmdir(path){try{path=SYSCALLS.getStr(path);FS.rmdir(path);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_stat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_symlinkat(target,dirfd,linkpath){try{target=SYSCALLS.getStr(target);linkpath=SYSCALLS.getStr(linkpath);linkpath=SYSCALLS.calculateAt(dirfd,linkpath);FS.symlink(target,linkpath);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_unlinkat(dirfd,path,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(!flags){FS.unlink(path)}else if(flags===512){FS.rmdir(path)}else{return-28}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var __emscripten_throw_longjmp=()=>{throw Infinity};var isLeapYear=year=>year%4===0&&(year%100!==0||year%400===0);var MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335];var MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334];var ydayFromDate=date=>{var leap=isLeapYear(date.getFullYear());var monthDaysCumulative=leap?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE;var yday=monthDaysCumulative[date.getMonth()]+date.getDate()-1;return yday};function __localtime_js(time,tmPtr){time=bigintToI53Checked(time);var date=new Date(time*1e3);HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getDay();var yday=ydayFromDate(date)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr+36>>2]=-(date.getTimezoneOffset()*60);var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dst=(summerOffset!=winterOffset&&date.getTimezoneOffset()==Math.min(winterOffset,summerOffset))|0;HEAP32[tmPtr+32>>2]=dst}var __mktime_js=function(tmPtr){var ret=(()=>{var date=new Date(HEAP32[tmPtr+20>>2]+1900,HEAP32[tmPtr+16>>2],HEAP32[tmPtr+12>>2],HEAP32[tmPtr+8>>2],HEAP32[tmPtr+4>>2],HEAP32[tmPtr>>2],0);var dst=HEAP32[tmPtr+32>>2];var guessedOffset=date.getTimezoneOffset();var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dstOffset=Math.min(winterOffset,summerOffset);if(dst<0){HEAP32[tmPtr+32>>2]=Number(summerOffset!=winterOffset&&dstOffset==guessedOffset)}else if(dst>0!=(dstOffset==guessedOffset)){var nonDstOffset=Math.max(winterOffset,summerOffset);var trueOffset=dst>0?dstOffset:nonDstOffset;date.setTime(date.getTime()+(trueOffset-guessedOffset)*6e4)}HEAP32[tmPtr+24>>2]=date.getDay();var yday=ydayFromDate(date)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getYear();var timeMs=date.getTime();if(isNaN(timeMs)){return-1}return timeMs/1e3})();return BigInt(ret)};function __munmap_js(addr,len,prot,flags,fd,offset){offset=bigintToI53Checked(offset);try{var stream=SYSCALLS.getStreamFromFD(fd);if(prot&2){SYSCALLS.doMsync(addr,stream,len,flags,offset)}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var _emscripten_get_now=()=>performance.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);HEAP64[ptime>>3]=BigInt(nsec);return 0}var readEmAsmArgsArray=[];var readEmAsmArgs=(sigPtr,buf)=>{readEmAsmArgsArray.length=0;var ch;while(ch=HEAPU8[sigPtr++]){var wide=ch!=105;wide&=ch!=112;buf+=wide&&buf%8?4:0;readEmAsmArgsArray.push(ch==112?HEAPU32[buf>>2]:ch==106?HEAP64[buf>>3]:ch==105?HEAP32[buf>>2]:HEAPF64[buf>>3]);buf+=wide?8:4}return readEmAsmArgsArray};var runEmAsmFunction=(code,sigPtr,argbuf)=>{var args=readEmAsmArgs(sigPtr,argbuf);return ASM_CONSTS[code](...args)};var _emscripten_asm_const_int=(code,sigPtr,argbuf)=>runEmAsmFunction(code,sigPtr,argbuf);var getHeapMax=()=>2147483648;var _emscripten_get_heap_max=()=>getHeapMax();var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_fdstat_get(fd,pbuf){try{var rightsBase=0;var rightsInheriting=0;var flags=0;{var stream=SYSCALLS.getStreamFromFD(fd);var type=stream.tty?2:FS.isDir(stream.mode)?3:FS.isLink(stream.mode)?7:4}HEAP8[pbuf]=type;HEAP16[pbuf+2>>1]=flags;HEAP64[pbuf+8>>3]=BigInt(rightsBase);HEAP64[pbuf+16>>3]=BigInt(rightsInheriting);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_pread(fd,iov,iovcnt,offset,pnum){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt,offset);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_pwrite(fd,iov,iovcnt,offset,pnum){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt,offset);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_sync(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);var rtn=stream.stream_ops?.fsync?.(stream);return rtn}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["UTF8ToString"]=UTF8ToString;Module["stringToUTF8"]=stringToUTF8;Module["lengthBytesUTF8"]=lengthBytesUTF8;var ASM_CONSTS={448965:$0=>{globalThis.picorubyRefs[$0]=null},449005:$0=>{globalThis.picorubyRefs[$0]=true},449045:$0=>{globalThis.picorubyRefs[$0]=false},449086:($0,$1)=>{globalThis.picorubyRefs[$0]=$1},449124:($0,$1)=>{globalThis.picorubyRefs[$0]=$1},449162:($0,$1,$2)=>{const str=UTF8ToString($1,$2);globalThis.picorubyRefs[$0]=str},449235:($0,$1)=>{const arr=globalThis.picorubyRefs[$0];const elem=globalThis.picorubyRefs[$1];arr.push(elem);delete globalThis.picorubyRefs[$1]},449374:($0,$1,$2)=>{const obj=globalThis.picorubyRefs[$0];const key=UTF8ToString($1);const val=globalThis.picorubyRefs[$2];obj[key]=val;delete globalThis.picorubyRefs[$2]}};function ble_dataview_length(ref_id){try{const dv=globalThis.picorubyRefs[ref_id];if(dv&&dv.byteLength!==undefined){return dv.byteLength}return 0}catch(e){console.error("ble_dataview_length failed:",e);return 0}}function ble_dataview_read(ref_id,out_buf,max_len){try{const dv=globalThis.picorubyRefs[ref_id];if(!dv)return 0;const len=Math.min(dv.byteLength,max_len);for(let i=0;i<len;i++){HEAPU8[out_buf+i]=dv.getUint8(i)}return len}catch(e){console.error("ble_dataview_read failed:",e);return 0}}function ble_create_uint8array(data,length){try{const buffer=new Uint8Array(HEAPU8.buffer,data,length);const copy=new Uint8Array(buffer);const refId=globalThis.picorubyRefs.push(copy)-1;return refId}catch(e){console.error("ble_create_uint8array failed:",e);return-1}}function ble_set_notify_handler(char_ref_id,callback_id){try{const char_obj=globalThis.picorubyRefs[char_ref_id];char_obj.addEventListener("characteristicvaluechanged",event=>{const dataview=event.target.value;const len=dataview.byteLength;const ptr=_malloc(len);for(let i=0;i<len;i++){HEAPU8[ptr+i]=dataview.getUint8(i)}ccall("ble_notify_callback","void",["number","number","number"],[callback_id,ptr,len]);_free(ptr)})}catch(e){console.error("ble_set_notify_handler failed:",e)}}function init_js_refs(){if(typeof globalThis.picorubyRefs==="undefined"){globalThis.picorubyRefs=[];globalThis.picorubyRefs.push(window)}if(typeof window._js_remove_event_listener_wrapper==="undefined"){window._js_remove_event_listener_wrapper=function(callback_id){if(!globalThis.picorubyEventHandlers)return false;const info=globalThis.picorubyEventHandlers[callback_id];if(!info)return false;info.target.removeEventListener(info.type,info.handler);delete globalThis.picorubyEventHandlers[callback_id];return true}}}function get_element(ref_id,index){try{const nodeList=globalThis.picorubyRefs[ref_id];const element=nodeList[index];if(element===undefined){return-1}const newRefId=globalThis.picorubyRefs.push(element)-1;return newRefId}catch(e){return-1}}function set_property(ref_id,key,value,value_len){try{if(!globalThis.picorubyRefs||ref_id>=globalThis.picorubyRefs.length){console.error("Invalid reference ID:",ref_id);return false}const obj=globalThis.picorubyRefs[ref_id];if(!obj){console.error("Object not found for ref_id:",ref_id);return false}const property=UTF8ToString(key);const val=UTF8ToString(value,value_len);obj[property]=val;return true}catch(e){console.error("Error in set_property:",e);return false}}function set_property_int(ref_id,key,value){try{const obj=globalThis.picorubyRefs[ref_id];if(!obj)return false;obj[UTF8ToString(key)]=value;return true}catch(e){console.error("Error in set_property_int:",e);return false}}function set_property_double(ref_id,key,value){try{const obj=globalThis.picorubyRefs[ref_id];if(!obj)return false;obj[UTF8ToString(key)]=value;return true}catch(e){console.error("Error in set_property_double:",e);return false}}function set_property_bool(ref_id,key,value){try{const obj=globalThis.picorubyRefs[ref_id];if(!obj)return false;obj[UTF8ToString(key)]=value?true:false;return true}catch(e){console.error("Error in set_property_bool:",e);return false}}function set_property_null(ref_id,key){try{const obj=globalThis.picorubyRefs[ref_id];if(!obj)return false;obj[UTF8ToString(key)]=null;return true}catch(e){console.error("Error in set_property_null:",e);return false}}function set_property_ref(ref_id,key,value_ref_id){try{const obj=globalThis.picorubyRefs[ref_id];const value=globalThis.picorubyRefs[value_ref_id];if(!obj)return false;obj[UTF8ToString(key)]=value;return true}catch(e){console.error("Error in set_property_ref:",e);return false}}function get_property(ref_id,key){try{const obj=globalThis.picorubyRefs[ref_id];const value=obj[UTF8ToString(key)];const newRefId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(value);return newRefId}catch(e){return-1}}function get_js_type(ref_id){try{const value=globalThis.picorubyRefs[ref_id];const type=typeof value;if(value===null)return 1;if(value===undefined)return 0;if(type==="boolean")return 2;if(type==="number")return 3;if(type==="string")return 5;if(value instanceof String)return 5;if(Array.isArray(value))return 7;if(type==="function")return 9;return 8}catch(e){console.error("Error in get_js_type (JS side):",e);return 0}}function get_js_property_type(ref_id,property_name){try{const obj=globalThis.picorubyRefs[ref_id];const propName=UTF8ToString(property_name);const value=obj[propName];const type=typeof value;if(value===null)return 1;if(value===undefined)return 0;if(type==="boolean")return 2;if(type==="number")return 3;if(type==="string")return 5;if(value instanceof String)return 5;if(Array.isArray(value))return 7;if(type==="function")return 9;return 8}catch(e){return 0}}function get_boolean_value(ref_id){return globalThis.picorubyRefs[ref_id]?true:false}function get_number_value(ref_id){return globalThis.picorubyRefs[ref_id]}function get_string_value_length(ref_id){const str=globalThis.picorubyRefs[ref_id];return lengthBytesUTF8(str)}function copy_string_value(ref_id,buffer,buffer_size){const str=globalThis.picorubyRefs[ref_id];stringToUTF8(str,buffer,buffer_size)}function js_string_equals(ref_id,ruby_str,ruby_str_len){const js_str=globalThis.picorubyRefs[ref_id];return js_str===UTF8ToString(ruby_str,ruby_str_len)}function call_method(ref_id,method,arg,arg_len){try{const obj=globalThis.picorubyRefs[ref_id];const methodName=UTF8ToString(method);const func=obj[methodName];const argString=UTF8ToString(arg,arg_len);let result;if(methodName==="new"){result=new obj(argString)}else{if(typeof func!=="function"){console.error("Method not found or not a function:",methodName);return-1}result=func.call(obj,argString)}const newRefId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);return newRefId}catch(e){console.error(e);return-1}}function call_method_no_arg(ref_id,method){try{const obj=globalThis.picorubyRefs[ref_id];const methodName=UTF8ToString(method);const func=obj[methodName];if(typeof func!=="function"){console.error("Method not found or not a function:",methodName);return-1}let result=func.call(obj);const newRefId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);return newRefId}catch(e){console.error(e);return-1}}function call_method_no_return(ref_id,method){try{const obj=globalThis.picorubyRefs[ref_id];const methodName=UTF8ToString(method);const func=obj[methodName];if(typeof func==="function"){func.call(obj)}}catch(e){console.error("call_method_no_return error:",e)}}function call_method_int(ref_id,method,arg){try{const obj=globalThis.picorubyRefs[ref_id];const methodName=UTF8ToString(method);const func=obj[methodName];let result;if(methodName==="new"){result=new obj(arg)}else{if(typeof func!=="function"){console.error("Method not found or not a function:",methodName);return-1}result=func.call(obj,arg)}const newRefId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);return newRefId}catch(e){console.error(e);return-1}}function call_method_str(ref_id,method,arg1,arg1_len,arg2,arg2_len){try{const obj=globalThis.picorubyRefs[ref_id];const methodName=UTF8ToString(method);const func=obj[methodName];const argString1=UTF8ToString(arg1,arg1_len);const argString2=UTF8ToString(arg2,arg2_len);let result;if(methodName==="new"){result=new obj(argString1,argString2)}else{if(typeof func!=="function"){console.error("Method not found or not a function:",methodName);return-1}result=func.call(obj,argString1,argString2)}const newRefId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);return newRefId}catch(e){console.error(e);return-1}}function call_method_with_ref(ref_id,method,arg_ref_id){try{const obj=globalThis.picorubyRefs[ref_id];const methodName=UTF8ToString(method);const func=obj[methodName];const argObj=globalThis.picorubyRefs[arg_ref_id];let result;if(methodName==="new"){result=new obj(argObj)}else{if(typeof func!=="function"){console.error("Method not found or not a function:",methodName);return-1}result=func.call(obj,argObj)}const newRefId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);return newRefId}catch(e){console.error(e);return-1}}function call_method_with_ref_ref(ref_id,method,arg_ref_1_id,arg_ref_2_id){try{const obj=globalThis.picorubyRefs[ref_id];const methodName=UTF8ToString(method);const func=obj[methodName];const argObj1=globalThis.picorubyRefs[arg_ref_1_id];const argObj2=globalThis.picorubyRefs[arg_ref_2_id];let result;if(methodName==="new"){result=new obj(argObj1,argObj2)}else{if(typeof func!=="function"){console.error("Method not found or not a function:",methodName);return-1}result=func.call(obj,argObj1,argObj2)}const newRefId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);return newRefId}catch(e){console.error(e);return-1}}function call_method_with_ref_str_str(ref_id,method,arg1_ref_id,arg2_str,arg2_len,arg3_str,arg3_len){try{const obj=globalThis.picorubyRefs[ref_id];const methodName=UTF8ToString(method);const func=obj[methodName];const argObj1=globalThis.picorubyRefs[arg1_ref_id];const argString2=UTF8ToString(arg2_str,arg2_len);const argString3=UTF8ToString(arg3_str,arg3_len);if(typeof func!=="function"){console.error("Method not found or not a function:",methodName);return-1}let result=func.call(obj,argObj1,argString2,argString3);const newRefId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);return newRefId}catch(e){console.error("Error in call_method_with_ref_str_str:",e);return-1}}function call_method_with_args(ref_id,method,args_json,args_json_len){try{const obj=globalThis.picorubyRefs[ref_id];const methodName=UTF8ToString(method);const func=obj[methodName];if(typeof func!=="function"){console.error("Method not found or not a function:",methodName);return-1}const argsStr=UTF8ToString(args_json,args_json_len);const argsData=JSON.parse(argsStr);if(!Array.isArray(argsData)){console.error("args_json must be a JSON array");return-1}const args=argsData.map(arg=>{switch(arg.type){case"string":return arg.value;case"integer":return arg.value;case"float":return arg.value;case"boolean":return arg.value;case"ref":return globalThis.picorubyRefs[arg.value];case"nil":return null;default:console.error("Unknown argument type:",arg.type);return null}});const result=func.call(obj,...args);const newRefId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);return newRefId}catch(e){console.error("Error in call_method_with_args:",e);return-1}}function call_constructor_with_args(ref_id,args_json,args_json_len){try{const ctor=globalThis.picorubyRefs[ref_id];if(typeof ctor!=="function"){console.error("Object is not a constructor function");return-1}const argsStr=UTF8ToString(args_json,args_json_len);const argsData=JSON.parse(argsStr);if(!Array.isArray(argsData)){console.error("args_json must be a JSON array");return-1}const args=argsData.map(arg=>{switch(arg.type){case"string":return arg.value;case"integer":return arg.value;case"float":return arg.value;case"boolean":return arg.value;case"ref":return globalThis.picorubyRefs[arg.value];case"nil":return null;default:console.error("Unknown argument type:",arg.type);return null}});const result=new ctor(...args);const newRefId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);return newRefId}catch(e){console.error("Error in call_constructor_with_args:",e);return-1}}function call_fetch_with_json_options(ref_id,url,options_json){try{const obj=globalThis.picorubyRefs[ref_id];const urlStr=UTF8ToString(url);const optionsStr=UTF8ToString(options_json);const options=JSON.parse(optionsStr);const result=obj.fetch(urlStr,options);const newRefId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);return newRefId}catch(e){console.error(e);return-1}}function setup_promise_handler(promise_id,callback_id,mrb_ptr,task_ptr){const promise=globalThis.picorubyRefs[promise_id];promise.then(result=>{const resultId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);ccall("resume_promise_task","void",["number","number","number","number"],[mrb_ptr,task_ptr,callback_id,resultId])})}function js_add_event_listener(ref_id,callback_id,event_type){const target=globalThis.picorubyRefs[ref_id];const type=UTF8ToString(event_type);const handler=event=>{if(!globalThis.picorubyEventHandlers||!globalThis.picorubyEventHandlers[callback_id]){return}if(type==="submit"||type==="click"&&target.tagName==="A"){event.preventDefault()}const eventRefId=globalThis.picorubyRefs.push(event)-1;ccall("call_ruby_callback","void",["number","number"],[callback_id,eventRefId])};target.addEventListener(type,handler);if(!globalThis.picorubyEventHandlers){globalThis.picorubyEventHandlers={}}globalThis.picorubyEventHandlers[callback_id]={target,type,handler}}function js_register_generic_callback(callback_id,callback_name){const name=UTF8ToString(callback_name);if(!globalThis.picorubyGenericCallbacks){globalThis.picorubyGenericCallbacks={}}globalThis.picorubyGenericCallbacks[name]=function(...args){const argRefIds=args.map(arg=>{const refId=globalThis.picorubyRefs.push(arg)-1;return refId});const argRefIdsPtr=_malloc(argRefIds.length*4);for(let i=0;i<argRefIds.length;i++){HEAP32[(argRefIdsPtr>>2)+i]=argRefIds[i]}const resultRefId=ccall("call_ruby_callback_sync_generic","number",["number","number","number"],[callback_id,argRefIdsPtr,argRefIds.length]);_free(argRefIdsPtr);if(resultRefId>=0&&resultRefId<globalThis.picorubyRefs.length){return globalThis.picorubyRefs[resultRefId]}return undefined}}function js_create_callback_function(callback_id){try{const fn=function(...args){const argRefIds=args.map(arg=>globalThis.picorubyRefs.push(arg)-1);const argRefIdsPtr=_malloc(argRefIds.length*4);for(let i=0;i<argRefIds.length;i++){HEAP32[(argRefIdsPtr>>2)+i]=argRefIds[i]}const resultRefId=ccall("call_ruby_callback_sync_generic","number",["number","number","number"],[callback_id,argRefIdsPtr,argRefIds.length]);_free(argRefIdsPtr);if(resultRefId>=0&&resultRefId<globalThis.picorubyRefs.length){return globalThis.picorubyRefs[resultRefId]}return undefined};return globalThis.picorubyRefs.push(fn)-1}catch(e){console.error("js_create_callback_function failed:",e);return-1}}function js_set_timeout(callback_id,delay_ms){const timerId=setTimeout(function(){if(!globalThis.picorubyTimeoutHandlers||!globalThis.picorubyTimeoutHandlers[callback_id]){return}ccall("call_ruby_callback","void",["number","number"],[callback_id,-1]);delete globalThis.picorubyTimeoutHandlers[callback_id]},delay_ms);if(!globalThis.picorubyTimeoutHandlers){globalThis.picorubyTimeoutHandlers={}}globalThis.picorubyTimeoutHandlers[callback_id]=timerId;return timerId}function js_clear_timeout(callback_id){try{if(!globalThis.picorubyTimeoutHandlers)return false;const timerId=globalThis.picorubyTimeoutHandlers[callback_id];if(timerId===undefined)return false;clearTimeout(timerId);delete globalThis.picorubyTimeoutHandlers[callback_id];return true}catch(e){console.error("Error in js_clear_timeout:",e);return false}}function js_remove_event_listener(callback_id){try{if(!globalThis.picorubyEventHandlers)return false;const info=globalThis.picorubyEventHandlers[callback_id];if(!info)return false;info.target.removeEventListener(info.type,info.handler);delete globalThis.picorubyEventHandlers[callback_id];return true}catch(e){console.error("Error in js_remove_event_listener:",e);return false}}function js_create_element(tag_name){try{const element=document.createElement(UTF8ToString(tag_name));const refId=globalThis.picorubyRefs.push(element)-1;return refId}catch(e){console.error("Error in js_create_element:",e);return-1}}function js_create_text_node(text){try{const node=document.createTextNode(UTF8ToString(text));const refId=globalThis.picorubyRefs.push(node)-1;return refId}catch(e){console.error("Error in js_create_text_node:",e);return-1}}function js_create_object(){try{const obj={};const refId=globalThis.picorubyRefs.push(obj)-1;return refId}catch(e){console.error("Error in js_create_object:",e);return-1}}function js_create_array(){try{const arr=[];const refId=globalThis.picorubyRefs.push(arr)-1;return refId}catch(e){console.error("Error in js_create_array:",e);return-1}}function js_append_child(parent_ref_id,child_ref_id){try{const parent=globalThis.picorubyRefs[parent_ref_id];const child=globalThis.picorubyRefs[child_ref_id];if(!parent||!child)return false;parent.appendChild(child);return true}catch(e){console.error("Error in js_append_child:",e);return false}}function js_remove_child(parent_ref_id,child_ref_id){try{const parent=globalThis.picorubyRefs[parent_ref_id];const child=globalThis.picorubyRefs[child_ref_id];if(!parent||!child)return false;parent.removeChild(child);return true}catch(e){console.error("Error in js_remove_child:",e);return false}}function js_replace_child(parent_ref_id,new_child_ref_id,old_child_ref_id){try{const parent=globalThis.picorubyRefs[parent_ref_id];const newChild=globalThis.picorubyRefs[new_child_ref_id];const oldChild=globalThis.picorubyRefs[old_child_ref_id];if(!parent||!newChild||!oldChild)return false;parent.replaceChild(newChild,oldChild);return true}catch(e){console.error("Error in js_replace_child:",e);return false}}function js_insert_before(parent_ref_id,new_child_ref_id,ref_child_ref_id){try{const parent=globalThis.picorubyRefs[parent_ref_id];const newChild=globalThis.picorubyRefs[new_child_ref_id];const refChild=globalThis.picorubyRefs[ref_child_ref_id];if(!parent||!newChild)return false;parent.insertBefore(newChild,refChild);return true}catch(e){console.error("Error in js_insert_before:",e);return false}}function js_set_attribute(ref_id,name,value){try{const element=globalThis.picorubyRefs[ref_id];if(!element||!element.setAttribute)return false;element.setAttribute(UTF8ToString(name),UTF8ToString(value));return true}catch(e){console.error("Error in js_set_attribute:",e);return false}}function js_remove_attribute(ref_id,name){try{const element=globalThis.picorubyRefs[ref_id];if(!element||!element.removeAttribute)return false;element.removeAttribute(UTF8ToString(name));return true}catch(e){console.error("Error in js_remove_attribute:",e);return false}}function setup_binary_handler(ref_id,mrb_ptr,task_ptr,callback_id){const response=globalThis.picorubyRefs[ref_id];if(!response||typeof response.arrayBuffer!=="function"){console.error("Invalid response object:",response);return 0}response.arrayBuffer().then(arrayBuffer=>{const uint8Array=new Uint8Array(arrayBuffer);const ptr=_malloc(uint8Array.length);const heapBytes=new Uint8Array(HEAPU8.buffer,ptr,uint8Array.length);heapBytes.set(uint8Array);ccall("resume_binary_task","void",["number","number","number","number","number"],[mrb_ptr,task_ptr,callback_id,ptr,uint8Array.length])}).catch(error=>{console.error("Error in arrayBuffer processing:",error)});return 0}function init_js_type_offsets(type_offset,value_offset,is_integer_offset,string_value_offset){globalThis.JS_TYPE_INFO_OFFSETS={type:type_offset,value:value_offset,is_integer:is_integer_offset,string_value:string_value_offset}}function js_get_type_info(ref_id,info){const value=globalThis.picorubyRefs[ref_id];const offsets=globalThis.JS_TYPE_INFO_OFFSETS;let type=typeof value;if(value===null){HEAP32[info+offsets.type>>2]=1;HEAP32[info+offsets.string_value>>2]=0}else if(Array.isArray(value)){HEAP32[info+offsets.type>>2]=7;HEAP32[info+offsets.value>>2]=value.length;HEAP32[info+offsets.string_value>>2]=0}else{switch(type){case"undefined":HEAP32[info+offsets.type>>2]=0;HEAP32[info+offsets.string_value>>2]=0;break;case"boolean":HEAP32[info+offsets.type>>2]=2;HEAPU8[info+offsets.value]=value?1:0;HEAP32[info+offsets.string_value>>2]=0;break;case"number":HEAP32[info+offsets.type>>2]=3;HEAPF64[info+offsets.value>>3]=value;HEAPU8[info+offsets.is_integer]=Number.isInteger(value)?1:0;HEAP32[info+offsets.string_value>>2]=0;break;case"bigint":case"string":case"symbol":{HEAP32[info+offsets.type>>2]=type==="bigint"?4:type==="string"?5:6;const str=type==="symbol"?value.description||"":value.toString();const length=lengthBytesUTF8(str)+1;const ptr=_malloc(length);stringToUTF8(str,ptr,length);HEAP32[info+offsets.string_value>>2]=ptr;break}case"object":HEAP32[info+offsets.type>>2]=8;HEAP32[info+offsets.string_value>>2]=0;break;case"function":HEAP32[info+offsets.type>>2]=9;HEAP32[info+offsets.string_value>>2]=0;break}}}function js_eval(script){try{var result=(0,eval)(UTF8ToString(script));if(result===undefined||result===null)return-1;var refId=globalThis.picorubyRefs.length;globalThis.picorubyRefs.push(result);return refId}catch(e){console.error("JS.eval error:",e);return-1}}function regexp_new(pattern,flags){try{var re=new RegExp(UTF8ToString(pattern),UTF8ToString(flags));return globalThis.picorubyRefs.push(re)-1}catch(e){console.error("RegExp creation failed:",e);return-1}}function regexp_test(ref_id,str,str_len){try{var re=globalThis.picorubyRefs[ref_id];re.lastIndex=0;return re.test(UTF8ToString(str,str_len))?1:0}catch(e){return 0}}function regexp_exec(ref_id,str,str_len){try{var re=globalThis.picorubyRefs[ref_id];re.lastIndex=0;var result=re.exec(UTF8ToString(str,str_len));if(result===null)return-1;return globalThis.picorubyRefs.push(result)-1}catch(e){return-1}}function regexp_match_index(ref_id){var result=globalThis.picorubyRefs[ref_id];return result.index}function regexp_match_length(ref_id){var result=globalThis.picorubyRefs[ref_id];return result.length}function regexp_match_item(ref_id,idx){var result=globalThis.picorubyRefs[ref_id];var item=result[idx];if(item===undefined)return 0;var len=lengthBytesUTF8(item)+1;var ptr=_malloc(len);stringToUTF8(item,ptr,len);return ptr}function regexp_match_item_is_undefined(ref_id,idx){var result=globalThis.picorubyRefs[ref_id];return result[idx]===undefined?1:0}function regexp_source(ref_id){var re=globalThis.picorubyRefs[ref_id];var str=re.source;var len=lengthBytesUTF8(str)+1;var ptr=_malloc(len);stringToUTF8(str,ptr,len);return ptr}function regexp_flags(ref_id){var re=globalThis.picorubyRefs[ref_id];var str=re.flags;var len=lengthBytesUTF8(str)+1;var ptr=_malloc(len);stringToUTF8(str,ptr,len);return ptr}function serial_write(ref_id,data,len){try{const port=globalThis.picorubyRefs[ref_id];if(!port||!port.writable){console.error("serial_write: port not writable");return}if(!globalThis.picorubySerialWriteQueues){globalThis.picorubySerialWriteQueues=Object.create(null)}const bytes=new Uint8Array(HEAPU8.buffer,data,len).slice();const key=String(ref_id);const prev=globalThis.picorubySerialWriteQueues[key]||Promise.resolve();const next=prev.then(async()=>{const writer=port.writable.getWriter();try{await writer.write(bytes)}finally{writer.releaseLock()}}).catch(e=>{console.error("serial_write queue failed:",e)});globalThis.picorubySerialWriteQueues[key]=next}catch(e){console.error("serial_write failed:",e)}}function serial_write_drain_promise(ref_id){try{const key=String(ref_id);const q=globalThis.picorubySerialWriteQueues&&globalThis.picorubySerialWriteQueues[key]||Promise.resolve();const p=q.then(()=>true).catch(e=>{console.error("serial_write_drain failed:",e);return false});return globalThis.picorubyRefs.push(p)-1}catch(e){console.error("serial_write_drain_promise failed:",e);const p=Promise.resolve(false);return globalThis.picorubyRefs.push(p)-1}}function serial_start_reading(ref_id,callback_id){try{const port=globalThis.picorubyRefs[ref_id];if(!port){console.error("serial_start_reading: port not found");return}if(!globalThis.picorubySerialReadStates){globalThis.picorubySerialReadStates=Object.create(null)}const key=String(ref_id);const state=globalThis.picorubySerialReadStates[key]||{running:false};if(state.running){return}state.running=true;globalThis.picorubySerialReadStates[key]=state;(async()=>{while(port.readable){const reader=port.readable.getReader();try{while(true){const{value,done}=await reader.read();if(done)break;const len=value.length;const ptr=_malloc(len);HEAPU8.set(value,ptr);ccall("serial_data_received","void",["number","number","number"],[callback_id,ptr,len]);_free(ptr)}}catch(e){const name=e&&e.name?e.name:"";const message=e&&e.message?e.message:String(e);const deviceLost=name==="NetworkError"||message.includes("device has been lost");if(!deviceLost){console.error("serial read error:",e)}}finally{reader.releaseLock()}}state.running=false})().catch(e=>{state.running=false;console.error("serial_start_reading async failed:",e)})}catch(e){console.error("serial_start_reading failed:",e)}}function serial_read_from_port(ref_id,terminal_ref_id){try{const port=globalThis.picorubyRefs[ref_id];const terminal=globalThis.picorubyRefs[terminal_ref_id];if(!port){console.error("serial_read_from_port: port not found");return}if(!globalThis.picorubySerialReadStates){globalThis.picorubySerialReadStates=Object.create(null)}const key=String(ref_id);const state=globalThis.picorubySerialReadStates[key]||{running:false,reader:null,stopRequested:false,onStopped:null};if(state.running){return}state.running=true;globalThis.picorubySerialReadStates[key]=state;(async()=>{const decoder=new TextDecoder("utf-8");while(port.readable&&!state.stopRequested){const reader=port.readable.getReader();state.reader=reader;try{while(true){const{value,done}=await reader.read();if(done)break;if(!value)continue;if(globalThis.picorubySerialBinCap&&globalThis.picorubySerialBinCap.isActive(port)){globalThis.picorubySerialBinCap.append(port,value);continue}const chars=decoder.decode(value,{stream:true});if(globalThis.picorubySerialCapture){globalThis.picorubySerialCapture.append(port,chars)}if(terminal)terminal.write(chars)}}catch(e){const name=e&&e.name?e.name:"";const message=e&&e.message?e.message:String(e);const deviceLost=name==="NetworkError"||message.includes("device has been lost");if(!deviceLost){console.error("serial read error:",e)}}finally{reader.releaseLock();if(state.reader===reader){state.reader=null}}}const tail=decoder.decode();if(tail){if(globalThis.picorubySerialCapture){globalThis.picorubySerialCapture.append(port,tail)}if(terminal)terminal.write(tail)}state.running=false;if(state.onStopped){state.onStopped()}else{globalThis.dispatchEvent(new CustomEvent("serial-reader-closed"))}})().catch(e=>{state.running=false;console.error("serial_read_from_port async failed:",e);if(state.onStopped){state.onStopped()}else{globalThis.dispatchEvent(new CustomEvent("serial-reader-closed"))}})}catch(e){console.error("serial_read_from_port failed:",e)}}function serial_port_open(port_ref_id,options_ref_id){try{const port=globalThis.picorubyRefs[port_ref_id];const options=globalThis.picorubyRefs[options_ref_id];const promise=port.open(options);return globalThis.picorubyRefs.push(promise)-1}catch(e){console.error("serial_port_open failed:",e);return-1}}function serial_request_port(){try{const serial=navigator&&navigator.serial;if(!serial||!serial.requestPort){console.error("serial_request_port: Web Serial API is not available");return-1}const promise=serial.requestPort();return globalThis.picorubyRefs.push(promise)-1}catch(e){console.error("serial_request_port failed:",e);return-1}}function serial_watch_connect_events(){try{const serial=navigator&&navigator.serial;if(!serial||!serial.addEventListener){return}if(globalThis.picorubySerialConnectWatcherInstalled){return}globalThis.picorubySerialConnectWatcherInstalled=true;serial.addEventListener("connect",e=>{const port=e&&e.target||e&&e.port||null;if(!port)return;globalThis.picorubyLastConnectedSerialPort=port;globalThis.dispatchEvent(new CustomEvent("serial-port-connect"))})}catch(e){console.error("serial_watch_connect_events failed:",e)}}function serial_take_last_connected_port(){try{const port=globalThis.picorubyLastConnectedSerialPort;globalThis.picorubyLastConnectedSerialPort=null;if(!port)return-1;return globalThis.picorubyRefs.push(port)-1}catch(e){console.error("serial_take_last_connected_port failed:",e);return-1}}function serial_port_close(ref_id){try{const port=globalThis.picorubyRefs[ref_id];if(port)port.close();const key=String(ref_id);if(globalThis.picorubySerialReadStates){delete globalThis.picorubySerialReadStates[key]}if(globalThis.picorubySerialWriteQueues){delete globalThis.picorubySerialWriteQueues[key]}if(globalThis.picorubySerialDisconnectHandlers&&port){const prev=globalThis.picorubySerialDisconnectHandlers[key];if(prev){port.removeEventListener("disconnect",prev)}delete globalThis.picorubySerialDisconnectHandlers[key]}if(globalThis.picorubySerialCapture&&port){globalThis.picorubySerialCapture.clear(port)}}catch(e){console.error("serial_port_close failed:",e)}}function serial_port_close_promise(ref_id){try{const port=globalThis.picorubyRefs[ref_id];const key=String(ref_id);if(globalThis.picorubySerialWriteQueues){delete globalThis.picorubySerialWriteQueues[key]}if(globalThis.picorubySerialDisconnectHandlers&&port){const prev=globalThis.picorubySerialDisconnectHandlers[key];if(prev){port.removeEventListener("disconnect",prev)}delete globalThis.picorubySerialDisconnectHandlers[key]}if(globalThis.picorubySerialCapture&&port){globalThis.picorubySerialCapture.clear(port)}const state=globalThis.picorubySerialReadStates&&globalThis.picorubySerialReadStates[key];if(globalThis.picorubySerialReadStates){delete globalThis.picorubySerialReadStates[key]}const p=new Promise(resolve=>{const doClose=()=>{if(!port){resolve(true);return}port.close().then(()=>resolve(true)).catch(()=>resolve(false))};if(state&&state.running){state.stopRequested=true;state.onStopped=doClose;if(state.reader){state.reader.cancel().catch(()=>{})}}else{doClose()}});return globalThis.picorubyRefs.push(p)-1}catch(e){console.error("serial_port_close_promise failed:",e);const p=Promise.resolve(false);return globalThis.picorubyRefs.push(p)-1}}function serial_set_on_disconnect(ref_id,callback_id){try{const port=globalThis.picorubyRefs[ref_id];if(!port){console.error("serial_set_on_disconnect: port not found");return}if(!globalThis.picorubySerialDisconnectHandlers){globalThis.picorubySerialDisconnectHandlers=Object.create(null)}const key=String(ref_id);const prev=globalThis.picorubySerialDisconnectHandlers[key];if(prev){port.removeEventListener("disconnect",prev)}const handler=()=>{ccall("serial_disconnect_callback","void",["number"],[callback_id])};globalThis.picorubySerialDisconnectHandlers[key]=handler;port.addEventListener("disconnect",handler)}catch(e){console.error("serial_set_on_disconnect failed:",e)}}function serial_capture_start(ref_id){try{const port=globalThis.picorubyRefs[ref_id];if(!port)return;if(!globalThis.picorubySerialCapture){const buffers=new WeakMap;const active=new WeakSet;const MAX_CHARS=256*1024;globalThis.picorubySerialCapture={start(p){buffers.set(p,"");active.add(p)},append(p,chunk){if(!p||!active.has(p))return;const prev=buffers.get(p)||"";let next=prev+chunk;if(next.length>MAX_CHARS){next=next.slice(next.length-MAX_CHARS)}buffers.set(p,next)},peek(p){return buffers.get(p)||""},stop(p){const out=buffers.get(p)||"";active.delete(p);return out},clear(p){active.delete(p);buffers.delete(p)}}}globalThis.picorubySerialCapture.start(port)}catch(e){console.error("serial_capture_start failed:",e)}}function serial_binary_capture_start(ref_id){try{const port=globalThis.picorubyRefs[ref_id];if(!port)return;if(!globalThis.picorubySerialBinCap){const buffers=new WeakMap;const active=new WeakSet;const MAX_BYTES=256*1024;globalThis.picorubySerialBinCap={start(p){buffers.set(p,{chunks:[],totalBytes:0});active.add(p)},isActive(p){return active.has(p)},append(p,value){const buf=buffers.get(p);if(!buf)return;const copy=new Uint8Array(value);buf.chunks.push(copy);buf.totalBytes+=copy.length;while(buf.totalBytes>MAX_BYTES&&buf.chunks.length>1){const removed=buf.chunks.shift();buf.totalBytes-=removed.length}},read(p,outPtr,maxBytes){const buf=buffers.get(p);if(!buf||buf.totalBytes===0)return 0;let written=0;while(written<maxBytes&&buf.chunks.length>0){const chunk=buf.chunks[0];const needed=maxBytes-written;if(chunk.length<=needed){HEAPU8.set(chunk,outPtr+written);written+=chunk.length;buf.chunks.shift()}else{HEAPU8.set(chunk.subarray(0,needed),outPtr+written);buf.chunks[0]=chunk.subarray(needed);written+=needed}}buf.totalBytes-=written;return written},stop(p){active.delete(p);buffers.delete(p)}}}globalThis.picorubySerialBinCap.start(port)}catch(e){console.error("serial_binary_capture_start failed:",e)}}function serial_binary_capture_read(ref_id,out_buf,max_bytes){try{const port=globalThis.picorubyRefs[ref_id];if(!port||!globalThis.picorubySerialBinCap)return 0;return globalThis.picorubySerialBinCap.read(port,out_buf,max_bytes)}catch(e){console.error("serial_binary_capture_read failed:",e);return 0}}function serial_binary_capture_stop(ref_id){try{const port=globalThis.picorubyRefs[ref_id];if(!port||!globalThis.picorubySerialBinCap)return;globalThis.picorubySerialBinCap.stop(port)}catch(e){console.error("serial_binary_capture_stop failed:",e)}}function serial_capture_get(ref_id,stop){try{const port=globalThis.picorubyRefs[ref_id];if(!port||!globalThis.picorubySerialCapture){return globalThis.picorubyRefs.push("")-1}const cap=globalThis.picorubySerialCapture;const out=stop?cap.stop(port):cap.peek(port);return globalThis.picorubyRefs.push(out)-1}catch(e){console.error("serial_capture_get failed:",e);return globalThis.picorubyRefs.push("")-1}}function ws_new(url){try{const ws=new WebSocket(UTF8ToString(url));const refId=globalThis.picorubyRefs.push(ws)-1;return refId}catch(e){console.error("WebSocket creation failed:",e);return-1}}function ws_send(ref_id,data){try{const ws=globalThis.picorubyRefs[ref_id];if(ws&&ws.readyState===WebSocket.OPEN){ws.send(UTF8ToString(data))}}catch(e){console.error("WebSocket send failed:",e)}}function ws_send_binary(ref_id,data,length){try{const ws=globalThis.picorubyRefs[ref_id];if(ws&&ws.readyState===WebSocket.OPEN){const buffer=new Uint8Array(HEAPU8.buffer,data,length);const copy=new Uint8Array(buffer);ws.send(copy.buffer)}}catch(e){console.error("WebSocket send_binary failed:",e)}}function ws_close(ref_id){try{const ws=globalThis.picorubyRefs[ref_id];if(ws){ws.close()}}catch(e){console.error("WebSocket close failed:",e)}}function ws_ready_state(ref_id){try{const ws=globalThis.picorubyRefs[ref_id];if(ws){return ws.readyState}return-1}catch(e){return-1}}function ws_set_binary_type(ref_id,type){try{const ws=globalThis.picorubyRefs[ref_id];if(ws){ws.binaryType=UTF8ToString(type)}}catch(e){console.error("WebSocket set_binary_type failed:",e)}}function ws_get_binary_type(ref_id,buffer,buffer_size){try{const ws=globalThis.picorubyRefs[ref_id];if(ws&&ws.binaryType){const type=ws.binaryType;const bytes=lengthBytesUTF8(type)+1;if(bytes<=buffer_size){stringToUTF8(type,buffer,buffer_size);return bytes-1}}return 0}catch(e){return 0}}function ws_set_onopen(ref_id,callback_id){const ws=globalThis.picorubyRefs[ref_id];ws.onopen=event=>{const eventRefId=globalThis.picorubyRefs.push(event)-1;ccall("call_ruby_callback","void",["number","number"],[callback_id,eventRefId])}}function ws_set_onmessage(ref_id,callback_id){const ws=globalThis.picorubyRefs[ref_id];ws.onmessage=event=>{let data=event.data;if(data instanceof ArrayBuffer){const uint8Array=new Uint8Array(data);const length=uint8Array.length;const ptr=_malloc(length);HEAPU8.set(uint8Array,ptr);ccall("call_ruby_callback_with_binary_data","void",["number","number","number"],[callback_id,ptr,length])}else{const eventRefId=globalThis.picorubyRefs.push(event)-1;ccall("call_ruby_callback","void",["number","number"],[callback_id,eventRefId])}}}function ws_set_onerror(ref_id,callback_id){const ws=globalThis.picorubyRefs[ref_id];ws.onerror=event=>{const eventRefId=globalThis.picorubyRefs.push(event)-1;ccall("call_ruby_callback","void",["number","number"],[callback_id,eventRefId])}}function ws_set_onclose(ref_id,callback_id){const ws=globalThis.picorubyRefs[ref_id];ws.onclose=event=>{const eventRefId=globalThis.picorubyRefs.push(event)-1;ccall("call_ruby_callback","void",["number","number"],[callback_id,eventRefId])}}function emscripten_date_now(){return Date.now()}var _ble_notify_callback,_call_ruby_callback,_resume_promise_task,_resume_binary_task,_call_ruby_callback_sync_generic,_mrb_tick_wasm,_mrb_run_step,_picorb_init,_picorb_create_task,_picorb_create_task_with_filename,_picorb_create_task_from_mrb,_serial_data_received,_serial_disconnect_callback,_call_ruby_callback_with_binary_data,_emscripten_builtin_memalign,_malloc,_free,_setThrew,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){_ble_notify_callback=Module["_ble_notify_callback"]=wasmExports["ble_notify_callback"];_call_ruby_callback=Module["_call_ruby_callback"]=wasmExports["call_ruby_callback"];_resume_promise_task=Module["_resume_promise_task"]=wasmExports["resume_promise_task"];_resume_binary_task=Module["_resume_binary_task"]=wasmExports["resume_binary_task"];_call_ruby_callback_sync_generic=Module["_call_ruby_callback_sync_generic"]=wasmExports["call_ruby_callback_sync_generic"];_mrb_tick_wasm=Module["_mrb_tick_wasm"]=wasmExports["mrb_tick_wasm"];_mrb_run_step=Module["_mrb_run_step"]=wasmExports["mrb_run_step"];_picorb_init=Module["_picorb_init"]=wasmExports["picorb_init"];_picorb_create_task=Module["_picorb_create_task"]=wasmExports["picorb_create_task"];_picorb_create_task_with_filename=Module["_picorb_create_task_with_filename"]=wasmExports["picorb_create_task_with_filename"];_picorb_create_task_from_mrb=Module["_picorb_create_task_from_mrb"]=wasmExports["picorb_create_task_from_mrb"];_serial_data_received=Module["_serial_data_received"]=wasmExports["serial_data_received"];_serial_disconnect_callback=Module["_serial_disconnect_callback"]=wasmExports["serial_disconnect_callback"];_call_ruby_callback_with_binary_data=Module["_call_ruby_callback_with_binary_data"]=wasmExports["call_ruby_callback_with_binary_data"];_emscripten_builtin_memalign=wasmExports["emscripten_builtin_memalign"];_malloc=Module["_malloc"]=wasmExports["malloc"];_free=Module["_free"]=wasmExports["free"];_setThrew=wasmExports["setThrew"];__emscripten_stack_restore=wasmExports["_emscripten_stack_restore"];__emscripten_stack_alloc=wasmExports["_emscripten_stack_alloc"];_emscripten_stack_get_current=wasmExports["emscripten_stack_get_current"];memory=wasmMemory=wasmExports["memory"];__indirect_function_table=wasmTable=wasmExports["__indirect_function_table"]}var wasmImports={__syscall_chdir:___syscall_chdir,__syscall_chmod:___syscall_chmod,__syscall_dup:___syscall_dup,__syscall_dup3:___syscall_dup3,__syscall_fcntl64:___syscall_fcntl64,__syscall_fstat64:___syscall_fstat64,__syscall_ftruncate64:___syscall_ftruncate64,__syscall_getcwd:___syscall_getcwd,__syscall_getdents64:___syscall_getdents64,__syscall_ioctl:___syscall_ioctl,__syscall_lstat64:___syscall_lstat64,__syscall_mkdirat:___syscall_mkdirat,__syscall_newfstatat:___syscall_newfstatat,__syscall_openat:___syscall_openat,__syscall_pipe:___syscall_pipe,__syscall_poll:___syscall_poll,__syscall_readlinkat:___syscall_readlinkat,__syscall_renameat:___syscall_renameat,__syscall_rmdir:___syscall_rmdir,__syscall_stat64:___syscall_stat64,__syscall_symlinkat:___syscall_symlinkat,__syscall_unlinkat:___syscall_unlinkat,_abort_js:__abort_js,_emscripten_throw_longjmp:__emscripten_throw_longjmp,_localtime_js:__localtime_js,_mktime_js:__mktime_js,_munmap_js:__munmap_js,_tzset_js:__tzset_js,ble_create_uint8array,ble_dataview_length,ble_dataview_read,ble_set_notify_handler,call_constructor_with_args,call_fetch_with_json_options,call_method,call_method_int,call_method_no_arg,call_method_no_return,call_method_str,call_method_with_args,call_method_with_ref,call_method_with_ref_ref,call_method_with_ref_str_str,clock_time_get:_clock_time_get,copy_string_value,emscripten_asm_const_int:_emscripten_asm_const_int,emscripten_date_now,emscripten_get_heap_max:_emscripten_get_heap_max,emscripten_get_now:_emscripten_get_now,emscripten_resize_heap:_emscripten_resize_heap,environ_get:_environ_get,environ_sizes_get:_environ_sizes_get,exit:_exit,fd_close:_fd_close,fd_fdstat_get:_fd_fdstat_get,fd_pread:_fd_pread,fd_pwrite:_fd_pwrite,fd_read:_fd_read,fd_seek:_fd_seek,fd_sync:_fd_sync,fd_write:_fd_write,get_boolean_value,get_element,get_js_property_type,get_js_type,get_number_value,get_property,get_string_value_length,init_js_refs,init_js_type_offsets,invoke_ddd,invoke_ii,invoke_iii,invoke_iiii,invoke_iiiii,invoke_ji,invoke_jii,invoke_vi,invoke_vii,invoke_viii,invoke_viiii,invoke_viiiii,invoke_viiiiiii,invoke_viiiij,invoke_viiiijii,invoke_viiij,invoke_viij,invoke_viiji,invoke_viijj,invoke_vij,invoke_vijiii,js_add_event_listener,js_append_child,js_clear_timeout,js_create_array,js_create_callback_function,js_create_element,js_create_object,js_create_text_node,js_eval,js_get_type_info,js_insert_before,js_register_generic_callback,js_remove_attribute,js_remove_child,js_remove_event_listener,js_replace_child,js_set_attribute,js_set_timeout,js_string_equals,proc_exit:_proc_exit,regexp_exec,regexp_flags,regexp_match_index,regexp_match_item,regexp_match_item_is_undefined,regexp_match_length,regexp_new,regexp_source,regexp_test,serial_binary_capture_read,serial_binary_capture_start,serial_binary_capture_stop,serial_capture_get,serial_capture_start,serial_port_close,serial_port_close_promise,serial_port_open,serial_read_from_port,serial_request_port,serial_set_on_disconnect,serial_start_reading,serial_take_last_connected_port,serial_watch_connect_events,serial_write,serial_write_drain_promise,set_property,set_property_bool,set_property_double,set_property_int,set_property_null,set_property_ref,setup_binary_handler,setup_promise_handler,ws_close,ws_get_binary_type,ws_new,ws_ready_state,ws_send,ws_send_binary,ws_set_binary_type,ws_set_onclose,ws_set_onerror,ws_set_onmessage,ws_set_onopen};function invoke_iiii(index,a1,a2,a3){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viii(index,a1,a2,a3){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_vi(index,a1){var sp=stackSave();try{getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_vii(index,a1,a2){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_ii(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iii(index,a1,a2){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_ji(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0);return 0n}}function invoke_viiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_vijiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiij(index,a1,a2,a3,a4,a5){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiijii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiii(index,a1,a2,a3,a4){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_vij(index,a1,a2){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiii(index,a1,a2,a3,a4){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viij(index,a1,a2,a3){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiij(index,a1,a2,a3,a4){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiji(index,a1,a2,a3,a4){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viijj(index,a1,a2,a3,a4){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_ddd(index,a1,a2){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_jii(index,a1,a2){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0);return 0n}}function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
|
|
2
|
+
;return moduleRtn}export default Module;
|
|
Binary file
|
data/lib/funicular/version.rb
CHANGED
data/lib/funicular.rb
CHANGED
|
@@ -1,8 +1,36 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require_relative "funicular/version"
|
|
4
|
+
require_relative "funicular/configuration"
|
|
5
|
+
require_relative "funicular/compiler"
|
|
4
6
|
|
|
5
7
|
module Funicular
|
|
6
8
|
class Error < StandardError; end
|
|
7
|
-
|
|
9
|
+
|
|
10
|
+
# Path to the directory containing vendored PicoRuby.wasm builds.
|
|
11
|
+
VENDOR_PICORUBY_DIR = File.expand_path("funicular/vendor/picoruby", __dir__)
|
|
12
|
+
|
|
13
|
+
class << self
|
|
14
|
+
def configuration
|
|
15
|
+
@configuration ||= Configuration.new
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def configure
|
|
19
|
+
yield configuration
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# Version of the @picoruby/wasm-wasi npm package whose builds are
|
|
23
|
+
# vendored under lib/funicular/vendor/picoruby/. Written by the
|
|
24
|
+
# funicular:vendor rake task at gem build time.
|
|
25
|
+
def vendored_wasm_version
|
|
26
|
+
@vendored_wasm_version ||= File.read(File.join(VENDOR_PICORUBY_DIR, "VERSION")).strip
|
|
27
|
+
rescue Errno::ENOENT
|
|
28
|
+
nil
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
if defined?(Rails)
|
|
34
|
+
require_relative "funicular/middleware"
|
|
35
|
+
require_relative "funicular/railtie"
|
|
8
36
|
end
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
namespace :funicular do
|
|
4
|
+
desc "Compile Funicular Ruby files to .mrb format"
|
|
5
|
+
task compile: :environment do
|
|
6
|
+
require "funicular/compiler"
|
|
7
|
+
|
|
8
|
+
source_dir = Rails.root.join("app", "funicular")
|
|
9
|
+
output_file = Rails.root.join("app", "assets", "builds", "app.mrb")
|
|
10
|
+
debug_mode = !Rails.env.production?
|
|
11
|
+
|
|
12
|
+
unless Dir.exist?(source_dir)
|
|
13
|
+
puts "Skipping Funicular compilation: #{source_dir} does not exist"
|
|
14
|
+
next
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
begin
|
|
18
|
+
compiler = Funicular::Compiler.new(
|
|
19
|
+
source_dir: source_dir,
|
|
20
|
+
output_file: output_file,
|
|
21
|
+
debug_mode: debug_mode
|
|
22
|
+
)
|
|
23
|
+
compiler.compile
|
|
24
|
+
rescue Funicular::Compiler::PicorbcNotFoundError => e
|
|
25
|
+
puts "ERROR: #{e.message}"
|
|
26
|
+
exit 1
|
|
27
|
+
rescue => e
|
|
28
|
+
puts "ERROR: Failed to compile Funicular application"
|
|
29
|
+
puts e.message
|
|
30
|
+
puts e.backtrace.join("\n")
|
|
31
|
+
exit 1
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
desc "Show all Funicular routes"
|
|
36
|
+
task routes: :environment do
|
|
37
|
+
require "funicular/commands/routes"
|
|
38
|
+
|
|
39
|
+
begin
|
|
40
|
+
Funicular::Commands::Routes.new.execute
|
|
41
|
+
rescue => e
|
|
42
|
+
puts "ERROR: Failed to display routes"
|
|
43
|
+
puts e.message
|
|
44
|
+
puts e.backtrace.join("\n")
|
|
45
|
+
exit 1
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
desc "Install Funicular debug assets and PicoRuby.wasm artifacts into a Rails app"
|
|
50
|
+
task install: ["install:debug_assets", "install:wasm"] do
|
|
51
|
+
puts ""
|
|
52
|
+
puts "All Funicular assets installed."
|
|
53
|
+
puts ""
|
|
54
|
+
puts "Next steps:"
|
|
55
|
+
puts " 1. In your layout, replace any hardcoded PicoRuby <script> tag with:"
|
|
56
|
+
puts ' <%= picoruby_include_tag %>'
|
|
57
|
+
puts ""
|
|
58
|
+
puts " 2. (Optional) Edit config/initializers/funicular.rb to choose the source"
|
|
59
|
+
puts " for each environment (:local_debug, :local_dist, :cdn)."
|
|
60
|
+
puts ""
|
|
61
|
+
puts " 3. (Optional, development only) Add to your layout to enable"
|
|
62
|
+
puts " the component highlighter:"
|
|
63
|
+
puts ' <% if Rails.env.development? %>'
|
|
64
|
+
puts ' <%= javascript_include_tag "funicular_debug", "data-turbo-track": "reload" %>'
|
|
65
|
+
puts ' <%= stylesheet_link_tag "funicular_debug", "data-turbo-track": "reload" %>'
|
|
66
|
+
puts ' <% end %>'
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
namespace :install do
|
|
70
|
+
desc "Install Funicular debug JS/CSS assets and the gem initializer"
|
|
71
|
+
task :debug_assets do
|
|
72
|
+
require "fileutils"
|
|
73
|
+
|
|
74
|
+
javascripts_dir = Rails.root.join("app", "assets", "javascripts")
|
|
75
|
+
stylesheets_dir = Rails.root.join("app", "assets", "stylesheets")
|
|
76
|
+
initializers_dir = Rails.root.join("config", "initializers")
|
|
77
|
+
|
|
78
|
+
FileUtils.mkdir_p(javascripts_dir)
|
|
79
|
+
FileUtils.mkdir_p(stylesheets_dir)
|
|
80
|
+
FileUtils.mkdir_p(initializers_dir)
|
|
81
|
+
|
|
82
|
+
source_js = File.expand_path("../funicular/assets/funicular_debug.js", __dir__)
|
|
83
|
+
source_css = File.expand_path("../funicular/assets/funicular_debug.css", __dir__)
|
|
84
|
+
source_initializer = File.expand_path("../funicular/assets/funicular.rb", __dir__)
|
|
85
|
+
|
|
86
|
+
dest_js = javascripts_dir.join("funicular_debug.js")
|
|
87
|
+
dest_css = stylesheets_dir.join("funicular_debug.css")
|
|
88
|
+
dest_initializer = initializers_dir.join("funicular.rb")
|
|
89
|
+
|
|
90
|
+
FileUtils.cp(source_js, dest_js)
|
|
91
|
+
FileUtils.cp(source_css, dest_css)
|
|
92
|
+
FileUtils.cp(source_initializer, dest_initializer)
|
|
93
|
+
|
|
94
|
+
puts "Installed Funicular debug assets:"
|
|
95
|
+
puts " - #{dest_js}"
|
|
96
|
+
puts " - #{dest_css}"
|
|
97
|
+
puts " - #{dest_initializer}"
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
desc "Install vendored PicoRuby.wasm artifacts (dist + debug) into public/picoruby/"
|
|
101
|
+
task :wasm do
|
|
102
|
+
require "fileutils"
|
|
103
|
+
|
|
104
|
+
vendor_root = File.expand_path("../funicular/vendor/picoruby", __dir__)
|
|
105
|
+
unless Dir.exist?(vendor_root)
|
|
106
|
+
abort "Vendored PicoRuby artifacts not found at #{vendor_root}. " \
|
|
107
|
+
"Reinstall the funicular gem or run `rake funicular:vendor` from a checkout."
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
dest_root = Rails.root.join("public", "picoruby")
|
|
111
|
+
FileUtils.mkdir_p(dest_root)
|
|
112
|
+
|
|
113
|
+
%w[dist debug].each do |variant|
|
|
114
|
+
src = File.join(vendor_root, variant)
|
|
115
|
+
dst = dest_root.join(variant)
|
|
116
|
+
|
|
117
|
+
unless Dir.exist?(src)
|
|
118
|
+
warn "Skipping #{variant}: #{src} not found"
|
|
119
|
+
next
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
FileUtils.rm_rf(dst)
|
|
123
|
+
FileUtils.mkdir_p(dst)
|
|
124
|
+
FileUtils.cp_r(File.join(src, "."), dst)
|
|
125
|
+
|
|
126
|
+
puts "Installed PicoRuby #{variant} build to #{dst}"
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
# Hook into assets:precompile for production deployment
|
|
133
|
+
if Rake::Task.task_defined?("assets:precompile")
|
|
134
|
+
Rake::Task["assets:precompile"].enhance(["funicular:compile"])
|
|
135
|
+
end
|