@omrips/viewstl 2.0.0-rc.3 → 2.0.0-rc.5

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.
Files changed (43) hide show
  1. package/README.md +19 -170
  2. package/build/{v2/THIRD-PARTY-NOTICES.txt → THIRD-PARTY-NOTICES.txt} +1006 -1006
  3. package/build/{v2/cad → cad}/occt-import-js.source.txt +19 -19
  4. package/build/chunks/archive-JU75RPTU.js +1 -0
  5. package/build/{v2/chunks/cad-VY42CMP4.js → chunks/cad-4JYHORYZ.js} +1 -1
  6. package/build/{v2/chunks/chunk-JH3H3JWA.js → chunks/chunk-OP2L7L4N.js} +1 -1
  7. package/build/{v2/chunks/chunk-ZMK3UZZE.js → chunks/chunk-PQYEV7WH.js} +1 -1
  8. package/build/{v2/chunks/chunk-R3HNTB5A.js → chunks/chunk-Y6VY64LY.js} +1 -1
  9. package/build/{v2/chunks/export-7OP4ZGGJ.js → chunks/export-VM6OQCQJ.js} +3 -3
  10. package/build/{v2/chunks/export-cad-QPBT756V.js → chunks/export-cad-QXCB6UDU.js} +1 -1
  11. package/build/{v2/chunks/export-zip-EDCWH5PX.js → chunks/export-zip-PVXETVLK.js} +1 -1
  12. package/build/{v2/chunks/print-check-2PU7CSL3.js → chunks/print-check-NJ4IONC5.js} +1 -1
  13. package/build/{v2/chunks/scene-export-KQBS7VRJ.js → chunks/scene-export-ZIXMUNLI.js} +1 -1
  14. package/build/chunks/scene-reader-JGHERXR2.js +1 -0
  15. package/build/{v2/node → node}/analysis-worker.js +11 -11
  16. package/build/{v2/node → node}/index.cjs +7 -7
  17. package/build/{v2/node → node}/index.js +6 -6
  18. package/build/stl_viewer.min.js +51 -0
  19. package/build/{v2/viewstl.cjs → viewstl.cjs} +752 -125
  20. package/build/{v2/viewstl.d.cts → viewstl.d.cts} +50 -0
  21. package/build/{v2/viewstl.d.ts → viewstl.d.ts} +50 -0
  22. package/build/{v2/viewstl.js → viewstl.js} +752 -125
  23. package/build/viewstl.min.js +51 -0
  24. package/build/{v2/viewstl.worker.js → viewstl.worker.js} +1 -1
  25. package/docs/releases/2.0.0-rc.5.md +46 -0
  26. package/docs/v2-compatibility.md +5 -5
  27. package/docs/v2-usage.md +128 -21
  28. package/docs/v2-verification.md +158 -0
  29. package/legacy/README.md +14 -8
  30. package/package.json +18 -35
  31. package/build/v2/README.md +0 -15
  32. package/build/v2/chunks/archive-VGS4J4Z7.js +0 -1
  33. package/build/v2/chunks/scene-reader-APUJOPUR.js +0 -1
  34. package/build/v2/stl_viewer.min.js +0 -51
  35. package/build/v2/viewstl.min.js +0 -51
  36. /package/build/{v2/cad → cad}/occt-import-js.js +0 -0
  37. /package/build/{v2/cad → cad}/occt-import-js.wasm +0 -0
  38. /package/build/{v2/cad → cad}/prepare-cad.source.txt +0 -0
  39. /package/build/{v2/chunks/chunk-U33KANV7.js → chunks/chunk-IK3WL53C.js} +0 -0
  40. /package/build/{v2/chunks/chunk-JS56KC3I.js → chunks/chunk-W5KVLGVR.js} +0 -0
  41. /package/build/{v2/chunks → chunks}/chunk-ZSV4PTIA.js +0 -0
  42. /package/build/{v2/node → node}/index.d.cts +0 -0
  43. /package/build/{v2/node → node}/index.d.ts +0 -0
