@gazefollower/web 0.0.0-stage → 2.2.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.
package/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ Commercial Software License Agreement
2
+ Copyright (c) 2026 GazeFollower. All rights reserved.
3
+
4
+ 1. Grant of License:
5
+ This software, compiled libraries, and associated demonstration files are provided for evaluation, research demonstration, and authorized commercial use in accordance with official licensing terms issued by GazeFollower.
6
+
7
+ 2. Restrictions:
8
+ - The compiled WebAssembly binaries, encrypted model weights, and distribution assets may not be decompiled, disassembled, or reverse engineered.
9
+ - Unauthorized redistribution, sublicensing, or mirroring of the proprietary binaries outside authorized channels is strictly prohibited.
10
+ - Live demonstration services and model access are subject to domain verification and server-assisted session authorization.
11
+
12
+ 3. Warranty Disclaimer:
13
+ The software is provided "AS IS", without warranty of any kind, express or implied. In no event shall the authors or copyright holders be liable for any claim, damages, or other liability arising from the use of the software.
14
+
15
+ For commercial licensing, enterprise deployment, or SDK inquiries, please visit:
16
+ https://gazefollower.com
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ # GazeFollower2 (Web SDK)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **High-Precision Client-Side Webcam Eye Tracking for Modern Browsers**
4
+ > 轻量、高精度、纯浏览器端运行的网页摄像头眼动追踪 SDK(v2.2.0)
5
+
6
+ ---
7
+
8
+ ## Overview
9
+
10
+ **GazeFollower2** brings real-time webcam eye tracking directly to standard desktop and mobile browsers without requiring specialized infrared hardware. All video frames are processed locally on the user's device.
11
+
12
+ - **Zero Hardware Dependency**: Works with standard built-in or USB webcams via browser `getUserMedia`.
13
+ - **Flexible Calibration**: Supports 5-point, 9-point, 13-point, 20-point, 28-point, random grid, and continuous smooth pursuit calibration modes.
14
+ - **Rich Gaze Telemetry**: Outputs viewport gaze coordinates (`x`, `y`) along with bilateral eye openness (`leftOpenness`, `rightOpenness`) and iris size (`leftIrisSize`, `rightIrisSize`).
15
+ - **WebGazer-Compatible API**: Drop-in compatible method signatures for seamless migration and jsPsych / PsychoJS integration.
16
+ - **Privacy First**: Video streams never leave the browser.
17
+
18
+ ---
19
+
20
+ ## Quick Start
21
+
22
+ ```html
23
+ <script type="module">
24
+ import GazeFollower2 from './dist/gazefollower2.min.js';
25
+
26
+ async function main() {
27
+ await GazeFollower2.register({ project_key: 'YOUR_PROJECT_KEY' });
28
+
29
+ GazeFollower2.setTrackingArea({
30
+ x: window.innerWidth * 0.1,
31
+ y: window.innerHeight * 0.1,
32
+ width: window.innerWidth * 0.8,
33
+ height: window.innerHeight * 0.8
34
+ });
35
+
36
+ GazeFollower2.setGazeListener((data, timestamp) => {
37
+ if (data) {
38
+ console.log(
39
+ `x=${data.x.toFixed(1)}, y=${data.y.toFixed(1)}, ` +
40
+ `openness=(${data.leftOpenness}, ${data.rightOpenness})`
41
+ );
42
+ }
43
+ });
44
+
45
+ await GazeFollower2.begin();
46
+ GazeFollower2.startCalibration('13-point', 'click');
47
+ }
48
+
49
+ main();
50
+ </script>
51
+ ```
52
+
53
+ ---
54
+
55
+ ## Live Demo & Licensing
56
+
57
+ - **Official Website & Console**: [https://gazefollower.com](https://gazefollower.com)
58
+ - **GitHub Pages Demo**: [https://ganchengzhu.github.io/GazeFollower2/](https://ganchengzhu.github.io/GazeFollower2/)
59
+ - **Support**: `support@gazefollower.com`
@@ -0,0 +1,5 @@
1
+ THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
2
+
3
+ This package bundles Google MediaPipe Face Landmarker model weights
4
+ (models/face_landmarker.task), licensed under the Apache License, Version 2.0:
5
+ https://www.apache.org/licenses/LICENSE-2.0
@@ -0,0 +1,16 @@
1
+
2
+ var createGazeVaultModule = (() => {
3
+ var _scriptName = import.meta.url;
4
+
5
+ return (
6
+ function(moduleArg = {}) {
7
+ var moduleRtn;
8
+
9
+ var Module=Object.assign({},moduleArg);var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof importScripts=="function";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptName){scriptDirectory=_scriptName}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{read_=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=(url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.init.initialized)FS.init();FS.ignorePermissions=false;TTY.init();callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";var isDataURI=filename=>filename.startsWith(dataURIPrefix);function findWasmBinary(){if(Module["locateFile"]){var f="gaze_vault.wasm";if(!isDataURI(f)){return locateFile(f)}return f}return new URL("gaze_vault.wasm",import.meta.url).href}var wasmBinaryFile;function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(binaryFile){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"){return fetch(binaryFile,{credentials:"same-origin"}).then(response=>{if(!response["ok"]){throw`failed to load wasm binary file at '${binaryFile}'`}return response["arrayBuffer"]()}).catch(()=>getBinarySync(binaryFile))}}return Promise.resolve().then(()=>getBinarySync(binaryFile))}function instantiateArrayBuffer(binaryFile,imports,receiver){return getBinaryPromise(binaryFile).then(binary=>WebAssembly.instantiate(binary,imports)).then(receiver,reason=>{err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)})}function instantiateAsync(binary,binaryFile,imports,callback){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(binaryFile)&&typeof fetch=="function"){return fetch(binaryFile,{credentials:"same-origin"}).then(response=>{var result=WebAssembly.instantiateStreaming(response,imports);return result.then(callback,function(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(binaryFile,imports,callback)})})}return instantiateArrayBuffer(binaryFile,imports,callback)}function getWasmImports(){return{a:wasmImports}}function createWasm(){var info=getWasmImports();function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["na"];updateMemoryViews();wasmTable=wasmExports["qa"];addOnInit(wasmExports["oa"]);removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}if(Module["instantiateWasm"]){try{return Module["instantiateWasm"](info,receiveInstance)}catch(e){err(`Module.instantiateWasm callback failed with error: ${e}`);readyPromiseReject(e)}}if(!wasmBinaryFile)wasmBinaryFile=findWasmBinary();instantiateAsync(wasmBinary,wasmBinaryFile,info,receiveInstantiationResult).catch(readyPromiseReject);return{}}var tempDouble;var tempI64;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var noExitRuntime=Module["noExitRuntime"]||true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var exceptionCaught=[];var uncaughtExceptionCount=0;var ___cxa_begin_catch=ptr=>{var info=new ExceptionInfo(ptr);if(!info.get_caught()){info.set_caught(true);uncaughtExceptionCount--}info.set_rethrown(false);exceptionCaught.push(info);___cxa_increment_exception_refcount(info.excPtr);return info.get_exception_ptr()};var exceptionLast=0;var ___cxa_end_catch=()=>{_setThrew(0,0);var info=exceptionCaught.pop();___cxa_decrement_exception_refcount(info.excPtr);exceptionLast=0};class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}get_exception_ptr(){var isPointer=___cxa_is_pointer_type(this.get_type());if(isPointer){return HEAPU32[this.excPtr>>2]}var adjusted=this.get_adjusted_ptr();if(adjusted!==0)return adjusted;return this.excPtr}}var ___resumeException=ptr=>{if(!exceptionLast){exceptionLast=ptr}throw exceptionLast};var setTempRet0=val=>__emscripten_tempret_set(val);var findMatchingCatch=args=>{var thrown=exceptionLast;if(!thrown){setTempRet0(0);return 0}var info=new ExceptionInfo(thrown);info.set_adjusted_ptr(thrown);var thrownType=info.get_type();if(!thrownType){setTempRet0(0);return thrown}for(var arg in args){var caughtType=args[arg];if(caughtType===0||caughtType===thrownType){break}var adjusted_ptr_addr=info.ptr+16;if(___cxa_can_catch(caughtType,thrownType,adjusted_ptr_addr)){setTempRet0(caughtType);return thrown}}setTempRet0(thrownType);return thrown};var ___cxa_find_matching_catch_2=()=>findMatchingCatch([]);var ___cxa_find_matching_catch_3=arg0=>findMatchingCatch([arg0]);var ___cxa_rethrow=()=>{var info=exceptionCaught.pop();if(!info){abort("no exception to throw")}var ptr=info.excPtr;if(!info.get_rethrown()){exceptionCaught.push(info);info.set_rethrown(true);info.set_caught(false);uncaughtExceptionCount++}exceptionLast=ptr;throw exceptionLast};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var ___cxa_uncaught_exceptions=()=>uncaughtExceptionCount;function syscallGetVarargI(){var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret}var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:path=>{if(path==="/")return"/";path=PATH.normalize(path);path=path.replace(/\/$/,"");var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(typeof crypto=="object"&&typeof crypto["getRandomValues"]=="function"){return view=>crypto.getRandomValues(view)}else abort("initRandomDevice")};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).substr(1);to=PATH_FS.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;var UTF8ArrayToString=(heapOrArray,idx,maxBytesToRead)=>{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&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.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}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}}heap[outIdx]=0;return outIdx-startIdx};function intArrayFromString(stringy,dontAddNull,length){var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops:ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.timestamp=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.timestamp=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output&&tty.output.length>0){out(UTF8ArrayToString(tty.output,0));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,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output,0));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16384|511,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.timestamp=Date.now();if(parent){parent.contents[name]=node;parent.timestamp=node.timestamp}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.timestamp);attr.mtime=new Date(node.timestamp);attr.ctime=new Date(node.timestamp);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){if(attr.mode!==undefined){node.mode=attr.mode}if(attr.timestamp!==undefined){node.timestamp=attr.timestamp}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){throw FS.genericErrors[44]},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){if(FS.isDir(old_node.mode)){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}}delete old_node.parent.contents[old_node.name];old_node.parent.timestamp=Date.now();old_node.name=new_name;new_dir.contents[new_name]=old_node;new_dir.timestamp=old_node.parent.timestamp;old_node.parent=new_dir},unlink(parent,name){delete parent.contents[name];parent.timestamp=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.timestamp=Date.now()},readdir(node){var entries=[".",".."];for(var key of Object.keys(node.contents)){entries.push(key)}return entries},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.timestamp=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},allocate(stream,offset,length){MEMFS.expandFileStorage(stream.node,offset+length);stream.node.usedBytes=Math.max(stream.node.usedBytes,offset+length)},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.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{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)}}allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}HEAP8.set(contents,ptr)}return{ptr:ptr,allocated:allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var asyncLoad=(url,onload,onerror,noRunDep)=>{var dep=!noRunDep?getUniqueRunDependency(`al ${url}`):"";readAsync(url,arrayBuffer=>{onload(new Uint8Array(arrayBuffer));if(dep)removeRunDependency(dep)},event=>{if(onerror){onerror()}else{throw`Loading data file "${url}" failed.`}});if(dep)addRunDependency(dep)};var FS_createDataFile=(parent,name,fileData,canRead,canWrite,canOwn)=>{FS.createDataFile(parent,name,fileData,canRead,canWrite,canOwn)};var preloadPlugins=Module["preloadPlugins"]||[];var FS_handledByPreloadPlugin=(byteArray,fullname,finish,onerror)=>{if(typeof Browser!="undefined")Browser.init();var handled=false;preloadPlugins.forEach(plugin=>{if(handled)return;if(plugin["canHandle"](fullname)){plugin["handle"](byteArray,fullname,finish,onerror);handled=true}});return handled};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);function processData(byteArray){function finish(byteArray){preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}onload?.();removeRunDependency(dep)}if(FS_handledByPreloadPlugin(byteArray,fullname,finish,()=>{onerror?.();removeRunDependency(dep)})){return}finish(byteArray)}addRunDependency(dep);if(typeof url=="string"){asyncLoad(url,processData,onerror)}else{processData(url)}};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 FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:class{constructor(errno){this.name="ErrnoError";this.errno=errno}},genericErrors:{},filesystems:null,syncFSRequests:0,FSStream:class{constructor(){this.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{constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.mounted=null;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.node_ops={};this.stream_ops={};this.rdev=rdev;this.readMode=292|73;this.writeMode=146}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={}){path=PATH_FS.resolve(path);if(!path)return{path:"",node:null};var defaults={follow_mount:true,recurse_count:0};opts=Object.assign(defaults,opts);if(opts.recurse_count>8){throw new FS.ErrnoError(32)}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}current=FS.lookupNode(current,parts[i]);current_path=PATH.join2(current_path,parts[i]);if(FS.isMountpoint(current)){if(!islast||islast&&opts.follow_mount){current=current.mounted.root}}if(!islast||opts.follow){var count=0;while(FS.isLink(current.mode)){var link=FS.readlink(current_path);current_path=PATH_FS.resolve(PATH.dirname(current_path),link);var lookup=FS.lookupPath(current_path,{recurse_count:opts.recurse_count+1});current=lookup.node;if(count++>40){throw new FS.ErrnoError(32)}}}}return{path:current_path,node:current}},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}else if(perms.includes("w")&&!(node.mode&146)){return 2}else 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){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}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&512){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},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},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)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},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:type,opts:opts,mountpoint: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);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];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||name==="."||name===".."){throw new FS.ErrnoError(28)}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)},create(path,mode){mode=mode!==undefined?mode:438;mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode){mode=mode!==undefined?mode:511;mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var i=0;i<dirs.length;++i){if(!dirs[i])continue;d+="/"+dirs[i];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)}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;if(!node.node_ops.readdir){throw new FS.ErrnoError(54)}return node.node_ops.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 PATH_FS.resolve(FS.getPath(link.parent),link.node_ops.readlink(link))},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;if(!node){throw new FS.ErrnoError(44)}if(!node.node_ops.getattr){throw new FS.ErrnoError(63)}return node.node_ops.getattr(node)},lstat(path){return FS.stat(path,true)},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}node.node_ops.setattr(node,{mode:mode&4095|node.mode&~4095,timestamp:Date.now()})},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.chmod(stream.node,mode)},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}node.node_ops.setattr(node,{timestamp:Date.now()})},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.chown(stream.node,uid,gid)},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}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}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)}node.node_ops.setattr(node,{size:len,timestamp:Date.now()})},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if((stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.truncate(stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;node.node_ops.setattr(node,{timestamp:Math.max(atime,mtime)})},open(path,flags,mode){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=typeof mode=="undefined"?438:mode;mode=mode&4095|32768}else{mode=0}var node;if(typeof path=="object"){node=path}else{path=PATH.normalize(path);try{var lookup=FS.lookupPath(path,{follow:!(flags&131072)});node=lookup.node}catch(e){}}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else{node=FS.mknod(path,mode,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:node,path:FS.getPath(node),flags:flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(Module["logReadFiles"]&&!(flags&1)){if(!FS.readFiles)FS.readFiles={};if(!(path in FS.readFiles)){FS.readFiles[path]=1}}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},allocate(stream,offset,length){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(offset<0||length<=0){throw new FS.ErrnoError(28)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(!FS.isFile(stream.node.mode)&&!FS.isDir(stream.node.mode)){throw new FS.ErrnoError(43)}if(!stream.stream_ops.allocate){throw new FS.ErrnoError(138)}stream.stream_ops.allocate(stream,offset,length)},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)}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"){throw new Error(`Invalid encoding type "${opts.encoding}"`)}var ret;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"){ret=UTF8ArrayToString(buf,0)}else if(opts.encoding==="binary"){ret=buf}FS.close(stream);return ret},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){var buf=new Uint8Array(lengthBytesUTF8(data)+1);var actualNumBytes=stringToUTF8Array(data,buf,0,buf.length);FS.write(stream,buf,0,actualNumBytes,undefined,opts.canOwn)}else if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{throw new Error("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});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){randomLeft=randomFill(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",16384|511,73);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}};ret.parent=ret;return ret}};return node}},{},"/proc/self/fd")},createStandardStreams(){if(Module["stdin"]){FS.createDevice("/dev","stdin",Module["stdin"])}else{FS.symlink("/dev/tty","/dev/stdin")}if(Module["stdout"]){FS.createDevice("/dev","stdout",null,Module["stdout"])}else{FS.symlink("/dev/tty","/dev/stdout")}if(Module["stderr"]){FS.createDevice("/dev","stderr",null,Module["stderr"])}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(){[44].forEach(code=>{FS.genericErrors[code]=new FS.ErrnoError(code);FS.genericErrors[code].stack="<generic error, no stack>"});FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS:MEMFS}},init(input,output,error){FS.init.initialized=true;Module["stdin"]=input||Module["stdin"];Module["stdout"]=output||Module["stdout"];Module["stderr"]=error||Module["stderr"];FS.createStandardStreams()},quit(){FS.init.initialized=false;for(var i=0;i<FS.streams.length;i++){var stream=FS.streams[i];if(!stream){continue}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){}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);if(!FS.createDevice.major)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.timestamp=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.timestamp=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(typeof XMLHttpRequest!="undefined"){throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else if(read_){try{obj.contents=intArrayFromString(read_(obj.url),true);obj.usedBytes=obj.contents.length}catch(e){throw new FS.ErrnoError(29)}}else{throw new Error("Cannot load without read() or XMLHttpRequest.")}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{constructor(){this.lengthKnown=false;this.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))throw new Error("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)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("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))throw new Error("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")throw new Error("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(typeof XMLHttpRequest!="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"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: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={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];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:ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var SYSCALLS={DEFAULT_POLLMASK:5,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 PATH.join2(dir,path)},doStat(func,path,buf){var stat=func(path);HEAP32[buf>>2]=stat.dev;HEAP32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAP32[buf+12>>2]=stat.uid;HEAP32[buf+16>>2]=stat.gid;HEAP32[buf+20>>2]=stat.rdev;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+24>>2]=tempI64[0],HEAP32[buf+28>>2]=tempI64[1];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();tempI64=[Math.floor(atime/1e3)>>>0,(tempDouble=Math.floor(atime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAPU32[buf+48>>2]=atime%1e3*1e3;tempI64=[Math.floor(mtime/1e3)>>>0,(tempDouble=Math.floor(mtime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+56>>2]=tempI64[0],HEAP32[buf+60>>2]=tempI64[1];HEAPU32[buf+64>>2]=mtime%1e3*1e3;tempI64=[Math.floor(ctime/1e3)>>>0,(tempDouble=Math.floor(ctime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+72>>2]=tempI64[0],HEAP32[buf+76>>2]=tempI64[1];HEAPU32[buf+80>>2]=ctime%1e3*1e3;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+88>>2]=tempI64[0],HEAP32[buf+92>>2]=tempI64[1];return 0},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_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_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_iflag,c_oflag:c_oflag,c_cflag:c_cflag,c_lflag:c_lflag,c_cc: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 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_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 __abort_js=()=>{abort("")};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{};var embind_init_charCodes=()=>{var codes=new Array(256);for(var i=0;i<256;++i){codes[i]=String.fromCharCode(i)}embind_charCodes=codes};var embind_charCodes;var readLatin1String=ptr=>{var ret="";var c=ptr;while(HEAPU8[c]){ret+=embind_charCodes[HEAPU8[c++]]}return ret};var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var BindingError;var throwBindingError=message=>{throw new BindingError(message)};var InternalError;var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;dependentTypes.forEach((dt,i)=>{if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}});if(0===unregisteredTypes.length){onComplete(typeConverters)}};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){if(!("argPackAdvance"in registeredInstance)){throw new TypeError("registerType registeredInstance requires argPackAdvance")}return sharedRegisterType(rawType,registeredInstance,options)}var GenericWireTypeSize=8;var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=readLatin1String(name);registerType(rawType,{name:name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},argPackAdvance:GenericWireTypeSize,readValueFromPointer:function(pointer){return this["fromWireType"](HEAPU8[pointer])},destructorFunction:null})};var shallowCopyInternalPointer=o=>({count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType});var throwInstanceAlreadyDeleted=obj=>{function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")};var finalizationRegistry=false;var detachFinalizer=handle=>{};var runDestructor=$$=>{if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}};var releaseClassHandle=$$=>{$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}};var downcastPointer=(ptr,ptrClass,desiredClass)=>{if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)};var registeredPointers={};var getInheritedInstanceCount=()=>Object.keys(registeredInstances).length;var getLiveInheritedInstances=()=>{var rv=[];for(var k in registeredInstances){if(registeredInstances.hasOwnProperty(k)){rv.push(registeredInstances[k])}}return rv};var deletionQueue=[];var flushPendingDeletes=()=>{while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}};var delayFunction;var setDelayFunction=fn=>{delayFunction=fn;if(deletionQueue.length&&delayFunction){delayFunction(flushPendingDeletes)}};var init_embind=()=>{Module["getInheritedInstanceCount"]=getInheritedInstanceCount;Module["getLiveInheritedInstances"]=getLiveInheritedInstances;Module["flushPendingDeletes"]=flushPendingDeletes;Module["setDelayFunction"]=setDelayFunction};var registeredInstances={};var getBasestPointer=(class_,ptr)=>{if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr};var getInheritedInstance=(class_,ptr)=>{ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]};var makeClassHandle=(prototype,record)=>{if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record,writable:true}}))};function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr:ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}var attachFinalizer=handle=>{if("undefined"===typeof FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$:$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)};var init_ClassHandle=()=>{Object.assign(ClassHandle.prototype,{isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;other.$$=other.$$;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right},clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}},delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}},isDeleted(){return!this.$$.ptr},deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}})};function ClassHandle(){}var createNamedFunction=(name,body)=>Object.defineProperty(body,"name",{value:name});var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;if(undefined!==numArguments){Module[name].numArguments=numArguments}}};var char_0=48;var char_9=57;var makeLegalFunctionName=name=>{if(undefined===name){return"_unknown"}name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return`_${name}`}return name};function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}var upcastPointer=(ptr,ptrClass,desiredClass)=>{while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr};function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle||!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(()=>clonedHandle["delete"]()));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function readPointer(pointer){return this["fromWireType"](HEAPU32[pointer>>2])}var init_RegisteredPointer=()=>{Object.assign(RegisteredPointer.prototype,{getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr},destructor(ptr){this.rawDestructor?.(ptr)},argPackAdvance:GenericWireTypeSize,readValueFromPointer:readPointer,fromWireType:RegisteredPointer_fromWireType})};function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&&registeredClass.baseClass===undefined){if(isConst){this["toWireType"]=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this["toWireType"]=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this["toWireType"]=genericPointerToWireType}}var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var dynCallLegacy=(sig,ptr,args)=>{sig=sig.replace(/p/g,"i");var f=Module["dynCall_"+sig];return f(ptr,...args)};var wasmTableMirror=[];var wasmTable;var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){if(funcPtr>=wasmTableMirror.length)wasmTableMirror.length=funcPtr+1;wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var dynCall=(sig,ptr,args=[])=>{if(sig.includes("j")){return dynCallLegacy(sig,ptr,args)}var rtn=getWasmTableEntry(ptr)(...args);return rtn};var getDynCaller=(sig,ptr)=>(...args)=>dynCall(sig,ptr,args);var embind__requireFunction=(signature,rawFunction)=>{signature=readLatin1String(signature);function makeDynCaller(){if(signature.includes("j")){return getDynCaller(signature,rawFunction)}return getWasmTableEntry(rawFunction)}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};var extendError=(baseErrorType,errorName)=>{var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return`${this.name}: ${this.message}`}};return errorClass};var UnboundTypeError;var getTypeName=type=>{var ptr=___getTypeName(type);var rv=readLatin1String(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var __embind_register_class=(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor)=>{name=readLatin1String(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);upcast&&=embind__requireFunction(upcastSignature,upcast);downcast&&=embind__requireFunction(downcastSignature,downcast);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError(`Cannot construct ${name} due to unbound types`,[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],base=>{base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(name,function(...args){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError("Use 'new' to construct "+name)}if(undefined===registeredClass.constructor_body){throw new BindingError(name+" has no accessible constructor")}var body=registeredClass.constructor_body[args.length];if(undefined===body){throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`)}return body.apply(this,args)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);if(registeredClass.baseClass){registeredClass.baseClass.__derivedClasses??=[];registeredClass.baseClass.__derivedClasses.push(registeredClass)}var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function newFunc(constructor,argumentList){if(!(constructor instanceof Function)){throw new TypeError(`new_ called with constructor type ${typeof constructor} which is not a function`)}var dummy=createNamedFunction(constructor.name||"unknownFunctionName",function(){});dummy.prototype=constructor.prototype;var obj=new dummy;var r=constructor.apply(obj,argumentList);return r instanceof Object?r:obj}function createJsInvoker(argTypes,isClassMethodFunc,returns,isAsync){var needsDestructorStack=usesDestructorStack(argTypes);var argCount=argTypes.length;var argsList="";var argsListWired="";for(var i=0;i<argCount-2;++i){argsList+=(i!==0?", ":"")+"arg"+i;argsListWired+=(i!==0?", ":"")+"arg"+i+"Wired"}var invokerFnBody=`\n return function (${argsList}) {\n if (arguments.length !== ${argCount-2}) {\n throwBindingError('function ' + humanName + ' called with ' + arguments.length + ' arguments, expected ${argCount-2}');\n }`;if(needsDestructorStack){invokerFnBody+="var destructors = [];\n"}var dtorStack=needsDestructorStack?"destructors":"null";var args1=["humanName","throwBindingError","invoker","fn","runDestructors","retType","classParam"];if(isClassMethodFunc){invokerFnBody+="var thisWired = classParam['toWireType']("+dtorStack+", this);\n"}for(var i=0;i<argCount-2;++i){invokerFnBody+="var arg"+i+"Wired = argType"+i+"['toWireType']("+dtorStack+", arg"+i+");\n";args1.push("argType"+i)}if(isClassMethodFunc){argsListWired="thisWired"+(argsListWired.length>0?", ":"")+argsListWired}invokerFnBody+=(returns||isAsync?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;++i){var paramName=i===1?"thisWired":"arg"+(i-2)+"Wired";if(argTypes[i].destructorFunction!==null){invokerFnBody+=`${paramName}_dtor(${paramName});\n`;args1.push(`${paramName}_dtor`)}}}if(returns){invokerFnBody+="var ret = retType['fromWireType'](rv);\n"+"return ret;\n"}else{}invokerFnBody+="}\n";return[args1,invokerFnBody]}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=argTypes[0].name!=="void";var closureArgs=[humanName,throwBindingError,cppInvokerFunc,cppTargetFunc,runDestructors,argTypes[0],argTypes[1]];for(var i=0;i<argCount-2;++i){closureArgs.push(argTypes[i+2])}if(!needsDestructorStack){for(var i=isClassMethodFunc?1:2;i<argTypes.length;++i){if(argTypes[i].destructorFunction!==null){closureArgs.push(argTypes[i].destructorFunction)}}}let[args,invokerFnBody]=createJsInvoker(argTypes,isClassMethodFunc,returns,isAsync);args.push(invokerFnBody);var invokerFn=newFunc(Function,args)(...closureArgs);return createNamedFunction(humanName,invokerFn)}var __embind_register_class_constructor=(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`constructor ${classType.name}`;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount-1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`,rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex!==-1){return signature.substr(0,argsIndex)}else{return signature}};var __embind_register_class_function=(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual,isAsync)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);methodName=getFunctionName(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`${classType.name}.${methodName}`;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`,rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context,isAsync);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})};var emval_freelist=[];var emval_handles=[];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var count_emval_handles=()=>emval_handles.length/2-5-emval_freelist.length;var init_emval=()=>{emval_handles.push(0,1,undefined,1,null,1,true,1,false,1);Module["count_emval_handles"]=count_emval_handles};var Emval={toValue:handle=>{if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),argPackAdvance:GenericWireTypeSize,readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var embindRepr=v=>{if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}};var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 8:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=readLatin1String(name);registerType(rawType,{name:name,fromWireType:value=>value,toWireType:(destructors,value)=>value,argPackAdvance:GenericWireTypeSize,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var fromWireType=value=>value;if(minRange===0){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift}var isUnsignedType=name.includes("unsigned");var checkAssertions=(value,toTypeName)=>{};var toWireType;if(isUnsignedType){toWireType=function(destructors,value){checkAssertions(value,this.name);return value>>>0}}else{toWireType=function(destructors,value){checkAssertions(value,this.name);return value}}registerType(primitiveType,{name:name,fromWireType:fromWireType,toWireType:toWireType,argPackAdvance:GenericWireTypeSize,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,fromWireType:decodeMemoryView,argPackAdvance:GenericWireTypeSize,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __embind_register_std_string=(rawType,name)=>{name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){var decodeStartPtr=payload;for(var i=0;i<=length;++i){var currentBytePtr=payload+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i<length;++i){a[i]=String.fromCharCode(HEAPU8[payload+i])}str=a.join("")}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||value instanceof Uint8Array||value instanceof Uint8ClampedArray||value instanceof Int8Array)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr,length+1)}else{if(valueIsOfTypeString){for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}else{for(var i=0;i<length;++i){HEAPU8[ptr+i]=value[i]}}}if(destructors!==null){destructors.push(_free,base)}return base},argPackAdvance:GenericWireTypeSize,readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead)=>{var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder)return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr));var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead)=>{var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codeUnit=str.charCodeAt(i);if(codeUnit>=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codeUnit=str.charCodeAt(i);if(codeUnit>=55296&&codeUnit<=57343)++i;len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=readLatin1String(name);var decodeString,encodeString,readCharAt,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16;readCharAt=pointer=>HEAPU16[pointer>>1]}else if(charSize===4){decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32;readCharAt=pointer=>HEAPU32[pointer>>2]}registerType(rawType,{name:name,fromWireType:value=>{var length=HEAPU32[value>>2];var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||readCharAt(currentBytePtr)==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},argPackAdvance:GenericWireTypeSize,readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_void=(rawType,name)=>{name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,argPackAdvance:0,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var __emscripten_fs_load_embedded_files=ptr=>{do{var name_addr=HEAPU32[ptr>>2];ptr+=4;var len=HEAPU32[ptr>>2];ptr+=4;var content=HEAPU32[ptr>>2];ptr+=4;var name=UTF8ToString(name_addr);FS.createPath("/",PATH.dirname(name),true,true);FS.createDataFile(name,null,HEAP8.subarray(content,content+len),true,true,true)}while(HEAPU32[ptr>>2])};var __emscripten_memcpy_js=(dest,src,num)=>HEAPU8.copyWithin(dest,src,src+num);var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var emval_returnValue=(returnType,destructorsRef,handle)=>{var destructors=[];var result=returnType["toWireType"](destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var __emval_as=(handle,returnType,destructorsRef)=>{handle=Emval.toValue(handle);returnType=requireRegisteredType(returnType,"emval::as");return emval_returnValue(returnType,destructorsRef,handle)};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}return symbol};var emval_methodCallers=[];var __emval_call_method=(caller,objHandle,methodName,destructorsRef,args)=>{caller=emval_methodCallers[caller];objHandle=Emval.toValue(objHandle);methodName=getStringOrSymbol(methodName);return caller(objHandle,objHandle[methodName],destructorsRef,args)};var emval_get_global=()=>{if(typeof globalThis=="object"){return globalThis}return function(){return Function}()("return this")()};var __emval_get_global=name=>{if(name===0){return Emval.toHandle(emval_get_global())}else{name=getStringOrSymbol(name);return Emval.toHandle(emval_get_global()[name])}};var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],"parameter "+i)}return a};var reflectConstruct=Reflect.construct;var __emval_get_method_caller=(argCount,argTypes,kind)=>{var types=emval_lookupTypes(argCount,argTypes);var retType=types.shift();argCount--;var functionBody=`return function (obj, func, destructorsRef, args) {\n`;var offset=0;var argsList=[];if(kind===0){argsList.push("obj")}var params=["retType"];var args=[retType];for(var i=0;i<argCount;++i){argsList.push("arg"+i);params.push("argType"+i);args.push(types[i]);functionBody+=` var arg${i} = argType${i}.readValueFromPointer(args${offset?"+"+offset:""});\n`;offset+=types[i]["argPackAdvance"]}var invoker=kind===1?"new func":"func.call";functionBody+=` var rv = ${invoker}(${argsList.join(", ")});\n`;if(!retType.isVoid){params.push("emval_returnValue");args.push(emval_returnValue);functionBody+=" return emval_returnValue(retType, destructorsRef, rv);\n"}functionBody+="};\n";params.push(functionBody);var invokerFunction=newFunc(Function,params)(...args);var functionName=`methodCaller<(${types.map(t=>t.name).join(", ")}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_get_property=(handle,key)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);return Emval.toHandle(handle[key])};var __emval_incref=handle=>{if(handle>9){emval_handles[handle+1]+=1}};var __emval_new_cstring=v=>Emval.toHandle(getStringOrSymbol(v));var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_take_value=(type,arg)=>{type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](arg);return Emval.toHandle(v)};var getHeapMax=()=>2147483648;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536;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}var alignUp=(x,multiple)=>x+(multiple-x%multiple)%multiple;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,alignUp(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=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"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 stringToAscii=(str,buffer)=>{for(var i=0;i<str.length;++i){HEAP8[buffer++]=str.charCodeAt(i)}HEAP8[buffer]=0};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;getEnvStrings().forEach((string,i)=>{var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;stringToAscii(string,ptr);bufSize+=string.length+1});return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(string=>bufSize+=string.length+1);HEAPU32[penviron_buf_size>>2]=bufSize;return 0};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}}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_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}}var convertI32PairToI53Checked=(lo,hi)=>hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN;function _fd_seek(fd,offset_low,offset_high,whence,newOffset){var offset=convertI32PairToI53Checked(offset_low,offset_high);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>2]=tempI64[0],HEAP32[newOffset+4>>2]=tempI64[1];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}}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(typeof offset!="undefined"){offset+=curr}}return ret};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 isLeapYear=year=>year%4===0&&(year%100!==0||year%400===0);var arraySum=(array,index)=>{var sum=0;for(var i=0;i<=index;sum+=array[i++]){}return sum};var MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31];var MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31];var addDays=(date,days)=>{var newDate=new Date(date.getTime());while(days>0){var leap=isLeapYear(newDate.getFullYear());var currentMonth=newDate.getMonth();var daysInCurrentMonth=(leap?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR)[currentMonth];if(days>daysInCurrentMonth-newDate.getDate()){days-=daysInCurrentMonth-newDate.getDate()+1;newDate.setDate(1);if(currentMonth<11){newDate.setMonth(currentMonth+1)}else{newDate.setMonth(0);newDate.setFullYear(newDate.getFullYear()+1)}}else{newDate.setDate(newDate.getDate()+days);return newDate}}return newDate};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var _strftime=(s,maxsize,format,tm)=>{var tm_zone=HEAPU32[tm+40>>2];var date={tm_sec:HEAP32[tm>>2],tm_min:HEAP32[tm+4>>2],tm_hour:HEAP32[tm+8>>2],tm_mday:HEAP32[tm+12>>2],tm_mon:HEAP32[tm+16>>2],tm_year:HEAP32[tm+20>>2],tm_wday:HEAP32[tm+24>>2],tm_yday:HEAP32[tm+28>>2],tm_isdst:HEAP32[tm+32>>2],tm_gmtoff:HEAP32[tm+36>>2],tm_zone:tm_zone?UTF8ToString(tm_zone):""};var pattern=UTF8ToString(format);var EXPANSION_RULES_1={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var rule in EXPANSION_RULES_1){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_1[rule])}var WEEKDAYS=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];var MONTHS=["January","February","March","April","May","June","July","August","September","October","November","December"];function leadingSomething(value,digits,character){var str=typeof value=="number"?value.toString():value||"";while(str.length<digits){str=character[0]+str}return str}function leadingNulls(value,digits){return leadingSomething(value,digits,"0")}function compareByDay(date1,date2){function sgn(value){return value<0?-1:value>0?1:0}var compare;if((compare=sgn(date1.getFullYear()-date2.getFullYear()))===0){if((compare=sgn(date1.getMonth()-date2.getMonth()))===0){compare=sgn(date1.getDate()-date2.getDate())}}return compare}function getFirstWeekStartDate(janFourth){switch(janFourth.getDay()){case 0:return new Date(janFourth.getFullYear()-1,11,29);case 1:return janFourth;case 2:return new Date(janFourth.getFullYear(),0,3);case 3:return new Date(janFourth.getFullYear(),0,2);case 4:return new Date(janFourth.getFullYear(),0,1);case 5:return new Date(janFourth.getFullYear()-1,11,31);case 6:return new Date(janFourth.getFullYear()-1,11,30)}}function getWeekBasedYear(date){var thisDate=addDays(new Date(date.tm_year+1900,0,1),date.tm_yday);var janFourthThisYear=new Date(thisDate.getFullYear(),0,4);var janFourthNextYear=new Date(thisDate.getFullYear()+1,0,4);var firstWeekStartThisYear=getFirstWeekStartDate(janFourthThisYear);var firstWeekStartNextYear=getFirstWeekStartDate(janFourthNextYear);if(compareByDay(firstWeekStartThisYear,thisDate)<=0){if(compareByDay(firstWeekStartNextYear,thisDate)<=0){return thisDate.getFullYear()+1}return thisDate.getFullYear()}return thisDate.getFullYear()-1}var EXPANSION_RULES_2={"%a":date=>WEEKDAYS[date.tm_wday].substring(0,3),"%A":date=>WEEKDAYS[date.tm_wday],"%b":date=>MONTHS[date.tm_mon].substring(0,3),"%B":date=>MONTHS[date.tm_mon],"%C":date=>{var year=date.tm_year+1900;return leadingNulls(year/100|0,2)},"%d":date=>leadingNulls(date.tm_mday,2),"%e":date=>leadingSomething(date.tm_mday,2," "),"%g":date=>getWeekBasedYear(date).toString().substring(2),"%G":getWeekBasedYear,"%H":date=>leadingNulls(date.tm_hour,2),"%I":date=>{var twelveHour=date.tm_hour;if(twelveHour==0)twelveHour=12;else if(twelveHour>12)twelveHour-=12;return leadingNulls(twelveHour,2)},"%j":date=>leadingNulls(date.tm_mday+arraySum(isLeapYear(date.tm_year+1900)?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR,date.tm_mon-1),3),"%m":date=>leadingNulls(date.tm_mon+1,2),"%M":date=>leadingNulls(date.tm_min,2),"%n":()=>"\n","%p":date=>{if(date.tm_hour>=0&&date.tm_hour<12){return"AM"}return"PM"},"%S":date=>leadingNulls(date.tm_sec,2),"%t":()=>"\t","%u":date=>date.tm_wday||7,"%U":date=>{var days=date.tm_yday+7-date.tm_wday;return leadingNulls(Math.floor(days/7),2)},"%V":date=>{var val=Math.floor((date.tm_yday+7-(date.tm_wday+6)%7)/7);if((date.tm_wday+371-date.tm_yday-2)%7<=2){val++}if(!val){val=52;var dec31=(date.tm_wday+7-date.tm_yday-1)%7;if(dec31==4||dec31==5&&isLeapYear(date.tm_year%400-1)){val++}}else if(val==53){var jan1=(date.tm_wday+371-date.tm_yday)%7;if(jan1!=4&&(jan1!=3||!isLeapYear(date.tm_year)))val=1}return leadingNulls(val,2)},"%w":date=>date.tm_wday,"%W":date=>{var days=date.tm_yday+7-(date.tm_wday+6)%7;return leadingNulls(Math.floor(days/7),2)},"%y":date=>(date.tm_year+1900).toString().substring(2),"%Y":date=>date.tm_year+1900,"%z":date=>{var off=date.tm_gmtoff;var ahead=off>=0;off=Math.abs(off)/60;off=off/60*100+off%60;return(ahead?"+":"-")+String("0000"+off).slice(-4)},"%Z":date=>date.tm_zone,"%%":()=>"%"};pattern=pattern.replace(/%%/g,"\0\0");for(var rule in EXPANSION_RULES_2){if(pattern.includes(rule)){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_2[rule](date))}}pattern=pattern.replace(/\0\0/g,"%");var bytes=intArrayFromString(pattern,false);if(bytes.length>maxsize){return 0}writeArrayToMemory(bytes,s);return bytes.length-1};var _strftime_l=(s,maxsize,format,tm,loc)=>_strftime(s,maxsize,format,tm);var FS_createPath=FS.createPath;var FS_unlink=path=>FS.unlink(path);var FS_createLazyFile=FS.createLazyFile;var FS_createDevice=FS.createDevice;FS.createPreloadedFile=FS_createPreloadedFile;FS.staticInit();Module["FS_createPath"]=FS.createPath;Module["FS_createDataFile"]=FS.createDataFile;Module["FS_createPreloadedFile"]=FS.createPreloadedFile;Module["FS_unlink"]=FS.unlink;Module["FS_createLazyFile"]=FS.createLazyFile;Module["FS_createDevice"]=FS.createDevice;embind_init_charCodes();BindingError=Module["BindingError"]=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};InternalError=Module["InternalError"]=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};init_ClassHandle();init_embind();init_RegisteredPointer();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");init_emval();var wasmImports={o:___cxa_begin_catch,q:___cxa_end_catch,a:___cxa_find_matching_catch_2,f:___cxa_find_matching_catch_3,G:___cxa_rethrow,u:___cxa_throw,Y:___cxa_uncaught_exceptions,d:___resumeException,D:___syscall_fcntl64,W:___syscall_ioctl,X:___syscall_openat,R:__abort_js,P:__embind_register_bigint,ba:__embind_register_bool,ma:__embind_register_class,la:__embind_register_class_constructor,s:__embind_register_class_function,aa:__embind_register_emval,I:__embind_register_float,p:__embind_register_integer,l:__embind_register_memory_view,H:__embind_register_std_string,y:__embind_register_std_wstring,ca:__embind_register_void,$:__emscripten_fs_load_embedded_files,_:__emscripten_memcpy_js,K:__emval_as,ea:__emval_call_method,ka:__emval_decref,ja:__emval_get_global,fa:__emval_get_method_caller,ha:__emval_get_property,ga:__emval_incref,J:__emval_new_cstring,ia:__emval_run_destructors,L:__emval_take_value,Z:_emscripten_resize_heap,T:_environ_get,U:_environ_sizes_get,B:_fd_close,V:_fd_read,N:_fd_seek,C:_fd_write,v:invoke_diii,da:invoke_diiiii,z:invoke_fiii,k:invoke_i,b:invoke_ii,c:invoke_iii,j:invoke_iiii,g:invoke_iiiii,E:invoke_iiiiii,r:invoke_iiiiiii,A:invoke_iiiiiiii,x:invoke_iiiiiiiiiiii,Q:invoke_iiji,M:invoke_jiiii,h:invoke_v,i:invoke_vi,e:invoke_vii,m:invoke_viii,F:invoke_viiii,n:invoke_viiiiiii,t:invoke_viiiiiiiiii,w:invoke_viiiiiiiiiiiiiii,O:invoke_viijii,S:_strftime_l};var wasmExports=createWasm();var ___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports["oa"])();var ___getTypeName=a0=>(___getTypeName=wasmExports["pa"])(a0);var _malloc=a0=>(_malloc=wasmExports["ra"])(a0);var _free=a0=>(_free=wasmExports["sa"])(a0);var _setThrew=(a0,a1)=>(_setThrew=wasmExports["ta"])(a0,a1);var __emscripten_tempret_set=a0=>(__emscripten_tempret_set=wasmExports["ua"])(a0);var __emscripten_stack_restore=a0=>(__emscripten_stack_restore=wasmExports["va"])(a0);var _emscripten_stack_get_current=()=>(_emscripten_stack_get_current=wasmExports["wa"])();var ___cxa_decrement_exception_refcount=a0=>(___cxa_decrement_exception_refcount=wasmExports["xa"])(a0);var ___cxa_increment_exception_refcount=a0=>(___cxa_increment_exception_refcount=wasmExports["ya"])(a0);var ___cxa_can_catch=(a0,a1,a2)=>(___cxa_can_catch=wasmExports["za"])(a0,a1,a2);var ___cxa_is_pointer_type=a0=>(___cxa_is_pointer_type=wasmExports["Aa"])(a0);var dynCall_iiji=Module["dynCall_iiji"]=(a0,a1,a2,a3,a4)=>(dynCall_iiji=Module["dynCall_iiji"]=wasmExports["Ba"])(a0,a1,a2,a3,a4);var dynCall_jiji=Module["dynCall_jiji"]=(a0,a1,a2,a3,a4)=>(dynCall_jiji=Module["dynCall_jiji"]=wasmExports["Ca"])(a0,a1,a2,a3,a4);var dynCall_viijii=Module["dynCall_viijii"]=(a0,a1,a2,a3,a4,a5,a6)=>(dynCall_viijii=Module["dynCall_viijii"]=wasmExports["Da"])(a0,a1,a2,a3,a4,a5,a6);var dynCall_jiiii=Module["dynCall_jiiii"]=(a0,a1,a2,a3,a4)=>(dynCall_jiiii=Module["dynCall_jiiii"]=wasmExports["Ea"])(a0,a1,a2,a3,a4);var dynCall_iiiiij=Module["dynCall_iiiiij"]=(a0,a1,a2,a3,a4,a5,a6)=>(dynCall_iiiiij=Module["dynCall_iiiiij"]=wasmExports["Fa"])(a0,a1,a2,a3,a4,a5,a6);var dynCall_iiiiijj=Module["dynCall_iiiiijj"]=(a0,a1,a2,a3,a4,a5,a6,a7,a8)=>(dynCall_iiiiijj=Module["dynCall_iiiiijj"]=wasmExports["Ga"])(a0,a1,a2,a3,a4,a5,a6,a7,a8);var dynCall_iiiiiijj=Module["dynCall_iiiiiijj"]=(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9)=>(dynCall_iiiiiijj=Module["dynCall_iiiiiijj"]=wasmExports["Ha"])(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9);var ___emscripten_embedded_file_data=Module["___emscripten_embedded_file_data"]=4024248;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_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_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_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_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_diii(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_diiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_v(index){var sp=stackSave();try{getWasmTableEntry(index)()}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_iiiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5)}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_iiiiiiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_fiii(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_i(index){var sp=stackSave();try{return getWasmTableEntry(index)()}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_iiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiji(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_iiji(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viijii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{dynCall_viijii(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_jiiii(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_jiiii(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["FS_createPreloadedFile"]=FS_createPreloadedFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(){if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();moduleRtn=readyPromise;
10
+
11
+
12
+ return moduleRtn;
13
+ }
14
+ );
15
+ })();
16
+ export default createGazeVaultModule;
Binary file
@@ -0,0 +1 @@
1
+ import{FilesetResolver,FaceLandmarker}from"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.3/vision_bundle.mjs";class FaceAlignment{constructor(){this.canvas="undefined"!=typeof document?document.createElement("canvas"):null,this.ctx=this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null,this.tmpCanvas="undefined"!=typeof document?document.createElement("canvas"):null,this.tmpCtx=this.tmpCanvas?this.tmpCanvas.getContext("2d",{willReadFrequently:!0}):null,this.lip_vertices=[61,91,14,178,402,324,95],this.left_vertices=[362,388,384,385,386,387,388,466,263,249,380,373,374,380,381,382,362],this.right_vertices=[33,246,161,160,159,158,157,173,133,155,154,153,145,144,163,7,33],this.left_iris_vertices=[474,475,476,477],this.right_iris_vertices=[469,470,471,472]}setFilterEnabled(t){}resetFilter(){}calculateArea(t){let e=0;for(let i=0;i<t.length;i++){let s=(i+1)%t.length;e+=t[i].x*t[s].y-t[s].x*t[i].y}return Math.abs(e/2)}calculatePolygonArea(t,e){if(!Array.isArray(t)||!Array.isArray(e)||e.length<3)return 0;const i=[];for(let s=0;s<e.length;s++){const n=t[e[s]];if(!n)return 0;i.push(n)}return this.calculateArea(i)}calculateIrisSize(t,e){if(!Array.isArray(t)||!Array.isArray(e)||e.length<4)return 0;const i=t[e[0]],s=t[e[1]],n=t[e[2]],o=t[e[3]];return i&&s&&n&&o?.5*(Math.hypot(i.x-n.x,i.y-n.y)+Math.hypot(s.x-o.x,s.y-o.y)):0}computeEyeMetrics(t){return{leftOpenness:Number(this.calculatePolygonArea(t,this.left_vertices).toFixed(3)),rightOpenness:Number(this.calculatePolygonArea(t,this.right_vertices).toFixed(3)),leftIrisSize:Number(this.calculateIrisSize(t,this.left_iris_vertices).toFixed(3)),rightIrisSize:Number(this.calculateIrisSize(t,this.right_iris_vertices).toFixed(3))}}process(t,e,i=null){const s=t.videoWidth||t.width||640,n=t.videoHeight||t.height||480;this.canvas.width!==s&&(this.canvas.width=s,this.canvas.height=n),this.ctx.drawImage(t,0,0,s,n);const o=e.map(t=>({x:t.x*s,y:t.y*n,z:t.z*s})),a=Math.min(...o.map(t=>t.x)),r=Math.max(...o.map(t=>t.x)),l=Math.min(...o.map(t=>t.y)),h=Math.max(...o.map(t=>t.y)),c=(Math.abs(a-r)-Math.abs(l-h))/4;let d=Math.max(0,a+c),u=Math.max(0,l-c),f=Math.min(s-1,r-c)-d,m=Math.min(n-1,h+c)-u;const p=Math.abs(o[362].x-o[133].x)/100,g=o[362].x-20*p,y=o[263].x+20*p-g,w=.75*y,k=g,v=(o[362].y+o[263].y)/2-.6*w,_=o[33].x-20*p,b=o[133].x+20*p-_,C=.75*b,F=[d,u,f,m],M=[k,v,y,w],S=[_,(o[33].y+o[133].y)/2-.6*C,b,C],P=t=>{let e=Math.max(0,Math.min(Math.round(t[0]),s-1)),i=Math.max(0,Math.min(Math.round(t[1]),n-1));return[e,i,Math.max(5,Math.min(Math.round(t[2]),s-e)),Math.max(5,Math.min(Math.round(t[3]),n-i))]},[T,x,A,I]=P(F),[z,E,j,L]=P(M),[G,N,O,D]=P(S),W=new Float32Array([A/s,I/n,T/s,x/n,j/s,L/n,z/s,E/n,O/s,D/n,G/s,N/n]),R=this.cropAndResize(T,x,A,I,224,224,!1),V=this.cropAndResize(z,E,j,L,112,112,!1),X=this.cropAndResize(G,N,O,D,112,112,!0),{leftOpenness:U,rightOpenness:$,leftIrisSize:Y,rightIrisSize:H}=this.computeEyeMetrics(o);return{faceTensor:R,leftTensor:V,rightTensor:X,rectTensor:W,landmarks:o,leftOpenness:U,rightOpenness:$,leftIrisSize:Y,rightIrisSize:H,rawRects:{face:[T,x,A,I],left:[z,E,j,L],right:[G,N,O,D]}}}cropAndResize(t,e,i,s,n,o,a){this.tmpCanvas.width!==n&&(this.tmpCanvas.width=n),this.tmpCanvas.height!==o&&(this.tmpCanvas.height=o),this.tmpCtx.save(),this.tmpCtx.clearRect(0,0,n,o),a&&(this.tmpCtx.translate(n,0),this.tmpCtx.scale(-1,1)),this.tmpCtx.drawImage(this.canvas,t,e,i,s,0,0,n,o),this.tmpCtx.restore();const r=this.tmpCtx.getImageData(0,0,n,o).data,l=new Float32Array(3*n*o),h=n*o;for(let t=0;t<h;t++)l[t]=r[4*t]/255,l[h+t]=r[4*t+1]/255,l[2*h+t]=r[4*t+2]/255;return l}}function isPrivateOrLocalHost(t){if(!t||"string"!=typeof t)return!1;const e=t.trim().toLowerCase();if("localhost"===e||"127.0.0.1"===e||"::1"===e||"[::1]"===e||"0.0.0.0"===e||e.endsWith(".local"))return!0;if(/^192\.168\.\d{1,3}\.\d{1,3}$/.test(e))return!0;if(/^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e))return!0;const i=/^172\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/.exec(e);if(i){const t=Number(i[1]);if(t>=16&&t<=31)return!0}return!1}class GazeVault{constructor(t={}){this.options=t||{},this.vaultModule=null,this.vaultInstance=null,this.keySlice=t.keySlice||t.key_slice||null,this.wasmModulePath=t.wasmModulePath||"./dist/gaze_vault.js",this.wasmBinaryPath=t.wasmBinaryPath||"./dist/gaze_vault.wasm",this.ticketEndpoint=t.ticketEndpoint||("undefined"!=typeof window&&window.location&&("gazefollower.com"===window.location.hostname||window.location.hostname.endsWith(".gazefollower.com")||isPrivateOrLocalHost(window.location.hostname))?`${window.location.origin}/commerce/v2/demo/ticket`:"https://gazefollower.com/commerce/v2/demo/ticket")}async fetchDemoTicket(){if("undefined"!=typeof window&&window.fetch)try{const t=await fetch(this.ticketEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_timestamp:Date.now(),sdk_version:"2.2.0"})});if(t.ok){const e=await t.json();if(e&&e.key_slice)return e.key_slice}else 403===t.status&&console.error("[GazeVault] Security Alert: Origin unauthorized by licensing server.")}catch(t){}const t="undefined"==typeof window,e="undefined"!=typeof window&&window.location&&isPrivateOrLocalHost(window.location.hostname);return(t||e&&!this.options.requireVault)&&!1!==this.options.allowLocalFallback?"1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f809":null}async init(){if(this.vaultInstance)return;if(this.keySlice||(this.keySlice=this.options.keySlice||this.options.key_slice||await this.fetchDemoTicket()),this.options.requireVault&&!this.keySlice)throw new Error("[GazeVault] Security Error: Missing server-issued decryption key slice.");let t;if("undefined"!=typeof window&&window.createGazeVaultModule)t=window.createGazeVaultModule;else try{const e=await(import(this.wasmModulePath));t=e.default||e.createGazeVaultModule||e}catch(e){try{const e="../dist/gaze_vault.js",i=await(import(e));t=i.default||i.createGazeVaultModule||i}catch(e){const i="./gaze_vault.js",s=await(import(i));t=s.default||s.createGazeVaultModule||s}}const e={};if("undefined"==typeof window){const t=await(import("node:fs")),i=(await(import("node:path"))).resolve(process.cwd(),"dist/gaze_vault.wasm");t.existsSync(i)&&(e.wasmBinary=t.readFileSync(i))}this.vaultModule=await t(e),this.vaultInstance=new this.vaultModule.GazeVault}decryptEmbedded(){if(!this.vaultInstance)throw new Error("GazeVault is not initialized. Call await vault.init() first.");const t=this.keySlice||"";if(!(this.vaultInstance.decryptEmbeddedWithSlice?this.vaultInstance.decryptEmbeddedWithSlice(t):this.vaultInstance.decryptEmbedded()))throw new Error("GazeVault failed to decrypt embedded model weights. Verify domain authorization.");return this.vaultInstance.getModelView()}decryptBuffer(t){if(!this.vaultInstance)throw new Error("GazeVault is not initialized. Call await vault.init() first.");const e=this.keySlice||"";if(!(this.vaultInstance.decryptBufferWithSlice?this.vaultInstance.decryptBufferWithSlice(t,e):this.vaultInstance.decryptBuffer(t)))throw new Error("GazeVault failed to decrypt model buffer. Verify domain authorization.");return this.vaultInstance.getModelView()}wipe(){this.vaultInstance&&this.vaultInstance.wipe()}release(){this.vaultInstance&&(this.vaultInstance.wipe(),this.vaultInstance.delete(),this.vaultInstance=null)}}function getInferenceWorkerSource(){return"\nlet session = null;\nlet activeProvider = null;\n\nasync function initWorker(cfg) {\n if (typeof importScripts === 'function' && cfg.ortScriptUrl) {\n importScripts(cfg.ortScriptUrl);\n }\n const ortInstance = self.ort;\n if (!ortInstance) {\n throw new Error(\"ONNX Runtime Web (ort) failed to load inside Worker.\");\n }\n if (ortInstance.env && ortInstance.env.wasm && cfg.wasmPaths) {\n ortInstance.env.wasm.wasmPaths = cfg.wasmPaths;\n }\n\n let modelData = null;\n if (cfg.keySlice && cfg.vaultModuleUrl) {\n const mod = await import(cfg.vaultModuleUrl);\n const createVault = mod.default || mod.createGazeVaultModule || mod;\n const vaultInstance = await createVault({\n locateFile: (p) => (p.endsWith('.wasm') && cfg.vaultBinaryUrl) ? cfg.vaultBinaryUrl : p\n });\n const ptr = vaultInstance._get_embedded_model_ptr();\n const size = vaultInstance._get_embedded_model_size();\n if (!ptr || size <= 0) {\n throw new Error(\"Embedded model missing in GazeVault.\");\n }\n const keyBytes = new TextEncoder().encode(cfg.keySlice);\n const kPtr = vaultInstance._malloc(keyBytes.length);\n vaultInstance.HEAPU8.set(keyBytes, kPtr);\n const ok = vaultInstance._decrypt_model(kPtr, keyBytes.length);\n vaultInstance._free(kPtr);\n if (!ok) {\n throw new Error(\"GazeVault decryption failed inside Worker.\");\n }\n modelData = new Uint8Array(vaultInstance.HEAPU8.subarray(ptr, ptr + size));\n try {\n if (typeof vaultInstance._wipe_model === 'function') vaultInstance._wipe_model();\n } catch (e) {}\n }\n\n if (!modelData) {\n throw new Error(\"Failed to obtain decrypted model weights in Worker.\");\n }\n\n let webgpuSupported = false;\n if (typeof navigator !== 'undefined' && navigator.gpu && typeof navigator.gpu.requestAdapter === 'function') {\n try {\n webgpuSupported = !!(await navigator.gpu.requestAdapter());\n } catch (e) {\n webgpuSupported = false;\n }\n }\n\n if (webgpuSupported) {\n try {\n session = await ortInstance.InferenceSession.create(modelData.slice(), {\n executionProviders: ['webgpu']\n });\n activeProvider = 'webgpu-worker';\n } catch (e) {\n session = null;\n }\n }\n\n if (!session) {\n const canThread = (typeof self !== 'undefined' && self.crossOriginIsolated === true);\n if (ortInstance.env && ortInstance.env.wasm) {\n ortInstance.env.wasm.numThreads = canThread ? 3 : 1;\n ortInstance.env.wasm.simd = true;\n if (!canThread) ortInstance.env.wasm.proxy = false;\n }\n session = await ortInstance.InferenceSession.create(modelData.slice(), {\n executionProviders: ['wasm'],\n graphOptimizationLevel: 'all',\n executionMode: 'sequential'\n });\n activeProvider = canThread ? 'wasm-cpu-3threads-worker' : 'wasm-cpu-1thread-worker';\n }\n\n modelData.fill(0);\n return { activeProvider };\n}\n\nself.onmessage = async (ev) => {\n const msg = ev.data || {};\n if (msg.type === 'init') {\n try {\n const res = await initWorker(msg.config || {});\n self.postMessage({ type: 'init_ok', id: msg.id, activeProvider: res.activeProvider });\n } catch (err) {\n self.postMessage({ type: 'init_err', id: msg.id, error: err ? (err.message || String(err)) : 'Worker init failed' });\n }\n return;\n }\n\n if (msg.type === 'detect') {\n if (!session) {\n self.postMessage({ type: 'detect_res', id: msg.id, output: null, gazeMs: 0 });\n return;\n }\n const t0 = performance.now();\n try {\n const ortInstance = self.ort;\n const feeds = {};\n if (session.inputNames.includes('face')) {\n feeds['face'] = new ortInstance.Tensor('float32', new Float32Array(msg.face), [1, 3, 224, 224]);\n }\n if (session.inputNames.includes('left')) {\n feeds['left'] = new ortInstance.Tensor('float32', new Float32Array(msg.left), [1, 3, 112, 112]);\n } else if (session.inputNames.includes('left_eye')) {\n feeds['left_eye'] = new ortInstance.Tensor('float32', new Float32Array(msg.left), [1, 3, 112, 112]);\n }\n if (session.inputNames.includes('right')) {\n feeds['right'] = new ortInstance.Tensor('float32', new Float32Array(msg.right), [1, 3, 112, 112]);\n } else if (session.inputNames.includes('right_eye')) {\n feeds['right_eye'] = new ortInstance.Tensor('float32', new Float32Array(msg.right), [1, 3, 112, 112]);\n }\n if (session.inputNames.includes('rect')) {\n feeds['rect'] = new ortInstance.Tensor('float32', new Float32Array(msg.rect), [1, 12]);\n }\n const results = await session.run(feeds);\n const outputName = session.outputNames[0];\n const outArr = new Float32Array(results[outputName].data);\n const gazeMs = performance.now() - t0;\n self.postMessage({ type: 'detect_res', id: msg.id, output: outArr.buffer, gazeMs }, [outArr.buffer]);\n } catch (err) {\n self.postMessage({ type: 'detect_res', id: msg.id, output: null, gazeMs: performance.now() - t0, error: err ? err.message : String(err) });\n }\n }\n};\n"}async function checkWebGPUSupport(){if("undefined"!=typeof navigator&&navigator.gpu&&"function"==typeof navigator.gpu.requestAdapter)try{return!!await navigator.gpu.requestAdapter()}catch(t){return!1}return!1}class GazeEstimator{constructor(t={}){this.options=t||{},this.session=null,this.vault=null,this.modelName="base",this.modelFile="GazeNet_Next_epoch_5.onnx",this.activeExecutionProvider=null,this.worker=null,this.workerUrl=null,this.workerReady=!1,this._workerSeq=0,this._workerPending=new Map}terminate(){if(this.worker){try{this.worker.terminate()}catch(t){}this.worker=null}if(this.workerUrl&&"undefined"!=typeof URL){try{URL.revokeObjectURL(this.workerUrl)}catch(t){}this.workerUrl=null}this.workerReady=!1;for(const[,t]of this._workerPending)t.resolve(null);this._workerPending.clear()}async _initWorker(t=null){if("undefined"==typeof window||"undefined"==typeof Worker||"undefined"==typeof Blob||"undefined"==typeof URL||!1===this.options.useWorker)return!1;try{const e=new GazeVault(this.options);let i=this.options.keySlice||this.options.key_slice||null;if(i||(i=await e.fetchDemoTicket()),!i)return!1;t&&t(.25);const s=window.location.href,n=this.options.wasmPaths||"./dist/",o=new URL(n.endsWith("/")?n:`${n}/`,s).href,a=new URL(this.options.ortScriptUrl||`${o}ort.min.js`,s).href,r=new URL(this.options.wasmModulePath||`${o}gaze_vault.js`,s).href,l=new URL(this.options.wasmBinaryPath||`${o}gaze_vault.wasm`,s).href,h=new Blob([getInferenceWorkerSource()],{type:"application/javascript"});this.workerUrl=URL.createObjectURL(h),this.worker=new Worker(this.workerUrl);const c=await new Promise((t,e)=>{const s=setTimeout(()=>e(new Error("Inference Worker init timeout")),12e3);this.worker.onmessage=i=>{const n=i.data||{};if("init_ok"===n.type)clearTimeout(s),t(n);else if("init_err"===n.type)clearTimeout(s),e(new Error(n.error||"Worker init error"));else if("detect_res"===n.type){const t=this._workerPending.get(n.id);t&&(this._workerPending.delete(n.id),t.resolve(n.output?Array.from(new Float32Array(n.output)):null))}},this.worker.onerror=t=>{clearTimeout(s),e(new Error(t?.message||"Worker runtime error"))},this.worker.postMessage({type:"init",id:0,config:{keySlice:i,ortScriptUrl:a,wasmPaths:o,vaultModuleUrl:r,vaultBinaryUrl:l}})});return this.workerReady=!0,this.activeExecutionProvider=c.activeProvider||"wasm-worker",console.log(`[GazeEstimator] Inference Worker initialized on ${this.activeExecutionProvider}!`),t&&t(1),!0}catch(t){return console.warn("[GazeEstimator] Worker initialization failed, falling back to main thread:",t.message||t),this.terminate(),!1}}async init(t=null){if(t&&t(.1),await this._initWorker(t))return;let e=null;try{console.log("[GazeEstimator] Initializing Wasm GazeVault for secure model decryption..."),this.vault=new GazeVault(this.options),await this.vault.init(),t&&t(.3),console.log("[GazeEstimator] Decrypting embedded neural model directly in Wasm memory..."),e=this.vault.decryptEmbedded()}catch(t){console.warn("[GazeEstimator] GazeVault in-memory decryption skipped/failed:",t.message)}if(!e&&!this.options.requireVault){const t=`models/${this.modelFile}`;if("undefined"==typeof window){const i=await(import("node:fs")),s=(await(import("node:path"))).resolve(process.cwd(),t);i.existsSync(s)&&(e=i.readFileSync(s))}else if(window.fetch)try{const i=await fetch(t);i.ok&&(e=new Uint8Array(await i.arrayBuffer()))}catch(e){console.warn(`[GazeEstimator] Direct fetch of ${t} failed:`,e)}}if(!e)throw new Error(`[GazeEstimator] Failed to load model weights for ${this.modelFile}.`);t&&t(.6);let i="undefined"!=typeof ort?ort:null;if(i||"undefined"!=typeof window||(i=(await(import("onnxruntime-web"))).default||await(import("onnxruntime-web"))),!i)throw new Error("ONNX Runtime Web (ort) is not available.");const s=await checkWebGPUSupport();console.log(`[GazeEstimator] Browser WebGPU support: ${s}`);let n=!1;if(s)try{console.log("[GazeEstimator] Attempting ONNX InferenceSession creation with WebGPU provider...");const t=e instanceof Uint8Array?e.slice():e;this.session=await i.InferenceSession.create(t,{executionProviders:["webgpu"]}),this.activeExecutionProvider="webgpu",n=!0,console.log("[GazeEstimator] InferenceSession successfully created on WebGPU hardware accelerator!")}catch(t){console.warn("[GazeEstimator] WebGPU initialization failed, falling back to 3-thread CPU engine:",t)}if(!n){const t="undefined"!=typeof globalThis&&!0===globalThis.crossOriginIsolated,s=t?3:1;console.log(`[GazeEstimator] Initializing WASM CPU inference engine (threads=${s}, crossOriginIsolated=${t})...`),i.env&&i.env.wasm&&(i.env.wasm.numThreads=s,i.env.wasm.simd=!0,t||(i.env.wasm.proxy=!1));const n=e instanceof Uint8Array?e.slice():e;this.session=await i.InferenceSession.create(n,{executionProviders:["wasm"],graphOptimizationLevel:"all",executionMode:"sequential"}),this.activeExecutionProvider=t?"wasm-cpu-3threads":"wasm-cpu-1thread",console.log(`[GazeEstimator] InferenceSession successfully created on ${this.activeExecutionProvider}!`)}this.vault&&this.vault.wipe(),t&&t(1)}async detect(t,e,i,s){if(this.workerReady&&this.worker){const n=++this._workerSeq;return await new Promise(o=>{this._workerPending.set(n,{resolve:o});const a=t instanceof Float32Array?t:new Float32Array(t),r=e instanceof Float32Array?e:new Float32Array(e),l=i instanceof Float32Array?i:new Float32Array(i),h=s instanceof Float32Array?s:new Float32Array(s);this.worker.postMessage({type:"detect",id:n,face:a.buffer,left:r.buffer,right:l.buffer,rect:h.buffer},[a.buffer,r.buffer,l.buffer,h.buffer])})}if(!this.session)return null;let n="undefined"!=typeof ort?ort:null;n||"undefined"!=typeof window||(n=(await(import("onnxruntime-web"))).default||await(import("onnxruntime-web")));const o={};this.session.inputNames.includes("face")&&(o.face=new n.Tensor("float32",t,[1,3,224,224])),this.session.inputNames.includes("left")?o.left=new n.Tensor("float32",e,[1,3,112,112]):this.session.inputNames.includes("left_eye")&&(o.left_eye=new n.Tensor("float32",e,[1,3,112,112])),this.session.inputNames.includes("right")?o.right=new n.Tensor("float32",i,[1,3,112,112]):this.session.inputNames.includes("right_eye")&&(o.right_eye=new n.Tensor("float32",i,[1,3,112,112])),this.session.inputNames.includes("rect")&&(o.rect=new n.Tensor("float32",s,[1,12]));try{const t=(await this.session.run(o))[this.session.outputNames[0]].data;return Array.from(t)}catch(t){return console.error("ONNX Inference Error:",t),null}}}class MultivariateRidgeCalibration{constructor(t=30){this.lambda="number"==typeof t&&Number.isFinite(t)&&t>0?t:30,this.weights=[]}get calibrationPenalty(){return this.lambda}set calibrationPenalty(t){const e=parseFloat(t);Number.isFinite(e)&&e>0&&(this.lambda=e)}get alpha(){return this.lambda}set alpha(t){const e=parseFloat(t);Number.isFinite(e)&&e>0&&(this.lambda=e)}train(t,e,i){const s=t.length;if(0===s)return;const n=Array.from({length:s},(t,s)=>[e[s],i[s]]),o=t.map(t=>[1,...t]),a=o[0].length,r=Array.from({length:a},(t,e)=>o.map(t=>t[e]));let l=Array.from({length:a},()=>new Float64Array(a).fill(0));for(let t=0;t<a;t++){for(let e=0;e<a;e++)for(let i=0;i<s;i++)l[t][e]+=r[t][i]*o[i][e];t>0&&(l[t][t]+=this.lambda)}let h=Array.from({length:a},()=>new Float64Array(2).fill(0));for(let t=0;t<a;t++)for(let e=0;e<s;e++)h[t][0]+=r[t][e]*n[e][0],h[t][1]+=r[t][e]*n[e][1];this.weights=this._solve(l,h)}predict(t){if(!this.weights||0===this.weights.length)return[0,0];const e=[1,...t];let i=0,s=0;for(let t=0;t<e.length;t++)i+=e[t]*this.weights[t][0],s+=e[t]*this.weights[t][1];return[i,s]}_solve(t,e){const i=t.length,s=e[0].length;for(let n=0;n<i;n++){let o=Math.abs(t[n][n]),a=n;for(let e=n+1;e<i;e++)Math.abs(t[e][n])>o&&(o=Math.abs(t[e][n]),a=e);let r=t[a];t[a]=t[n],t[n]=r;let l=e[a];if(e[a]=e[n],e[n]=l,0!==t[n][n])for(let o=n+1;o<i;o++){let a=-t[o][n]/t[n][n];for(let e=n;e<i;e++)n===e?t[o][e]=0:t[o][e]+=a*t[n][e];for(let t=0;t<s;t++)e[o][t]+=a*e[n][t]}}let n=Array.from({length:i},()=>new Float64Array(s).fill(0));for(let o=i-1;o>=0;o--)if(0!==t[o][o])for(let i=0;i<s;i++){n[o][i]=e[o][i]/t[o][o];for(let s=o-1;s>=0;s--)e[s][i]-=t[s][o]*n[o][i]}return n}}class ParticleFX{constructor(){this.canvas=null,this.ctx=null,this.particles=[],this.rings=[],this.animId=null,this.initCanvas()}initCanvas(){"undefined"!=typeof document&&(this.canvas=document.getElementById("gf-fx-canvas"),this.canvas||(this.canvas=document.createElement("canvas"),this.canvas.id="gf-fx-canvas",Object.assign(this.canvas.style,{position:"fixed",top:"0",left:"0",width:"100vw",height:"100vh",pointerEvents:"none",zIndex:"9999999"}),document.body.appendChild(this.canvas)),this.ctx=this.canvas.getContext("2d"),this.resize(),window.addEventListener("resize",()=>this.resize()))}resize(){if(!this.canvas)return;const t=window.devicePixelRatio||1;this.canvas.width=window.innerWidth*t,this.canvas.height=window.innerHeight*t,this.ctx&&(this.ctx.setTransform(1,0,0,1,0,0),this.ctx.scale(t,t))}burst(t,e,i={}){this.canvas&&this.ctx||this.initCanvas();const s=i.count||18,n=i.color||"#165dff";i.colors,this.rings.push({x:t,y:e,radius:i.initialRadius||8,maxRadius:i.ringMax||54,width:3,color:n,alpha:.85,growth:3.2}),this.rings.push({x:t,y:e,radius:.5*(i.initialRadius||8),maxRadius:.75*(i.ringMax||54),width:1.8,color:"#4080ff",alpha:.6,growth:2.2});for(let i=0;i<s;i++){const o=2*Math.PI/s*i+.5*(Math.random()-.5),a=3+6*Math.random(),r=2.5+3*Math.random(),l=Math.random()>.4?n:Math.random()>.5?"#4080ff":"#ffffff";this.particles.push({x:t,y:e,vx:Math.cos(o)*a,vy:Math.sin(o)*a,drag:.92+.03*Math.random(),gravity:.15+.08*Math.random(),size:r,initialSize:r,color:l,alpha:.95,decay:.022+.015*Math.random(),rotation:0,rotSpeed:0,shape:"circle"})}this.animId||this.loop()}loop(){if(this.ctx){this.ctx.clearRect(0,0,window.innerWidth,window.innerHeight);for(let t=this.rings.length-1;t>=0;t--){const e=this.rings[t];e.radius+=e.growth,e.alpha-=.045,e.width*=.94,e.alpha<=0||e.radius>=e.maxRadius?this.rings.splice(t,1):(this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(e.x,e.y,e.radius,0,2*Math.PI),this.ctx.strokeStyle=e.color,this.ctx.globalAlpha=Math.max(0,e.alpha),this.ctx.lineWidth=Math.max(.5,e.width),this.ctx.shadowBlur=12,this.ctx.shadowColor=e.color,this.ctx.stroke(),this.ctx.restore())}for(let t=this.particles.length-1;t>=0;t--){const e=this.particles[t];if(e.x+=e.vx,e.y+=e.vy,e.vx*=e.drag,e.vy*=e.drag,e.vy+=e.gravity,e.alpha-=e.decay,e.size=Math.max(0,e.initialSize*e.alpha),e.rotation+=e.rotSpeed,e.alpha<=0||e.size<=.3)this.particles.splice(t,1);else{if(this.ctx.save(),this.ctx.translate(e.x,e.y),this.ctx.rotate(e.rotation),this.ctx.globalAlpha=Math.max(0,e.alpha),this.ctx.fillStyle=e.color,this.ctx.shadowBlur=8,this.ctx.shadowColor=e.color,"circle"===e.shape)this.ctx.beginPath(),this.ctx.arc(0,0,e.size,0,2*Math.PI),this.ctx.fill();else if("spark"===e.shape)this.ctx.beginPath(),this.ctx.moveTo(0,1.5*-e.size),this.ctx.lineTo(.6*e.size,0),this.ctx.lineTo(0,1.5*e.size),this.ctx.lineTo(.6*-e.size,0),this.ctx.closePath(),this.ctx.fill();else if("star"===e.shape){this.ctx.beginPath();const t=1.4*e.size,i=.45*e.size;for(let e=0;e<8;e++){const s=e%2==0?t:i,n=e*Math.PI/4,o=Math.cos(n)*s,a=Math.sin(n)*s;0===e?this.ctx.moveTo(o,a):this.ctx.lineTo(o,a)}this.ctx.closePath(),this.ctx.fill()}this.ctx.restore()}}this.particles.length>0||this.rings.length>0?this.animId=requestAnimationFrame(()=>this.loop()):(this.ctx.clearRect(0,0,window.innerWidth,window.innerHeight),this.animId=null)}}}const particleFX=new ParticleFX;function normalizeTrackingArea(t){const e="undefined"!=typeof window?window.innerWidth:1920,i="undefined"!=typeof window?window.innerHeight:1080;if(!t)return{x:0,y:0,width:e,height:i};if(Array.isArray(t)&&t.length>=4)return{x:Math.max(0,t[0]),y:Math.max(0,t[1]),width:Math.max(50,t[2]),height:Math.max(50,t[3])};if("object"==typeof t){const s=void 0!==t.x?t.x:void 0!==t.left?t.left:0,n=void 0!==t.y?t.y:void 0!==t.top?t.top:0;let o=void 0!==t.width?t.width:void 0!==t.right?t.right-s:e,a=void 0!==t.height?t.height:void 0!==t.bottom?t.bottom-n:i;return{x:Math.max(0,s),y:Math.max(0,n),width:Math.max(50,o),height:Math.max(50,a)}}return{x:0,y:0,width:e,height:i}}function generateNPoints(t,e){const i=e.x,s=e.y,n=e.width,o=e.height;if(t<=1)return[[i+.5*n,s+.5*o]];if(2===t)return[[i+.25*n,s+.5*o],[i+.75*n,s+.5*o]];if(3===t)return[[i+.2*n,s+.5*o],[i+.5*n,s+.5*o],[i+.8*n,s+.5*o]];if(4===t)return[[i+.2*n,s+.2*o],[i+.8*n,s+.2*o],[i+.2*n,s+.8*o],[i+.8*n,s+.8*o]];const a=.1*n,r=.1*o,l=n-2*a,h=o-2*r;let c=Math.max(1,Math.round(Math.sqrt(t*(n/o)))),d=Math.ceil(t/c);for(;c*d<t;)c++;const u=[],f=c>1?l/(c-1):0,m=d>1?h/(d-1):0;for(let e=0;e<d;e++)for(let n=0;n<c;n++)u.length<t&&u.push([i+a+(c>1?n*f:.5*l),s+r+(d>1?e*m:.5*h)]);return u}"undefined"!=typeof window&&(window.particleFX=particleFX);class CalibrationManager{constructor(t){this.gf=t,this.mode="13-point",this.method="click",this.order="random",this.frameLatency=2,this.latencyOffsetMs=78,this.setLatency(78),this._trackingArea=null,this.isActive=!1,this.points=[],this.currentIndex=0,this.autoPrepareMs=1500,this.autoWaitMs=500,this.nFramesNeedCollect=45,this.nFramesAdded=0,this.pointOnsetTimestamp=0,this.featureFullTime=0,this.isWaitingWaitTime=!1,this.preClickMs=200,this.clickSampleCount=24,this.postClickDelay=100,this.clickWatchdogMs=2500,this.isWaitingPostClick=!1,this.clickCollecting=!1,this.clickCollectedCount=0,this.clickTargetX=0,this.clickTargetY=0,this.clickTimeoutId=null,this.clickTransitionTimeoutId=null,this.lissajousSpeed=250,this.lissajousDuration=25e3,this.lissajousPrepareMs=1500,this.lissajousT=0,this.lissajousStartTime=0,this._lissajousMoveStartTime=0,this._lissajousAnim=null,this._lissajousAreaKey="",this._lissajousLut=null,this.featureQueue=[],this._rafId=null,this._lastProgress=-1,this.currentScale=1,this.currentX=0,this.currentY=0,this.customRender=!1,this.onPointCallback=null,this.onProgressCallback=null,this.onFinishCallback=null,this.instructionEl=null,"undefined"!=typeof document&&this.initDOM()}setTrackingArea(t){return this._trackingArea=normalizeTrackingArea(t),this}getTrackingArea(){return this._trackingArea||(this._trackingArea=normalizeTrackingArea(this.gf?this.gf._trackingArea:null)),this._trackingArea}get tracking_area(){return this.getTrackingArea()}set tracking_area(t){this.setTrackingArea(t)}get trackingArea(){return this.getTrackingArea()}set trackingArea(t){this.setTrackingArea(t)}setLatency(t){"number"==typeof t&&(t<=20?(this.frameLatency=t,this.latencyOffsetMs=Math.round(t*(1e3/30))):(this.latencyOffsetMs=t,this.frameLatency=Math.round(t/(1e3/30))))}setClickSampleCount(t=24){const e=parseInt(t,10);return Number.isFinite(e)&&e>0&&(this.clickSampleCount=e),this}getClickSampleCount(){return this.clickSampleCount}setSamplesPerPoint(t=24){return this.setClickSampleCount(t)}getSamplesPerPoint(){return this.getClickSampleCount()}setPreClickMs(t=200){const e=parseInt(t,10);return Number.isFinite(e)&&e>=0&&(this.preClickMs=e),this}getPreClickMs(){return this.preClickMs}setPostClickDelay(t=100){const e=parseInt(t,10);return Number.isFinite(e)&&e>=0&&(this.postClickDelay=e),this}getPostClickDelay(){return this.postClickDelay}computeLissajousLength(t=null,e=null,i=3,s=2){const n=this.getTrackingArea(),o="number"==typeof t&&t>0?t:n.width,a="number"==typeof e&&e>0?e:n.height,r=2*Math.PI/1e3;let l=0;const h=.4*o,c=.4*a;for(let t=0;t<1e3;t++){const e=t*r,n=h*i*Math.cos(i*e),o=c*s*Math.cos(s*e);l+=Math.hypot(n,o)*r}return l}setLissajousSpeed(t=250){const e=parseFloat(t);if(Number.isFinite(e)&&e>0){this.lissajousSpeed=e;const t=this.computeLissajousLength();this.lissajousDuration=Math.round(t/e*1e3)}return this.lissajousDuration}getLissajousSpeed(){return this.lissajousSpeed}setLissajousDuration(t=25e3){const e=parseFloat(t);if(Number.isFinite(e)&&e>0){this.lissajousDuration=e;const t=this.computeLissajousLength();this.lissajousSpeed=Math.round(t/(e/1e3))}return this.lissajousSpeed}initDOM(){this.container=document.createElement("div"),this.container.id="gf-calibration-container",Object.assign(this.container.style,{position:"fixed",top:"0",left:"0",width:"100vw",height:"100vh",zIndex:"999999",pointerEvents:"none",display:"none",background:"#f4f6f9"}),this.dot=document.createElement("div"),Object.assign(this.dot.style,{position:"absolute",top:"0",left:"0",width:"50px",height:"50px",background:"#00B050",borderRadius:"50%",willChange:"transform",backfaceVisibility:"hidden",transform:"translate3d(-100px, -100px, 0) scale(1)",cursor:"pointer",pointerEvents:"auto",boxShadow:"0 3px 14px rgba(0, 176, 80, 0.45)",transition:"none",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none"}),this.dotCrossSvg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.dotCrossSvg.setAttribute("viewBox","0 0 50 50"),this.dotCrossSvg.setAttribute("width","50"),this.dotCrossSvg.setAttribute("height","50"),Object.assign(this.dotCrossSvg.style,{position:"absolute",top:"0",left:"0",width:"50px",height:"50px",pointerEvents:"none",display:"block"}),this.dotCrossSvg.innerHTML='\n <line x1="16" y1="25" x2="34" y2="25" stroke="#ffffff" stroke-width="2.5" stroke-linecap="round" />\n <line x1="25" y1="16" x2="25" y2="34" stroke="#ffffff" stroke-width="2.5" stroke-linecap="round" />\n <circle cx="25" cy="25" r="1.5" fill="#ffffff" />\n ',this.dot.appendChild(this.dotCrossSvg),this.dotLabel=document.createElement("span"),Object.assign(this.dotLabel.style,{position:"absolute",top:"0",left:"0",width:"50px",height:"50px",display:"none",alignItems:"center",justifyContent:"center",color:"#ffffff",fontSize:"17px",fontWeight:"700",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",fontVariantNumeric:"tabular-nums",userSelect:"none",pointerEvents:"none",lineHeight:"1",textAlign:"center"}),this.dot.appendChild(this.dotLabel),this.dot.addEventListener("mouseenter",()=>{this.isWaitingPostClick||"lissajous"===this.mode||this.updateTransform(1.1)}),this.dot.addEventListener("mouseleave",()=>{this.isWaitingPostClick||"lissajous"===this.mode||this.updateTransform(1)}),this.dot.addEventListener("click",()=>{this.isActive&&"click"===this.method&&"lissajous"!==this.mode&&this.triggerClick(this.currentX,this.currentY)}),this.container.appendChild(this.dot),this.instructionEl=document.createElement("div"),this.instructionEl.id="gf-calibration-instruction",Object.assign(this.instructionEl.style,{position:"fixed",top:"16px",left:"50%",transform:"translateX(-50%)",padding:"7px 18px",borderRadius:"9999px",background:"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(203, 213, 225, 0.9)",boxShadow:"0 4px 14px rgba(15, 23, 42, 0.08)",color:"#1e293b",fontSize:"14px",fontWeight:"600",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Microsoft YaHei', sans-serif",letterSpacing:"0.01em",lineHeight:"1.35",whiteSpace:"nowrap",pointerEvents:"none",userSelect:"none",zIndex:"1"}),this.container.appendChild(this.instructionEl),document.body.appendChild(this.container)}_resolveInstructionText(t,e,i={}){if("string"==typeof i.instruction)return i.instruction;const s=i.lang||i.language||"undefined"!=typeof document&&document.documentElement&&document.documentElement.lang||"undefined"!=typeof navigator&&(navigator.language||navigator.languages&&navigator.languages[0])||"en",n=String(s).toLowerCase().startsWith("zh");return"lissajous"===t||"smooth_pursuit"===t||"smooth-pursuit"===t||"smoothPursuit"===t||"click"!==e?n?"请注视目标点":"Please fix on the target":n?"请注视并点击目标点":"Please fix on and click the target"}triggerClick(t=null,e=null){if(!this.isActive||"lissajous"===this.mode)return;if(this.isWaitingPostClick||this.clickCollecting)return;this.isWaitingPostClick=!0,this.clickCollecting=!0,this.clickCollectedCount=0;const i=null!=t?t:this.currentX,s=null!=e?e:this.currentY;this.clickTargetX=i,this.clickTargetY=s;const n=performance.now();!this.customRender&&this.dot&&(this.dot.style.transition="transform 0.15s cubic-bezier(0.2, 0.8, 0.2, 1), opacity 0.15s ease",this.updateTransform(.92),this.dot.style.opacity="0.9",this.showProgress(0),this._lastProgress=0);const o=n-this.preClickMs,a=this.featureQueue.filter(t=>t.timestamp>=o&&t.timestamp<=n);if(a.length>0)for(const t of a)this.clickCollectedCount<this.clickSampleCount&&(this.gf.addCalibrationPoint(t.features,i,s),this.clickCollectedCount++);else if(0===this.featureQueue.length&&(!this.gf||!this.gf.videoElement)&&this.gf&&this.gf.lastFeatures)return this.gf.addCalibrationPoint(this.gf.lastFeatures,i,s),this.clickCollectedCount++,void this._finishClickCollection();if(this.onProgressCallback)try{this.onProgressCallback({progress:Math.min(1,this.clickCollectedCount/this.clickSampleCount),x:i,y:s,index:this.currentIndex,total:this.points?this.points.length:1,collected:this.clickCollectedCount,target:this.clickSampleCount})}catch(t){console.error("[CalibrationManager] Error in onProgress callback during click:",t)}this.clickCollectedCount>=this.clickSampleCount?this._finishClickCollection():(this.clickTimeoutId&&clearTimeout(this.clickTimeoutId),this.clickTimeoutId=setTimeout(()=>{this.clickCollecting&&this._finishClickCollection()},this.clickWatchdogMs))}_finishClickCollection(){(this.clickCollecting||this.isWaitingPostClick)&&(this.clickCollecting=!1,this.clickTimeoutId&&(clearTimeout(this.clickTimeoutId),this.clickTimeoutId=null),0===this.clickCollectedCount&&this.gf&&this.gf.lastFeatures&&(this.gf.addCalibrationPoint(this.gf.lastFeatures,this.clickTargetX,this.clickTargetY),this.clickCollectedCount++),this.showProgress(99),this._lastProgress=99,!this.customRender&&this.dot&&(this.updateTransform(1),this.dot.style.opacity="1.0",particleFX.burst(this.clickTargetX,this.clickTargetY,{color:"#00B050",count:20})),this.clickTransitionTimeoutId&&clearTimeout(this.clickTransitionTimeoutId),this.clickTransitionTimeoutId=setTimeout(()=>{this.isWaitingPostClick=!1,this.nextPoint()},this.postClickDelay))}updateTransform(t=this.currentScale){this.currentScale=t,this.dot.style.transform=`translate3d(${this.currentX-25}px, ${this.currentY-25}px, 0) scale(${t})`}updateDotPos(t,e){if(this.currentX=t,this.currentY=e,this.dot&&!this.customRender&&(this.dot.style.transform=`translate3d(${t-25}px, ${e-25}px, 0) scale(${this.currentScale})`),this.onPointCallback)try{this.onPointCallback({x:t,y:e,index:this.currentIndex,total:this.points?this.points.length:"lissajous"===this.mode?1:0,mode:this.mode,method:this.method})}catch(t){console.error("[CalibrationManager] Error in onPoint callback:",t)}}showCrosshair(){this.customRender||(this.dotCrossSvg&&(this.dotCrossSvg.style.display="block"),this.dotLabel&&(this.dotLabel.style.display="none"))}showProgress(t){if(this.customRender||(this.dotCrossSvg&&(this.dotCrossSvg.style.display="none"),this.dotLabel&&(this.dotLabel.style.display="flex",this.dotLabel.textContent=t.toString())),this.onProgressCallback)try{this.onProgressCallback({progress:t,x:this.currentX,y:this.currentY,index:this.currentIndex,total:this.points?this.points.length:1})}catch(t){console.error("[CalibrationManager] Error in onProgress callback:",t)}}start(t="13-point",e="click",i=null,s="random",n={}){null!=i&&this.setLatency(i);let o={};t&&"object"==typeof t&&!Array.isArray(t)?(o=t,t=o.mode||"13-point",e=o.method||"click",void 0!==o.latency&&this.setLatency(o.latency),s=o.order||"random"):n&&"object"==typeof n&&(o=n),this.customRender=!1===o.render||!0===o.headless||!0===o.customUI,this.onPointCallback="function"==typeof o.onPoint?o.onPoint:null,this.onProgressCallback="function"==typeof o.onProgress?o.onProgress:null,this.onFinishCallback="function"==typeof o.onFinish?o.onFinish:null,void 0!==o.clickSampleCount?this.setClickSampleCount(o.clickSampleCount):void 0!==o.samplesPerPoint?this.setClickSampleCount(o.samplesPerPoint):void 0!==o.sampleCount&&this.setClickSampleCount(o.sampleCount),void 0!==o.preClickMs?this.setPreClickMs(o.preClickMs):void 0!==o.preClickBufferMs&&this.setPreClickMs(o.preClickBufferMs),void 0!==o.postClickDelay?this.setPostClickDelay(o.postClickDelay):void 0!==o.clickTransitionDelay?this.setPostClickDelay(o.clickTransitionDelay):void 0!==o.clickWaitMs&&this.setPostClickDelay(o.clickWaitMs),void 0!==o.clickWatchdogMs&&(this.clickWatchdogMs=o.clickWatchdogMs),(o.tracking_area||o.trackingArea)&&this.setTrackingArea(o.tracking_area||o.trackingArea);let a=t;"smooth_pursuit"!==t&&"smooth-pursuit"!==t&&"smoothPursuit"!==t||(a="lissajous"),this.mode=a,this.method=e,this.order=s,this.isActive=!0,this.instructionEl&&(this.instructionEl.textContent=this._resolveInstructionText(a,e,o),this.instructionEl.style.display=!0===o.showInstruction?"block":"none"),this.container&&(this.container.style.display=this.customRender?"none":"block"),this.gf.isCalibrated=!1,this.gf.clearData();const r=this.getTrackingArea(),l=r.x,h=r.y,c=r.width,d=r.height;let u=[];if(Array.isArray(t))u=t.map(t=>Array.isArray(t)?[t[0],t[1]]:[t.x,t.y]);else if(o.points&&Array.isArray(o.points))u=o.points.map(t=>Array.isArray(t)?[t[0],t[1]]:[t.x,t.y]);else if("5-point"===a||5===a||"5"===a)u=[[.15,.15],[.85,.15],[.5,.5],[.15,.85],[.85,.85]].map(([t,e])=>[l+t*c,h+e*d]);else if("9-point"===a||9===a||"9"===a)u=[[.15,.15],[.5,.15],[.85,.15],[.15,.5],[.5,.5],[.85,.5],[.15,.85],[.5,.85],[.85,.85]].map(([t,e])=>[l+t*c,h+e*d]);else if("13-point"===a||13===a||"13"===a)u=[[.12,.12],[.5,.12],[.88,.12],[.28,.28],[.72,.28],[.12,.5],[.5,.5],[.88,.5],[.28,.72],[.72,.72],[.12,.88],[.5,.88],[.88,.88]].map(([t,e])=>[l+t*c,h+e*d]);else if("20-point"===a||20===a||"20"===a){const t=4,e=5,i=.1*c,s=.12*d,n=(c-2*i)/(e-1),o=(d-2*s)/(t-1);for(let a=0;a<t;a++)for(let t=0;t<e;t++)u.push([l+i+t*n,h+s+a*o])}else if("28-point"===a||28===a||"28"===a){const t=4,e=7,i=.08*c,s=.12*d,n=(c-2*i)/(e-1),o=(d-2*s)/(t-1);for(let a=0;a<t;a++)for(let t=0;t<e;t++)u.push([l+i+t*n,h+s+a*o])}else if("random"===a){const t=13,e=.12*c,i=.12*d;for(let s=0;s<t;s++)u.push([l+e+Math.random()*(c-2*e),h+i+Math.random()*(d-2*i)])}else u="lissajous"===a?[]:"number"==typeof a||!isNaN(parseInt(a,10))&&Number.isFinite(parseInt(a,10))?generateNPoints(Math.max(1,parseInt(a,10)),r):[[.12,.12],[.5,.12],[.88,.12],[.28,.28],[.72,.28],[.12,.5],[.5,.5],[.88,.5],[.28,.72],[.72,.72],[.12,.88],[.5,.88],[.88,.88]].map(([t,e])=>[l+t*c,h+e*d]);if("random"===this.order&&"lissajous"!==a&&"random"!==a){this.points=[...u];for(let t=this.points.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[this.points[t],this.points[e]]=[this.points[e],this.points[t]]}}else this.points=u;if(this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=null),this.currentIndex=0,this.nFramesAdded=0,this.isWaitingWaitTime=!1,this.featureFullTime=0,this.isWaitingPostClick=!1,this.clickCollecting=!1,this.clickCollectedCount=0,this.clickTimeoutId&&(clearTimeout(this.clickTimeoutId),this.clickTimeoutId=null),this.clickTransitionTimeoutId&&(clearTimeout(this.clickTransitionTimeoutId),this.clickTransitionTimeoutId=null),this._cancelLissajousAnim(),this.lissajousT=0,this.lissajousStartTime=0,this._lissajousMoveStartTime=0,this._lissajousAreaKey="",this.pointOnsetTimestamp=performance.now(),this.featureQueue=[],this._lastProgress=-1,this.currentScale=1,this.showCrosshair(),"lissajous"===this.mode){this.dot&&!this.customRender&&(this.dot.style.transition="none",this.dot.style.pointerEvents="none"),this.setLissajousSpeed(this.lissajousSpeed||250);const t=l+c/2,e=h+d/2;this.updateDotPos(t,e),this.showCrosshair()}else this.points.length>0&&(this.dot&&!this.customRender&&(this.dot.style.pointerEvents="auto",this.dot.style.transition="none"),this.updateDotPos(this.points[0][0],this.points[0][1]));"auto"!==this.method&&"lissajous"!==this.mode||this.autoLoop()}recordCurrentPoint(t=null){let e=t||this.gf.lastFeatures;e&&this.gf.addCalibrationPoint(e,this.currentX,this.currentY)}nextPoint(){this.currentIndex++,this.currentIndex>=this.points.length?this.finish():(this.dot&&!this.customRender&&(this.dot.style.transition="none"),this.updateDotPos(this.points[this.currentIndex][0],this.points[this.currentIndex][1]),this.pointOnsetTimestamp=performance.now(),this.nFramesAdded=0,this.isWaitingWaitTime=!1,this.featureFullTime=0,this.isWaitingPostClick=!1,this.clickCollecting=!1,this.clickCollectedCount=0,this.clickTimeoutId&&(clearTimeout(this.clickTimeoutId),this.clickTimeoutId=null),this.clickTransitionTimeoutId&&(clearTimeout(this.clickTransitionTimeoutId),this.clickTransitionTimeoutId=null),this._lastProgress=-1,this.showCrosshair())}feedFeatures(t,e){if(this.isActive)if(this.featureQueue.push({timestamp:e,features:t}),this.featureQueue.length>100&&this.featureQueue.shift(),"lissajous"===this.mode){if(this.lissajousStartTime){const i=this._lissajousMoveStartTime||this.lissajousStartTime+this.lissajousPrepareMs;if(e>=i){const s=e-this.latencyOffsetMs-i;if(s>0&&s<=this.lissajousDuration){const e=this.getLissajousPos(s);this.gf.addCalibrationPoint(t,e.x,e.y)}}}}else if("click"===this.method){if(this.clickCollecting){this.gf.addCalibrationPoint(t,this.clickTargetX,this.clickTargetY),this.clickCollectedCount++;const e=Math.min(99,Math.max(0,Math.floor(this.clickCollectedCount/this.clickSampleCount*100)));if(this._lastProgress!==e&&(this.showProgress(e),this._lastProgress=e),this.onProgressCallback)try{this.onProgressCallback({progress:Math.min(1,this.clickCollectedCount/this.clickSampleCount),x:this.clickTargetX,y:this.clickTargetY,index:this.currentIndex,total:this.points?this.points.length:1,collected:this.clickCollectedCount,target:this.clickSampleCount})}catch(t){console.error("[CalibrationManager] Error in onProgress callback during feedFeatures:",t)}this.clickCollectedCount>=this.clickSampleCount&&this._finishClickCollection()}}else if("auto"===this.method){if(this.isWaitingWaitTime)return;if(performance.now()-this.pointOnsetTimestamp>=this.autoPrepareMs&&this.nFramesAdded<this.nFramesNeedCollect){this.gf.addCalibrationPoint(t,this.currentX,this.currentY),this.nFramesAdded++;const e=Math.min(99,Math.max(1,Math.round(this.nFramesAdded/this.nFramesNeedCollect*100)));this._lastProgress!==e&&(this.showProgress(e),this._lastProgress=e),this.nFramesAdded===this.nFramesNeedCollect&&(this.featureFullTime=performance.now(),this.isWaitingWaitTime=!0)}}}_cancelLissajousAnim(){if(this._lissajousAnim){try{this._lissajousAnim.cancel()}catch(t){}this._lissajousAnim=null}}_ensureLissajousLut(t){const e=`${t.x}:${t.y}:${t.width}:${t.height}`;if(this._lissajousLut&&this._lissajousAreaKey===e)return this._lissajousLut;const i=1024,s=t.x+t.width/2,n=t.y+t.height/2,o=.4*t.width,a=.4*t.height,r=new Float64Array(i+1),l=new Float64Array(i+1),h=new Float64Array(i+1);let c=s,d=n;r[0]=c,l[0]=d,h[0]=0;for(let t=1;t<=i;t++){const e=t/i*Math.PI*2,u=s+o*Math.sin(3*e),f=n+a*Math.sin(2*e);r[t]=u,l[t]=f,h[t]=h[t-1]+Math.hypot(u-c,f-d),c=u,d=f}const u=h[i]||1;return this._lissajousAreaKey=e,this._lissajousLut={N:i,cumLen:h,ptsX:r,ptsY:l,totalLen:u,cx:s,cy:n},this._lissajousLut}_smoothPursuitNormalizedProgress(t,e){if(t<=0)return 0;if(t>=e)return 1;const i=Math.max(e,1),s=Math.min(1200,.1*i),n=Math.min(800,.08*i),o=Math.max(0,i-s-n),a=.5*s+o+.5*n;if(a<=0)return t/i;let r=0;if(t<=s&&s>0)r=.5*(t-s/Math.PI*Math.sin(Math.PI*t/s));else if(t<=i-n)r=.5*s+(t-s);else{const e=t-(i-n);r=.5*s+o+(n>0?.5*(e+n/Math.PI*Math.sin(Math.PI*e/n)):0)}return Math.min(1,Math.max(0,r/a))}getLissajousPos(t){const e=this.getTrackingArea(),i=this._ensureLissajousLut(e);if(t<=0)return{x:i.cx,y:i.cy};if(t>=this.lissajousDuration)return{x:i.cx,y:i.cy};const s=this._smoothPursuitNormalizedProgress(t,this.lissajousDuration)*i.totalLen;let n=0,o=i.N;for(;n+1<o;){const t=n+o>>1;i.cumLen[t]<=s?n=t:o=t}const a=i.cumLen[o]-i.cumLen[n],r=a>1e-6?(s-i.cumLen[n])/a:0;return{x:i.ptsX[n]+(i.ptsX[o]-i.ptsX[n])*r,y:i.ptsY[n]+(i.ptsY[o]-i.ptsY[n])*r}}_startLissajousCompositorAnim(t=0){if(this._cancelLissajousAnim(),!this.dot||this.customRender||"function"!=typeof this.dot.animate)return!1;const e=[];for(let t=0;t<=360;t++){const i=t/360*this.lissajousDuration,s=this.getLissajousPos(i);e.push({transform:`translate3d(${(s.x-25).toFixed(2)}px, ${(s.y-25).toFixed(2)}px, 0) scale(1)`})}try{const i=this.dot.animate(e,{duration:this.lissajousDuration,easing:"linear",fill:"forwards"});return t>0&&(i.currentTime=t),this._lissajousAnim=i,!0}catch(t){return this._lissajousAnim=null,!1}}autoLoop(t){if(!this.isActive)return;const e="number"==typeof t&&t>0?t:performance.now();if("lissajous"===this.mode){this.lissajousStartTime||(this.dot.style.transition="none",this.lissajousStartTime=e,this._lissajousMoveStartTime=0,this.showCrosshair(),this._lastProgress=-1);const t=e-this.lissajousStartTime,i=this.getTrackingArea(),s=i.x+i.width/2,n=i.y+i.height/2;if(t<this.lissajousPrepareMs)0!==this._lastProgress&&(this.updateDotPos(s,n),this.showCrosshair(),this._lastProgress=0);else{const i=t-this.lissajousPrepareMs;if(this._lissajousMoveStartTime||(this._lissajousMoveStartTime=e-i,this._startLissajousCompositorAnim(i)),i>=this.lissajousDuration)return void this.finish();const s=this.getLissajousPos(i);if(this._lissajousAnim){if(this.currentX=s.x,this.currentY=s.y,this.onPointCallback)try{this.onPointCallback({x:s.x,y:s.y,index:this.currentIndex,total:1,mode:this.mode,method:this.method})}catch(t){}}else this.updateDotPos(s.x,s.y);const n=Math.min(99,Math.max(1,Math.round(i/this.lissajousDuration*100)));this._lastProgress!==n&&(this.showProgress(n),this._lastProgress=n)}}else"auto"===this.method&&this.isWaitingWaitTime&&e-this.featureFullTime>=this.autoWaitMs&&(particleFX.burst(this.currentX,this.currentY,{color:"#00B050",count:20}),this.isWaitingWaitTime=!1,this.nextPoint());this._rafId=requestAnimationFrame(t=>this.autoLoop(t))}finish(){if(this.isActive=!1,this._cancelLissajousAnim(),this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=null),this.clickTimeoutId&&(clearTimeout(this.clickTimeoutId),this.clickTimeoutId=null),this.clickTransitionTimeoutId&&(clearTimeout(this.clickTransitionTimeoutId),this.clickTransitionTimeoutId=null),this.clickCollecting=!1,this.isWaitingPostClick=!1,this.customRender||(this.showCrosshair(),this.container&&(this.container.style.display="none")),this.gf.trainCalibration(),this.gf.listener&&this.gf.listener(null,null),this.onFinishCallback)try{this.onFinishCallback()}catch(t){console.error("[CalibrationManager] Error in onFinish callback:",t)}}}class LowPassFilter{constructor(t=1){this.a=t,this.y=null,this.s=null,this.initialized=!1}filter(t,e=null){const i=null==e?this.a:e;let s;if("number"==typeof t)return this.initialized?s=i*t+(1-i)*this.s:(s=t,this.initialized=!0),this.y=t,this.s=s,s;if(Array.isArray(t)){if(!this.initialized)return this.initialized=!0,this.y=t.slice(),this.s=t.slice(),t.slice();s=new Array(t.length);for(let e=0;e<t.length;e++){const n=t[e],o=this.s[e];if("number"==typeof n){const t="number"==typeof i?i:Array.isArray(i)?i[e]:1;s[e]=t*n+(1-t)*o}else if(n&&"object"==typeof n){const t={},a=Array.isArray(i)&&i[e]&&"object"==typeof i[e]?i[e]:null,r="number"==typeof i?i:Array.isArray(i)&&"number"==typeof i[e]?i[e]:1;for(const e of Object.keys(n)){const i=a&&"number"==typeof a[e]?a[e]:r;t[e]=i*n[e]+(1-i)*o[e]}s[e]=t}else s[e]=n}return this.y=t.slice(),this.s=s.slice(),s}if(t&&"object"==typeof t){if(!this.initialized)return this.initialized=!0,this.y={...t},this.s={...t},{...t};s={};for(const e of Object.keys(t)){const n=i&&"object"==typeof i&&"number"==typeof i[e]?i[e]:"number"==typeof i?i:1;s[e]=n*t[e]+(1-n)*this.s[e]}return this.y={...t},this.s={...s},s}return t}reset(){this.initialized=!1,this.y=null,this.s=null}setLookAhead(t=2){return this.lookAhead=t,this.look_ahead=t,this}getLookAhead(){return this.lookAhead||2}}class OneEuroFilter{constructor(t=30,e=.6,i=.005,s=1){this.freq=t,this.minCutoff=e,this.beta=i,this.dCutoff=s,this.xFilter=new LowPassFilter,this.dxFilter=new LowPassFilter,this.lastTime=null}_alpha(t){const e=1/Math.max(this.freq,1e-5);if("number"==typeof t)return 1/(1+1/(2*Math.PI*Math.max(t,1e-5))/e);if(Array.isArray(t))return t.map(t=>this._alpha(t));if(t&&"object"==typeof t){const e={};for(const i of Object.keys(t))e[i]=this._alpha(t[i]);return e}return 1}_zerosLike(t){if("number"==typeof t)return 0;if(Array.isArray(t))return t.map(t=>this._zerosLike(t));if(t&&"object"==typeof t){const e={};for(const i of Object.keys(t))e[i]=0;return e}return 0}_diff(t,e,i){if("number"==typeof t)return(t-e)*i;if(Array.isArray(t))return t.map((t,s)=>this._diff(t,e?e[s]:t,i));if(t&&"object"==typeof t){const s={};for(const n of Object.keys(t)){const o=e&&void 0!==e[n]?e[n]:t[n];s[n]=(t[n]-o)*i}return s}return 0}_calcCutoff(t){if("number"==typeof t)return this.minCutoff+this.beta*Math.abs(t);if(Array.isArray(t))return t.map(t=>this._calcCutoff(t));if(t&&"object"==typeof t){const e={};for(const i of Object.keys(t))e[i]=this.minCutoff+this.beta*Math.abs(t[i]);return e}return this.minCutoff}filter(t,e=null){if(null!==e&&null!==this.lastTime){let t=e-this.lastTime;t>1e11?t/=1e9:t>1e5?t/=1e6:t>.5&&(t/=1e3),t>.001&&t<1&&(this.freq=1/t)}let i;this.lastTime=e,i=this.xFilter.initialized?this._diff(t,this.xFilter.y,this.freq):this._zerosLike(t);const s=this._alpha(this.dCutoff),n=this.dxFilter.filter(i,s),o=this._calcCutoff(n),a=this._alpha(o);return this.xFilter.filter(t,a)}filterValues(t,e,i=null){const s=null!=i?i:"undefined"!=typeof performance?performance.now():Date.now(),n=this.filter([t,e],s);return[n[0],n[1]]}reset(){this.xFilter.reset(),this.dxFilter.reset(),this.lastTime=null}setLookAhead(t=2){return this.lookAhead=t,this.look_ahead=t,this}getLookAhead(){return this.lookAhead||2}}class HeuristicFilter{constructor(t=2){this.rawX=[],this.rawY=[],this.dummyX=NaN,this.dummyY=NaN,this._lookAhead=2,this.setLookAhead(t)}get look_ahead(){return this._lookAhead}set look_ahead(t){this.setLookAhead(t)}get lookAhead(){return this._lookAhead}set lookAhead(t){this.setLookAhead(t)}setLookAhead(t=2){const e=Number(t);if(Number.isFinite(e)&&e>=1){const t=Math.max(1,Math.round(e));t!==this._lookAhead&&(this._lookAhead=t,this.reset())}return this}getLookAhead(){return this._lookAhead}reset(){return this.rawX=[],this.rawY=[],this.dummyX=NaN,this.dummyY=NaN,this}filterValues(t,e){return Array.isArray(t)&&void 0===e&&([t,e]=t),this.rawX=this.doFilter(!0,t),this.rawY=this.doFilter(!1,e),this.rawX.length>=2*this._lookAhead?Number.isNaN(this.dummyX)&&Number.isNaN(this.dummyY)?[t,e]:[this.dummyX,this.dummyY]:[t,e]}filter_values(t){if(!Array.isArray(t)||t.length<2)throw new Error("HeuristicFilter.filter_values requires an array of two values [x, y]");return this.filterValues(t[0],t[1])}doFilter(t,e){let i=t?this.rawX:this.rawY;i.push(e);const s=2*this._lookAhead+1;for(;i.length>s;)i.shift();if(i.length===s){for(let t=1;t<=this._lookAhead;t++){const e=i[this._lookAhead-t]<i[this._lookAhead]&&i[this._lookAhead]>i[this._lookAhead+t],s=i[this._lookAhead-t]>i[this._lookAhead]&&i[this._lookAhead]<i[this._lookAhead+t];if(e||s){const e=Math.abs(i[this._lookAhead-t]-i[this._lookAhead]),s=Math.abs(i[this._lookAhead+t]-i[this._lookAhead]);i[this._lookAhead]=e<s?i[this._lookAhead-t]:i[this._lookAhead+t]}}t?this.dummyX=i[this._lookAhead]:this.dummyY=i[this._lookAhead],i.shift()}return i}}class GazeSessionManager{constructor(t={}){this.options=Object.assign({endpoint:this._resolveDefaultEndpoint(),autoHeartbeat:!0,heartbeatIntervalMs:3e4},t),this.endpoint=this._normalizeEndpoint(this.options.endpoint),this.inviteToken=this.options.inviteToken||null,this.signedTicket=this.options.signedTicket||this.options.sessionTicket||null,this.sessionId=this.options.sessionId||null,this.projectId=this.options.projectId||null,this.keySlice=this.options.keySlice||this.options.key_slice||null,this.statsProvider=this.options.statsProvider||null,this.status="uninitialized",this.pointsDeducted=0,this.isPointCharged=!1,this.startedAt=null,this._heartbeatTimer=null,this._lastPingTime=0,this.onPointDeducted=this.options.onPointDeducted||null,this.onError=this.options.onError||null,this.onStateChange=this.options.onStateChange||null}_decodeTicketClaims(t){if(!t||"string"!=typeof t||!t.includes("."))return null;const e=t.split(".");if(2!==e.length||!e[0])return null;try{let t,i=e[0].replace(/-/g,"+").replace(/_/g,"/");for(;i.length%4!=0;)i+="=";if("function"==typeof atob){const e=atob(i),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);t=(new TextDecoder).decode(s)}else t=Buffer.from(i,"base64").toString("utf-8");return JSON.parse(t)}catch(t){return null}}_resolveDefaultEndpoint(){if("undefined"!=typeof window&&window.location){const t=window.location.hostname;if("gazefollower.com"===t||t.endsWith(".gazefollower.com")||isPrivateOrLocalHost(t))return window.location.origin}return"https://gazefollower.com"}_normalizeEndpoint(t){return t?t.replace(/\/+$/,""):"https://gazefollower.com"}_setState(t,e={}){const i=this.status;if(this.status=t,this.onStateChange)try{this.onStateChange({oldStatus:i,newStatus:t,sessionId:this.sessionId,pointsDeducted:this.pointsDeducted,detail:e})}catch(t){console.error("[GazeSessionManager] onStateChange hook error:",t)}}_emitError(t,e,i=null){const s={code:t,message:e,originalError:i,sessionId:this.sessionId};if(this._setState("error",s),this.onError)try{this.onError(s)}catch(t){console.error("[GazeSessionManager] onError hook error:",t)}return s}async init(){if(this.inviteToken)try{const t=`${this.endpoint}/commerce/web-sdk/invite/${encodeURIComponent(this.inviteToken)}`,e="GET"===String(this.options.inviteMethod||"POST").toUpperCase()?{method:"GET"}:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({origin:"undefined"!=typeof window&&window.location?window.location.origin:null,participant_id:this.options.participantId||null})},i=await fetch(t,e);if(!i.ok){const t=(await i.json().catch(()=>({}))).detail||`邀请链接兑换失败 (${i.status})`;throw new Error(t)}const s=await i.json();return this.sessionId=s.session_id,this.signedTicket=s.signed_ticket||s.ticket,this.projectId=s.project_id,this.keySlice=s.key_slice||this.keySlice,this.pointsDeducted=s.points_deducted||0,this._setState("active"===s.status?"active":"ready",{mode:"invite",project:s.project_name}),{success:!0,sessionId:this.sessionId,projectId:this.projectId,signedTicket:this.signedTicket,keySlice:this.keySlice,mode:"invite"}}catch(t){throw this._emitError("INVITE_REDEMPTION_FAILED",t.message,t),t}if(this.signedTicket)try{if(!this.sessionId||!this.projectId){const t=this._decodeTicketClaims(this.signedTicket);t&&(this.sessionId||!t.s&&!t.sub||(this.sessionId=t.s||t.sub),this.projectId||!t.p&&!t.prj||(this.projectId=t.p||t.prj))}if(!this.sessionId)throw new Error("缺少有效的会话标识 (Session ID)。请在参数中指定或使用规范签发的票据。");return this._setState("ready",{mode:"signed_ticket"}),{success:!0,sessionId:this.sessionId,projectId:this.projectId,signedTicket:this.signedTicket,keySlice:this.keySlice,mode:"signed_ticket"}}catch(t){throw this._emitError("TICKET_PARSE_FAILED",t.message,t),t}if(this.sessionId)return this._setState("ready",{mode:"resume"}),{success:!0,sessionId:this.sessionId,mode:"resume"};throw new Error("[GazeSessionManager] 初始化失败:必须提供 inviteToken、signedTicket 或已有的 sessionId 之一。")}async preflight(t={}){this.sessionId||await this.init();try{const e=`${this.endpoint}/commerce/web-sdk/sessions/${encodeURIComponent(this.sessionId)}/preflight`,i={"Content-Type":"application/json"};this.signedTicket&&(i["X-Session-Ticket"]=this.signedTicket);const s={screen_width:t.screenWidth||("undefined"!=typeof window?window.innerWidth:1920),screen_height:t.screenHeight||("undefined"!=typeof window?window.innerHeight:1080),calibration_score:void 0!==t.calibrationScore?t.calibrationScore:null,device_info:{user_agent:"undefined"!=typeof navigator?navigator.userAgent:null,platform:"undefined"!=typeof navigator?navigator.platform:null,device_memory:"undefined"!=typeof navigator?navigator.deviceMemory:null}},n=await fetch(e,{method:"POST",headers:i,body:JSON.stringify(s)});if(!n.ok){const t=await n.json().catch(()=>({}));throw new Error(t.detail||`预检更新失败 (${n.status})`)}const o=await n.json();return this._setState("calibrated",o),{success:!0,sessionId:this.sessionId,status:"calibrated",pointsDeducted:0,message:"标定预检通过,未正式开始前不扣点"}}catch(t){throw this._emitError("PREFLIGHT_FAILED",t.message,t),t}}async start(){this.sessionId||await this.init();try{const t=`${this.endpoint}/commerce/web-sdk/sessions/${encodeURIComponent(this.sessionId)}/start`,e={"Content-Type":"application/json"};this.signedTicket&&(e["X-Session-Ticket"]=this.signedTicket);const i=await fetch(t,{method:"POST",headers:e});if(!i.ok){const t=await i.json().catch(()=>({})),e=t.message||t.detail||`正式采集启动失败 (${i.status})`;if(402===i.status)throw new Error("[点数不足] 该研究项目账户可用采集点数已耗尽,请联系研究负责人或管理员充值点数包。");if(403===i.status)throw new Error(`[配额限制] ${e}`);throw new Error(e)}const s=await i.json();if(this.startedAt=s.started_at||Date.now(),this.pointsDeducted=void 0!==s.points_deducted?s.points_deducted:1,this.isPointCharged=!0,this._setState("active",s),this.onPointDeducted)try{this.onPointDeducted({sessionId:this.sessionId,pointsDeducted:this.pointsDeducted,startedAt:this.startedAt,message:s.message})}catch(t){console.error("[GazeSessionManager] onPointDeducted callback error:",t)}return this.options.autoHeartbeat&&this._startHeartbeat(),{success:!0,sessionId:this.sessionId,status:"active",pointsDeducted:this.pointsDeducted,startedAt:this.startedAt}}catch(t){throw this._emitError("START_FAILED",t.message,t),t}}async ping(t={}){if(!this.sessionId||"active"!==this.status)return;const e=t&&Object.keys(t).length>0?t:"function"==typeof this.statsProvider&&this.statsProvider()||{};try{const t=`${this.endpoint}/commerce/web-sdk/sessions/${encodeURIComponent(this.sessionId)}/ping`,i={"Content-Type":"application/json"};this.signedTicket&&(i["X-Session-Ticket"]=this.signedTicket),await fetch(t,{method:"POST",headers:i,body:JSON.stringify({current_fps:e.fps??e.current_fps??null,frames_processed:e.framesProcessed??e.frames_processed??null,face_detected_ratio:e.faceDetectedRatio??e.face_detected_ratio??null})}),this._lastPingTime=Date.now()}catch(t){console.warn("[GazeSessionManager] Ping telemetry warning:",t.message)}}_startHeartbeat(){this._stopHeartbeat(),this._heartbeatTimer=setInterval(()=>{this.ping()},this.options.heartbeatIntervalMs)}_stopHeartbeat(){this._heartbeatTimer&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=null)}async finish(t={}){if(this._stopHeartbeat(),!this.sessionId)return{success:!0};try{const e=`${this.endpoint}/commerce/web-sdk/sessions/${encodeURIComponent(this.sessionId)}/finish`,i={"Content-Type":"application/json"};return this.signedTicket&&(i["X-Session-Ticket"]=this.signedTicket),await fetch(e,{method:"POST",headers:i,body:JSON.stringify({participant_notes:t.notes||t.participantNotes||null,completed_trials:t.completedTrials||null,total_duration_sec:this.startedAt?Math.round((Date.now()-this.startedAt)/1e3):null})}),this._setState("completed",t),{success:!0,sessionId:this.sessionId,status:"completed"}}catch(t){return this._emitError("FINISH_FAILED",t.message,t),{success:!1,error:t.message}}}destroy(){this._stopHeartbeat(),this.status="destroyed"}}class GazeFollower2{constructor(t={}){let e={};"number"==typeof t?e={look_ahead:t}:t&&"object"==typeof t&&(e=t),this.options=e,this.enableGazeFilter=void 0===e.enableGazeFilter||!!e.enableGazeFilter,this.oneEuroFilter=new OneEuroFilter(30,.6,.005,1),this.heuristicFilter=new HeuristicFilter(2),this.filter=this.oneEuroFilter;const i=void 0!==e.calibrationPenalty?e.calibrationPenalty:void 0!==e.penalty?e.penalty:void 0!==e.ridgeAlpha?e.ridgeAlpha:30;this.calibrationPenalty="number"==typeof i&&i>0?i:30,this.ridgeCalibrator=new MultivariateRidgeCalibration(this.calibrationPenalty),this._trackingArea=normalizeTrackingArea(e.tracking_area||e.trackingArea||null),this.modelName="base",this.modelFile="GazeNet_Next_epoch_5.onnx",this.endpoint=e.endpoint||this._resolveDefaultEndpoint(),this.faceAlignment=new FaceAlignment,this.estimator=new GazeEstimator(e),this.caliManager=new CalibrationManager(this),this._isRegistered=!1,this._registrationTicket=null,this._sessionId=null,this._keySlice=null,this._remainingUses=null,this.sessionManager=null,this.faceLandmarker=null,this._isReady=!1,this.isCalibrated=!1,this.isPaused=!0,this.collectedFeatures=[],this.collectedX=[],this.collectedY=[],this.listener=null,this.statsListener=null,this.videoElement=null,this.overlayCanvas=null,this.showVid=!0,this.showFaceOverlay=!0,this.stream=null,this.lastFeatures=null,this.rawX=null,this.rawY=null,this.targetX=null,this.targetY=null,this.smoothX=null,this.smoothY=null,this.leftOpenness=null,this.rightOpenness=null,this.leftIrisSize=null,this.rightIrisSize=null,this.isFaceDetected=!1,this._lastInferenceTimestamp=0,this._latestVideoFrameSeq=0,this._waitingForVideoFrame=!1,this._vfcHandle=null,this._vfcWatchdog=null,this.register=this.register.bind(this),this.setSessionManager=this.setSessionManager.bind(this),this.preflight=this.preflight.bind(this),this.startCollection=this.startCollection.bind(this),this.finishSession=this.finishSession.bind(this),this.setModelName=this.setModelName.bind(this),this.getModelName=this.getModelName.bind(this),this.setTrackingArea=this.setTrackingArea.bind(this),this.getTrackingArea=this.getTrackingArea.bind(this),this.setCalibrationPenalty=this.setCalibrationPenalty.bind(this),this.getCalibrationPenalty=this.getCalibrationPenalty.bind(this),this.startCalibration=this.startCalibration.bind(this),this.resetFilter=this.resetFilter.bind(this),this.setLookAhead=this.setLookAhead.bind(this),this.setHeuristicFilter=this.setHeuristicFilter.bind(this),this.setOneEuroFilter=this.setOneEuroFilter.bind(this),this.setStatsListener=this.setStatsListener.bind(this),e.sessionManager&&this.setSessionManager(e.sessionManager)}_resolveDefaultEndpoint(){if("undefined"!=typeof window&&window.location){const t=window.location.hostname;if("gazefollower.com"===t||t.endsWith(".gazefollower.com"))return window.location.origin;if(isPrivateOrLocalHost(t))return"localhost"!==t&&"127.0.0.1"!==t||!window.location.port||"8000"===window.location.port?window.location.origin:"http://127.0.0.1:8000"}return"https://gazefollower.com"}_syncFromSessionManager(t){t&&(this.endpoint=t.endpoint||this.endpoint,this._sessionId=t.sessionId||this._sessionId,this._registrationTicket=t.signedTicket||this._registrationTicket,t.keySlice&&(this._keySlice=t.keySlice,this.estimator&&(this.estimator.options.keySlice=t.keySlice,this.estimator.vault&&(this.estimator.vault.keySlice=t.keySlice))),(t.sessionId||t.signedTicket)&&(this._isRegistered=!0))}setSessionManager(t){if(!t||"object"!=typeof t)throw new Error("[GazeFollower2] setSessionManager(manager) requires a valid GazeSessionManager instance.");return this.sessionManager=t,t.statsProvider=()=>this.pipelineStats||{},this._syncFromSessionManager(t),this}async register(t={}){const e="string"==typeof t?{license_key:t}:t||{},i=(e.project_key||e.projectKey||e.license_key||e.licenseKey||"").trim();if(!i)throw new Error("[GazeFollower2] register({ project_key | license_key }) requires a valid key string.");const s=(e.endpoint||this.endpoint||this._resolveDefaultEndpoint()).replace(/\/+$/,"");this.licenseKey=i,this.endpoint=s;const n=`gf2_session_${i.slice(0,16)}`;let o=e.session_id||e.sessionId||null;if(!o&&!e.forceNewSession&&"undefined"!=typeof window&&window.sessionStorage)try{o=window.sessionStorage.getItem(n)}catch(t){}const a=void 0===e.defer_deduction||!!e.defer_deduction,r={license_key:i,project_key:i.startsWith("gfp_pub_")?i:e.project_key||null,participant_id:e.participant_id||e.participantId||null,session_id:o||null,defer_deduction:a,origin:"undefined"!=typeof window&&window.location?window.location.origin:"*"};let l;try{l=await fetch(`${s}/commerce/web-sdk/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})}catch(t){try{l=await fetch(`${s}/commerce/v2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})}catch(e){throw new Error(`[GazeFollower2] Network request to licensing server failed: ${t.message}`)}}const h=await l.json().catch(()=>({}));if(!l.ok||!h.success){const t=h.message||h.detail||`License registration failed with status ${l.status}`;throw this._isRegistered=!1,this._registrationTicket=null,this._keySlice=null,new Error(`[GazeFollower2] Registration Rejected: ${t}`)}if(this._isRegistered=!0,this._registrationTicket=h.signed_ticket||null,this._sessionId=h.session_id||null,this._keySlice=h.key_slice||null,this._remainingUses=void 0!==h.remaining_uses?h.remaining_uses:null,"undefined"!=typeof window&&window.sessionStorage&&this._sessionId)try{window.sessionStorage.setItem(n,this._sessionId)}catch(t){}this.estimator&&(this.estimator.options.keySlice=this._keySlice,this.estimator.vault&&(this.estimator.vault.keySlice=this._keySlice));const c=this.sessionManager||new GazeSessionManager({endpoint:this.endpoint,sessionId:this._sessionId,projectId:h.project_id||"web_sdk",signedTicket:this._registrationTicket,keySlice:this._keySlice});return c.endpoint=this.endpoint,c.sessionId=this._sessionId,c.projectId=h.project_id||c.projectId||"web_sdk",c.signedTicket=this._registrationTicket,c.keySlice=this._keySlice,c.pointsDeducted=h.points_deducted||0,c.status="active"===h.status?"active":"ready",this.setSessionManager(c),console.log(`[GazeFollower2] Session initialized (${c.status}). Session: ${this._sessionId}, Remaining uses: ${this._remainingUses}`),{success:!0,session_id:this._sessionId,project_id:c.projectId,status:c.status,points_deducted:c.pointsDeducted,remaining_uses:this._remainingUses,signed_ticket:this._registrationTicket,message:h.message||"Authorized"}}async preflight(t={}){if(!this.sessionManager)throw new Error("[GazeFollower2] No active sessionManager. Call register() or setSessionManager() first.");return await this.sessionManager.preflight(t)}async startCollection(){if(!this.sessionManager)throw new Error("[GazeFollower2] No active sessionManager. Call register() or setSessionManager() first.");return await this.sessionManager.start()}async finishSession(t={}){if(this.licenseKey&&"undefined"!=typeof window&&window.sessionStorage)try{window.sessionStorage.removeItem(`gf2_session_${this.licenseKey.slice(0,16)}`)}catch(t){}return this.sessionManager?await this.sessionManager.finish(t):{success:!0}}setModelName(t="base"){if("base"!==t&&"GazeNet_Next_epoch_5"!==t)throw new Error(`Unsupported model name: "${t}". Only "base" (GazeNet_Next_epoch_5.onnx) is supported.`);return this.modelName="base",this.modelFile="GazeNet_Next_epoch_5.onnx",this.estimator&&(this.estimator.modelName="base",this.estimator.modelFile="GazeNet_Next_epoch_5.onnx"),this}getModelName(){return this.modelName||"base"}setCalibrationPenalty(t=30){const e=parseFloat(t);return Number.isFinite(e)&&e>0&&(this.calibrationPenalty=e,this.ridgeCalibrator&&(this.ridgeCalibrator.lambda=e,this.ridgeCalibrator.calibrationPenalty=e)),this}getCalibrationPenalty(){return this.calibrationPenalty}setClickSampleCount(t=24){return this.caliManager&&this.caliManager.setClickSampleCount(t),this}getClickSampleCount(){return this.caliManager?this.caliManager.getClickSampleCount():24}setCalibrationSamples(t=24){return this.setClickSampleCount(t)}setPreClickMs(t=200){return this.caliManager&&this.caliManager.setPreClickMs(t),this}getPreClickMs(){return this.caliManager?this.caliManager.getPreClickMs():200}setPostClickDelay(t=100){return this.caliManager&&this.caliManager.setPostClickDelay(t),this}getPostClickDelay(){return this.caliManager?this.caliManager.getPostClickDelay():100}setTrackingArea(t){return this._trackingArea=normalizeTrackingArea(t),this.caliManager&&this.caliManager.setTrackingArea(this._trackingArea),this}getTrackingArea(){return this._trackingArea||(this._trackingArea=normalizeTrackingArea(null)),this._trackingArea}get tracking_area(){return this.getTrackingArea()}set tracking_area(t){this.setTrackingArea(t)}get trackingArea(){return this.getTrackingArea()}set trackingArea(t){this.setTrackingArea(t)}resetFilter(){return this.filter&&"function"==typeof this.filter.reset&&this.filter.reset(),this.faceAlignment&&"function"==typeof this.faceAlignment.resetFilter&&this.faceAlignment.resetFilter(),this}isReady(){return!(!this._isReady||!this.videoElement||this.videoElement.srcObject&&!(this.videoElement.readyState>=2))}setGazeListener(t){return this.listener=t,this}clearGazeListener(){return this.listener=null,this}getCurrentPrediction(){return null!==this.targetX&&null!==this.targetY?{x:this.targetX,y:this.targetY,leftOpenness:this.leftOpenness,rightOpenness:this.rightOpenness,leftIrisSize:this.leftIrisSize,rightIrisSize:this.rightIrisSize}:null}async begin(t=null,e=null){let i=t,s=e;if(t&&"object"==typeof t&&(s=t,i="function"==typeof s.onProgress?s.onProgress:"function"==typeof s.progressCallback?s.progressCallback:null),s&&"object"==typeof s)if(s.sessionManager)this.setSessionManager(s.sessionManager);else if(this._isRegistered||!s.inviteToken&&!s.signedTicket)!this._isRegistered&&(s.project_key||s.projectKey||s.license_key||s.licenseKey)&&await this.register(s);else{const t=new GazeSessionManager(Object.assign({endpoint:this.endpoint},s));await t.init(),this.setSessionManager(t)}if(this.sessionManager&&(this.sessionManager.sessionId||!this.sessionManager.inviteToken&&!this.sessionManager.signedTicket||await this.sessionManager.init(),this._syncFromSessionManager(this.sessionManager)),!this._isRegistered)throw new Error("[GazeFollower2] Registration Required: Please call await GazeFollower2.register({ project_key }) or attach a GazeSessionManager via setSessionManager() before begin().");return s&&"object"==typeof s&&this._applyFilterOptions(s),this._isReady||await this.init(i,s),this.isPaused=!1,await this.startWebcam(),this}_applyFilterOptions(t){if(!t||"object"!=typeof t)return;const e=void 0!==t.enableGazeFilter?t.enableGazeFilter:t.enabled;void 0!==e&&(this.enableGazeFilter=!!e)}pause(){return this.isPaused=!0,this.resetFilter(),this}resume(){return this.isPaused=!1,this._fpsFrameCount=0,this._fpsLastTime=0,this._waitingForVideoFrame&&(this._waitingForVideoFrame=!1,setTimeout(()=>this.inferenceLoop(),0)),this}end(){if(this.isPaused=!0,this._stopVideoFrameProducer(),this._fpsFrameCount=0,this._fpsLastTime=0,this._currentFps=0,this.estimator&&"function"==typeof this.estimator.terminate&&this.estimator.terminate(),this.stream){try{this.stream.getTracks().forEach(t=>t.stop())}catch(t){console.warn("Error stopping stream tracks:",t)}this.stream=null}if(this.videoElement){this.videoElement.srcObject=null;try{this.videoElement.pause()}catch(t){}}return this.overlayCanvas&&this.overlayCanvas.getContext("2d").clearRect(0,0,this.overlayCanvas.width,this.overlayCanvas.height),this.resetFilter(),this.rawX=null,this.rawY=null,this.targetX=null,this.targetY=null,this.smoothX=null,this.smoothY=null,this.leftOpenness=null,this.rightOpenness=null,this.leftIrisSize=null,this.rightIrisSize=null,this}stop(){return this.end()}showVideo(t){return this.showVid=!!t,this.videoElement&&(this.videoElement.style.opacity=this.showVid?"1":"0"),this}showVideoPreview(t){return this.showVideo(t)}showVideoElement(t){return this.showVideo(t)}showPredictionPoints(t){return this.showFaceOverlay=!!t,this.overlayCanvas&&(this.overlayCanvas.style.opacity=this.showFaceOverlay?"1":"0"),this}getVideoElementCanvas(){return this.overlayCanvas}clearData(){return this.collectedFeatures=[],this.collectedX=[],this.collectedY=[],this.isCalibrated=!1,this.ridgeCalibrator=new MultivariateRidgeCalibration(this.calibrationPenalty),this.resetFilter(),this}recordScreenPosition(t,e,i="click"){return!!this.lastFeatures&&(this.addCalibrationPoint(this.lastFeatures,t,e),!0)}setLookAhead(t=2){return this.filter&&"function"==typeof this.filter.setLookAhead&&this.filter.setLookAhead(t),this.oneEuroFilter&&"function"==typeof this.oneEuroFilter.setLookAhead&&this.oneEuroFilter.setLookAhead(t),this.heuristicFilter&&"function"==typeof this.heuristicFilter.setLookAhead&&this.heuristicFilter.setLookAhead(t),this}setHeuristicFilter(t=!0,e=2){return this.enableGazeFilter=!!t,t&&(this.heuristicFilter?this.heuristicFilter.setLookAhead(e):this.heuristicFilter=new HeuristicFilter(e),this.filter=this.heuristicFilter),this}setStatsListener(t){return this.statsListener=t,this}setOneEuroFilter(t=.6,e=.005,i=1){return this.oneEuroFilter?(this.oneEuroFilter.minCutoff=t,this.oneEuroFilter.beta=e,this.oneEuroFilter.dCutoff=i):this.oneEuroFilter=new OneEuroFilter(30,t,e,i),this.filter=this.oneEuroFilter,this.enableGazeFilter=!0,this}setLissajousSpeed(t=250){return this.caliManager&&this.caliManager.setLissajousSpeed(t),this}getLissajousSpeed(){return this.caliManager?this.caliManager.getLissajousSpeed():250}startCalibration(t="13-point",e="click",i=78,s="random",n={}){return this.clearData(),this.caliManager.start(t,e,i,s,n),this}triggerCalibrationClick(t=null,e=null){return this.caliManager&&this.caliManager.triggerClick(t,e),this}async init(t=null,e=null){let i=e,s=t;if(t&&"object"==typeof t&&(i=t,s="function"==typeof i.onProgress?i.onProgress:"function"==typeof i.progressCallback?i.progressCallback:null),i&&"object"==typeof i&&(this._applyFilterOptions(i),this.options=Object.assign(this.options||{},i)),console.log("Loading GazeFollower2 SDK..."),this.estimator){const t=this._keySlice||this.sessionManager&&this.sessionManager.keySlice;t&&(this.estimator.options.keySlice=t),this.endpoint&&(this.estimator.options.endpoint=this.endpoint),this.options&&void 0!==this.options.requireVault&&(this.estimator.options.requireVault=!!this.options.requireVault)}this.estimator.session||await this.estimator.init(s);const n=i&&(i.wasmLoaderPath||i.wasmPath)||this.options&&(this.options.wasmLoaderPath||this.options.wasmPath)||"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.3/wasm",o=await FilesetResolver.forVisionTasks(n),a=i&&(i.modelAssetPath||i.faceLandmarkerPath)||this.options&&(this.options.modelAssetPath||this.options.faceLandmarkerPath)||"/models/face_landmarker.task",r=i&&i.delegate||this.options&&this.options.delegate||"CPU",l=async(t,e)=>await FaceLandmarker.createFromOptions(o,{baseOptions:{modelAssetPath:e,delegate:t},runningMode:"VIDEO",numFaces:1,minFaceDetectionConfidence:.3,minFacePresenceConfidence:.3,minTrackingConfidence:.3,outputFaceBlendshapes:!1});try{console.log(`[GazeFollower2] Initializing FaceLandmarker (delegate: ${r}, model: ${a})...`),this.faceLandmarker=await l(r,a)}catch(t){console.warn(`[GazeFollower2] FaceLandmarker init with ${r} & local model failed:`,t);try{this.faceLandmarker=await l("CPU",a)}catch(t){console.warn("[GazeFollower2] Local model failed, falling back to Google Cloud Storage CDN...",t);const e="https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task";this.faceLandmarker=await l("CPU",e)}}return this.initDOM(),this._isReady=!0,console.log("GazeFollower2 SDK ready!"),this}initDOM(){this.videoElement&&this.overlayCanvas||(this.videoElement=document.createElement("video"),this.videoElement.autoplay=!0,this.videoElement.muted=!0,this.videoElement.defaultMuted=!0,this.videoElement.playsInline=!0,this.videoElement.setAttribute("playsinline",""),this.videoElement.setAttribute("webkit-playsinline",""),Object.assign(this.videoElement.style,{position:"fixed",top:"50%",left:"50%",maxWidth:"100vw",maxHeight:"100vh",transform:"translate(-50%, -50%) scaleX(-1)",zIndex:"-2",opacity:this.showVid?"1":"0"}),this.overlayCanvas=document.createElement("canvas"),Object.assign(this.overlayCanvas.style,{position:"fixed",top:"50%",left:"50%",maxWidth:"100vw",maxHeight:"100vh",transform:"translate(-50%, -50%) scaleX(-1)",zIndex:"-1",opacity:this.showFaceOverlay?"1":"0",pointerEvents:"none"}),document.body.appendChild(this.videoElement),document.body.appendChild(this.overlayCanvas),this.renderLoop())}async startWebcam(){return new Promise(async(t,e)=>{try{if("undefined"==typeof navigator||!navigator.mediaDevices||"function"!=typeof navigator.mediaDevices.getUserMedia){const t="undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname;throw new Error(t?`Camera API unavailable on insecure HTTP (${window.location.origin}). Use HTTPS or add this origin to chrome://flags/#unsafely-treat-insecure-origin-as-secure.`:"Camera API (navigator.mediaDevices.getUserMedia) is unavailable in this browser context.")}const e=this.options&&this.options.deviceId?String(this.options.deviceId):"",i=e?{width:{ideal:640},height:{ideal:480},frameRate:{ideal:30},deviceId:{exact:e}}:{width:{ideal:640},height:{ideal:480},frameRate:{ideal:30},facingMode:{ideal:"user"}};this.stream=await navigator.mediaDevices.getUserMedia({video:i,audio:!1}),this.videoElement.srcObject=this.stream;let s=!1;const n=async()=>{if(!s&&this.videoElement.videoWidth&&this.videoElement.videoHeight){s=!0,this.overlayCanvas.width=this.videoElement.videoWidth,this.overlayCanvas.height=this.videoElement.videoHeight;try{await this.videoElement.play()}catch(t){console.warn("Video play failed:",t)}this._startVideoFrameProducer(),this.inferenceLoop(),t()}};this.videoElement.onloadedmetadata=n,this.videoElement.onloadeddata=n,this.videoElement.oncanplay=n;try{await this.videoElement.play()}catch(t){}this.videoElement.readyState>=2&&n()}catch(t){console.error("Camera access failed:",t),e(t)}})}_startVideoFrameProducer(){this._stopVideoFrameProducer();const t=this.videoElement;if(!t||"function"!=typeof t.requestVideoFrameCallback)return;const e=()=>{this.stream&&this.videoElement===t?(this._latestVideoFrameSeq+=1,this._waitingForVideoFrame&&!this.isPaused&&(this._waitingForVideoFrame=!1,this._vfcWatchdog&&(clearTimeout(this._vfcWatchdog),this._vfcWatchdog=null),this.inferenceLoop()),this._vfcHandle=t.requestVideoFrameCallback(e)):this._vfcHandle=null};this._vfcHandle=t.requestVideoFrameCallback(e)}_stopVideoFrameProducer(){if(this._vfcWatchdog&&(clearTimeout(this._vfcWatchdog),this._vfcWatchdog=null),null!==this._vfcHandle&&this.videoElement&&"function"==typeof this.videoElement.cancelVideoFrameCallback)try{this.videoElement.cancelVideoFrameCallback(this._vfcHandle)}catch(t){}this._vfcHandle=null,this._waitingForVideoFrame=!1}async inferenceLoop(){if(this.isPaused)return void setTimeout(()=>this.inferenceLoop(),100);const t=this._latestVideoFrameSeq,e=performance.now(),i=Math.max(e,(this._lastInferenceTimestamp||0)+1);this._lastInferenceTimestamp=i;let s=0,n=0,o=0;try{this.videoElement&&this.videoElement.paused&&this.videoElement.readyState>=2&&this.videoElement.play().catch(()=>{});const t=performance.now();let e=null;if(this.faceLandmarker&&this.videoElement&&this.videoElement.readyState>=2)try{e=this.faceLandmarker.detectForVideo(this.videoElement,i)}catch(t){console.warn("[GazeFollower2] detectForVideo warning:",t)}if(s=performance.now()-t,e&&e.faceLandmarks&&e.faceLandmarks.length>0){this.isFaceDetected=!0;const t=performance.now(),{faceTensor:s,leftTensor:a,rightTensor:r,rectTensor:l,rawRects:h,leftOpenness:c,rightOpenness:d,leftIrisSize:u,rightIrisSize:f}=this.faceAlignment.process(this.videoElement,e.faceLandmarks[0],i);this.leftOpenness=c,this.rightOpenness=d,this.leftIrisSize=u,this.rightIrisSize=f,n=performance.now()-t,this.caliManager&&this.caliManager.isActive&&!this.caliManager.customRender||this.drawOverlay(h);const m=performance.now(),p=await this.estimator.detect(s,a,r,l);if(o=performance.now()-m,p&&(this.lastFeatures=p,this.caliManager.feedFeatures(p,i),this.isCalibrated)){const t=this.ridgeCalibrator,[e,s]=t.predict(p);this.rawX=e,this.rawY=s;let n=e,o=s;if(this.enableGazeFilter&&this.filter){const[t,a]=this.filter.filterValues(e,s,i);n=t,o=a}this.targetX=n,this.targetY=o,this.listener&&this.listener({x:n,y:o,leftOpenness:this.leftOpenness,rightOpenness:this.rightOpenness,leftIrisSize:this.leftIrisSize,rightIrisSize:this.rightIrisSize},i)}}else this.isFaceDetected=!1,this.resetFilter(),this.caliManager&&this.caliManager.isActive&&!this.caliManager.customRender||this.drawOverlay(null),this.lastFeatures=null,this.rawX=null,this.rawY=null,this.targetX=null,this.targetY=null,this.leftOpenness=null,this.rightOpenness=null,this.leftIrisSize=null,this.rightIrisSize=null}catch(t){console.warn("[GazeFollower2] Error in inferenceLoop frame:",t),this.isFaceDetected=!1}const a=performance.now()-i;if(this._fpsLastTime){this._fpsFrameCount=(this._fpsFrameCount||0)+1;const t=i-this._fpsLastTime;t>=500&&(this._currentFps=1e3*this._fpsFrameCount/t,this._fpsFrameCount=0,this._fpsLastTime=i)}else this._fpsLastTime=i,this._fpsFrameCount=0;const r=.2;if(this._smoothTotalMs=this._smoothTotalMs?.8*this._smoothTotalMs+r*a:a,this._smoothMediaMs=this._smoothMediaMs?.8*this._smoothMediaMs+r*s:s,this._smoothGazeMs=this._smoothGazeMs?.8*this._smoothGazeMs+r*o:o,this._smoothAlignMs=this._smoothAlignMs?.8*this._smoothAlignMs+r*n:n,this.pipelineStats={fps:Number((this._currentFps||0).toFixed(1)),totalMs:Number(this._smoothTotalMs.toFixed(1)),mediapipeMs:Number(this._smoothMediaMs.toFixed(1)),gazeMs:Number(this._smoothGazeMs.toFixed(1)),faceAlignMs:Number(this._smoothAlignMs.toFixed(1)),isFaceDetected:this.isFaceDetected},this.statsListener&&"function"==typeof this.statsListener)try{this.statsListener(this.pipelineStats)}catch(t){console.warn("statsListener callback error:",t)}if(this.isPaused)return this._waitingForVideoFrame=!1,void setTimeout(()=>this.inferenceLoop(),100);this.videoElement&&!this.videoElement.paused&&"function"==typeof this.videoElement.requestVideoFrameCallback?(null===this._vfcHandle&&this.stream&&this._startVideoFrameProducer(),this._latestVideoFrameSeq!==t?setTimeout(()=>this.inferenceLoop(),0):(this._waitingForVideoFrame=!0,this._vfcWatchdog&&clearTimeout(this._vfcWatchdog),this._vfcWatchdog=setTimeout(()=>{this._vfcWatchdog=null,this._waitingForVideoFrame&&!this.isPaused&&this.stream&&(this._waitingForVideoFrame=!1,this.inferenceLoop())},100))):setTimeout(()=>this.inferenceLoop(),16)}drawOverlay(t){if(!this.showFaceOverlay)return void(this._overlayDrawn&&(this.overlayCanvas.getContext("2d").clearRect(0,0,this.overlayCanvas.width,this.overlayCanvas.height),this._overlayDrawn=!1));const e=this.overlayCanvas.getContext("2d");e.clearRect(0,0,this.overlayCanvas.width,this.overlayCanvas.height),this._overlayDrawn=!0,t&&(e.strokeStyle="green",e.lineWidth=2,e.strokeRect(...t.face),e.strokeStyle="red",e.strokeRect(...t.left),e.strokeRect(...t.right))}renderLoop(){null!==this.targetX&&null!==this.targetY&&(null===this.smoothX&&(this.smoothX=this.targetX),null===this.smoothY&&(this.smoothY=this.targetY),this.smoothX+=.2*(this.targetX-this.smoothX),this.smoothY+=.2*(this.targetY-this.smoothY)),requestAnimationFrame(()=>this.renderLoop())}addCalibrationPoint(t,e,i){return this.collectedFeatures.push(t),this.collectedX.push(e),this.collectedY.push(i),this}trainCalibration(){return 0!==this.collectedFeatures.length&&(this.ridgeCalibrator=new MultivariateRidgeCalibration(this.calibrationPenalty),this.ridgeCalibrator.train(this.collectedFeatures,this.collectedX,this.collectedY),this.isCalibrated=!0,!0)}}const instance=new GazeFollower2;GazeFollower2.register=function(t){return instance.register(t)},GazeFollower2.setSessionManager=function(t){return instance.setSessionManager(t)},GazeFollower2.preflight=function(t){return instance.preflight(t)},GazeFollower2.startCollection=function(){return instance.startCollection()},GazeFollower2.finishSession=function(t){return instance.finishSession(t)},GazeFollower2.setModelName=function(t){return instance.setModelName(t)},GazeFollower2.getModelName=function(){return instance.getModelName()},GazeFollower2.setTrackingArea=function(t){return instance.setTrackingArea(t)},GazeFollower2.getTrackingArea=function(){return instance.getTrackingArea()},GazeFollower2.setCalibrationPenalty=function(t){return instance.setCalibrationPenalty(t)},GazeFollower2.getCalibrationPenalty=function(){return instance.getCalibrationPenalty()},GazeFollower2.startCalibration=function(...t){return instance.startCalibration(...t)},GazeFollower2.begin=function(...t){return instance.begin(...t)},GazeFollower2.end=function(){return instance.end()},GazeFollower2.stop=function(){return instance.stop()},GazeFollower2.pause=function(){return instance.pause()},GazeFollower2.resume=function(){return instance.resume()},GazeFollower2.isReady=function(){return instance.isReady()},GazeFollower2.setGazeListener=function(t){return instance.setGazeListener(t)},GazeFollower2.clearGazeListener=function(){return instance.clearGazeListener()},GazeFollower2.getCurrentPrediction=function(){return instance.getCurrentPrediction()},GazeFollower2.showVideo=function(t){return instance.showVideo(t)},GazeFollower2.showPredictionPoints=function(t){return instance.showPredictionPoints(t)},GazeFollower2.clearData=function(){return instance.clearData()},GazeFollower2.setClickSampleCount=function(t){return instance.setClickSampleCount(t)},GazeFollower2.getClickSampleCount=function(){return instance.getClickSampleCount()},GazeFollower2.setCalibrationSamples=function(t){return instance.setCalibrationSamples(t)},GazeFollower2.setPreClickMs=function(t){return instance.setPreClickMs(t)},GazeFollower2.getPreClickMs=function(){return instance.getPreClickMs()},GazeFollower2.setPostClickDelay=function(t){return instance.setPostClickDelay(t)},GazeFollower2.getPostClickDelay=function(){return instance.getPostClickDelay()},GazeFollower2.triggerCalibrationClick=function(...t){return instance.triggerCalibrationClick(...t)},GazeFollower2.trainCalibration=function(){return instance.trainCalibration()},GazeFollower2.recordScreenPosition=function(...t){return instance.recordScreenPosition(...t)},GazeFollower2.setLookAhead=function(...t){return instance.setLookAhead(...t)},GazeFollower2.setHeuristicFilter=function(...t){return instance.setHeuristicFilter(...t)},GazeFollower2.setOneEuroFilter=function(...t){return instance.setOneEuroFilter(...t)},GazeFollower2.setStatsListener=function(...t){return instance.setStatsListener(...t)},"undefined"!=typeof window&&(window.GazeFollower2=instance,window.GazeSessionManager=GazeSessionManager,window.webgazer=instance,window.particleFX=particleFX,instance.particleFX=particleFX);const GazeFollower=GazeFollower2;export{GazeFollower,GazeFollower2,GazeSessionManager,instance as default};
Binary file
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
- {
1
+ {
2
2
  "name": "@gazefollower/web",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.2.0",
4
+ "description": "GazeFollower2: High-precision client-side webcam eye tracking SDK for modern browsers.",
5
+ "main": "./dist/gazefollower2.min.js",
6
+ "module": "./dist/gazefollower2.min.js",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": "./dist/gazefollower2.min.js",
10
+ "./dist/*": "./dist/*",
11
+ "./models/*": "./models/*"
12
+ },
13
+ "files": [
14
+ "dist/gazefollower2.min.js",
15
+ "dist/gaze_vault.js",
16
+ "dist/gaze_vault.wasm",
17
+ "models/face_landmarker.task",
18
+ "README.md",
19
+ "LICENSE",
20
+ "THIRD_PARTY_NOTICES.txt"
21
+ ],
22
+ "keywords": [
23
+ "eye-tracking",
24
+ "gaze-tracking",
25
+ "gazefollower",
26
+ "gazefollower2",
27
+ "webgazer",
28
+ "webcam"
29
+ ],
30
+ "homepage": "https://gazefollower.com",
31
+ "author": "GazeFollower Team",
32
+ "license": "SEE LICENSE IN LICENSE",
33
+ "publishConfig": {
34
+ "access": "public",
35
+ "registry": "https://registry.npmjs.org/"
36
+ }
37
+ }