@@ -1,11 +1,11 @@
1
-
2
- var occtimportjs = (() => {
3
- var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;
4
- if (typeof __filename != 'undefined') _scriptName = _scriptName || __filename;
5
- return (
6
- function(moduleArg = {}) {
7
- var moduleRtn;
8
-
1
+
2
+ var occtimportjs = (() => {
3
+ var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;
4
+ if (typeof __filename != 'undefined') _scriptName = _scriptName || __filename;
5
+ return (
6
+ function(moduleArg = {}) {
7
+ var moduleRtn;
8
+
9
9
  var Module=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"&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){}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 readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);var ret=fs.readFileSync(filename);return ret};readAsync=(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);return new Promise((resolve,reject)=>{fs.readFile(filename,binary?undefined:"utf8",(err,data)=>{if(err)reject(err);else resolve(binary?data.buffer:data)})})};if(!Module["thisProgram"]&&process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else 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)}{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=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}return fetch(url,{credentials:"same-origin"}).then(response=>{if(response.ok){return response.arrayBuffer()}return Promise.reject(new Error(response.status+" : "+response.url))})}}}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"];var wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}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(){var preRuns=Module["preRun"];if(preRuns){if(typeof preRuns=="function")preRuns=[preRuns];preRuns.forEach(addOnPreRun)}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();FS.ignorePermissions=false;TTY.init();callRuntimeCallbacks(__ATINIT__)}function postRun(){var postRuns=Module["postRun"];if(postRuns){if(typeof postRuns=="function")postRuns=[postRuns];postRuns.forEach(addOnPostRun)}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;what+=". Build with -sASSERTIONS for more info.";if(runtimeInitialized){___trap()}var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";var isDataURI=filename=>filename.startsWith(dataURIPrefix);var isFileURI=filename=>filename.startsWith("file://");function findWasmBinary(){var f="occt-import-js.wasm";if(!isDataURI(f)){return locateFile(f)}return f}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){return readAsync(binaryFile).then(response=>new Uint8Array(response),()=>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)&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE&&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["_"];updateMemoryViews();wasmTable=wasmExports["ba"];addOnInit(wasmExports["$"]);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)}}wasmBinaryFile??=findWasmBinary();instantiateAsync(wasmBinary,wasmBinaryFile,info,receiveInstantiationResult).catch(readyPromiseReject);return{}}var tempDouble;var tempI64;function ExitStatus(status){this.name="ExitStatus";this.message=`Program terminated with exit(${status})`;this.status=status}var callRuntimeCallbacks=callbacks=>{callbacks.forEach(f=>f(Module))};var noExitRuntime=Module["noExitRuntime"]||true;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 if(ENVIRONMENT_IS_NODE){try{var crypto_module=require("crypto");var randomFillSync=crypto_module["randomFillSync"];if(randomFillSync){return view=>crypto_module["randomFillSync"](view)}var randomBytes=crypto_module["randomBytes"];return view=>(view.set(randomBytes(view.byteLength)),view)}catch(e){}}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:undefined;var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead=NaN)=>{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(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else 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};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));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output&&tty.output.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var zeroMemory=(address,size)=>{HEAPU8.fill(0,address,address+size)};var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var mmapAlloc=size=>{size=alignMemory(size,65536);var ptr=_emscripten_builtin_memalign(65536,size);if(ptr)zeroMemory(ptr,size);return ptr};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",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},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&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var asyncLoad=(url,onload,onerror,noRunDep)=>{var dep=!noRunDep?getUniqueRunDependency(`al ${url}`):"";readAsync(url).then(arrayBuffer=>{onload(new Uint8Array(arrayBuffer));if(dep)removeRunDependency(dep)},err=>{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,readFiles:{},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,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);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);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;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,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(Module["logReadFiles"]&&!(flags&1)){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)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){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)}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(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){[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}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var 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);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{try{obj.contents=readBinary(obj.url);obj.usedBytes=obj.contents.length}catch(e){throw new FS.ErrnoError(29)}}},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}}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,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*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*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*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_chmod(path,mode){try{path=SYSCALLS.getStr(path);FS.chmod(path,mode);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_faccessat(dirfd,path,amode,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(amode&~7){return-28}var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;if(!node){return-44}var perms="";if(amode&4)perms+="r";if(amode&2)perms+="w";if(amode&1)perms+="x";if(perms&&FS.nodePermissions(node,perms)){return-2}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function syscallGetVarargI(){var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret}var syscallGetVarargP=syscallGetVarargI;function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fstat64(fd,buf){try{var stream=SYSCALLS.getStreamFromFD(fd);return SYSCALLS.doStat(FS.stat,stream.path,buf)}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_lstat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.lstat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_newfstatat(dirfd,path,buf,flags){try{path=SYSCALLS.getStr(path);var nofollow=flags&256;var allowEmpty=flags&4096;flags=flags&~6400;path=SYSCALLS.calculateAt(dirfd,path,allowEmpty);return SYSCALLS.doStat(nofollow?FS.lstat:FS.stat,path,buf)}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}}function ___syscall_rmdir(path){try{path=SYSCALLS.getStr(path);FS.rmdir(path);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_stat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.stat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_unlinkat(dirfd,path,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(flags===0){FS.unlink(path)}else if(flags===512){FS.rmdir(path)}else{abort("Invalid flags passed to unlinkat")}return 0}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(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={}){return sharedRegisterType(rawType,registeredInstance,options)}var GenericWireTypeSize=8;var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=readLatin1String(name);registerType(rawType,{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 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}}}};function readPointer(pointer){return this["fromWireType"](HEAPU32[pointer>>2])}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 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,fromWireType:value=>value,toWireType:(destructors,value)=>value,argPackAdvance:GenericWireTypeSize,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var createNamedFunction=(name,body)=>Object.defineProperty(body,"name",{value:name});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}
10
10
  function craftInvokerFunction(humanName, argTypes, classType, invoker, target, isAsync) {
11
11
  if (isAsync || argTypes.length < 2) throw new Error('Unsupported CAD binding');
@@ -44,14 +44,14 @@ var __emval_get_method_caller = (argCount, argTypes, kind) => {
44
44
  if (!retType.isVoid) return emval_returnValue(retType, destructorsRef, result);
45
45
  });
46
46
  };
47
- 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_array=()=>Emval.toHandle([]);var __emval_new_cstring=v=>Emval.toHandle(getStringOrSymbol(v));var __emval_new_object=()=>Emval.toHandle({});var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_set_property=(handle,key,value)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value};var __emval_take_value=(type,arg)=>{type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](arg);return Emval.toHandle(v)};var isLeapYear=year=>year%4===0&&(year%100!==0||year%400===0);var MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335];var MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334];var ydayFromDate=date=>{var leap=isLeapYear(date.getFullYear());var monthDaysCumulative=leap?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE;var yday=monthDaysCumulative[date.getMonth()]+date.getDate()-1;return yday};var convertI32PairToI53Checked=(lo,hi)=>hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN;function __localtime_js(time_low,time_high,tmPtr){var time=convertI32PairToI53Checked(time_low,time_high);var date=new Date(time*1e3);HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getDay();var yday=ydayFromDate(date)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr+36>>2]=-(date.getTimezoneOffset()*60);var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dst=(summerOffset!=winterOffset&&date.getTimezoneOffset()==Math.min(winterOffset,summerOffset))|0;HEAP32[tmPtr+32>>2]=dst}function __munmap_js(addr,len,prot,flags,fd,offset_low,offset_high){var offset=convertI32PairToI53Checked(offset_low,offset_high);try{var stream=SYSCALLS.getStreamFromFD(fd);if(prot&2){SYSCALLS.doMsync(addr,stream,len,flags,offset)}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var _emscripten_date_now=()=>Date.now();function jsStackTrace(){return(new Error).stack.toString()}var warnOnce=text=>{warnOnce.shown||={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;if(ENVIRONMENT_IS_NODE)text="warning: "+text;err(text)}};function getCallstack(flags){var callstack=jsStackTrace();var iThisFunc=callstack.lastIndexOf("_emscripten_log");var iThisFunc2=callstack.lastIndexOf("_emscripten_get_callstack");var iNextLine=callstack.indexOf("\n",Math.max(iThisFunc,iThisFunc2))+1;callstack=callstack.slice(iNextLine);if(flags&8&&typeof emscripten_source_map=="undefined"){warnOnce('Source map information is not available, emscripten_log with EM_LOG_C_STACK will be ignored. Build with "--pre-js $EMSCRIPTEN/src/emscripten-source-map.min.js" linker flag to add source map loading to code.');flags^=8;flags|=16}var lines=callstack.split("\n");callstack="";var newFirefoxRe=new RegExp("\\s*(.*?)@(.*?):([0-9]+):([0-9]+)");var firefoxRe=new RegExp("\\s*(.*?)@(.*):(.*)(:(.*))?");var chromeRe=new RegExp("\\s*at (.*?) \\((.*):(.*):(.*)\\)");for(var l in lines){var line=lines[l];var symbolName="";var file="";var lineno=0;var column=0;var parts=chromeRe.exec(line);if(parts&&parts.length==5){symbolName=parts[1];file=parts[2];lineno=parts[3];column=parts[4]}else{parts=newFirefoxRe.exec(line)||firefoxRe.exec(line);if(parts&&parts.length>=4){symbolName=parts[1];file=parts[2];lineno=parts[3];column=parts[4]|0}else{callstack+=line+"\n";continue}}var haveSourceMap=false;if(flags&8){var orig=emscripten_source_map.originalPositionFor({line:lineno,column});haveSourceMap=orig?.source;if(haveSourceMap){if(flags&64){orig.source=orig.source.substring(orig.source.replace(/\\/g,"/").lastIndexOf("/")+1)}callstack+=` at ${symbolName} (${orig.source}:${orig.line}:${orig.column})\n`}}if(flags&16||!haveSourceMap){if(flags&64){file=file.substring(file.replace(/\\/g,"/").lastIndexOf("/")+1)}callstack+=(haveSourceMap?` = ${symbolName}`:` at ${symbolName}`)+` (${file}:${lineno}:${column})\n`}}callstack=callstack.replace(/\s+$/,"");return callstack}function _emscripten_get_callstack(flags,str,maxbytes){var callstack=getCallstack(flags);if(!str||maxbytes<=0){return lengthBytesUTF8(callstack)+1}var bytesWrittenExcludingNull=stringToUTF8(callstack,str,maxbytes);return bytesWrittenExcludingNull+1}var getHeapMax=()=>Math.min(2147483648,Module["viewstlMaxHeapBytes"]||2147483648);var _emscripten_get_heap_max=()=>getHeapMax();var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(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};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}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}}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(curr<len){break}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}}FS.createPreloadedFile=FS_createPreloadedFile;FS.staticInit();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_emval();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");var wasmImports={M:___syscall_chmod,N:___syscall_faccessat,h:___syscall_fcntl64,I:___syscall_fstat64,Q:___syscall_ioctl,F:___syscall_lstat64,G:___syscall_newfstatat,j:___syscall_openat,B:___syscall_rmdir,H:___syscall_stat64,C:___syscall_unlinkat,A:__abort_js,w:__embind_register_bigint,V:__embind_register_bool,U:__embind_register_emval,n:__embind_register_float,f:__embind_register_function,b:__embind_register_integer,a:__embind_register_memory_view,m:__embind_register_std_string,i:__embind_register_std_wstring,W:__embind_register_void,J:__emscripten_get_now_is_monotonic,x:__emscripten_lookup_name,L:__emscripten_memcpy_js,e:__emval_as,q:__emval_call_method,T:__emval_decref,u:__emval_get_global,p:__emval_get_method_caller,k:__emval_get_property,Y:__emval_incref,X:__emval_new_array,r:__emval_new_cstring,Z:__emval_new_object,o:__emval_run_destructors,c:__emval_set_property,d:__emval_take_value,t:__localtime_js,s:__munmap_js,O:__tzset_js,K:_emscripten_date_now,R:_emscripten_get_callstack,z:_emscripten_get_heap_max,y:_emscripten_resize_heap,D:_environ_get,E:_environ_sizes_get,S:_exit,g:_fd_close,P:_fd_read,v:_fd_seek,l:_fd_write};var wasmExports=createWasm();var ___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports["$"])();var ___getTypeName=a0=>(___getTypeName=wasmExports["aa"])(a0);var _malloc=a0=>(_malloc=wasmExports["ca"])(a0);var _free=a0=>(_free=wasmExports["da"])(a0);var _htons=a0=>(_htons=wasmExports["ea"])(a0);var _emscripten_builtin_memalign=(a0,a1)=>(_emscripten_builtin_memalign=wasmExports["fa"])(a0,a1);var ___trap=()=>(___trap=wasmExports["ga"])();var dynCall_viijii=Module["dynCall_viijii"]=(a0,a1,a2,a3,a4,a5,a6)=>(dynCall_viijii=Module["dynCall_viijii"]=wasmExports["ha"])(a0,a1,a2,a3,a4,a5,a6);var dynCall_viiiiji=Module["dynCall_viiiiji"]=(a0,a1,a2,a3,a4,a5,a6,a7)=>(dynCall_viiiiji=Module["dynCall_viiiiji"]=wasmExports["ia"])(a0,a1,a2,a3,a4,a5,a6,a7);var dynCall_jiji=Module["dynCall_jiji"]=(a0,a1,a2,a3,a4)=>(dynCall_jiji=Module["dynCall_jiji"]=wasmExports["ja"])(a0,a1,a2,a3,a4);var dynCall_iiiiij=Module["dynCall_iiiiij"]=(a0,a1,a2,a3,a4,a5,a6)=>(dynCall_iiiiij=Module["dynCall_iiiiij"]=wasmExports["ka"])(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["la"])(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["ma"])(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9);var calledRun;var calledPrerun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(){if(runDependencies>0){return}if(!calledPrerun){calledPrerun=1;preRun();if(runDependencies>0){return}}function doRun(){if(calledRun)return;calledRun=1;Module["calledRun"]=1;if(ABORT)return;initRuntime();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>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;
48
-
49
-
50
- return moduleRtn;
51
- }
52
- );
53
- })();
54
- if (typeof exports === 'object' && typeof module === 'object')
55
- module.exports = occtimportjs;
56
- else if (typeof define === 'function' && define['amd'])
57
- define([], () => occtimportjs);
47
+ 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_array=()=>Emval.toHandle([]);var __emval_new_cstring=v=>Emval.toHandle(getStringOrSymbol(v));var __emval_new_object=()=>Emval.toHandle({});var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_set_property=(handle,key,value)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value};var __emval_take_value=(type,arg)=>{type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](arg);return Emval.toHandle(v)};var isLeapYear=year=>year%4===0&&(year%100!==0||year%400===0);var MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335];var MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334];var ydayFromDate=date=>{var leap=isLeapYear(date.getFullYear());var monthDaysCumulative=leap?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE;var yday=monthDaysCumulative[date.getMonth()]+date.getDate()-1;return yday};var convertI32PairToI53Checked=(lo,hi)=>hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN;function __localtime_js(time_low,time_high,tmPtr){var time=convertI32PairToI53Checked(time_low,time_high);var date=new Date(time*1e3);HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getDay();var yday=ydayFromDate(date)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr+36>>2]=-(date.getTimezoneOffset()*60);var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dst=(summerOffset!=winterOffset&&date.getTimezoneOffset()==Math.min(winterOffset,summerOffset))|0;HEAP32[tmPtr+32>>2]=dst}function __munmap_js(addr,len,prot,flags,fd,offset_low,offset_high){var offset=convertI32PairToI53Checked(offset_low,offset_high);try{var stream=SYSCALLS.getStreamFromFD(fd);if(prot&2){SYSCALLS.doMsync(addr,stream,len,flags,offset)}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var _emscripten_date_now=()=>Date.now();function jsStackTrace(){return(new Error).stack.toString()}var warnOnce=text=>{warnOnce.shown||={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;if(ENVIRONMENT_IS_NODE)text="warning: "+text;err(text)}};function getCallstack(flags){var callstack=jsStackTrace();var iThisFunc=callstack.lastIndexOf("_emscripten_log");var iThisFunc2=callstack.lastIndexOf("_emscripten_get_callstack");var iNextLine=callstack.indexOf("\n",Math.max(iThisFunc,iThisFunc2))+1;callstack=callstack.slice(iNextLine);if(flags&8&&typeof emscripten_source_map=="undefined"){warnOnce('Source map information is not available, emscripten_log with EM_LOG_C_STACK will be ignored. Build with "--pre-js $EMSCRIPTEN/src/emscripten-source-map.min.js" linker flag to add source map loading to code.');flags^=8;flags|=16}var lines=callstack.split("\n");callstack="";var newFirefoxRe=new RegExp("\\s*(.*?)@(.*?):([0-9]+):([0-9]+)");var firefoxRe=new RegExp("\\s*(.*?)@(.*):(.*)(:(.*))?");var chromeRe=new RegExp("\\s*at (.*?) \\((.*):(.*):(.*)\\)");for(var l in lines){var line=lines[l];var symbolName="";var file="";var lineno=0;var column=0;var parts=chromeRe.exec(line);if(parts&&parts.length==5){symbolName=parts[1];file=parts[2];lineno=parts[3];column=parts[4]}else{parts=newFirefoxRe.exec(line)||firefoxRe.exec(line);if(parts&&parts.length>=4){symbolName=parts[1];file=parts[2];lineno=parts[3];column=parts[4]|0}else{callstack+=line+"\n";continue}}var haveSourceMap=false;if(flags&8){var orig=emscripten_source_map.originalPositionFor({line:lineno,column});haveSourceMap=orig?.source;if(haveSourceMap){if(flags&64){orig.source=orig.source.substring(orig.source.replace(/\\/g,"/").lastIndexOf("/")+1)}callstack+=` at ${symbolName} (${orig.source}:${orig.line}:${orig.column})\n`}}if(flags&16||!haveSourceMap){if(flags&64){file=file.substring(file.replace(/\\/g,"/").lastIndexOf("/")+1)}callstack+=(haveSourceMap?` = ${symbolName}`:` at ${symbolName}`)+` (${file}:${lineno}:${column})\n`}}callstack=callstack.replace(/\s+$/,"");return callstack}function _emscripten_get_callstack(flags,str,maxbytes){var callstack=getCallstack(flags);if(!str||maxbytes<=0){return lengthBytesUTF8(callstack)+1}var bytesWrittenExcludingNull=stringToUTF8(callstack,str,maxbytes);return bytesWrittenExcludingNull+1}var getHeapMax=()=>Math.min(2147483648,Module["viewstlMaxHeapBytes"]||2147483648);var _emscripten_get_heap_max=()=>getHeapMax();var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(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};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}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}}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(curr<len){break}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}}FS.createPreloadedFile=FS_createPreloadedFile;FS.staticInit();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_emval();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");var wasmImports={M:___syscall_chmod,N:___syscall_faccessat,h:___syscall_fcntl64,I:___syscall_fstat64,Q:___syscall_ioctl,F:___syscall_lstat64,G:___syscall_newfstatat,j:___syscall_openat,B:___syscall_rmdir,H:___syscall_stat64,C:___syscall_unlinkat,A:__abort_js,w:__embind_register_bigint,V:__embind_register_bool,U:__embind_register_emval,n:__embind_register_float,f:__embind_register_function,b:__embind_register_integer,a:__embind_register_memory_view,m:__embind_register_std_string,i:__embind_register_std_wstring,W:__embind_register_void,J:__emscripten_get_now_is_monotonic,x:__emscripten_lookup_name,L:__emscripten_memcpy_js,e:__emval_as,q:__emval_call_method,T:__emval_decref,u:__emval_get_global,p:__emval_get_method_caller,k:__emval_get_property,Y:__emval_incref,X:__emval_new_array,r:__emval_new_cstring,Z:__emval_new_object,o:__emval_run_destructors,c:__emval_set_property,d:__emval_take_value,t:__localtime_js,s:__munmap_js,O:__tzset_js,K:_emscripten_date_now,R:_emscripten_get_callstack,z:_emscripten_get_heap_max,y:_emscripten_resize_heap,D:_environ_get,E:_environ_sizes_get,S:_exit,g:_fd_close,P:_fd_read,v:_fd_seek,l:_fd_write};var wasmExports=createWasm();var ___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports["$"])();var ___getTypeName=a0=>(___getTypeName=wasmExports["aa"])(a0);var _malloc=a0=>(_malloc=wasmExports["ca"])(a0);var _free=a0=>(_free=wasmExports["da"])(a0);var _htons=a0=>(_htons=wasmExports["ea"])(a0);var _emscripten_builtin_memalign=(a0,a1)=>(_emscripten_builtin_memalign=wasmExports["fa"])(a0,a1);var ___trap=()=>(___trap=wasmExports["ga"])();var dynCall_viijii=Module["dynCall_viijii"]=(a0,a1,a2,a3,a4,a5,a6)=>(dynCall_viijii=Module["dynCall_viijii"]=wasmExports["ha"])(a0,a1,a2,a3,a4,a5,a6);var dynCall_viiiiji=Module["dynCall_viiiiji"]=(a0,a1,a2,a3,a4,a5,a6,a7)=>(dynCall_viiiiji=Module["dynCall_viiiiji"]=wasmExports["ia"])(a0,a1,a2,a3,a4,a5,a6,a7);var dynCall_jiji=Module["dynCall_jiji"]=(a0,a1,a2,a3,a4)=>(dynCall_jiji=Module["dynCall_jiji"]=wasmExports["ja"])(a0,a1,a2,a3,a4);var dynCall_iiiiij=Module["dynCall_iiiiij"]=(a0,a1,a2,a3,a4,a5,a6)=>(dynCall_iiiiij=Module["dynCall_iiiiij"]=wasmExports["ka"])(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["la"])(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["ma"])(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9);var calledRun;var calledPrerun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(){if(runDependencies>0){return}if(!calledPrerun){calledPrerun=1;preRun();if(runDependencies>0){return}}function doRun(){if(calledRun)return;calledRun=1;Module["calledRun"]=1;if(ABORT)return;initRuntime();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>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;
48
+
49
+
50
+ return moduleRtn;
51
+ }
52
+ );
53
+ })();
54
+ if (typeof exports === 'object' && typeof module === 'object')
55
+ module.exports = occtimportjs;
56
+ else if (typeof define === 'function' && define['amd'])
57
+ define([], () => occtimportjs);
@@ -0,0 +1 @@
1
+ import{a,b,c,d}from"./chunk-Y6VY64LY.js";import"./chunk-ZSV4PTIA.js";import"./chunk-OP2L7L4N.js";import"./chunk-W5KVLGVR.js";import"./chunk-IK3WL53C.js";export{d as parse3MF,a as safePath,b as unzipChecked,c as zipScene};
@@ -1 +1 @@
1
- import{a as A,c as E}from"./chunk-JH3H3JWA.js";import{a as w}from"./chunk-JS56KC3I.js";import"./chunk-U33KANV7.js";var u=128*1024**2;function D(t){return u+t*40}async function x(t){let{default:s}=await import(new URL("../cad/occt-import-js.js",import.meta.url).href);return s({...t,locateFile:()=>new URL("../cad/occt-import-js.wasm",import.meta.url).href})}function C(t,s=A,c=0){if(!t?.success||!Array.isArray(t.meshes)||!t.meshes.length)throw new Error("No supported surfaces were found in this CAD file. Export a self-contained STEP or IGES solid/surface model.");let n=0,m=0,f=!1;for(let r of t.meshes){let a=r.attributes?.position?.array,o=r.index?.array;if(!a?.length||a.length%3||!o||o.length%3)throw new Error("Invalid CAD mesh");if(n+=o.length/3,!Number.isSafeInteger(n)||n>s.max_triangles)throw new Error("Triangle limit exceeded");m+=(a.length+o.length+(r.attributes.normal?.array?.length||0))*16,f||=!!r.color||!!r.brep_faces?.some(e=>e.color)}if(!n)throw new Error("This CAD file contains no viewable surfaces.");w(s,c+m+n*224,"CAD model");let h=new Float32Array(n*9),l=f?new Float32Array(h.length):null,d=[144/255,144/255,144/255],i=0;function y(r,a,o){if(!r||r.length!==3||r.some(e=>!Number.isFinite(e)||e<0||e>1))throw new Error("Invalid CAD color");for(let e=a;e<o;e+=3)l.set(r,e)}for(let r of t.meshes){let a=r.attributes.position.array,o=r.index.array;for(let e=0;e<o.length;e++){let g=o[e];if(!Number.isSafeInteger(g)||g<0||g*3+2>=a.length)throw new Error("Invalid CAD triangle index");for(let p=0;p<3;p++)h[i+e*3+p]=a[g*3+p]}if(l){y(r.color||d,i,i+o.length*3);for(let e of r.brep_faces||[])if(e.color){if(!Number.isSafeInteger(e.first)||!Number.isSafeInteger(e.last)||e.first<0||e.last<e.first||e.last>=o.length/3)throw new Error("Invalid CAD face range");y(e.color,i+e.first*9,i+(e.last+1)*9)}}i+=o.length*3}return E(h,l,s)}async function L(t,s,c=A,n=()=>{},m=x){let f=/\.(step|stp|iges|igs)(?:[?#]|$)/i.exec(s)?.[1].toLowerCase();if(!f)throw new Error("Unsupported CAD format");if(!(t instanceof ArrayBuffer)||!t.byteLength||t.byteLength>c.max_file_bytes)throw new Error("Invalid or oversized CAD file");w(c,D(t.byteLength),"CAD file");let h=Math.floor(Math.min(512*1024**2,((c.max_memory_bytes??Number.MAX_SAFE_INTEGER)-u-t.byteLength*3)/2)/65536)*65536;if(h<32*1024**2)throw new Error("CAD import exceeds the device safety budget.");n("loading-cad");let l;try{l=await m({viewstlMaxHeapBytes:h,print(){},printErr(){}})}catch{throw new Error("The CAD reader could not start. Check the connection and that WebAssembly is allowed, then try again.")}n("parsing-cad");let d=/^(step|stp)$/.test(f)?"step":"iges",i;try{i=l[d==="step"?"ReadStepFile":"ReadIgesFile"](new Uint8Array(t),{linearUnit:"millimeter",linearDeflectionType:"bounding_box_ratio",linearDeflection:.001,angularDeflection:.5})}catch{throw new Error("This CAD file could not be processed within the reader limits. Try a smaller or simplified STEP/IGES export.")}return{...C(i,c,u+t.byteLength*3+l.HEAPU8.byteLength),format:d,units:"mm"}}export{u as CAD_OVERHEAD,C as cadGeometry,D as cadMemory,L as parseCAD};
1
+ import{a as A,c as E}from"./chunk-OP2L7L4N.js";import{a as w}from"./chunk-W5KVLGVR.js";import"./chunk-IK3WL53C.js";var u=128*1024**2;function D(t){return u+t*40}async function x(t){let{default:s}=await import(new URL("../cad/occt-import-js.js",import.meta.url).href);return s({...t,locateFile:()=>new URL("../cad/occt-import-js.wasm",import.meta.url).href})}function C(t,s=A,c=0){if(!t?.success||!Array.isArray(t.meshes)||!t.meshes.length)throw new Error("No supported surfaces were found in this CAD file. Export a self-contained STEP or IGES solid/surface model.");let n=0,m=0,f=!1;for(let r of t.meshes){let a=r.attributes?.position?.array,o=r.index?.array;if(!a?.length||a.length%3||!o||o.length%3)throw new Error("Invalid CAD mesh");if(n+=o.length/3,!Number.isSafeInteger(n)||n>s.max_triangles)throw new Error("Triangle limit exceeded");m+=(a.length+o.length+(r.attributes.normal?.array?.length||0))*16,f||=!!r.color||!!r.brep_faces?.some(e=>e.color)}if(!n)throw new Error("This CAD file contains no viewable surfaces.");w(s,c+m+n*224,"CAD model");let h=new Float32Array(n*9),l=f?new Float32Array(h.length):null,d=[144/255,144/255,144/255],i=0;function y(r,a,o){if(!r||r.length!==3||r.some(e=>!Number.isFinite(e)||e<0||e>1))throw new Error("Invalid CAD color");for(let e=a;e<o;e+=3)l.set(r,e)}for(let r of t.meshes){let a=r.attributes.position.array,o=r.index.array;for(let e=0;e<o.length;e++){let g=o[e];if(!Number.isSafeInteger(g)||g<0||g*3+2>=a.length)throw new Error("Invalid CAD triangle index");for(let p=0;p<3;p++)h[i+e*3+p]=a[g*3+p]}if(l){y(r.color||d,i,i+o.length*3);for(let e of r.brep_faces||[])if(e.color){if(!Number.isSafeInteger(e.first)||!Number.isSafeInteger(e.last)||e.first<0||e.last<e.first||e.last>=o.length/3)throw new Error("Invalid CAD face range");y(e.color,i+e.first*9,i+(e.last+1)*9)}}i+=o.length*3}return E(h,l,s)}async function L(t,s,c=A,n=()=>{},m=x){let f=/\.(step|stp|iges|igs)(?:[?#]|$)/i.exec(s)?.[1].toLowerCase();if(!f)throw new Error("Unsupported CAD format");if(!(t instanceof ArrayBuffer)||!t.byteLength||t.byteLength>c.max_file_bytes)throw new Error("Invalid or oversized CAD file");w(c,D(t.byteLength),"CAD file");let h=Math.floor(Math.min(512*1024**2,((c.max_memory_bytes??Number.MAX_SAFE_INTEGER)-u-t.byteLength*3)/2)/65536)*65536;if(h<32*1024**2)throw new Error("CAD import exceeds the device safety budget.");n("loading-cad");let l;try{l=await m({viewstlMaxHeapBytes:h,print(){},printErr(){}})}catch{throw new Error("The CAD reader could not start. Check the connection and that WebAssembly is allowed, then try again.")}n("parsing-cad");let d=/^(step|stp)$/.test(f)?"step":"iges",i;try{i=l[d==="step"?"ReadStepFile":"ReadIgesFile"](new Uint8Array(t),{linearUnit:"millimeter",linearDeflectionType:"bounding_box_ratio",linearDeflection:.001,angularDeflection:.5})}catch{throw new Error("This CAD file could not be processed within the reader limits. Try a smaller or simplified STEP/IGES export.")}return{...C(i,c,u+t.byteLength*3+l.HEAPU8.byteLength),format:d,units:"mm"}}export{u as CAD_OVERHEAD,C as cadGeometry,D as cadMemory,L as parseCAD};
@@ -1 +1 @@
1
- import{a as k}from"./chunk-JS56KC3I.js";var z=Object.freeze({max_file_bytes:256*1024*1024,max_triangles:5e6,max_uncompressed_bytes:256*1024*1024,max_archive_entries:1024,max_memory_bytes:Number.MAX_SAFE_INTEGER});function O(e){if(typeof e!="string"||!/^#[\da-f]{6}$/i.test(e))throw new Error("Color must be #RRGGBB");return[1,3,5].map(i=>parseInt(e.slice(i,i+2),16)/255)}function U(e,i=null,I=z){if(!(e instanceof Float32Array)||!e.length||e.length%9)throw new Error("Geometry must contain complete triangles");if(e.length/9>I.max_triangles)throw new Error("Triangle limit exceeded");if(k(I,67108864+e.length/9*224),i&&(!(i instanceof Float32Array)||i.length!==e.length))throw new Error("Invalid vertex colors");let u={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]};for(let r=0;r<e.length;r++){let f=e[r],t=r%3;if(!Number.isFinite(f))throw new Error("Non-finite vertex coordinate");if(u.min[t]=Math.min(u.min[t],f),u.max[t]=Math.max(u.max[t],f),i&&(!Number.isFinite(i[r])||i[r]<0||i[r]>1))throw new Error("Invalid vertex color")}let y=new Float32Array(e.length),b=new Float32Array(Math.ceil(e.length/9/64)*6),h=0,s=0,l=0;for(let r=0;r<e.length;r+=9){let f=e[r+3]-e[r],t=e[r+4]-e[r+1],c=e[r+5]-e[r+2],n=e[r+6]-e[r],o=e[r+7]-e[r+1],x=e[r+8]-e[r+2],w=t*x-c*o,M=c*n-f*x,g=f*o-t*n,E=Math.hypot(w,M,g);h+=E/2,s+=(e[r]*w+e[r+1]*M+e[r+2]*g)/6,E||l++;for(let a=0;a<9;a+=3)y[r+a]=w/(E||1),y[r+a+1]=M/(E||1),y[r+a+2]=g/(E||1);let m=Math.floor(r/9/64)*6;r/9%64===0&&b.set([1/0,1/0,1/0,-1/0,-1/0,-1/0],m);for(let a=0;a<9;a++){let d=a%3;b[m+d]=Math.min(b[m+d],e[r+a]),b[m+3+d]=Math.max(b[m+3+d],e[r+a])}}if(!Number.isFinite(h)||!Number.isFinite(s))throw new Error("Geometry magnitude exceeds numeric limits");return{positions:e,normals:y,colors:i,blocks:b,bounds:u,triangles:e.length/9,area:h,volume:Math.abs(s),degenerateTriangles:l}}function j(e,{smooth:i=!1,edges:I=!1,wire:u=!1,edgeAngle:y=1}={}){let b=new Map,h=new Uint32Array(e.length/3),s=[],l=[];for(let t=0;t<e.length;t+=3){let c=`${e[t]},${e[t+1]},${e[t+2]}`,n=b.get(c);n===void 0&&(n=s.length,b.set(c,n),s.push([e[t],e[t+1],e[t+2]]),l.push([0,0,0])),h[t/3]=n}let r=new Map;for(let t=0;t<e.length;t+=9){let c=e[t+3]-e[t],n=e[t+4]-e[t+1],o=e[t+5]-e[t+2],x=e[t+6]-e[t],w=e[t+7]-e[t+1],M=e[t+8]-e[t+2],g=[n*M-o*w,o*x-c*M,c*w-n*x],E=Math.hypot(...g)||1;for(let m=0;m<3;m++)if(i)for(let a=0;a<3;a++)l[h[t/3+m]][a]+=g[a];if(I||u)for(let m=0;m<3;m++){let a=h[t/3+m],d=h[t/3+(m+1)%3],A=a<d?`${a}:${d}`:`${d}:${a}`,F=g.map(v=>v/E),_=r.get(A);_?(_.count++,_.n.reduce((v,N,T)=>v+N*F[T],0)<Math.cos(y*Math.PI/180)&&(_.sharp=!0)):r.set(A,{a,b:d,n:F,count:1,sharp:!1})}}let f={};if(i){f.smoothNormals=new Float32Array(e.length);for(let t=0;t<h.length;t++){let c=l[h[t]],n=Math.hypot(...c)||1;f.smoothNormals.set(c.map(o=>o/n),t*3)}}for(let[t,c,n]of[[I,"edges",o=>o.count!==2||o.sharp],[u,"wire",()=>!0]])if(t){let o=[...r.values()].filter(n),x=new Float32Array(o.length*6);o.forEach((w,M)=>{x.set(s[w.a],M*6),x.set(s[w.b],M*6+3)}),f[c]=x,c==="edges"&&(f.edgeAngle=y)}return f}function D(e,i=[1,1,1],I=[0,0,0]){let u=new ArrayBuffer(84+e.triangles*50),y=new DataView(u),b=e.positions;new Uint8Array(u).set(new TextEncoder().encode("Binary STL by ViewSTL 2")),y.setUint32(80,e.triangles,!0);for(let h=0;h<e.triangles;h++){let s=84+h*50,l=Array.from({length:9},(n,o)=>(b[h*9+o]-I[o%3])*i[o%3]),r=[l[3]-l[0],l[4]-l[1],l[5]-l[2]],f=[l[6]-l[0],l[7]-l[1],l[8]-l[2]],t=[r[1]*f[2]-r[2]*f[1],r[2]*f[0]-r[0]*f[2],r[0]*f[1]-r[1]*f[0]],c=Math.hypot(...t)||1;for(let n=0;n<3;n++)y.setFloat32(s+n*4,t[n]/c,!0);for(let n=0;n<9;n++)y.setFloat32(s+12+n*4,l[n],!0);if(e.colors){let n=[0,1,2].map(o=>Math.round(e.colors[h*9+o]*31));y.setUint16(s+48,32768|n[0]<<10|n[1]<<5|n[2],!0)}}return u}export{z as a,O as b,U as c,j as d,D as e};
1
+ import{a as k}from"./chunk-W5KVLGVR.js";var z=Object.freeze({max_file_bytes:256*1024*1024,max_triangles:5e6,max_uncompressed_bytes:256*1024*1024,max_archive_entries:1024,max_memory_bytes:Number.MAX_SAFE_INTEGER});function O(e){if(typeof e!="string"||!/^#[\da-f]{6}$/i.test(e))throw new Error("Color must be #RRGGBB");return[1,3,5].map(i=>parseInt(e.slice(i,i+2),16)/255)}function U(e,i=null,I=z){if(!(e instanceof Float32Array)||!e.length||e.length%9)throw new Error("Geometry must contain complete triangles");if(e.length/9>I.max_triangles)throw new Error("Triangle limit exceeded");if(k(I,67108864+e.length/9*224),i&&(!(i instanceof Float32Array)||i.length!==e.length))throw new Error("Invalid vertex colors");let u={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]};for(let r=0;r<e.length;r++){let f=e[r],t=r%3;if(!Number.isFinite(f))throw new Error("Non-finite vertex coordinate");if(u.min[t]=Math.min(u.min[t],f),u.max[t]=Math.max(u.max[t],f),i&&(!Number.isFinite(i[r])||i[r]<0||i[r]>1))throw new Error("Invalid vertex color")}let y=new Float32Array(e.length),b=new Float32Array(Math.ceil(e.length/9/64)*6),h=0,s=0,l=0;for(let r=0;r<e.length;r+=9){let f=e[r+3]-e[r],t=e[r+4]-e[r+1],c=e[r+5]-e[r+2],n=e[r+6]-e[r],o=e[r+7]-e[r+1],x=e[r+8]-e[r+2],w=t*x-c*o,M=c*n-f*x,g=f*o-t*n,E=Math.hypot(w,M,g);h+=E/2,s+=(e[r]*w+e[r+1]*M+e[r+2]*g)/6,E||l++;for(let a=0;a<9;a+=3)y[r+a]=w/(E||1),y[r+a+1]=M/(E||1),y[r+a+2]=g/(E||1);let m=Math.floor(r/9/64)*6;r/9%64===0&&b.set([1/0,1/0,1/0,-1/0,-1/0,-1/0],m);for(let a=0;a<9;a++){let d=a%3;b[m+d]=Math.min(b[m+d],e[r+a]),b[m+3+d]=Math.max(b[m+3+d],e[r+a])}}if(!Number.isFinite(h)||!Number.isFinite(s))throw new Error("Geometry magnitude exceeds numeric limits");return{positions:e,normals:y,colors:i,blocks:b,bounds:u,triangles:e.length/9,area:h,volume:Math.abs(s),degenerateTriangles:l}}function j(e,{smooth:i=!1,edges:I=!1,wire:u=!1,edgeAngle:y=1}={}){let b=new Map,h=new Uint32Array(e.length/3),s=[],l=[];for(let t=0;t<e.length;t+=3){let c=`${e[t]},${e[t+1]},${e[t+2]}`,n=b.get(c);n===void 0&&(n=s.length,b.set(c,n),s.push([e[t],e[t+1],e[t+2]]),l.push([0,0,0])),h[t/3]=n}let r=new Map;for(let t=0;t<e.length;t+=9){let c=e[t+3]-e[t],n=e[t+4]-e[t+1],o=e[t+5]-e[t+2],x=e[t+6]-e[t],w=e[t+7]-e[t+1],M=e[t+8]-e[t+2],g=[n*M-o*w,o*x-c*M,c*w-n*x],E=Math.hypot(...g)||1;for(let m=0;m<3;m++)if(i)for(let a=0;a<3;a++)l[h[t/3+m]][a]+=g[a];if(I||u)for(let m=0;m<3;m++){let a=h[t/3+m],d=h[t/3+(m+1)%3],A=a<d?`${a}:${d}`:`${d}:${a}`,F=g.map(v=>v/E),_=r.get(A);_?(_.count++,_.n.reduce((v,N,T)=>v+N*F[T],0)<Math.cos(y*Math.PI/180)&&(_.sharp=!0)):r.set(A,{a,b:d,n:F,count:1,sharp:!1})}}let f={};if(i){f.smoothNormals=new Float32Array(e.length);for(let t=0;t<h.length;t++){let c=l[h[t]],n=Math.hypot(...c)||1;f.smoothNormals.set(c.map(o=>o/n),t*3)}}for(let[t,c,n]of[[I,"edges",o=>o.count!==2||o.sharp],[u,"wire",()=>!0]])if(t){let o=[...r.values()].filter(n),x=new Float32Array(o.length*6);o.forEach((w,M)=>{x.set(s[w.a],M*6),x.set(s[w.b],M*6+3)}),f[c]=x,c==="edges"&&(f.edgeAngle=y)}return f}function D(e,i=[1,1,1],I=[0,0,0]){let u=new ArrayBuffer(84+e.triangles*50),y=new DataView(u),b=e.positions;new Uint8Array(u).set(new TextEncoder().encode("Binary STL by ViewSTL 2")),y.setUint32(80,e.triangles,!0);for(let h=0;h<e.triangles;h++){let s=84+h*50,l=Array.from({length:9},(n,o)=>(b[h*9+o]-I[o%3])*i[o%3]),r=[l[3]-l[0],l[4]-l[1],l[5]-l[2]],f=[l[6]-l[0],l[7]-l[1],l[8]-l[2]],t=[r[1]*f[2]-r[2]*f[1],r[2]*f[0]-r[0]*f[2],r[0]*f[1]-r[1]*f[0]],c=Math.hypot(...t)||1;for(let n=0;n<3;n++)y.setFloat32(s+n*4,t[n]/c,!0);for(let n=0;n<9;n++)y.setFloat32(s+12+n*4,l[n],!0);if(e.colors){let n=[0,1,2].map(o=>Math.round(e.colors[h*9+o]*31));y.setUint16(s+48,32768|n[0]<<10|n[1]<<5|n[2],!0)}}return u}export{z as a,O as b,U as c,j as d,D as e};
@@ -1 +1 @@
1
- import{c as p,d as c,e as x,h as d}from"./chunk-U33KANV7.js";var u=r=>{if(!Number.isFinite(r))throw new Error("Non-finite export coordinate");return Object.is(r,-0)?"0":String(r)},b=r=>String(r).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"").replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"})[t]),m=class{constructor(t){this.limit=t,this.bytes=0}add(t){if(this.bytes+=t,this.bytes>this.limit)throw new Error("Export size limit exceeded")}},g=class{constructor(t){this.budget=t,this.parts=[],this.pending=""}write(t){this.pending+=t,this.pending.length>=32768&&this.flush()}flush(){if(!this.pending)return;let t=new TextEncoder().encode(this.pending);this.budget.add(t.byteLength),this.parts.push(t),this.pending=""}finish(){return this.flush(),this.parts}};function f(r,t){let i=r.positions,e=r.matrix,n=[0,3,6].map(o=>d(e,[i[t+o],i[t+o+1],i[t+o+2]]));if(n.flat().some(o=>!Number.isFinite(o)))throw new Error("Non-finite export coordinate");let a=e[0]*(e[5]*e[10]-e[9]*e[6])-e[4]*(e[1]*e[10]-e[9]*e[2])+e[8]*(e[1]*e[6]-e[5]*e[2]);a<0&&([n[1],n[2]]=[n[2],n[1]]);let s=c(p(n[1],n[0]),p(n[2],n[0]));if(!Number.isFinite(Math.hypot(...s)))throw new Error("Geometry magnitude exceeds export limits");return{vertices:n,normal:x(s),degenerate:!Math.hypot(...s),reflected:a<0}}function h(r,t){return r.color||(r.colors?Array.from(r.colors.subarray(t,t+3)):[144/255,144/255,144/255])}var w=(r,t=1)=>"#"+[...r,t].map(i=>Math.round(Math.max(0,Math.min(1,i))*255).toString(16).padStart(2,"0")).join("").toUpperCase(),y=(r,t)=>[0,1,2].map(i=>(h(r,t)[i]+h(r,t+3)[i]+h(r,t+6)[i])/3);function E(r,t){let i=0;return t({loaded:0,total:r,phase:"exporting"}),()=>{i++,(i%1024===0||i===r)&&t({loaded:i,total:r,phase:"exporting"})}}export{u as a,b,m as c,g as d,f as e,h as f,w as g,y as h,E as i};
1
+ import{c as p,d as c,e as x,h as d}from"./chunk-IK3WL53C.js";var u=r=>{if(!Number.isFinite(r))throw new Error("Non-finite export coordinate");return Object.is(r,-0)?"0":String(r)},b=r=>String(r).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"").replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"})[t]),m=class{constructor(t){this.limit=t,this.bytes=0}add(t){if(this.bytes+=t,this.bytes>this.limit)throw new Error("Export size limit exceeded")}},g=class{constructor(t){this.budget=t,this.parts=[],this.pending=""}write(t){this.pending+=t,this.pending.length>=32768&&this.flush()}flush(){if(!this.pending)return;let t=new TextEncoder().encode(this.pending);this.budget.add(t.byteLength),this.parts.push(t),this.pending=""}finish(){return this.flush(),this.parts}};function f(r,t){let i=r.positions,e=r.matrix,n=[0,3,6].map(o=>d(e,[i[t+o],i[t+o+1],i[t+o+2]]));if(n.flat().some(o=>!Number.isFinite(o)))throw new Error("Non-finite export coordinate");let a=e[0]*(e[5]*e[10]-e[9]*e[6])-e[4]*(e[1]*e[10]-e[9]*e[2])+e[8]*(e[1]*e[6]-e[5]*e[2]);a<0&&([n[1],n[2]]=[n[2],n[1]]);let s=c(p(n[1],n[0]),p(n[2],n[0]));if(!Number.isFinite(Math.hypot(...s)))throw new Error("Geometry magnitude exceeds export limits");return{vertices:n,normal:x(s),degenerate:!Math.hypot(...s),reflected:a<0}}function h(r,t){return r.color||(r.colors?Array.from(r.colors.subarray(t,t+3)):[144/255,144/255,144/255])}var w=(r,t=1)=>"#"+[...r,t].map(i=>Math.round(Math.max(0,Math.min(1,i))*255).toString(16).padStart(2,"0")).join("").toUpperCase(),y=(r,t)=>[0,1,2].map(i=>(h(r,t)[i]+h(r,t+3)[i]+h(r,t+6)[i])/3);function E(r,t){let i=0;return t({loaded:0,total:r,phase:"exporting"}),()=>{i++,(i%1024===0||i===r)&&t({loaded:i,total:r,phase:"exporting"})}}export{u as a,b,m as c,g as d,f as e,h as f,w as g,y as h,E as i};
@@ -1,4 +1,4 @@
1
- import{a as Mt,d as It}from"./chunk-ZSV4PTIA.js";import{a as Y,b as Rt,c as vt}from"./chunk-JH3H3JWA.js";import{a as G}from"./chunk-JS56KC3I.js";import{a as K,b as me,f as wt,g as bt,h as St}from"./chunk-U33KANV7.js";var yt=K(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.CHAR=`
1
+ import{a as Mt,d as It}from"./chunk-ZSV4PTIA.js";import{a as Y,b as Rt,c as vt}from"./chunk-OP2L7L4N.js";import{a as G}from"./chunk-W5KVLGVR.js";import{a as K,b as me,f as wt,g as bt,h as St}from"./chunk-IK3WL53C.js";var yt=K(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.CHAR=`
2
2
  \r -\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}`;f.S=` \r
3
3
  `;f.NAME_START_CHAR=":A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}";f.NAME_CHAR="-"+f.NAME_START_CHAR+".0-9\xB7\u0300-\u036F\u203F-\u2040";f.CHAR_RE=new RegExp("^["+f.CHAR+"]$","u");f.S_RE=new RegExp("^["+f.S+"]+$","u");f.NAME_START_CHAR_RE=new RegExp("^["+f.NAME_START_CHAR+"]$","u");f.NAME_CHAR_RE=new RegExp("^["+f.NAME_CHAR+"]$","u");f.NAME_RE=new RegExp("^["+f.NAME_START_CHAR+"]["+f.NAME_CHAR+"]*$","u");f.NMTOKEN_RE=new RegExp("^["+f.NAME_CHAR+"]+$","u");var at=9,ot=10,ht=13,lt=32;f.S_LIST=[lt,ot,ht,at];function pe(e){return e>=lt&&e<=55295||e===ot||e===ht||e===at||e>=57344&&e<=65533||e>=65536&&e<=1114111}f.isChar=pe;function ge(e){return e===lt||e===ot||e===ht||e===at}f.isS=ge;function Lt(e){return e>=65&&e<=90||e>=97&&e<=122||e===58||e===95||e===8204||e===8205||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}f.isNameStartChar=Lt;function Ee(e){return Lt(e)||e>=48&&e<=57||e===45||e===46||e===183||e>=768&&e<=879||e>=8255&&e<=8256}f.isNameChar=Ee});var $t=K(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.CHAR="-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}";c.RESTRICTED_CHAR="-\b\v\f-\x7F-\x84\x86-\x9F";c.S=` \r
4
4
  `;c.NAME_START_CHAR=":A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}";c.NAME_CHAR="-"+c.NAME_START_CHAR+".0-9\xB7\u0300-\u036F\u203F-\u2040";c.CHAR_RE=new RegExp("^["+c.CHAR+"]$","u");c.RESTRICTED_CHAR_RE=new RegExp("^["+c.RESTRICTED_CHAR+"]$","u");c.S_RE=new RegExp("^["+c.S+"]+$","u");c.NAME_START_CHAR_RE=new RegExp("^["+c.NAME_START_CHAR+"]$","u");c.NAME_CHAR_RE=new RegExp("^["+c.NAME_CHAR+"]$","u");c.NAME_RE=new RegExp("^["+c.NAME_START_CHAR+"]["+c.NAME_CHAR+"]*$","u");c.NMTOKEN_RE=new RegExp("^["+c.NAME_CHAR+"]+$","u");var Pt=9,kt=10,Ot=13,Ht=32;c.S_LIST=[Ht,kt,Ot,Pt];function Ce(e){return e>=1&&e<=55295||e>=57344&&e<=65533||e>=65536&&e<=1114111}c.isChar=Ce;function _e(e){return e>=1&&e<=8||e===11||e===12||e>=14&&e<=31||e>=127&&e<=132||e>=134&&e<=159}c.isRestrictedChar=_e;function Fe(e){return e===9||e===10||e===13||e>31&&e<127||e===133||e>159&&e<=55295||e>=57344&&e<=65533||e>=65536&&e<=1114111}c.isCharAndNotRestricted=Fe;function De(e){return e===Ht||e===kt||e===Ot||e===Pt}c.isS=De;function Bt(e){return e>=65&&e<=90||e>=97&&e<=122||e===58||e===95||e===8204||e===8205||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}c.isNameStartChar=Bt;function Ae(e){return Bt(e)||e>=48&&e<=57||e===45||e===46||e===183||e>=768&&e<=879||e>=8255&&e<=8256}c.isNameChar=Ae});var Xt=K(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.NC_NAME_START_CHAR="A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}";F.NC_NAME_CHAR="-"+F.NC_NAME_START_CHAR+".0-9\xB7\u0300-\u036F\u203F-\u2040";F.NC_NAME_START_CHAR_RE=new RegExp("^["+F.NC_NAME_START_CHAR+"]$","u");F.NC_NAME_CHAR_RE=new RegExp("^["+F.NC_NAME_CHAR+"]$","u");F.NC_NAME_RE=new RegExp("^["+F.NC_NAME_START_CHAR+"]["+F.NC_NAME_CHAR+"]*$","u");function Ut(e){return e>=65&&e<=90||e===95||e>=97&&e<=122||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8204&&e<=8205||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}F.isNCNameStartChar=Ut;function Te(e){return Ut(e)||e===45||e===46||e>=48&&e<=57||e===183||e>=768&&e<=879||e>=8255&&e<=8256}F.isNCNameChar=Te});var he=K(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.SaxesParser=V.EVENTS=void 0;var q=yt(),Ne=$t(),At=Xt(),D=q.isS,we=q.isChar,z=q.isNameStartChar,Wt=q.isNameChar,ie=q.S_LIST,be=q.NAME_RE,Se=Ne.isChar,Re=At.isNCNameStartChar,ve=At.isNCNameChar,Me=At.NC_NAME_RE,rt="http://www.w3.org/XML/1998/namespace",j="http://www.w3.org/2000/xmlns/",Ie={__proto__:null,xml:rt,xmlns:j},Le={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},x=-1,R=-2,jt=0,ye=1,ct=2,Pe=3,U=4,ke=5,Oe=6,He=7,ut=8,Be=9,$e=10,Ue=11,Xe=12,_=13,J=14,dt=15,We=16,ft=17,je=18,Ve=19,xt=20,qe=21,Ge=22,ze=23,Vt=24,mt=25,tt=26,qt=27,Qe=28,Ze=29,Gt=30,Ke=31,Ye=32,B=33,Je=34,pt=35,Q=36,gt=37,ts=38,zt=39,Qt=40,es=41,Zt=42,ss=43,is=44,Et=9,N=10,Ct=13,Kt=32,Yt=33,re=34,Z=38,ne=39,et=45,st=47,rs=59,k=60,X=61,p=62,E=63,ae=91,W=93,Jt=133,te=8232,it=e=>e===re||e===ne,oe=[re,ne],ns=[...oe,ae,p],as=[...oe,k,W],os=[X,E,...ie],hs=[...ie,p,Z,k];function Ft(e,t,s){switch(t){case"xml":s!==rt&&e.fail(`xml prefix must be bound to ${rt}.`);break;case"xmlns":s!==j&&e.fail(`xmlns prefix must be bound to ${j}.`);break;default:}switch(s){case j:e.fail(t===""?`the default namespace may not be set to ${s}.`:`may not assign a prefix (even "xmlns") to the URI ${j}.`);break;case rt:switch(t){case"xml":break;case"":e.fail(`the default namespace may not be set to ${s}.`);break;default:e.fail("may not assign the xml namespace to another prefix.")}break;default:}}function ls(e,t){for(let s of Object.keys(t))Ft(e,s,t[s])}var cs=e=>Me.test(e),us=e=>be.test(e),$=0,ee=1,_t=2;V.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var se={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"},Dt=class{constructor(t){this.opt=t??{},this.fragmentOpt=!!this.opt.fragment;let s=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,s){this.nameStartCheck=Re,this.nameCheck=ve,this.isName=cs,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},Ie);let i=this.opt.additionalNamespaces;i!=null&&(ls(this,i),Object.assign(this.ns,i))}else this.nameStartCheck=z,this.nameCheck=Wt,this.isName=us,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var t;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=$,this.attribList=[];let{fragmentOpt:s}=this;this.state=s?_:jt,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=s,this.xmlDeclPossible=!s,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:i}=this.opt;if(i===void 0){if(this.opt.forceXMLVersion===!0)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");i="1.0"}this.setXMLVersion(i),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(Le),(t=this.readyHandler)===null||t===void 0||t.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(t,s){this[se[t]]=s}off(t){this[se[t]]=void 0}makeError(t){var s;let i=(s=this.fileName)!==null&&s!==void 0?s:"";return this.trackPosition&&(i.length>0&&(i+=":"),i+=`${this.line}:${this.column}`),i.length>0&&(i+=": "),new Error(i+t)}fail(t){let s=this.makeError(t),i=this.errorHandler;if(i===void 0)throw s;return i(s),this}write(t){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let s=!1;t===null?(s=!0,t=""):typeof t=="object"&&(t=t.toString()),this.carriedFromPrevious!==void 0&&(t=`${this.carriedFromPrevious}${t}`,this.carriedFromPrevious=void 0);let i=t.length,r=t.charCodeAt(i-1);!s&&(r===Ct||r>=55296&&r<=56319)&&(this.carriedFromPrevious=t[i-1],i--,t=t.slice(0,i));let{stateTable:n}=this;for(this.chunk=t,this.i=0;this.i<i;)n[this.state].call(this);return this.chunkPosition+=i,s?this.end():this}close(){return this.write(null)}getCode10(){let{chunk:t,i:s}=this;if(this.prevI=s,this.i=s+1,s>=t.length)return x;let i=t.charCodeAt(s);if(this.column++,i<55296){if(i>=Kt||i===Et)return i;switch(i){case N:return this.line++,this.column=0,this.positionAtNewLine=this.position,N;case Ct:return t.charCodeAt(s+1)===N&&(this.i=s+2),this.line++,this.column=0,this.positionAtNewLine=this.position,R;default:return this.fail("disallowed character."),i}}if(i>56319)return i>=57344&&i<=65533||this.fail("disallowed character."),i;let r=65536+(i-55296)*1024+(t.charCodeAt(s+1)-56320);return this.i=s+2,r>1114111&&this.fail("disallowed character."),r}getCode11(){let{chunk:t,i:s}=this;if(this.prevI=s,this.i=s+1,s>=t.length)return x;let i=t.charCodeAt(s);if(this.column++,i<55296){if(i>31&&i<127||i>159&&i!==te||i===Et)return i;switch(i){case N:return this.line++,this.column=0,this.positionAtNewLine=this.position,N;case Ct:{let n=t.charCodeAt(s+1);(n===N||n===Jt)&&(this.i=s+2)}case Jt:case te:return this.line++,this.column=0,this.positionAtNewLine=this.position,R;default:return this.fail("disallowed character."),i}}if(i>56319)return i>=57344&&i<=65533||this.fail("disallowed character."),i;let r=65536+(i-55296)*1024+(t.charCodeAt(s+1)-56320);return this.i=s+2,r>1114111&&this.fail("disallowed character."),r}getCodeNorm(){let t=this.getCode();return t===R?N:t}unget(){this.i=this.prevI,this.column--}captureTo(t){let{i:s}=this,{chunk:i}=this;for(;;){let r=this.getCode(),n=r===R,o=n?N:r;if(o===x||t.includes(o))return this.text+=i.slice(s,this.prevI),o;n&&(this.text+=`${i.slice(s,this.prevI)}
@@ -1,4 +1,4 @@
1
- import{a as y,b as M,c as F,d as v,e as $,f as k,g as E,h as S,i as I}from"./chunk-ZMK3UZZE.js";import{a as j}from"./chunk-JH3H3JWA.js";import{a as _}from"./chunk-JS56KC3I.js";import"./chunk-U33KANV7.js";function U(t,a){return`${String(t||"scene").split(/[\\/]/).pop().split(/[?#]/)[0].replace(/[<>:"|*\x00-\x1f\x7f]/g,"_").replace(/\.(?:stl|obj|3mf|step|stp|iges|igs|zip|vsb|vsj)$/i,"").replace(/[. ]+$/g,"").slice(0,160)||"scene"}.${a}`}function L(t={}){let a={stp:"step",igs:"iges"},l=String(t.format||"").toLowerCase(),f=a[l]||l;if(!["stl","obj","3mf","step","iges"].includes(f))throw new Error("Export format must be stl, obj, 3mf, step or iges");let n=t.units??"mm";if(!["mm","inch"].includes(n))throw new Error("Export units must be mm or inch");for(let m of["apply_transforms","colors"])if(t[m]!==void 0&&typeof t[m]!="boolean")throw new Error(`${m} must be a boolean`);if(t.on_progress!==void 0&&typeof t.on_progress!="function")throw new Error("on_progress must be a function");let e=t.colors!==!1&&["obj","3mf"].includes(f),p=f==="obj"&&e?"zip":f;return{format:f,units:n,colors:e,apply_transforms:t.apply_transforms!==!1,filename:U(t.filename,p)}}function A(t,a){let l=t.reduce((n,e)=>n+e.geometry.triangles,0);return 67108864+l*{stl:192,obj:2400,"3mf":3e3,step:12e3,iges:4e3}[a.format]+t.length*4096}function z(t,a,l){let f=t.reduce((o,i)=>o+i.positions.length/9,0);if(f>4294967295)throw new Error("STL triangle count limit exceeded");a.add(84+f*50);let n=new Uint8Array(84);n.set(new TextEncoder().encode("Binary STL by ViewSTL 2")),new DataView(n.buffer).setUint32(80,f,!0);let e=[n],p,m,c=0,d=0;for(let o of t)for(let i=0;i<o.positions.length;i+=9){(!p||c===p.length)&&(p=new Uint8Array(Math.min(f-d,16384)*50),m=new DataView(p.buffer),e.push(p),c=0);let{vertices:r,normal:g}=$(o,i),w=[...g,...r.flat()];for(let s=0;s<w.length;s++){if(!Number.isFinite(Math.fround(w[s])))throw new Error("STL coordinate exceeds float32 range");m.setFloat32(c+s*4,w[s],!0)}c+=50,d++,l()}return new Blob(e,{type:"model/stl"})}async function D(t,a,l,f,n){let e=new v(l),p=new v(l),m=new Map;e.write(`# ViewSTL mesh export; units: ${a.units}
1
+ import{a as y,b as M,c as F,d as v,e as $,f as k,g as E,h as S,i as I}from"./chunk-PQYEV7WH.js";import{a as j}from"./chunk-OP2L7L4N.js";import{a as _}from"./chunk-W5KVLGVR.js";import"./chunk-IK3WL53C.js";function U(t,a){return`${String(t||"scene").split(/[\\/]/).pop().split(/[?#]/)[0].replace(/[<>:"|*\x00-\x1f\x7f]/g,"_").replace(/\.(?:stl|obj|3mf|step|stp|iges|igs|zip|vsb|vsj)$/i,"").replace(/[. ]+$/g,"").slice(0,160)||"scene"}.${a}`}function L(t={}){let a={stp:"step",igs:"iges"},l=String(t.format||"").toLowerCase(),f=a[l]||l;if(!["stl","obj","3mf","step","iges"].includes(f))throw new Error("Export format must be stl, obj, 3mf, step or iges");let n=t.units??"mm";if(!["mm","inch"].includes(n))throw new Error("Export units must be mm or inch");for(let m of["apply_transforms","colors"])if(t[m]!==void 0&&typeof t[m]!="boolean")throw new Error(`${m} must be a boolean`);if(t.on_progress!==void 0&&typeof t.on_progress!="function")throw new Error("on_progress must be a function");let e=t.colors!==!1&&["obj","3mf"].includes(f),p=f==="obj"&&e?"zip":f;return{format:f,units:n,colors:e,apply_transforms:t.apply_transforms!==!1,filename:U(t.filename,p)}}function A(t,a){let l=t.reduce((n,e)=>n+e.geometry.triangles,0);return 67108864+l*{stl:192,obj:2400,"3mf":3e3,step:12e3,iges:4e3}[a.format]+t.length*4096}function z(t,a,l){let f=t.reduce((o,i)=>o+i.positions.length/9,0);if(f>4294967295)throw new Error("STL triangle count limit exceeded");a.add(84+f*50);let n=new Uint8Array(84);n.set(new TextEncoder().encode("Binary STL by ViewSTL 2")),new DataView(n.buffer).setUint32(80,f,!0);let e=[n],p,m,c=0,d=0;for(let o of t)for(let i=0;i<o.positions.length;i+=9){(!p||c===p.length)&&(p=new Uint8Array(Math.min(f-d,16384)*50),m=new DataView(p.buffer),e.push(p),c=0);let{vertices:r,normal:g}=$(o,i),w=[...g,...r.flat()];for(let s=0;s<w.length;s++){if(!Number.isFinite(Math.fround(w[s])))throw new Error("STL coordinate exceeds float32 range");m.setFloat32(c+s*4,w[s],!0)}c+=50,d++,l()}return new Blob(e,{type:"model/stl"})}async function D(t,a,l,f,n){let e=new v(l),p=new v(l),m=new Map;e.write(`# ViewSTL mesh export; units: ${a.units}
2
2
  `),a.colors&&e.write(`mtllib materials.mtl
3
3
  `);let c=0,d=0,o;for(let r of t){let g=String(r.name).replace(/[^\p{L}\p{N}_.-]/gu,"_").slice(0,160)||"model";e.write(`o model_${r.id}_${g}
4
4
  s off
@@ -11,7 +11,7 @@ illum 1
11
11
  `),o=x)}for(let u of s)e.write(`v ${u.map(y).join(" ")}
12
12
  `);e.write(`vn ${h.map(y).join(" ")}
13
13
  `),d++,e.write(`f ${[1,2,3].map(u=>`${c+u}//${d}`).join(" ")}
14
- `),c+=3,n()}}let i=e.finish();return a.colors?(await import("./export-zip-EDCWH5PX.js")).zipExport([["model.obj",i],["materials.mtl",p.finish()]],f):new Blob(i,{type:"model/obj"})}function C(t){let a=[],l=new Map,f=new Uint32Array(t.positions.length/3),n=new Map,e=0,p=0,m;for(let c=0;c<t.positions.length;c+=9){let{vertices:d,degenerate:o}=$(t,c);if(o)throw new Error("3MF export requires non-degenerate triangles");m??=d[0];let[i,r,g]=d.map(s=>s.map((h,u)=>h-m[u]));p+=i[0]*(r[1]*g[2]-r[2]*g[1])+i[1]*(r[2]*g[0]-r[0]*g[2])+i[2]*(r[0]*g[1]-r[1]*g[0]);let w=d.map(s=>{let h=s.map(y).join(","),u=l.get(h);return u===void 0&&(u=a.length,l.set(h,u),a.push(s)),u});f.set(w,e),e+=3;for(let s=0;s<3;s++){let h=w[s],u=w[(s+1)%3],x=Math.min(h,u)+":"+Math.max(h,u),b=n.get(x)||{count:0,direction:0};b.count++,b.direction+=h<u?1:-1,n.set(x,b)}}for(let c of n.values())if(c.count!==2||c.direction!==0)throw new Error("3MF export requires closed meshes with consistent triangle winding; use STL or OBJ for open surfaces");if(!(p>0))throw new Error("3MF export requires positive mesh volume and outward triangle winding");return{points:a,indices:f}}async function B(t,a,l,f,n){let e=new v(l),p=new Map,m=(i,r)=>E(k(i,r),i.opacity);if(a.colors)for(let i of t)for(let r=0;r<i.positions.length;r+=3){let g=m(i,r);p.has(g)||p.set(g,p.size)}if(e.write(`<?xml version="1.0" encoding="UTF-8"?>
14
+ `),c+=3,n()}}let i=e.finish();return a.colors?(await import("./export-zip-PVXETVLK.js")).zipExport([["model.obj",i],["materials.mtl",p.finish()]],f):new Blob(i,{type:"model/obj"})}function C(t){let a=[],l=new Map,f=new Uint32Array(t.positions.length/3),n=new Map,e=0,p=0,m;for(let c=0;c<t.positions.length;c+=9){let{vertices:d,degenerate:o}=$(t,c);if(o)throw new Error("3MF export requires non-degenerate triangles");m??=d[0];let[i,r,g]=d.map(s=>s.map((h,u)=>h-m[u]));p+=i[0]*(r[1]*g[2]-r[2]*g[1])+i[1]*(r[2]*g[0]-r[0]*g[2])+i[2]*(r[0]*g[1]-r[1]*g[0]);let w=d.map(s=>{let h=s.map(y).join(","),u=l.get(h);return u===void 0&&(u=a.length,l.set(h,u),a.push(s)),u});f.set(w,e),e+=3;for(let s=0;s<3;s++){let h=w[s],u=w[(s+1)%3],x=Math.min(h,u)+":"+Math.max(h,u),b=n.get(x)||{count:0,direction:0};b.count++,b.direction+=h<u?1:-1,n.set(x,b)}}for(let c of n.values())if(c.count!==2||c.direction!==0)throw new Error("3MF export requires closed meshes with consistent triangle winding; use STL or OBJ for open surfaces");if(!(p>0))throw new Error("3MF export requires positive mesh volume and outward triangle winding");return{points:a,indices:f}}async function B(t,a,l,f,n){let e=new v(l),p=new Map,m=(i,r)=>E(k(i,r),i.opacity);if(a.colors)for(let i of t)for(let r=0;r<i.positions.length;r+=3){let g=m(i,r);p.has(g)||p.set(g,p.size)}if(e.write(`<?xml version="1.0" encoding="UTF-8"?>
15
15
  <model unit="${a.units==="inch"?"inch":"millimeter"}" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"${a.colors?' xmlns:m="http://schemas.microsoft.com/3dmanufacturing/material/2015/02" recommendedextensions="m"':""}>
16
16
  <metadata name="Application">ViewSTL</metadata>
17
17
  <resources>
@@ -26,4 +26,4 @@ illum 1
26
26
  `)}e.write(`</resources><build>
27
27
  `),t.forEach((i,r)=>e.write(`<item objectid="${r+2}"/>
28
28
  `)),e.write(`</build></model>
29
- `);let c=i=>{let r=new v(l);return r.write(i),r.finish()},d=[["3D/3dmodel.model",e.finish()],["[Content_Types].xml",c('<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/></Types>')],["_rels/.rels",c('<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rel0" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel" Target="/3D/3dmodel.model"/></Relationships>')]],o=(await import("./export-zip-EDCWH5PX.js")).zipExport(d,f);return o.slice(0,o.size,"model/3mf")}async function K(t,a,l=j,f=()=>{}){let n=L(a);if(!Array.isArray(t)||!t.length)throw new Error("No models to export");let e=0;for(let o of t){if(!(o.positions instanceof Float32Array)||!o.positions.length||o.positions.length%9)throw new Error("Invalid export geometry");if(o.matrix?.length!==16||Array.from(o.matrix).some(i=>!Number.isFinite(i)))throw new Error("Invalid export transform");if(o.colors&&(!(o.colors instanceof Float32Array)||o.colors.length!==o.positions.length))throw new Error("Invalid export colors");if(n.colors){for(let i of[o.colors,o.color])if(i){for(let r of i)if(!Number.isFinite(r)||r<0||r>1)throw new Error("Invalid export colors")}if(!Number.isFinite(o.opacity)||o.opacity<0||o.opacity>1)throw new Error("Invalid export opacity")}e+=o.positions.length/9}if(e>l.max_triangles)throw new Error("Export triangle limit exceeded");_(l,A(t.map(o=>({geometry:{triangles:o.positions.length/9}})),n),"export");let p=n.format==="3mf"||n.format==="obj"&&n.colors,m=new F(p?l.max_uncompressed_bytes:l.max_file_bytes),c=I(e,f),d;if(n.format==="stl")d=z(t,m,c);else if(n.format==="obj")d=await D(t,n,m,l,c);else if(n.format==="3mf")d=await B(t,n,m,l,c);else{let o=await import("./export-cad-QPBT756V.js");d=n.format==="step"?o.writeSTEP(t,n,m,c):o.writeIGES(t,n,m,c)}return f({loaded:e,total:e,phase:"complete"}),{blob:d,filename:n.filename,format:n.format,units:n.units,model_ids:t.map(o=>o.id),triangles:e,representation:"mesh"}}export{K as exportGeometry};
29
+ `);let c=i=>{let r=new v(l);return r.write(i),r.finish()},d=[["3D/3dmodel.model",e.finish()],["[Content_Types].xml",c('<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/></Types>')],["_rels/.rels",c('<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rel0" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel" Target="/3D/3dmodel.model"/></Relationships>')]],o=(await import("./export-zip-PVXETVLK.js")).zipExport(d,f);return o.slice(0,o.size,"model/3mf")}async function K(t,a,l=j,f=()=>{}){let n=L(a);if(!Array.isArray(t)||!t.length)throw new Error("No models to export");let e=0;for(let o of t){if(!(o.positions instanceof Float32Array)||!o.positions.length||o.positions.length%9)throw new Error("Invalid export geometry");if(o.matrix?.length!==16||Array.from(o.matrix).some(i=>!Number.isFinite(i)))throw new Error("Invalid export transform");if(o.colors&&(!(o.colors instanceof Float32Array)||o.colors.length!==o.positions.length))throw new Error("Invalid export colors");if(n.colors){for(let i of[o.colors,o.color])if(i){for(let r of i)if(!Number.isFinite(r)||r<0||r>1)throw new Error("Invalid export colors")}if(!Number.isFinite(o.opacity)||o.opacity<0||o.opacity>1)throw new Error("Invalid export opacity")}e+=o.positions.length/9}if(e>l.max_triangles)throw new Error("Export triangle limit exceeded");_(l,A(t.map(o=>({geometry:{triangles:o.positions.length/9}})),n),"export");let p=n.format==="3mf"||n.format==="obj"&&n.colors,m=new F(p?l.max_uncompressed_bytes:l.max_file_bytes),c=I(e,f),d;if(n.format==="stl")d=z(t,m,c);else if(n.format==="obj")d=await D(t,n,m,l,c);else if(n.format==="3mf")d=await B(t,n,m,l,c);else{let o=await import("./export-cad-QXCB6UDU.js");d=n.format==="step"?o.writeSTEP(t,n,m,c):o.writeIGES(t,n,m,c)}return f({loaded:e,total:e,phase:"complete"}),{blob:d,filename:n.filename,format:n.format,units:n.units,model_ids:t.map(o=>o.id),triangles:e,representation:"mesh"}}export{K as exportGeometry};
@@ -1,4 +1,4 @@
1
- import{a as w,d as u,e as H}from"./chunk-ZMK3UZZE.js";import{c as G,e as x}from"./chunk-U33KANV7.js";var X=p=>{let N=w(p).toUpperCase(),[I,$]=N.split("E");return(I.includes(".")?I:I+".")+($===void 0?"":"E"+$)},v=p=>"'"+String(p).replace(/[\x00-\x1f\x7f]/g," ").replace(/['\\\u0080-\uffff]/g,N=>N==="'"?"''":N==="\\"?"\\\\":"\\X2\\"+N.charCodeAt(0).toString(16).padStart(4,"0").toUpperCase()+"\\X0\\")+"'";function ee(p,N,I,$){let E=new u(I);E.write(`ISO-10303-21;
1
+ import{a as w,d as u,e as H}from"./chunk-PQYEV7WH.js";import{c as G,e as x}from"./chunk-IK3WL53C.js";var X=p=>{let N=w(p).toUpperCase(),[I,$]=N.split("E");return(I.includes(".")?I:I+".")+($===void 0?"":"E"+$)},v=p=>"'"+String(p).replace(/[\x00-\x1f\x7f]/g," ").replace(/['\\\u0080-\uffff]/g,N=>N==="'"?"''":N==="\\"?"\\\\":"\\X2\\"+N.charCodeAt(0).toString(16).padStart(4,"0").toUpperCase()+"\\X0\\")+"'";function ee(p,N,I,$){let E=new u(I);E.write(`ISO-10303-21;
2
2
  HEADER;
3
3
  FILE_DESCRIPTION(('ViewSTL mesh surfaces'),'2;1');
4
4
  `),E.write(`FILE_NAME('scene.step','${new Date().toISOString().slice(0,19)}',(''),(''),'ViewSTL','ViewSTL','');
@@ -1 +1 @@
1
- import{c as a}from"./chunk-ZMK3UZZE.js";import{b as c,c as f}from"./chunk-ZSV4PTIA.js";import"./chunk-U33KANV7.js";function w(r,o){if(r.length>o.max_archive_entries)throw new Error("Export archive entry limit exceeded");let p=[],s=new a(o.max_file_bytes),i=new f((e,t)=>{if(e)throw e;s.add(t.byteLength),p.push(t)});for(let[e,t]of r){let n=new c(e,{level:6});i.add(n);for(let u of t)n.push(u,!1);n.push(new Uint8Array,!0)}return i.end(),new Blob(p,{type:"application/zip"})}export{w as zipExport};
1
+ import{c as a}from"./chunk-PQYEV7WH.js";import{b as c,c as f}from"./chunk-ZSV4PTIA.js";import"./chunk-IK3WL53C.js";function w(r,o){if(r.length>o.max_archive_entries)throw new Error("Export archive entry limit exceeded");let p=[],s=new a(o.max_file_bytes),i=new f((e,t)=>{if(e)throw e;s.add(t.byteLength),p.push(t)});for(let[e,t]of r){let n=new c(e,{level:6});i.add(n);for(let u of t)n.push(u,!1);n.push(new Uint8Array,!0)}return i.end(),new Blob(p,{type:"application/zip"})}export{w as zipExport};
@@ -1 +1 @@
1
- import{a as re}from"./chunk-JS56KC3I.js";import{h as oe}from"./chunk-U33KANV7.js";function ae(e={}){let o=e.level??"basic";if(!["basic","detailed"].includes(o))throw new Error("Choose basic or detailed print checks");let l=(n,i,f=1e9)=>{if(!Number.isFinite(n)||n<=0||n>f)throw new Error(`Invalid ${i}`);return n},r=null;if(e.profile!=null){if(e.profile.technology!=="fdm")throw new Error("Only FDM profiles are supported");r={technology:"fdm"};for(let n of["min_wall_mm","line_width_mm"])e.profile[n]!=null&&(r[n]=l(e.profile[n],n));if(e.profile.overhang_degrees!=null&&(r.overhang_degrees=l(e.profile.overhang_degrees,"overhang angle",89.9)),e.profile.build_volume_mm!=null){if(!Array.isArray(e.profile.build_volume_mm)||e.profile.build_volume_mm.length!==3)throw new Error("Build volume requires X, Y and Z");r.build_volume_mm=e.profile.build_volume_mm.map(n=>l(n,"build volume"))}}let c=l(e.max_time_ms??3e4,"check time limit",12e4);return{level:o,profile:r,apply_transforms:e.apply_transforms!==!1,units_confirmed:e.units_confirmed===!0,max_time_ms:c}}var le=e=>64*1024**2+e*2400;var O=(e,o)=>e.map((l,r)=>l-o[r]),R=(e,o)=>e.reduce((l,r,c)=>l+r*o[c],0),C=(e,o)=>[e[1]*o[2]-e[2]*o[1],e[2]*o[0]-e[0]*o[2],e[0]*o[1]-e[1]*o[0]];function D(e,o){return[0,3,6].map(l=>Array.from(e.subarray(o*9+l,o*9+l+3)))}function fe(e,o){let l=e.length/9,r=new Float64Array(l*6);for(let i=0;i<l;i++){i%1024===0&&o();for(let f=0;f<3;f++)r[i*6+f]=Math.min(e[i*9+f],e[i*9+3+f],e[i*9+6+f]),r[i*6+f+3]=Math.max(e[i*9+f],e[i*9+3+f],e[i*9+6+f])}let c=Uint32Array.from({length:l},(i,f)=>f),n=(i,f)=>{o();let w=[1/0,1/0,1/0,-1/0,-1/0,-1/0];for(let u=i;u<f;u++)for(let m=0;m<3;m++)w[m]=Math.min(w[m],r[c[u]*6+m]),w[m+3]=Math.max(w[m+3],r[c[u]*6+m+3]);let _={b:w,start:i,end:f};if(f-i>16){let u=[0,1,2].map(z=>w[z+3]-w[z]),m=u.indexOf(Math.max(...u));c.subarray(i,f).sort((z,$)=>r[z*6+m]+r[z*6+m+3]-(r[$*6+m]+r[$*6+m+3]));let g=i+f>>>1;_.left=n(i,g),_.right=n(g,f)}return _};return{root:n(0,l),ids:c,boxes:r}}var ce=(e,o,l)=>[0,1,2].every(r=>e[r]<=o[r+3]+l&&e[r+3]+l>=o[r]);function ue(e,o,l,r){let c=(n,i,f)=>{if(r(),!!ce(n.b,i.b,o))if(!n.left&&!i.left)for(let w=n.start;w<n.end;w++)for(let _=i.start;_<i.end;_++){let u=e.ids[w],m=e.ids[_];f&&u>=m||ce(e.boxes.subarray(u*6,u*6+6),e.boxes.subarray(m*6,m*6+6),o)&&l(u,m)}else f?(c(n.left,n.left,!0),c(n.left,n.right,!1),c(n.right,n.right,!0)):n.left&&(!i.left||n.end-n.start>=i.end-i.start)?(c(n.left,i,!1),c(n.right,i,!1)):(c(n,i.left,!1),c(n,i.right,!1))};c(e.root,e.root,!0)}var G=(e,o,l)=>(o[0]-e[0])*(l[1]-e[1])-(o[1]-e[1])*(l[0]-e[0]);function me(e,o,l,r){let c=C(O(e[1],e[0]),O(e[2],e[0])),n=C(O(o[1],o[0]),O(o[2],o[0])),i=Math.hypot(...c),f=Math.hypot(...n);if(!i||!f)return 0;let w=o.map(d=>R(O(d,e[0]),c)/i),_=e.map(d=>R(O(d,o[0]),n)/f);if([w,_].some(d=>d.every(b=>b>r)||d.every(b=>b<-r)))return 0;let u=C(c.map(d=>d/i),n.map(d=>d/f));if(Math.hypot(...u)<1e-10){if(Math.max(...w.map(Math.abs))>r)return 0;let d=c.map(Math.abs).indexOf(Math.max(...c.map(Math.abs))),b=A=>A.filter((S,I)=>I!==d);if(l>=2){let A=(I,k)=>I.every((P,p)=>P===k[p]),S=e.filter(I=>o.some(k=>A(I,k)));if(S.length===3)return 1;if(S.length===2){let I=e.find(P=>!S.some(p=>A(P,p))),k=o.find(P=>!S.some(p=>A(P,p)));return G(b(S[0]),b(S[1]),b(I))*G(b(S[0]),b(S[1]),b(k))>0?1:0}}let E=e.map(b),q=o.map(b),B=Math.sign(G(...q));for(let A=0;A<3&&E.length;A++){let S=q[A],I=q[(A+1)%3],k=[];for(let P=0;P<E.length;P++){let p=E[P],j=E[(P+1)%E.length],x=B*G(S,I,p),Q=B*G(S,I,j);if(x>=0&&k.push(p),x>=0!=Q>=0){let K=x/(x-Q);k.push(p.map((Z,W)=>Z+(j[W]-Z)*K))}}E=k}return Math.abs(E.reduce((A,S,I)=>{let k=E[(I+1)%E.length],P=E[0];return A+(S[0]-P[0])*(k[1]-P[1])-(S[1]-P[1])*(k[0]-P[0])},0))/2>r*r*4?1:0}if(l>=2)return 0;let m=u.map(d=>d/Math.hypot(...u)),g=(d,b)=>{let E=[];for(let q=0;q<3;q++){Math.abs(b[q])<=r&&E.push(R(d[q],m));let B=(q+1)%3;if(b[q]*b[B]<0){let V=b[q]/(b[q]-b[B]);E.push(R(d[q].map((A,S)=>A+(d[B][S]-A)*V),m))}}return E.length?[Math.min(...E),Math.max(...E)]:null},z=g(e,_),$=g(o,w);if(!z||!$)return 0;let L=Math.min(z[1],$[1])-Math.max(z[0],$[0]);return L>r?1:l?0:L>=-r?2:0}function ye(e,o,l,r){let c=O(l[1],l[0]),n=O(l[2],l[0]),i=C(o,n),f=R(c,i);if(Math.abs(f)<=Math.hypot(...c)*Math.hypot(...n)*1e-12)return null;let w=O(e,l[0]),_=R(w,i)/f,u=C(w,c),m=R(o,u)/f,g=R(n,u)/f;return _<-1e-10||m<-1e-10||_+m>1+1e-10||g<=r?null:{t:g,edge:Math.min(_,m,1-_-m)<1e-8}}function ve(e,o,l,r){let c=0,n=1/0;for(let i=0;i<3;i++)if(Math.abs(o[i])<1e-15){if(e[i]<l[i]-r||e[i]>l[i+3]+r)return!1}else{let f=(l[i]-r-e[i])/o[i],w=(l[i+3]+r-e[i])/o[i];if(c=Math.max(c,Math.min(f,w)),n=Math.min(n,Math.max(f,w)),c>n)return!1}return!0}function ie(e,o,l,r,c,n,i){let f=[],w=_=>{if(i(),!!ve(l,r,_.b,c))if(_.left)w(_.left),w(_.right);else for(let u=_.start;u<_.end;u++){let m=e.ids[u];if(!n(m))continue;let g=ye(l,r,D(o,m),c);g&&f.push({...g,id:m})}};return w(e.root),f}var we=[["degenerate_faces","Degenerate triangles","error"],["near_degenerate_faces","Very small or thin triangles","warning"],["duplicate_faces","Duplicate triangles","error"],["boundary_edges","Open boundaries","error"],["nonmanifold_edges","Non-manifold edges","error"],["nonmanifold_vertices","Non-manifold vertices","error"],["winding","Triangle winding","error"],["components","Separate connected parts","info"],["intersections","Self-intersections","error"],["shell_orientation","Shell orientation and volume","error"],["units","Physical units","warning"],["build_volume","Build volume fit","warning"],["overhangs","Overhangs","warning"],["bed_contact","Bed contact","warning"],["thin_walls","Thin walls / small features","warning"]];function Se(e,o={},l={},r=()=>{}){let c=ae(o),n=e.positions.length/9;if(!(e.positions instanceof Float32Array)||!Number.isSafeInteger(n)||n<1||e.matrix?.length!==16||Array.from(e.matrix).some(p=>!Number.isFinite(p)))throw new Error("Invalid print-check geometry");if(n>(l.max_triangles??5e6))throw new Error("Print check triangle limit exceeded");re(l,le(n),"print check");let i=performance.now(),f=i+c.max_time_ms,w=0,_="Topology",u=()=>{if(++w%128===0){if(performance.now()>f)throw new Error("PRINT_TIME_LIMIT");r({phase:_,elapsed_ms:performance.now()-i})}},m=we.map(([p,j,x])=>({code:p,label:j,severity:x,status:"not_run",count:0,triangle_ids:[],edge_vertices:[],message:"Not run"})),g=p=>m.find(j=>j.code===p),z=(p,j,x)=>Object.assign(g(p),{status:j,message:x}),$=(p,j)=>{let x=g(p);x.count++,j!=null&&x.triangle_ids.length<128&&x.triangle_ids.push(j)},L=(p,j)=>{let x=g(p);x.status=x.count?"issue":"pass",x.message=j||`${x.count} found`},d=new Float64Array(e.positions.length),b=[1/0,1/0,1/0],E=[-1/0,-1/0,-1/0],q=!1,B,V=[],A=[],S,I=0,k={model_id:e.id,name:e.name,triangles:n,checks:m,settings:c,dimensions_mm:null,volume_mm3:null,volume_valid:!1,elapsed_ms:0,summary:"incomplete"};try{r({phase:_,elapsed_ms:0});for(let t=0;t<e.positions.length;t+=3){t%3072===0&&u();let s=oe(e.matrix,Array.from(e.positions.subarray(t,t+3)));if(s.some(a=>!Number.isFinite(a)))throw new Error("Invalid print-check coordinate");d.set(s,t);for(let a=0;a<3;a++)b[a]=Math.min(b[a],s[a]),E[a]=Math.max(E[a],s[a])}k.dimensions_mm=E.map((t,s)=>t-b[s]);let p=Math.max(...k.dimensions_mm),j=Math.max(...b.map(Math.abs),...E.map(Math.abs));I=Math.max(p*1e-10,j*Number.EPSILON*64,1e-12),k.tolerance_mm=I;for(let t=0;t<d.length;t++)d[t]-=b[t%3];let x=new Uint32Array(n*3),Q=[],K=new Map,Z=new Map,W=new Map,H=[],J=Int32Array.from({length:n},(t,s)=>s),te=t=>{for(;J[t]!==t;)J[t]=J[J[t]],t=J[t];return t},he=(t,s)=>{t=te(t),s=te(s),t!==s&&(J[s]=t)};for(let t=0;t<n;t++){u();for(let h=0;h<3;h++){let M=t*9+h*3,F=Array.from(e.positions.subarray(M,M+3)).join(","),T=K.get(F);T===void 0&&(T=Q.length,K.set(F,T),Q.push(M),H.push([])),x[t*3+h]=T,H[T].push(t)}let s=D(d,t),a=C(O(s[1],s[0]),O(s[2],s[0])),y=Math.hypot(...a);y?y<=I*Math.max(...s.map((h,M)=>Math.hypot(...O(h,s[(M+1)%3]))))&&$("near_degenerate_faces",t):$("degenerate_faces",t);let v=Array.from(x.subarray(t*3,t*3+3)).sort((h,M)=>h-M).join(":");W.has(v)?$("duplicate_faces",t):W.set(v,t);for(let h=0;h<3;h++){let M=x[t*3+h],F=x[t*3+(h+1)%3],T=Math.min(M,F)+":"+Math.max(M,F),N=Z.get(T);N||(N={a:M,b:F,faces:[],direction:0},Z.set(T,N)),N.faces.length&&he(t,N.faces[0]),N.faces.push(t),N.direction+=M<F?1:-1}}let ne=new Set;for(let t of Z.values()){u();let s;if(t.faces.length===1?s="boundary_edges":t.faces.length!==2?(s="nonmanifold_edges",ne.add(t.a),ne.add(t.b)):t.direction!==0&&(s="winding"),s){$(s,t.faces[0]);let a=g(s);a.edge_vertices.length<256*6&&a.edge_vertices.push(...e.positions.subarray(Q[t.a],Q[t.a]+3),...e.positions.subarray(Q[t.b],Q[t.b]+3))}}for(let t=0;t<H.length;t++){if(u(),ne.has(t)){$("nonmanifold_vertices",H[t][0]);continue}let s=new Set(H[t]),a=new Set,y=[H[t][0]];for(;y.length;){u();let v=y.pop();if(!a.has(v)){a.add(v);for(let h=0;h<3;h++){let M=x[v*3+h],F=x[v*3+(h+1)%3];if(M!==t&&F!==t)continue;let T=Z.get(Math.min(M,F)+":"+Math.max(M,F));for(let N of T.faces)a.has(N)||y.push(N)}}}a.size!==s.size&&$("nonmanifold_vertices",H[t][0])}let X=new Map;S=new Int32Array(n);for(let t=0;t<n;t++){u();let s=te(t);X.has(s)||(X.set(s,X.size),A.push([]),V.push(0));let a=X.get(s);S[t]=a,A[a].push(t);let y=D(d,t),v=D(d,A[a][0])[0];V[a]+=R(O(y[0],v),C(O(y[1],v),O(y[2],v)))/6}for(let t of["degenerate_faces","near_degenerate_faces","duplicate_faces","boundary_edges","nonmanifold_edges","nonmanifold_vertices","winding"])L(t);g("components").count=X.size,z("components",X.size>1?"issue":"pass",`${X.size} connected part${X.size===1?"":"s"}. Separate parts can be intentional.`),q=!0,z("units",e.source_units||c.units_confirmed?"pass":"inconclusive",e.source_units?`File units: ${e.source_units}; measurements in mm.`:c.units_confirmed?"Current scale confirmed as millimetres.":"File has no physical units. Confirm the current millimetre scale before using size estimates.");let Y=c.profile;Y?.build_volume_mm&&(g("build_volume").count=k.dimensions_mm.filter((t,s)=>t>Y.build_volume_mm[s]+I).length,L("build_volume",g("build_volume").count?"Exceeds the supplied build volume in the current orientation. Try another orientation or scale in your slicer.":"Fits by dimensions only in the current orientation; placement and printer exclusions are not checked."));let se=m.filter(t=>t.severity==="error"&&t.status!=="not_run").every(t=>t.status==="pass");if(c.level==="detailed"){_="Spatial index",B=fe(d,u),_="Self-intersections";let t=0;if(ue(B,I,(s,a)=>{u();let y=Array.from(x.subarray(s*3,s*3+3)).filter(h=>x.subarray(a*3,a*3+3).includes(h)).length,v=me(D(d,s),D(d,a),y,I);if(v===1){$("intersections",s);let h=g("intersections");h.triangle_ids.length<128&&h.triangle_ids.push(a)}else v===2&&t++},u),L("intersections"),t&&!g("intersections").count&&z("intersections","inconclusive",`${t} near-contact pairs require inspection at the reported numerical tolerance.`),se&&g("intersections").status==="pass"){_="Shell containment";let s=!1;for(let a=0;a<A.length;a++){u();let y=D(d,A[a][0]),v=[0,1,2].map(M=>(y[0][M]+y[1][M]+y[2][M])/3),h=null;for(let M of[[1,.371,.529],[.217,1,.413],[.317,.193,1]]){let F=ie(B,d,v,M,I,N=>S[N]!==a,u);if(F.some(N=>N.edge))continue;let T=new Map;for(let N of F)T.set(S[N.id],(T.get(S[N.id])||0)+1);h=[...T.values()].filter(N=>N%2===1).length;break}if(h===null){s=!0;continue}(Math.abs(V[a])<=I**3||Math.sign(V[a])!==(h%2?-1:1))&&$("shell_orientation",A[a][0])}L("shell_orientation","Outer shells must face outward; cavity shells face inward."),s&&!g("shell_orientation").count&&z("shell_orientation","inconclusive","Shell containment is numerically ambiguous."),g("shell_orientation").status==="pass"&&(k.volume_mm3=V.reduce((a,y)=>a+y,0),k.volume_valid=!0)}else z("shell_orientation","inconclusive","Requires a closed, consistently wound mesh without intersections.")}else z("shell_orientation","not_run","Run Detailed check for intersections, nested shells and validated volume.");if(Y){_="FDM estimates";let t=g("units").status==="pass";if(!t)for(let s of["build_volume","bed_contact","thin_walls"])z(s,"inconclusive","Confirm physical units first.");if(Y.overhang_degrees!=null)if(!se||(c.level==="detailed"?!k.volume_valid:A.length!==1||V[0]<=0))z("overhangs","inconclusive","Fix triangle winding and mesh defects before estimating overhangs.");else{let s=-Math.sin(Y.overhang_degrees*Math.PI/180),a=0;for(let y=0;y<n;y++){u();let v=D(d,y),h=C(O(v[1],v[0]),O(v[2],v[0])),M=Math.hypot(...h);v.every(F=>F[2]<=I*8)||h[2]/M<s&&($("overhangs",y),a+=M/2)}g("overhangs").estimated=!0,g("overhangs").area_mm2=a,L("overhangs",`Potential support regions above ${Y.overhang_degrees}\xB0 from vertical. +Z is up; bridges/supports are not simulated.`)}if(t){let s=0;for(let y=0;y<n;y++){u();let v=D(d,y);v.every(h=>h[2]<=I*8)&&(s+=Math.hypot(...C(O(v[1],v[0]),O(v[2],v[0])))/2)}g("bed_contact").area_mm2=s,g("bed_contact").estimated=!0,g("bed_contact").count=s<=I**2?1:0,L("bed_contact","Contact area after virtually lowering this model onto an XY bed. Adhesion/stability are not predicted; scene placement is unchanged.");let a=Y.min_wall_mm??Y.line_width_mm;if(a!=null&&c.level==="detailed"&&k.volume_valid){_="Sampled wall thickness";let y=0,v=0,h=1/0,M=Math.max(1,Math.ceil(n/2048));for(let F=0;F<n;F+=M){u();let T=D(d,F),N=C(O(T[1],T[0]),O(T[2],T[0])),de=Math.hypot(...N),pe=N.map(U=>-U/de),ge=[0,1,2].map(U=>(T[0][U]+T[1][U]+T[2][U])/3),ee=ie(B,d,ge,pe,I*8,U=>U!==F,u).sort((U,_e)=>U.t-_e.t);if(!ee.length||ee[0].edge){v++;continue}y++,h=Math.min(h,ee[0].t),ee[0].t<a&&$("thin_walls",F)}Object.assign(g("thin_walls"),{estimated:!0,samples:y,unresolved_samples:v,minimum_sampled_mm:Number.isFinite(h)?h:null}),z("thin_walls",g("thin_walls").count?"issue":"inconclusive",`${y} face-centre samples; threshold ${a} mm. Sampling can miss thin features and does not prove a minimum wall thickness.`)}else a!=null&&z("thin_walls","inconclusive","Requires Detailed check with valid closed volume and confirmed units.")}}}catch(p){if(p.message!=="PRINT_TIME_LIMIT")throw p;for(let j of m)j.status==="not_run"&&(j.message=`Time limit reached during ${_}; this check was not completed.`);if(!q)for(let j of m.slice(0,8))j.status="inconclusive",j.message="Topology check exceeded the time limit; counts are partial.";k.limit_reason="time"}let P=m.slice(0,11);return k.summary=m.some(p=>p.status==="issue"&&p.severity!=="info")?"issues_found":P.some(p=>["not_run","inconclusive"].includes(p.status))||m.some(p=>p.status==="inconclusive")?"incomplete":"no_issues_found",k.elapsed_ms=performance.now()-i,k}export{Se as checkMesh};
1
+ import{a as re}from"./chunk-W5KVLGVR.js";import{h as oe}from"./chunk-IK3WL53C.js";function ae(e={}){let o=e.level??"basic";if(!["basic","detailed"].includes(o))throw new Error("Choose basic or detailed print checks");let l=(n,i,f=1e9)=>{if(!Number.isFinite(n)||n<=0||n>f)throw new Error(`Invalid ${i}`);return n},r=null;if(e.profile!=null){if(e.profile.technology!=="fdm")throw new Error("Only FDM profiles are supported");r={technology:"fdm"};for(let n of["min_wall_mm","line_width_mm"])e.profile[n]!=null&&(r[n]=l(e.profile[n],n));if(e.profile.overhang_degrees!=null&&(r.overhang_degrees=l(e.profile.overhang_degrees,"overhang angle",89.9)),e.profile.build_volume_mm!=null){if(!Array.isArray(e.profile.build_volume_mm)||e.profile.build_volume_mm.length!==3)throw new Error("Build volume requires X, Y and Z");r.build_volume_mm=e.profile.build_volume_mm.map(n=>l(n,"build volume"))}}let c=l(e.max_time_ms??3e4,"check time limit",12e4);return{level:o,profile:r,apply_transforms:e.apply_transforms!==!1,units_confirmed:e.units_confirmed===!0,max_time_ms:c}}var le=e=>64*1024**2+e*2400;var O=(e,o)=>e.map((l,r)=>l-o[r]),R=(e,o)=>e.reduce((l,r,c)=>l+r*o[c],0),C=(e,o)=>[e[1]*o[2]-e[2]*o[1],e[2]*o[0]-e[0]*o[2],e[0]*o[1]-e[1]*o[0]];function D(e,o){return[0,3,6].map(l=>Array.from(e.subarray(o*9+l,o*9+l+3)))}function fe(e,o){let l=e.length/9,r=new Float64Array(l*6);for(let i=0;i<l;i++){i%1024===0&&o();for(let f=0;f<3;f++)r[i*6+f]=Math.min(e[i*9+f],e[i*9+3+f],e[i*9+6+f]),r[i*6+f+3]=Math.max(e[i*9+f],e[i*9+3+f],e[i*9+6+f])}let c=Uint32Array.from({length:l},(i,f)=>f),n=(i,f)=>{o();let w=[1/0,1/0,1/0,-1/0,-1/0,-1/0];for(let u=i;u<f;u++)for(let m=0;m<3;m++)w[m]=Math.min(w[m],r[c[u]*6+m]),w[m+3]=Math.max(w[m+3],r[c[u]*6+m+3]);let _={b:w,start:i,end:f};if(f-i>16){let u=[0,1,2].map(z=>w[z+3]-w[z]),m=u.indexOf(Math.max(...u));c.subarray(i,f).sort((z,$)=>r[z*6+m]+r[z*6+m+3]-(r[$*6+m]+r[$*6+m+3]));let g=i+f>>>1;_.left=n(i,g),_.right=n(g,f)}return _};return{root:n(0,l),ids:c,boxes:r}}var ce=(e,o,l)=>[0,1,2].every(r=>e[r]<=o[r+3]+l&&e[r+3]+l>=o[r]);function ue(e,o,l,r){let c=(n,i,f)=>{if(r(),!!ce(n.b,i.b,o))if(!n.left&&!i.left)for(let w=n.start;w<n.end;w++)for(let _=i.start;_<i.end;_++){let u=e.ids[w],m=e.ids[_];f&&u>=m||ce(e.boxes.subarray(u*6,u*6+6),e.boxes.subarray(m*6,m*6+6),o)&&l(u,m)}else f?(c(n.left,n.left,!0),c(n.left,n.right,!1),c(n.right,n.right,!0)):n.left&&(!i.left||n.end-n.start>=i.end-i.start)?(c(n.left,i,!1),c(n.right,i,!1)):(c(n,i.left,!1),c(n,i.right,!1))};c(e.root,e.root,!0)}var G=(e,o,l)=>(o[0]-e[0])*(l[1]-e[1])-(o[1]-e[1])*(l[0]-e[0]);function me(e,o,l,r){let c=C(O(e[1],e[0]),O(e[2],e[0])),n=C(O(o[1],o[0]),O(o[2],o[0])),i=Math.hypot(...c),f=Math.hypot(...n);if(!i||!f)return 0;let w=o.map(d=>R(O(d,e[0]),c)/i),_=e.map(d=>R(O(d,o[0]),n)/f);if([w,_].some(d=>d.every(b=>b>r)||d.every(b=>b<-r)))return 0;let u=C(c.map(d=>d/i),n.map(d=>d/f));if(Math.hypot(...u)<1e-10){if(Math.max(...w.map(Math.abs))>r)return 0;let d=c.map(Math.abs).indexOf(Math.max(...c.map(Math.abs))),b=A=>A.filter((S,I)=>I!==d);if(l>=2){let A=(I,k)=>I.every((P,p)=>P===k[p]),S=e.filter(I=>o.some(k=>A(I,k)));if(S.length===3)return 1;if(S.length===2){let I=e.find(P=>!S.some(p=>A(P,p))),k=o.find(P=>!S.some(p=>A(P,p)));return G(b(S[0]),b(S[1]),b(I))*G(b(S[0]),b(S[1]),b(k))>0?1:0}}let E=e.map(b),q=o.map(b),B=Math.sign(G(...q));for(let A=0;A<3&&E.length;A++){let S=q[A],I=q[(A+1)%3],k=[];for(let P=0;P<E.length;P++){let p=E[P],j=E[(P+1)%E.length],x=B*G(S,I,p),Q=B*G(S,I,j);if(x>=0&&k.push(p),x>=0!=Q>=0){let K=x/(x-Q);k.push(p.map((Z,W)=>Z+(j[W]-Z)*K))}}E=k}return Math.abs(E.reduce((A,S,I)=>{let k=E[(I+1)%E.length],P=E[0];return A+(S[0]-P[0])*(k[1]-P[1])-(S[1]-P[1])*(k[0]-P[0])},0))/2>r*r*4?1:0}if(l>=2)return 0;let m=u.map(d=>d/Math.hypot(...u)),g=(d,b)=>{let E=[];for(let q=0;q<3;q++){Math.abs(b[q])<=r&&E.push(R(d[q],m));let B=(q+1)%3;if(b[q]*b[B]<0){let V=b[q]/(b[q]-b[B]);E.push(R(d[q].map((A,S)=>A+(d[B][S]-A)*V),m))}}return E.length?[Math.min(...E),Math.max(...E)]:null},z=g(e,_),$=g(o,w);if(!z||!$)return 0;let L=Math.min(z[1],$[1])-Math.max(z[0],$[0]);return L>r?1:l?0:L>=-r?2:0}function ye(e,o,l,r){let c=O(l[1],l[0]),n=O(l[2],l[0]),i=C(o,n),f=R(c,i);if(Math.abs(f)<=Math.hypot(...c)*Math.hypot(...n)*1e-12)return null;let w=O(e,l[0]),_=R(w,i)/f,u=C(w,c),m=R(o,u)/f,g=R(n,u)/f;return _<-1e-10||m<-1e-10||_+m>1+1e-10||g<=r?null:{t:g,edge:Math.min(_,m,1-_-m)<1e-8}}function ve(e,o,l,r){let c=0,n=1/0;for(let i=0;i<3;i++)if(Math.abs(o[i])<1e-15){if(e[i]<l[i]-r||e[i]>l[i+3]+r)return!1}else{let f=(l[i]-r-e[i])/o[i],w=(l[i+3]+r-e[i])/o[i];if(c=Math.max(c,Math.min(f,w)),n=Math.min(n,Math.max(f,w)),c>n)return!1}return!0}function ie(e,o,l,r,c,n,i){let f=[],w=_=>{if(i(),!!ve(l,r,_.b,c))if(_.left)w(_.left),w(_.right);else for(let u=_.start;u<_.end;u++){let m=e.ids[u];if(!n(m))continue;let g=ye(l,r,D(o,m),c);g&&f.push({...g,id:m})}};return w(e.root),f}var we=[["degenerate_faces","Degenerate triangles","error"],["near_degenerate_faces","Very small or thin triangles","warning"],["duplicate_faces","Duplicate triangles","error"],["boundary_edges","Open boundaries","error"],["nonmanifold_edges","Non-manifold edges","error"],["nonmanifold_vertices","Non-manifold vertices","error"],["winding","Triangle winding","error"],["components","Separate connected parts","info"],["intersections","Self-intersections","error"],["shell_orientation","Shell orientation and volume","error"],["units","Physical units","warning"],["build_volume","Build volume fit","warning"],["overhangs","Overhangs","warning"],["bed_contact","Bed contact","warning"],["thin_walls","Thin walls / small features","warning"]];function Se(e,o={},l={},r=()=>{}){let c=ae(o),n=e.positions.length/9;if(!(e.positions instanceof Float32Array)||!Number.isSafeInteger(n)||n<1||e.matrix?.length!==16||Array.from(e.matrix).some(p=>!Number.isFinite(p)))throw new Error("Invalid print-check geometry");if(n>(l.max_triangles??5e6))throw new Error("Print check triangle limit exceeded");re(l,le(n),"print check");let i=performance.now(),f=i+c.max_time_ms,w=0,_="Topology",u=()=>{if(++w%128===0){if(performance.now()>f)throw new Error("PRINT_TIME_LIMIT");r({phase:_,elapsed_ms:performance.now()-i})}},m=we.map(([p,j,x])=>({code:p,label:j,severity:x,status:"not_run",count:0,triangle_ids:[],edge_vertices:[],message:"Not run"})),g=p=>m.find(j=>j.code===p),z=(p,j,x)=>Object.assign(g(p),{status:j,message:x}),$=(p,j)=>{let x=g(p);x.count++,j!=null&&x.triangle_ids.length<128&&x.triangle_ids.push(j)},L=(p,j)=>{let x=g(p);x.status=x.count?"issue":"pass",x.message=j||`${x.count} found`},d=new Float64Array(e.positions.length),b=[1/0,1/0,1/0],E=[-1/0,-1/0,-1/0],q=!1,B,V=[],A=[],S,I=0,k={model_id:e.id,name:e.name,triangles:n,checks:m,settings:c,dimensions_mm:null,volume_mm3:null,volume_valid:!1,elapsed_ms:0,summary:"incomplete"};try{r({phase:_,elapsed_ms:0});for(let t=0;t<e.positions.length;t+=3){t%3072===0&&u();let s=oe(e.matrix,Array.from(e.positions.subarray(t,t+3)));if(s.some(a=>!Number.isFinite(a)))throw new Error("Invalid print-check coordinate");d.set(s,t);for(let a=0;a<3;a++)b[a]=Math.min(b[a],s[a]),E[a]=Math.max(E[a],s[a])}k.dimensions_mm=E.map((t,s)=>t-b[s]);let p=Math.max(...k.dimensions_mm),j=Math.max(...b.map(Math.abs),...E.map(Math.abs));I=Math.max(p*1e-10,j*Number.EPSILON*64,1e-12),k.tolerance_mm=I;for(let t=0;t<d.length;t++)d[t]-=b[t%3];let x=new Uint32Array(n*3),Q=[],K=new Map,Z=new Map,W=new Map,H=[],J=Int32Array.from({length:n},(t,s)=>s),te=t=>{for(;J[t]!==t;)J[t]=J[J[t]],t=J[t];return t},he=(t,s)=>{t=te(t),s=te(s),t!==s&&(J[s]=t)};for(let t=0;t<n;t++){u();for(let h=0;h<3;h++){let M=t*9+h*3,F=Array.from(e.positions.subarray(M,M+3)).join(","),T=K.get(F);T===void 0&&(T=Q.length,K.set(F,T),Q.push(M),H.push([])),x[t*3+h]=T,H[T].push(t)}let s=D(d,t),a=C(O(s[1],s[0]),O(s[2],s[0])),y=Math.hypot(...a);y?y<=I*Math.max(...s.map((h,M)=>Math.hypot(...O(h,s[(M+1)%3]))))&&$("near_degenerate_faces",t):$("degenerate_faces",t);let v=Array.from(x.subarray(t*3,t*3+3)).sort((h,M)=>h-M).join(":");W.has(v)?$("duplicate_faces",t):W.set(v,t);for(let h=0;h<3;h++){let M=x[t*3+h],F=x[t*3+(h+1)%3],T=Math.min(M,F)+":"+Math.max(M,F),N=Z.get(T);N||(N={a:M,b:F,faces:[],direction:0},Z.set(T,N)),N.faces.length&&he(t,N.faces[0]),N.faces.push(t),N.direction+=M<F?1:-1}}let ne=new Set;for(let t of Z.values()){u();let s;if(t.faces.length===1?s="boundary_edges":t.faces.length!==2?(s="nonmanifold_edges",ne.add(t.a),ne.add(t.b)):t.direction!==0&&(s="winding"),s){$(s,t.faces[0]);let a=g(s);a.edge_vertices.length<256*6&&a.edge_vertices.push(...e.positions.subarray(Q[t.a],Q[t.a]+3),...e.positions.subarray(Q[t.b],Q[t.b]+3))}}for(let t=0;t<H.length;t++){if(u(),ne.has(t)){$("nonmanifold_vertices",H[t][0]);continue}let s=new Set(H[t]),a=new Set,y=[H[t][0]];for(;y.length;){u();let v=y.pop();if(!a.has(v)){a.add(v);for(let h=0;h<3;h++){let M=x[v*3+h],F=x[v*3+(h+1)%3];if(M!==t&&F!==t)continue;let T=Z.get(Math.min(M,F)+":"+Math.max(M,F));for(let N of T.faces)a.has(N)||y.push(N)}}}a.size!==s.size&&$("nonmanifold_vertices",H[t][0])}let X=new Map;S=new Int32Array(n);for(let t=0;t<n;t++){u();let s=te(t);X.has(s)||(X.set(s,X.size),A.push([]),V.push(0));let a=X.get(s);S[t]=a,A[a].push(t);let y=D(d,t),v=D(d,A[a][0])[0];V[a]+=R(O(y[0],v),C(O(y[1],v),O(y[2],v)))/6}for(let t of["degenerate_faces","near_degenerate_faces","duplicate_faces","boundary_edges","nonmanifold_edges","nonmanifold_vertices","winding"])L(t);g("components").count=X.size,z("components",X.size>1?"issue":"pass",`${X.size} connected part${X.size===1?"":"s"}. Separate parts can be intentional.`),q=!0,z("units",e.source_units||c.units_confirmed?"pass":"inconclusive",e.source_units?`File units: ${e.source_units}; measurements in mm.`:c.units_confirmed?"Current scale confirmed as millimetres.":"File has no physical units. Confirm the current millimetre scale before using size estimates.");let Y=c.profile;Y?.build_volume_mm&&(g("build_volume").count=k.dimensions_mm.filter((t,s)=>t>Y.build_volume_mm[s]+I).length,L("build_volume",g("build_volume").count?"Exceeds the supplied build volume in the current orientation. Try another orientation or scale in your slicer.":"Fits by dimensions only in the current orientation; placement and printer exclusions are not checked."));let se=m.filter(t=>t.severity==="error"&&t.status!=="not_run").every(t=>t.status==="pass");if(c.level==="detailed"){_="Spatial index",B=fe(d,u),_="Self-intersections";let t=0;if(ue(B,I,(s,a)=>{u();let y=Array.from(x.subarray(s*3,s*3+3)).filter(h=>x.subarray(a*3,a*3+3).includes(h)).length,v=me(D(d,s),D(d,a),y,I);if(v===1){$("intersections",s);let h=g("intersections");h.triangle_ids.length<128&&h.triangle_ids.push(a)}else v===2&&t++},u),L("intersections"),t&&!g("intersections").count&&z("intersections","inconclusive",`${t} near-contact pairs require inspection at the reported numerical tolerance.`),se&&g("intersections").status==="pass"){_="Shell containment";let s=!1;for(let a=0;a<A.length;a++){u();let y=D(d,A[a][0]),v=[0,1,2].map(M=>(y[0][M]+y[1][M]+y[2][M])/3),h=null;for(let M of[[1,.371,.529],[.217,1,.413],[.317,.193,1]]){let F=ie(B,d,v,M,I,N=>S[N]!==a,u);if(F.some(N=>N.edge))continue;let T=new Map;for(let N of F)T.set(S[N.id],(T.get(S[N.id])||0)+1);h=[...T.values()].filter(N=>N%2===1).length;break}if(h===null){s=!0;continue}(Math.abs(V[a])<=I**3||Math.sign(V[a])!==(h%2?-1:1))&&$("shell_orientation",A[a][0])}L("shell_orientation","Outer shells must face outward; cavity shells face inward."),s&&!g("shell_orientation").count&&z("shell_orientation","inconclusive","Shell containment is numerically ambiguous."),g("shell_orientation").status==="pass"&&(k.volume_mm3=V.reduce((a,y)=>a+y,0),k.volume_valid=!0)}else z("shell_orientation","inconclusive","Requires a closed, consistently wound mesh without intersections.")}else z("shell_orientation","not_run","Run Detailed check for intersections, nested shells and validated volume.");if(Y){_="FDM estimates";let t=g("units").status==="pass";if(!t)for(let s of["build_volume","bed_contact","thin_walls"])z(s,"inconclusive","Confirm physical units first.");if(Y.overhang_degrees!=null)if(!se||(c.level==="detailed"?!k.volume_valid:A.length!==1||V[0]<=0))z("overhangs","inconclusive","Fix triangle winding and mesh defects before estimating overhangs.");else{let s=-Math.sin(Y.overhang_degrees*Math.PI/180),a=0;for(let y=0;y<n;y++){u();let v=D(d,y),h=C(O(v[1],v[0]),O(v[2],v[0])),M=Math.hypot(...h);v.every(F=>F[2]<=I*8)||h[2]/M<s&&($("overhangs",y),a+=M/2)}g("overhangs").estimated=!0,g("overhangs").area_mm2=a,L("overhangs",`Potential support regions above ${Y.overhang_degrees}\xB0 from vertical. +Z is up; bridges/supports are not simulated.`)}if(t){let s=0;for(let y=0;y<n;y++){u();let v=D(d,y);v.every(h=>h[2]<=I*8)&&(s+=Math.hypot(...C(O(v[1],v[0]),O(v[2],v[0])))/2)}g("bed_contact").area_mm2=s,g("bed_contact").estimated=!0,g("bed_contact").count=s<=I**2?1:0,L("bed_contact","Contact area after virtually lowering this model onto an XY bed. Adhesion/stability are not predicted; scene placement is unchanged.");let a=Y.min_wall_mm??Y.line_width_mm;if(a!=null&&c.level==="detailed"&&k.volume_valid){_="Sampled wall thickness";let y=0,v=0,h=1/0,M=Math.max(1,Math.ceil(n/2048));for(let F=0;F<n;F+=M){u();let T=D(d,F),N=C(O(T[1],T[0]),O(T[2],T[0])),de=Math.hypot(...N),pe=N.map(U=>-U/de),ge=[0,1,2].map(U=>(T[0][U]+T[1][U]+T[2][U])/3),ee=ie(B,d,ge,pe,I*8,U=>U!==F,u).sort((U,_e)=>U.t-_e.t);if(!ee.length||ee[0].edge){v++;continue}y++,h=Math.min(h,ee[0].t),ee[0].t<a&&$("thin_walls",F)}Object.assign(g("thin_walls"),{estimated:!0,samples:y,unresolved_samples:v,minimum_sampled_mm:Number.isFinite(h)?h:null}),z("thin_walls",g("thin_walls").count?"issue":"inconclusive",`${y} face-centre samples; threshold ${a} mm. Sampling can miss thin features and does not prove a minimum wall thickness.`)}else a!=null&&z("thin_walls","inconclusive","Requires Detailed check with valid closed volume and confirmed units.")}}}catch(p){if(p.message!=="PRINT_TIME_LIMIT")throw p;for(let j of m)j.status==="not_run"&&(j.message=`Time limit reached during ${_}; this check was not completed.`);if(!q)for(let j of m.slice(0,8))j.status="inconclusive",j.message="Topology check exceeded the time limit; counts are partial.";k.limit_reason="time"}let P=m.slice(0,11);return k.summary=m.some(p=>p.status==="issue"&&p.severity!=="info")?"issues_found":P.some(p=>["not_run","inconclusive"].includes(p.status))||m.some(p=>p.status==="inconclusive")?"incomplete":"no_issues_found",k.elapsed_ms=performance.now()-i,k}export{Se as checkMesh};
@@ -1 +1 @@
1
- import{c as a}from"./chunk-R3HNTB5A.js";import"./chunk-ZSV4PTIA.js";import{e as p}from"./chunk-JH3H3JWA.js";import"./chunk-JS56KC3I.js";import"./chunk-U33KANV7.js";function g(i,t,l,n){let o=[];for(let e of t)o.push({id:e.id,bin:p(e,e.scale,e.center)}),n({loaded:o.length,total:t.length,phase:"exporting"});n({loaded:t.length,total:t.length,phase:"packaging"});let c=a({vsj:i,files:o},l);return n({loaded:t.length,total:t.length,phase:"complete"}),new Blob([c],{type:"application/zip"})}export{g as exportSceneArchive};
1
+ import{c as a}from"./chunk-Y6VY64LY.js";import"./chunk-ZSV4PTIA.js";import{e as p}from"./chunk-OP2L7L4N.js";import"./chunk-W5KVLGVR.js";import"./chunk-IK3WL53C.js";function g(i,t,l,n){let o=[];for(let e of t)o.push({id:e.id,bin:p(e,e.scale,e.center)}),n({loaded:o.length,total:t.length,phase:"exporting"});n({loaded:t.length,total:t.length,phase:"packaging"});let c=a({vsj:i,files:o},l);return n({loaded:t.length,total:t.length,phase:"complete"}),new Blob([c],{type:"application/zip"})}export{g as exportSceneArchive};
@@ -0,0 +1 @@
1
+ import{b as v}from"./chunk-Y6VY64LY.js";import"./chunk-ZSV4PTIA.js";import{b as _}from"./chunk-OP2L7L4N.js";import"./chunk-W5KVLGVR.js";import"./chunk-IK3WL53C.js";var I=["flat","smooth","wireframe","edges","mesh","xray","studio","orientation"];function E(e,n){if(!I.includes(e))throw new Error("Invalid display mode");if(typeof n!="boolean")throw new Error("smooth_shading must be a boolean");return{display:e,smooth_shading:e==="smooth"||n}}function S(e){if(e==null)return null;if(!["x","y","z"].includes(e.axis))throw new Error("Section axis must be x, y or z");if(!Number.isFinite(e.position)||e.position<0||e.position>1)throw new Error("Section position must be between 0 and 1");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new Error("Section flip must be a boolean");return{axis:e.axis,position:e.position,flip:e.flip??!1}}var g=["x","y","z","rotationx","rotationy","rotationz","scalex","scaley","scalez"],f=e=>e.startsWith("scale"),d=(e,n,r=!1)=>{if(typeof e!="number"||!Number.isFinite(e)||Math.abs(e)>Number.MAX_SAFE_INTEGER||r&&e<=0)throw new Error(`Invalid animation ${n}`);return e},h=(e,n)=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid animation ${n}`);return e};function j(e){return Object.fromEntries(g.map(n=>[n,d(e[n]??(f(n)?e.scale??1:0),n,f(n))]))}function y(e){h(e,"definition");let n={},r=new Set;for(let t of["delta","exact"]){if(e[t]==null)continue;let o=h(e[t],t),i={},s=d(o.msec??300,"duration",!0);if(o.loop!==void 0&&typeof o.loop!="boolean")throw new Error("Animation loop must be a boolean");let l=t==="delta"&&!!o.loop;for(let a of g){let c=o[a]??(f(a)?o.scale:void 0);if(c!==void 0){if(r.has(a))throw new Error(`Animation delta/exact conflict: ${a}`);if(d(c,a,t==="exact"&&f(a)),l&&f(a)&&c<0)throw new Error("Looping scale deltas cannot be negative");i[a]=c,r.add(a)}}if(!Object.keys(i).length)throw new Error("Animation track needs a transform");n[t]={...i,msec:s,...l?{loop:!0}:{}}}if(!Object.keys(n).length)throw new Error("Animation needs delta or exact");return n}function x(e){if(h(e,"playback state"),e.version!==1||typeof e.paused!="boolean")throw new Error("Invalid animation playback state version or paused flag");let n=d(e.elapsed_ms,"elapsed time");if(n<0)throw new Error("Invalid animation elapsed time");h(e.origin,"origin");for(let r of g)d(e.origin[r],r,f(r));if(!Array.isArray(e.center)||e.center.length!==3)throw new Error("Invalid animation pivot");return{version:1,elapsed_ms:n,paused:e.paused,origin:j(e.origin),center:e.center.map(r=>d(r,"pivot"))}}function k(e,n,r){let t=y(e),o=r==null?null:x(r),i=o?.origin??j(n),s=Object.entries(t).map(([a,c])=>{let p=Object.entries(c).filter(([u])=>g.includes(u));if(a==="delta")for(let[u,A]of p)d(i[u]+A,`${u} endpoint`,f(u));return{mode:a,values:p,duration:c.msec,loop:!!c.loop,done:!1}}),l={animation:t,origin:i,tracks:s,elapsed_ms:o?.elapsed_ms??0,paused:o?.paused??!1,last_time:null};return O({...l,tracks:s.map(a=>({...a}))},{}),l}function O(e,n){let r=[];for(let o of e.tracks){if(o.done)continue;let i=e.elapsed_ms/o.duration,s=o.loop?i:Math.min(i,1);for(let[l,a]of o.values){let c=e.origin[l],p=o.mode==="delta"?c+a*s:c*(1-s)+a*s;r.push([l,d(p,`${l} result`,f(l))])}}let t=!1;for(let[o,i]of r)t||=f(o)&&n[o]!==i,n[o]=i;for(let o of e.tracks)!o.loop&&e.elapsed_ms>=o.duration&&(o.done=!0);return t&&(n._stats=null),e.tracks.some(o=>!o.done)}var w=["x","y","z"],m=(e,n,r=!1)=>{if(typeof e!="number"||!Number.isFinite(e)||r&&e<=0)throw new Error(`Invalid scene ${n}`);return e},P=e=>String(e||"").match(/\.(vsb|vsj)(?:[?#]|$)/i)?.[1].toLowerCase()||"";function b(e,n){if(!e||!Array.isArray(e.models)||!e.models.length||e.models.length>n.max_archive_entries)throw new Error("Invalid, empty or oversized scene manifest");let r={models:[]};for(let t of["center_models","auto_rotate","grid"])if(e[t]!==void 0){if(typeof e[t]!="boolean")throw new Error(`Invalid scene ${t}`);r[t]=e[t]}if(e.bg_color!==void 0&&(e.bg_color!=="transparent"&&_(e.bg_color),r.bg_color=e.bg_color),e.infinite_grid&&(r.infinite_grid={spacing:m(e.infinite_grid.spacing,"grid spacing",!0),height:m(e.infinite_grid.height,"grid height")}),e.camera_state){let t={};for(let s of["position","target","up"])t[s]=Object.fromEntries(w.map(l=>[l,m(e.camera_state[s]?.[l],"camera")]));let o=w.map(s=>t.position[s]-t.target[s]),i=w.map(s=>t.up[s]);if(!Math.hypot(...o)||!Math.hypot(...i)||!Math.hypot(o[1]*i[2]-o[2]*i[1],o[2]*i[0]-o[0]*i[2],o[0]*i[1]-o[1]*i[0]))throw new Error("Invalid scene camera");r.camera_state=t}for(let t of e.models){if(!t||typeof t.filename!="string"||!t.filename||t.filename.length>8192||/[\x00-\x1f\x7f]/.test(t.filename))throw new Error("Scene model filename is missing or invalid");if(P(t.filename))throw new Error("Nested scene references are not supported");let o={filename:t.filename};typeof t.orig_filename=="string"&&(o.orig_filename=t.orig_filename.slice(0,200));for(let i of w)for(let s of["","rotation","scale"]){let l=s+i;t[l]!==void 0&&(o[l]=m(t[l],l,s==="scale"))}if(t.scale!==void 0&&(o.scale=m(t.scale,"scale",!0)),t.opacity!==void 0&&(o.opacity=m(t.opacity,"opacity"),o.opacity<0||o.opacity>1))throw new Error("Invalid scene opacity");if(t.color!=null&&(t.color!=="transparent"&&_(t.color),o.color=t.color),o.units=t.units??"mm",!["mm","inch"].includes(o.units))throw new Error("Invalid scene units");if(Object.assign(o,E(t.display??"flat",t.smooth_shading??t.display==="smooth")),o.section=S(t.section),t.view_edges!==void 0&&typeof t.view_edges!="boolean")throw new Error("Invalid scene edges");if(o.view_edges=!!t.view_edges,t.animation!=null&&(o.animation=y(t.animation)),t.animation_state!=null){if(!o.animation)throw new Error("Playback state needs an animation");o.animation_state=x(t.animation_state)}o.animation&&k(o.animation,o,o.animation_state),r.models.push(o)}return r}function C(e,n,r){let t=Object.create(null),o=e;if(n==="vsb"){let i=v(e,r);if(o=i.get("json_data.vsj"),!o)throw new Error("VSB manifest json_data.vsj is missing");let s=b(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(o)),r);for(let l of s.models){let a=i.get(l.filename);if(!a)throw new Error("VSB model file is missing: "+l.filename);t[l.filename]=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)}return{scene:s,files:t}}return{scene:b(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(o)),r),files:null}}export{C as readSceneDocument};