mjswan 0.4.1 → 0.4.3

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.
@@ -15610,4 +15610,4 @@ fn calculateOutputIndex(index: u32) -> u32 {
15610
15610
  }`},CR=n=>{let e=n[1].dims,t=n[2].dims,r=n[0].dims,i=n[1].dataType,s=!(Pe.areEqual(e,t)&&Pe.areEqual(t,r)),a=e,o=Pe.size(e);if(s){let c=Wd.calcShape(Wd.calcShape(e,t,!1),r,!1);if(!c)throw new Error("Can't perform where op on the given tensors");a=c,o=Pe.size(a)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>ER(c,n,a,s,i),getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...Ct(r,e,t,a)]})}},mz=n=>{n.compute(CR(n.inputs))}}),gz,Ite=Ze(()=>{Uee(),YC(),Oee(),$ee(),Gee(),Hee(),Vee(),Xee(),Kee(),Zee(),ete(),tte(),nte(),rte(),ite(),ste(),ate(),ote(),lte(),cte(),ute(),dte(),hte(),fte(),pte(),PF(),Ate(),mte(),gte(),yte(),xte(),qC(),vte(),OF(),_te(),bte(),wte(),zF(),Ete(),Ol(),XC(),Cte(),gz=new Map([["Abs",[uL]],["Acos",[dL]],["Acosh",[hL]],["Add",[jL]],["ArgMax",[aL,ww]],["ArgMin",[sL,ww]],["Asin",[fL]],["Asinh",[pL]],["Atan",[AL]],["Atanh",[mL]],["Attention",[oL]],["AveragePool",[XF,YF]],["BatchNormalization",[lL]],["BiasAdd",[cL]],["BiasSplitGelu",[VL]],["Cast",[yL,gL]],["Ceil",[vL]],["Clip",[xL]],["Concat",[nF,rF]],["Conv",[Mw,Bw]],["ConvTranspose",[fF,hF]],["Cos",[_L]],["Cosh",[bL]],["CumSum",[pF,AF]],["DepthToSpace",[mF,gF]],["DequantizeLinear",[rz,iz]],["Div",[WL]],["Einsum",[yF,xF]],["Elu",[wL,np]],["Equal",[qL]],["Erf",[EL]],["Exp",[CL]],["Expand",[vF]],["FastGelu",[_F]],["Floor",[IL]],["FusedConv",[Mw,Bw]],["Gather",[wF,bF]],["GatherElements",[MF,BF]],["GatherBlockQuantized",[IF,SF]],["GatherND",[EF,CF]],["Gelu",[SL]],["Gemm",[RF,TF]],["GlobalAveragePool",[KF,JF]],["GlobalMaxPool",[nz,tz]],["Greater",[KL]],["GreaterOrEqual",[eF]],["GridSample",[DF,kF]],["GroupQueryAttention",[$F]],["HardSigmoid",[QL,NL]],["InstanceNormalization",[GF]],["LayerNormalization",[HF]],["LeakyRelu",[BL,np]],["Less",[ZL]],["LessOrEqual",[tF]],["Log",[GL]],["MatMul",[VF]],["MatMulNBits",[jF,WF]],["MaxPool",[ZF,ez]],["Mul",[YL]],["MultiHeadAttention",[QF,NF]],["Neg",[TL]],["Not",[ML]],["Pad",[qF]],["Pow",[XL]],["QuickGelu",[HL,np]],["Range",[sz]],["Reciprocal",[RL]],["ReduceMin",[eL]],["ReduceMean",[YP]],["ReduceMax",[ZP]],["ReduceSum",[nL]],["ReduceProd",[tL]],["ReduceL1",[XP]],["ReduceL2",[JP]],["ReduceLogSum",[iL]],["ReduceLogSumExp",[KP]],["ReduceSumSquare",[rL]],["Relu",[DL]],["Resize",[lz,cz]],["RotaryEmbedding",[UF]],["ScatterND",[oz,az]],["Sigmoid",[kL]],["Sin",[PL]],["Sinh",[LL]],["Slice",[dz,hz]],["SkipLayerNormalization",[uz]],["Split",[LF,FF]],["Sqrt",[FL]],["Softmax",[fz,pz]],["Sub",[JL]],["Tan",[zL]],["Tanh",[UL]],["ThresholdedRelu",[$L,np]],["Tile",[Az]],["Transpose",[LP,FP]],["Where",[mz]]])}),yz,Ste=Ze(()=>{ms(),Ro(),Wt(),yz=class{constructor(n){this.backend=n,this.repo=new Map,this.attributesBound=!1}getArtifact(n){return this.repo.get(n)}setArtifact(n,e){this.repo.set(n,e)}run(n,e,t,r,i){Qa(n.programInfo.name);let s=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let o=[];for(let c of e)o.push({binding:o.length,resource:{buffer:c.buffer}});for(let c of t)o.push({binding:o.length,resource:{buffer:c.buffer}});i&&o.push({binding:o.length,resource:i});let l=s.createBindGroup({layout:n.computePipeline.getBindGroupLayout(0),entries:o,label:n.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:n.computePipeline,bindGroup:l,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}a.setPipeline(n.computePipeline),a.setBindGroup(0,l),a.dispatchWorkgroups(...r),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Js(n.programInfo.name)}dispose(){}build(n,e){Qa(n.name);let t=this.backend.device,r=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(c=>{t.features.has(c.feature)&&r.push(`enable ${c.extension};`)});let i=PP(e,this.backend.device.limits),s=n.getShaderSource(i),a=`${r.join(`
15611
15611
  `)}
15612
15612
  ${i.additionalImplementations}
15613
- ${s}`,o=t.createShaderModule({code:a,label:n.name});un("verbose",()=>`[WebGPU] ${n.name} shader code: ${a}`);let l=t.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:n.name});return Js(n.name),{programInfo:n,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(n){let e=typeof n=="number"?n:n.x,t=typeof n=="number"?1:n.y||1,r=typeof n=="number"?1:n.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=i&&t<=i&&r<=i)return[e,t,r];let s=e*t*r,a=Math.ceil(Math.sqrt(s));if(a>i){if(a=Math.ceil(Math.cbrt(s)),a>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),xz={};mh(xz,{WebGpuBackend:()=>vz});var IR,SR,BR,vz,Bte=Ze(()=>{ms(),Lt(),Ro(),RP(),Fee(),Ite(),Ste(),IR=(n,e)=>{if(e.length!==n.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${n.length}.`);let t=[];for(let r=0;r<n.length;++r){let i=n[r].dataType;switch(e[r]){case"none":{t.push("");break}case"type":{t.push(`${i}`);break}case"rank":{let s=n[r].dims.length;t.push(`${i};${s}`);break}case"dims":{let s=n[r].dims.join(",");t.push(`${i};${s}`);break}default:throw new Error(`unsupported input dependency: ${e[r]}`)}}return t.join("|")},SR=(n,e,t)=>{let r=n.name;return n.shaderCache?.hint&&(r+="["+n.shaderCache.hint+"]"),r+=":"+t+`:${IR(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},BR=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},vz=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let n=this.kernelCustomData.get(this.currentKernelId);return n||(n={},this.kernelCustomData.set(this.currentKernelId,n)),n}async initialize(n,e){this.env=n;let t=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxBufferSize:e.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:e.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:e.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:e.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:e.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},i=s=>e.features.has(s)&&t.push(s)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await e.requestDevice(r),this.adapterInfo=new BR(e.info||await e.requestAdapterInfo()),this.gpuDataManager=NP(this),this.programManager=new yz(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,HC(n.logLevel,!!n.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let n=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Qa(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(n.getMappedRange()),t=this.pendingQueries.get(n);for(let r=0;r<e.length/2;r++){let i=t[r],s=i.kernelId,a=this.kernels.get(s),o=a.kernelType,l=a.kernelName,c=i.programName,d=i.inputTensorViews,h=i.outputTensorViews,p=e[r*2],A=e[r*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=p);let g=Number(p-this.queryTimeBase),m=Number(A-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(m))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(x=>({dims:x.dims,dataType:uo(x.dataType)})),outputsMetadata:h.map(x=>({dims:x.dims,dataType:uo(x.dataType)})),kernelId:s,kernelType:o,kernelName:l,programName:c,startTime:g,endTime:m});else{let x="";d.forEach((_,b)=>{x+=`input[${b}]: [${_.dims}] | ${uo(_.dataType)}, `});let y="";h.forEach((_,b)=>{y+=`output[${b}]: [${_.dims}] | ${uo(_.dataType)}, `}),console.log(`[profiling] kernel "${s}|${o}|${l}|${c}" ${x}${y}start time: ${g} ns, execution time: ${m-g} ns`)}Og("GPU",`${c}::${p}::${A}`)}n.unmap(),this.pendingQueries.delete(n)}),Js()}run(n,e,t,r,i,s){Qa(n.name);let a=[];for(let _=0;_<e.length;++_){let b=e[_].data;if(b===0)continue;let w=this.gpuDataManager.get(b);if(!w)throw new Error(`no GPU data for input: ${b}`);a.push(w)}let{outputs:o,dispatchGroup:l,programUniforms:c}=n.getRunData(e),d=t.length===0?o.map((_,b)=>b):t;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let h=[],p=[];for(let _=0;_<o.length;++_){if(!Number.isInteger(d[_])||d[_]<-3||d[_]>=s)throw new Error(`Invalid output index: ${d[_]}`);if(d[_]===-3)continue;let b=d[_]===-1,w=d[_]===-2,C=b||w?i(o[_].dataType,o[_].dims):r(d[_],o[_].dataType,o[_].dims);if(h.push(C),C.data===0)continue;let S=this.gpuDataManager.get(C.data);if(!S)throw new Error(`no GPU data for output: ${C.data}`);if(b&&this.temporaryData.push(S),w){let M=this.kernelPersistentData.get(this.currentKernelId);M||(M=[],this.kernelPersistentData.set(this.currentKernelId,M)),M.push(S)}p.push(S)}if(a.length!==e.length||p.length!==h.length){if(p.length===0)return Js(n.name),h;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let A;if(c){let _=0,b=[];c.forEach(M=>{let T=typeof M.data=="number"?[M.data]:M.data;if(T.length===0)return;let R=M.type===10?2:4,k,V;M.type===10?(V=T.length>4?16:T.length>2?8:T.length*R,k=T.length>4?16:R*T.length):(V=T.length<=2?T.length*R:16,k=16),_=Math.ceil(_/V)*V,b.push(_);let P=M.type===10?8:4;_+=T.length>4?Math.ceil(T.length/P)*k:T.length*R});let w=16;_=Math.ceil(_/w)*w;let C=new ArrayBuffer(_);c.forEach((M,T)=>{let R=b[T],k=typeof M.data=="number"?[M.data]:M.data;if(M.type===6)new Int32Array(C,R,k.length).set(k);else if(M.type===12)new Uint32Array(C,R,k.length).set(k);else if(M.type===10)new Uint16Array(C,R,k.length).set(k);else if(M.type===1)new Float32Array(C,R,k.length).set(k);else throw new Error(`Unsupported uniform type: ${uo(M.type)}`)});let S=this.gpuDataManager.create(_,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(S.buffer,0,C,0,_),this.gpuDataManager.release(S.id),A={offset:0,size:_,buffer:S.buffer}}let g=this.programManager.normalizeDispatchGroupSize(l),m=g[1]===1&&g[2]===1,x=SR(n,e,m),y=this.programManager.getArtifact(x);if(y||(y=this.programManager.build(n,g),this.programManager.setArtifact(x,y),un("info",()=>`[artifact] key: ${x}, programName: ${n.name}`)),c&&y.uniformVariablesInfo){if(c.length!==y.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${y.uniformVariablesInfo.length}, got ${c.length} in program "${y.programInfo.name}".`);for(let _=0;_<c.length;_++){let b=c[_],w=b.type,C=typeof b.data=="number"?1:b.data.length,[S,M]=y.uniformVariablesInfo[_];if(w!==S||C!==M)throw new Error(`Uniform variable ${_} mismatch: expect type ${S} with size ${M}, got type ${w} with size ${C} in program "${y.programInfo.name}".`)}}if(un("info",()=>`[ProgramManager] run "${n.name}" (key=${x}) with ${g[0]}x${g[1]}x${g[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let _={kernelId:this.currentKernelId,programName:y.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(_),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(_)}return this.programManager.run(y,a,p,g,A),Js(n.name),h}upload(n,e){this.gpuDataManager.upload(n,e)}memcpy(n,e){this.gpuDataManager.memcpy(n,e)}async download(n,e){await this.gpuDataManager.download(n,e)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,e,t,r){let i=gz.get(n);if(!i)throw new Error(`kernel not implemented: ${n}`);let s={kernelType:n,kernelName:r,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(e,s)}releaseKernel(n){let e=this.kernelPersistentData.get(n);if(e){for(let t of e)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,e,t){let r=this.kernels.get(n);if(!r)throw new Error(`kernel not created: ${n}`);let i=r.kernelType,s=r.kernelName,a=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${s}" is not allowed to be called recursively`);this.currentKernelId=n,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),un("info",()=>`[WebGPU] Start to run kernel "[${i}] ${s}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(e,o[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${s}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${i}] ${s}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,e,t,r){let i=this.sessionExternalDataMapping.get(n);i||(i=new Map,this.sessionExternalDataMapping.set(n,i));let s=i.get(e),a=this.gpuDataManager.registerExternalBuffer(t,r,s);return i.set(e,[a,t]),a}unregisterBuffers(n){let e=this.sessionExternalDataMapping.get(n);e&&(e.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let e=this.gpuDataManager.get(n);if(!e)throw new Error(`no GPU data for buffer: ${n}`);return e.buffer}createDownloader(n,e,t){return async()=>{let r=await vw(this,n,e);return VC(r.buffer,t)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){un("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){un("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){un("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),t=n.length;this.pendingKernels=[];for(let r=0;r<t;r++){let i=this.getComputePassEncoder(),s=n[r];this.writeTimestamp(this.pendingDispatchNumber*2),i.setPipeline(s.computePipeline),i.setBindGroup(0,s.bindGroup),i.dispatchWorkgroups(...s.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(e[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),_z={};mh(_z,{init:()=>bz});var Xm,MR,bz,Mte=Ze(()=>{Lt(),Ro(),jt(),Lee(),Xm=class wz{constructor(e,t,r,i){this.module=e,this.dataType=t,this.data=r,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=Pe.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=Pe.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=Pe.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let e=Pe.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Pe.size(e)!==Pe.size(this.dims))throw new Error("Invalid new shape");return new wz(this.module,this.dataType,this.data,e)}},MR=class{constructor(n,e,t){this.module=n,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let r=n.PTR_SIZE,i=t/n.PTR_SIZE,s=r===4?"i32":"i64";this.opKernelContext=Number(n.getValue(r*i++,s));let a=Number(n.getValue(r*i++,s));this.outputCount=Number(n.getValue(r*i++,s)),this.customDataOffset=Number(n.getValue(r*i++,"*")),this.customDataSize=Number(n.getValue(r*i++,s));let o=[];for(let l=0;l<a;l++){let c=Number(n.getValue(r*i++,s)),d=Number(n.getValue(r*i++,"*")),h=Number(n.getValue(r*i++,s)),p=[];for(let A=0;A<h;A++)p.push(Number(n.getValue(r*i++,s)));o.push(new Xm(n,c,d,p))}this.inputs=o}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(n,e){let t=e?.inputs?.map(a=>typeof a=="number"?this.inputs[a]:a)??this.inputs,r=e?.outputs??[],i=(a,o,l)=>new Xm(this.module,o,this.output(a,l),l),s=(a,o)=>{let l=Rc(a,o);if(!l)throw new Error(`Unsupported data type: ${a}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new Xm(this.module,a,c,o)};return this.backend.run(n,t,r,i,s,this.outputCount)}output(n,e){let t=this.module.stackSave();try{let r=this.module.PTR_SIZE,i=r===4?"i32":"i64",s=this.module.stackAlloc((1+e.length)*r);this.module.setValue(s,e.length,i);for(let a=0;a<e.length;a++)this.module.setValue(s+r*(a+1),e[a],i);return this.module._JsepOutput(this.opKernelContext,n,s)}catch(r){throw new Error(`Failed to generate kernel's output[${n}] with dims [${e}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${r}`)}finally{this.module.stackRestore(t)}}},bz=async(n,e,t,r)=>{let i=e.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(n==="webgpu"){let s=(Bte(),Rp(xz)).WebGpuBackend,a=new s;await a.initialize(t,r),i("webgpu",[a,o=>a.alloc(Number(o)),o=>a.free(o),(o,l,c,d=!1)=>{if(d)un("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(l)}, size=${Number(c)}`),a.memcpy(Number(o),Number(l));else{un("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let h=e.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(c));a.upload(Number(l),h)}},async(o,l,c)=>{un("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${l}, size=${c}`),await a.download(Number(o),()=>e.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(o,l,c)=>a.createKernel(o,Number(l),c,e.UTF8ToString(e._JsepGetNodeName(Number(l)))),o=>a.releaseKernel(o),(o,l,c,d)=>{un("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${o}, contextDataOffset=${l}`);let h=new MR(e,a,Number(l));return a.computeKernel(Number(o),h,d)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let s=new kP(t);i("webnn",[s,()=>s.reserveTensorId(),a=>s.releaseTensorId(a),async(a,o,l,c,d)=>s.ensureTensor(a,o,l,c,d),(a,o)=>{s.uploadTensor(a,o)},async(a,o)=>s.downloadTensor(a,o),(a,o)=>s.registerMLContext(a,o),!!t.trace])}}}),TR,nI,rI,wl,RR,Q_,qg,iI,sI,P_,aI,oI,lI,Ez=Ze(()=>{ms(),Nee(),Qee(),Lt(),tu(),UC(),SP(),TR=(n,e)=>{kn()._OrtInit(n,e)!==0&&wn("Can't initialize onnxruntime.")},nI=async n=>{TR(n.wasm.numThreads,Gg(n.logLevel))},rI=async(n,e)=>{kn().asyncInit?.();let t=n.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(t){if(typeof t.limits!="object"||typeof t.features!="object"||typeof t.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let r=n.webgpu.powerPreference;if(r!==void 0&&r!=="low-power"&&r!=="high-performance")throw new Error(`Invalid powerPreference setting: "${r}"`);let i=n.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:r,forceFallbackAdapter:i}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let r=(Mte(),Rp(_z)).init;e==="webgpu"&&await r("webgpu",kn(),n,t),e==="webnn"&&await r("webnn",kn(),n)}},wl=new Map,RR=n=>{let e=kn(),t=e.stackSave();try{let r=e.PTR_SIZE,i=e.stackAlloc(2*r);e._OrtGetInputOutputCount(n,i,i+r)!==0&&wn("Can't get session input/output count.");let s=r===4?"i32":"i64";return[Number(e.getValue(i,s)),Number(e.getValue(i+r,s))]}finally{e.stackRestore(t)}},Q_=(n,e)=>{let t=kn(),r=t.stackSave(),i=0;try{let s=t.PTR_SIZE,a=t.stackAlloc(2*s);t._OrtGetInputOutputMetadata(n,e,a,a+s)!==0&&wn("Can't get session input/output metadata.");let o=Number(t.getValue(a,"*"));i=Number(t.getValue(a+s,"*"));let l=t.HEAP32[i/4];if(l===0)return[o,0];let c=t.HEAPU32[i/4+1],d=[];for(let h=0;h<c;h++){let p=Number(t.getValue(i+8+h*s,"*"));d.push(p!==0?t.UTF8ToString(p):Number(t.getValue(i+8+(h+c)*s,"*")))}return[o,l,d]}finally{t.stackRestore(r),i!==0&&t._OrtFree(i)}},qg=n=>{let e=kn(),t=e._malloc(n.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return e.HEAPU8.set(n,t),[t,n.byteLength]},iI=async(n,e)=>{let t,r,i=kn();Array.isArray(n)?[t,r]=n:n.buffer===i.HEAPU8.buffer?[t,r]=[n.byteOffset,n.byteLength]:[t,r]=qg(n);let s=0,a=0,o=0,l=[],c=[],d=[];try{if([a,l]=await IP(e),e?.externalData&&i.mountExternalData){let w=[];for(let C of e.externalData){let S=typeof C=="string"?C:C.path;w.push(GC(typeof C=="string"?C:C.data).then(M=>{i.mountExternalData(S,M)}))}await Promise.all(w)}for(let w of e?.executionProviders??[])if((typeof w=="string"?w:w.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof w!="string"){let C=w,S=C?.context,M=C?.gpuDevice,T=C?.deviceType,R=C?.powerPreference;S?i.currentContext=S:M?i.currentContext=await i.webnnCreateMLContext(M):i.currentContext=await i.webnnCreateMLContext({deviceType:T,powerPreference:R})}else i.currentContext=await i.webnnCreateMLContext();break}s=await i._OrtCreateSession(t,r,a),i.webgpuOnCreateSession?.(s),s===0&&wn("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(s,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[h,p]=RR(s),A=!!e?.enableGraphCapture,g=[],m=[],x=[],y=[],_=[];for(let w=0;w<h;w++){let[C,S,M]=Q_(s,w);C===0&&wn("Can't get an input name."),c.push(C);let T=i.UTF8ToString(C);g.push(T),x.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:uo(S),shape:M})}for(let w=0;w<p;w++){let[C,S,M]=Q_(s,w+h);C===0&&wn("Can't get an output name."),d.push(C);let T=i.UTF8ToString(C);m.push(T),y.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:uo(S),shape:M});{if(A&&e?.preferredOutputLocation===void 0){_.push("gpu-buffer");continue}let R=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[T]??"cpu",k=i.webnnIsGraphOutput;if(R==="cpu"&&k&&k(s,T)){_.push("ml-tensor-cpu-output");continue}if(R!=="cpu"&&R!=="cpu-pinned"&&R!=="gpu-buffer"&&R!=="ml-tensor")throw new Error(`Not supported preferred output location: ${R}.`);if(A&&R!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${R}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(R)}}let b=null;return _.some(w=>w==="gpu-buffer"||w==="ml-tensor"||w==="ml-tensor-cpu-output")&&(o=i._OrtCreateBinding(s),o===0&&wn("Can't create IO binding."),b={handle:o,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(w=>w==="ml-tensor-cpu-output"?"ml-tensor":w).map(w=>yw(w))}),wl.set(s,[s,c,d,b,A,!1]),[s,g,m,x,y]}catch(h){throw c.forEach(p=>i._OrtFree(p)),d.forEach(p=>i._OrtFree(p)),o!==0&&i._OrtReleaseBinding(o)!==0&&wn("Can't release IO binding."),s!==0&&i._OrtReleaseSession(s)!==0&&wn("Can't release session."),h}finally{i._free(t),a!==0&&i._OrtReleaseSessionOptions(a)!==0&&wn("Can't release session options."),l.forEach(h=>i._free(h)),i.unmountExternalData?.()}},sI=n=>{let e=kn(),t=wl.get(n);if(!t)throw new Error(`cannot release session. invalid session id: ${n}`);let[r,i,s,a,o]=t;a&&(o&&e._OrtClearBoundOutputs(a.handle)!==0&&wn("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&wn("Can't release IO binding.")),e.jsepOnReleaseSession?.(n),e.webnnOnReleaseSession?.(n),e.webgpuOnReleaseSession?.(n),i.forEach(l=>e._OrtFree(l)),s.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(r)!==0&&wn("Can't release session."),wl.delete(n)},P_=async(n,e,t,r,i,s,a=!1)=>{if(!n){e.push(0);return}let o=kn(),l=o.PTR_SIZE,c=n[0],d=n[1],h=n[3],p=h,A,g;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let y=n[2].gpuBuffer;g=Rc(Tc(c),d);{let _=o.jsepRegisterBuffer;if(!_)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=_(r,s,y,g)}}else if(h==="ml-tensor"){let y=n[2].mlTensor;g=Rc(Tc(c),d);let _=o.webnnRegisterMLTensor;if(!_)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=_(r,y,Tc(c),d)}else{let y=n[2];if(Array.isArray(y)){g=l*y.length,A=o._malloc(g),t.push(A);for(let _=0;_<y.length;_++){if(typeof y[_]!="string")throw new TypeError(`tensor data at index ${_} is not a string`);o.setValue(A+_*l,Us(y[_],t),"*")}}else{let _=o.webnnIsGraphInput,b=o.webnnIsGraphOutput;if(c!=="string"&&_&&b){let w=o.UTF8ToString(i);if(_(r,w)||b(r,w)){let C=Tc(c);g=Rc(C,d),p="ml-tensor";let S=o.webnnCreateTemporaryTensor,M=o.webnnUploadTensor;if(!S||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let T=await S(r,C,d);M(T,new Uint8Array(y.buffer,y.byteOffset,y.byteLength)),A=T}else g=y.byteLength,A=o._malloc(g),t.push(A),o.HEAPU8.set(new Uint8Array(y.buffer,y.byteOffset,g),A)}else g=y.byteLength,A=o._malloc(g),t.push(A),o.HEAPU8.set(new Uint8Array(y.buffer,y.byteOffset,g),A)}}let m=o.stackSave(),x=o.stackAlloc(4*d.length);try{d.forEach((_,b)=>o.setValue(x+b*l,_,l===4?"i32":"i64"));let y=o._OrtCreateTensor(Tc(c),A,g,x,d.length,yw(p));y===0&&wn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(y)}finally{o.stackRestore(m)}},aI=async(n,e,t,r,i,s)=>{let a=kn(),o=a.PTR_SIZE,l=wl.get(n);if(!l)throw new Error(`cannot run inference. invalid session id: ${n}`);let c=l[0],d=l[1],h=l[2],p=l[3],A=l[4],g=l[5],m=e.length,x=r.length,y=0,_=[],b=[],w=[],C=[],S=[],M=a.stackSave(),T=a.stackAlloc(m*o),R=a.stackAlloc(m*o),k=a.stackAlloc(x*o),V=a.stackAlloc(x*o);try{[y,_]=CP(s),Uc("wasm prepareInputOutputTensor");for(let j=0;j<m;j++)await P_(t[j],b,C,n,d[e[j]],e[j],A);for(let j=0;j<x;j++)await P_(i[j],w,C,n,h[r[j]],m+r[j],A);Oc("wasm prepareInputOutputTensor");for(let j=0;j<m;j++)a.setValue(T+j*o,b[j],"*"),a.setValue(R+j*o,d[e[j]],"*");for(let j=0;j<x;j++)a.setValue(k+j*o,w[j],"*"),a.setValue(V+j*o,h[r[j]],"*");if(p&&!g){let{handle:j,outputPreferredLocations:J,outputPreferredLocationsEncoded:X}=p;if(d.length!==m)throw new Error(`input count from feeds (${m}) is expected to be always equal to model's input count (${d.length}).`);Uc("wasm bindInputsOutputs");for(let $=0;$<m;$++){let Y=e[$];await a._OrtBindInput(j,d[Y],b[$])!==0&&wn(`Can't bind input[${$}] for session=${n}.`)}for(let $=0;$<x;$++){let Y=r[$];i[$]?.[3]?(S.push(w[$]),a._OrtBindOutput(j,h[Y],w[$],0)!==0&&wn(`Can't bind pre-allocated output[${$}] for session=${n}.`)):a._OrtBindOutput(j,h[Y],0,X[Y])!==0&&wn(`Can't bind output[${$}] to ${J[$]} for session=${n}.`)}Oc("wasm bindInputsOutputs"),wl.set(n,[c,d,h,p,A,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let P;p?P=await a._OrtRunWithBinding(c,p.handle,x,k,y):P=await a._OrtRun(c,R,T,m,V,x,k,y),P!==0&&wn("failed to call OrtRun().");let H=[],B=[];Uc("wasm ProcessOutputTensor");for(let j=0;j<x;j++){let J=Number(a.getValue(k+j*o,"*"));if(J===w[j]||S.includes(w[j])){H.push(i[j]),J!==w[j]&&a._OrtReleaseTensor(J)!==0&&wn("Can't release tensor.");continue}let X=a.stackSave(),$=a.stackAlloc(4*o),Y=!1,ne,L=0;try{a._OrtGetTensorData(J,$,$+o,$+2*o,$+3*o)!==0&&wn(`Can't access output tensor data on index ${j}.`);let G=o===4?"i32":"i64",le=Number(a.getValue($,G));L=a.getValue($+o,"*");let oe=a.getValue($+o*2,"*"),Ae=Number(a.getValue($+o*3,G)),ue=[];for(let Te=0;Te<Ae;Te++)ue.push(Number(a.getValue(oe+Te*o,G)));a._OrtFree(oe)!==0&&wn("Can't free memory for tensor dims.");let pe=ue.reduce((Te,ke)=>Te*ke,1);ne=uo(le);let be=p?.outputPreferredLocations[r[j]];if(ne==="string"){if(be==="gpu-buffer"||be==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Te=[];for(let ke=0;ke<pe;ke++){let Oe=a.getValue(L+ke*o,"*"),ft=a.getValue(L+(ke+1)*o,"*"),He=ke===pe-1?void 0:ft-Oe;Te.push(a.UTF8ToString(Oe,He))}H.push([ne,ue,Te,"cpu"])}else if(be==="gpu-buffer"&&pe>0){let Te=a.jsepGetBuffer;if(!Te)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ke=Te(L),Oe=Rc(le,pe);if(Oe===void 0||!OC(ne))throw new Error(`Unsupported data type: ${ne}`);Y=!0,H.push([ne,ue,{gpuBuffer:ke,download:a.jsepCreateDownloader(ke,Oe,ne),dispose:()=>{a._OrtReleaseTensor(J)!==0&&wn("Can't release tensor.")}},"gpu-buffer"])}else if(be==="ml-tensor"&&pe>0){let Te=a.webnnEnsureTensor,ke=a.webnnIsGraphInputOutputTypeSupported;if(!Te||!ke)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Rc(le,pe)===void 0||!$C(ne))throw new Error(`Unsupported data type: ${ne}`);if(!ke(n,ne,!1))throw new Error(`preferredLocation "ml-tensor" for ${ne} output is not supported by current WebNN Context.`);let Oe=await Te(n,L,le,ue,!1);Y=!0,H.push([ne,ue,{mlTensor:Oe,download:a.webnnCreateMLTensorDownloader(L,ne),dispose:()=>{a.webnnReleaseTensorId(L),a._OrtReleaseTensor(J)}},"ml-tensor"])}else if(be==="ml-tensor-cpu-output"&&pe>0){let Te=a.webnnCreateMLTensorDownloader(L,ne)(),ke=H.length;Y=!0,B.push((async()=>{let Oe=[ke,await Te];return a.webnnReleaseTensorId(L),a._OrtReleaseTensor(J),Oe})()),H.push([ne,ue,[],"cpu"])}else{let Te=j0(ne),ke=new Te(pe);new Uint8Array(ke.buffer,ke.byteOffset,ke.byteLength).set(a.HEAPU8.subarray(L,L+ke.byteLength)),H.push([ne,ue,ke,"cpu"])}}finally{a.stackRestore(X),ne==="string"&&L&&a._free(L),Y||a._OrtReleaseTensor(J)}}p&&!A&&(a._OrtClearBoundOutputs(p.handle)!==0&&wn("Can't clear bound outputs."),wl.set(n,[c,d,h,p,A,!1]));for(let[j,J]of await Promise.all(B))H[j][2]=J;return Oc("wasm ProcessOutputTensor"),H}finally{a.webnnOnRunEnd?.(c),a.stackRestore(M),b.forEach(P=>a._OrtReleaseTensor(P)),w.forEach(P=>a._OrtReleaseTensor(P)),C.forEach(P=>a._free(P)),y!==0&&a._OrtReleaseRunOptions(y),_.forEach(P=>a._free(P))}},oI=n=>{let e=kn(),t=wl.get(n);if(!t)throw new Error("invalid session id");let r=t[0],i=e._OrtEndProfiling(r);i===0&&wn("Can't get an profile file name."),e._OrtFree(i)},lI=n=>{let e=[];for(let t of n){let r=t[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),El,es,Ad,Hf,Vf,Jm,L_,Km,_c,bc,DR,Cz,Iz,Sz,Bz,Mz,Tz,Rz,Dz=Ze(()=>{ms(),Ez(),tu(),FC(),El=()=>!!Dn.wasm.proxy&&typeof document<"u",Ad=!1,Hf=!1,Vf=!1,Km=new Map,_c=(n,e)=>{let t=Km.get(n);t?t.push(e):Km.set(n,[e])},bc=()=>{if(Ad||!Hf||Vf||!es)throw new Error("worker not ready")},DR=n=>{switch(n.data.type){case"init-wasm":Ad=!1,n.data.err?(Vf=!0,L_[1](n.data.err)):(Hf=!0,L_[0]()),Jm&&(URL.revokeObjectURL(Jm),Jm=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Km.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},Cz=async()=>{if(!Hf){if(Ad)throw new Error("multiple calls to 'initWasm()' detected.");if(Vf)throw new Error("previous call to 'initWasm()' failed.");if(Ad=!0,El())return new Promise((n,e)=>{es?.terminate(),wP().then(([t,r])=>{try{es=r,es.onerror=s=>e(s),es.onmessage=DR,L_=[n,e];let i={type:"init-wasm",in:Dn};!i.in.wasm.wasmPaths&&(t||gw)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm",import.meta.url).href}),es.postMessage(i),Jm=t}catch(i){e(i)}},e)});try{await zC(Dn.wasm),await nI(Dn),Hf=!0}catch(n){throw Vf=!0,n}finally{Ad=!1}}},Iz=async n=>{if(El())return bc(),new Promise((e,t)=>{_c("init-ep",[e,t]);let r={type:"init-ep",in:{epName:n,env:Dn}};es.postMessage(r)});await rI(Dn,n)},Sz=async n=>El()?(bc(),new Promise((e,t)=>{_c("copy-from",[e,t]);let r={type:"copy-from",in:{buffer:n}};es.postMessage(r,[n.buffer])})):qg(n),Bz=async(n,e)=>{if(El()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return bc(),new Promise((t,r)=>{_c("create",[t,r]);let i={type:"create",in:{model:n,options:{...e}}},s=[];n instanceof Uint8Array&&s.push(n.buffer),es.postMessage(i,s)})}else return iI(n,e)},Mz=async n=>{if(El())return bc(),new Promise((e,t)=>{_c("release",[e,t]);let r={type:"release",in:n};es.postMessage(r)});sI(n)},Tz=async(n,e,t,r,i,s)=>{if(El()){if(t.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return bc(),new Promise((a,o)=>{_c("run",[a,o]);let l=t,c={type:"run",in:{sessionId:n,inputIndices:e,inputs:l,outputIndices:r,options:s}};es.postMessage(c,lI(l))})}else return aI(n,e,t,r,i,s)},Rz=async n=>{if(El())return bc(),new Promise((e,t)=>{_c("end-profiling",[e,t]);let r={type:"end-profiling",in:n};es.postMessage(r)});oI(n)}}),F_,kR,kz,Tte=Ze(()=>{ms(),Dz(),Lt(),LC(),SP(),F_=(n,e)=>{switch(n.location){case"cpu":return[n.type,n.dims,n.data,"cpu"];case"gpu-buffer":return[n.type,n.dims,{gpuBuffer:n.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[n.type,n.dims,{mlTensor:n.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${n.location} for ${e()}`)}},kR=n=>{switch(n[3]){case"cpu":return new Ii(n[0],n[2],n[1]);case"gpu-buffer":{let e=n[0];if(!OC(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:t,download:r,dispose:i}=n[2];return Ii.fromGpuBuffer(t,{dataType:e,dims:n[1],download:r,dispose:i})}case"ml-tensor":{let e=n[0];if(!$C(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:r,dispose:i}=n[2];return Ii.fromMLTensor(t,{dataType:e,dims:n[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},kz=class{async fetchModelAndCopyToWasmMemory(n){return Sz(await GC(n))}async loadModel(n,e){Qa();let t;typeof n=="string"?t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Bz(t,e),Js()}async dispose(){return Mz(this.sessionId)}async run(n,e,t){Qa();let r=[],i=[];Object.entries(n).forEach(h=>{let p=h[0],A=h[1],g=this.inputNames.indexOf(p);if(g===-1)throw new Error(`invalid input '${p}'`);r.push(A),i.push(g)});let s=[],a=[];Object.entries(e).forEach(h=>{let p=h[0],A=h[1],g=this.outputNames.indexOf(p);if(g===-1)throw new Error(`invalid output '${p}'`);s.push(A),a.push(g)});let o=r.map((h,p)=>F_(h,()=>`input "${this.inputNames[i[p]]}"`)),l=s.map((h,p)=>h?F_(h,()=>`output "${this.outputNames[a[p]]}"`):null),c=await Tz(this.sessionId,i,o,a,l,t),d={};for(let h=0;h<c.length;h++)d[this.outputNames[a[h]]]=s[h]??kR(c[h]);return Js(),d}startProfiling(){}endProfiling(){Rz(this.sessionId)}}}),Nz={};mh(Nz,{OnnxruntimeWebAssemblyBackend:()=>Dw,initializeFlags:()=>Rw,wasmBackend:()=>Qz});var Rw,Dw,Qz,Rte=Ze(()=>{ms(),Dz(),Tte(),Rw=()=>{(typeof Dn.wasm.initTimeout!="number"||Dn.wasm.initTimeout<0)&&(Dn.wasm.initTimeout=0);let n=Dn.wasm.simd;if(typeof n!="boolean"&&n!==void 0&&n!=="fixed"&&n!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${n}". Reset it to \`false\` and ignore SIMD feature checking.`),Dn.wasm.simd=!1),typeof Dn.wasm.proxy!="boolean"&&(Dn.wasm.proxy=!1),typeof Dn.wasm.trace!="boolean"&&(Dn.wasm.trace=!1),typeof Dn.wasm.numThreads!="number"||!Number.isInteger(Dn.wasm.numThreads)||Dn.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Dn.wasm.numThreads=1;else{let e=typeof navigator>"u"?mee("node:os").cpus().length:navigator.hardwareConcurrency;Dn.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Dw=class{async init(n){Rw(),await Cz(),await Iz(n)}async createInferenceSessionHandler(n,e){let t=new kz;return await t.loadModel(n,e),t}},Qz=new Dw});ms();ms();ms();var Dte="1.24.3";{let n=(Rte(),Rp(Nz)).wasmBackend;xd("webgpu",n,5),xd("webnn",n,5),xd("cpu",n,10),xd("wasm",n,10)}Object.defineProperty(Dn.versions,"web",{value:Dte,enumerable:!0});class kte{constructor(e,t={}){this.config=e,this.options=t,this.policyModule=null,this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null,this.context=null,this.policyJointNames=(e.policy_joint_names??[]).slice(),this.numActions=this.policyJointNames.length,this.lastActions=new Float32Array(this.numActions),this.defaultJointPos=this.normalizeArray(e.default_joint_pos??[],this.numActions,0)}async init(e){this.context=e,this.policyModule=await this.buildPolicyModule(e),this.buildObservationGroups()}reset(e){this.lastActions.fill(0),this.policyModule?.reset();for(const t of Object.values(this.obsGroups))for(const r of t)r.reset&&r.reset(e);if(e){for(const[t,r]of Object.entries(this.historyConfig))if(r.steps>1){const i=this.buildFrame(this.obsGroups[t]??[],e),s=this.historyBuffers[t];for(let a=0;a<r.steps;a++)s.set(i,a*i.length)}}}update(e){this.policyModule?.update();for(const t of Object.values(this.obsGroups))for(const r of t)r.update&&r.update(e)}collectObservationsByKey(e){this.update(e);const t={};for(const[r,i]of Object.entries(this.obsGroups)){const s=this.historyConfig[r];if(s&&s.steps>1){const a=this.buildFrame(i,e),o=this.historyBuffers[r];for(let l=o.length-1;l>=a.length;l--)o[l]=o[l-a.length];o.set(a,0),t[r]=new Float32Array(o)}else t[r]=this.buildFrame(i,e)}return t}collectObservations(e){const t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];const r=Object.keys(t)[0];return r?t[r]:new Float32Array(0)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];const e=Object.keys(this.obsSizes)[0];return e?this.obsSizes[e]:0}getObservationLayout(){if(this.defaultObsKey&&this.obsLayouts[this.defaultObsKey])return this.obsLayouts[this.defaultObsKey].map(t=>({...t}));const e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(t=>({...t})):[]}getPolicyModuleContext(){return this.policyModule?.getContext()??{}}getPolicyModule(){return this.policyModule}getContext(){return this.context}getPolicyJointNames(){return this.policyJointNames.slice()}getNumActions(){return this.numActions}getDefaultJointPos(){return new Float32Array(this.defaultJointPos)}getLastActions(){return new Float32Array(this.lastActions)}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){const t=this.options.policyModules??{},r=this.config.policy_module,i=r?t[r]:t.default;if(r&&!i)throw new Error(`Unknown policy module: ${r}`);if(!i)return null;const s=new i(this.config);return await s.init(e),s}buildObservationGroups(){const e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;for(const[r,i]of Object.entries(t)){if(Array.isArray(i)){const s=i.map(a=>{const o=e[a.name];if(!o)throw new Error(`Unknown observation type: ${a.name}`);return new o(this,a)});this.registerGroup(r,s,i);continue}if(i&&typeof i=="object"){const s=i;if(Array.isArray(s.components)){const a=s.components.map(c=>{const d=e[c.name];if(!d)throw new Error(`Unknown observation type: ${c.name}`);const h={...c,history_steps:1};return new d(this,h)}),o=Math.max(1,Math.floor(s.history_steps??1)),l=!!s.interleaved;this.registerGroup(r,a,s.components,{steps:o,interleaved:l})}}}this.obsGroups.policy?this.defaultObsKey="policy":this.obsGroups.observation?this.defaultObsKey="observation":this.obsGroups.obs_history?this.defaultObsKey="obs_history":this.defaultObsKey=Object.keys(this.obsGroups)[0]??null}registerGroup(e,t,r,i){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((a,o)=>({name:r[o]?.name??`obs_${o}`,size:a.size}));const s=this.obsLayouts[e].reduce((a,o)=>a+o.size,0);i&&i.steps>1?(this.historyConfig[e]=i,this.historyBuffers[e]=new Float32Array(s*i.steps),this.obsSizes[e]=s*i.steps):this.obsSizes[e]=s}buildFrame(e,t){const r=e.reduce((a,o)=>a+o.size,0),i=new Float32Array(r);let s=0;for(const a of e){const o=a.compute(t),l=o instanceof Float32Array?o:Float32Array.from(o);if(l.length!==a.size)throw new Error(`Observation size mismatch: expected ${a.size}, got ${l.length}`);i.set(l,s),s+=l.length}return i}normalizeArray(e,t,r){const i=new Float32Array(t);for(let s=0;s<t;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}}Dn.wasm.proxy=!1;Dn.wasm.numThreads=1;class Nte{constructor(e){if(!e?.path)throw new Error("OnnxModule requires a path.");this.config=e,this.session=null;const t=e.meta?.in_keys??["policy"],r=e.meta?.out_keys??["action"];this.inKeys=t.map(i=>Array.isArray(i)?i.join(","):i),this.outKeys=r.map(i=>Array.isArray(i)?i.join(","):i),this.isRecurrent=this.inKeys.includes("adapt_hx")}async init(){const e=await fetch(this.config.path);if(!e.ok)throw new Error(`Failed to fetch ONNX model: ${e.status}`);const t=await e.arrayBuffer();this.session=await PC.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"})}initInput(){return this.isRecurrent?{is_init:new Ii("bool",[!0],[1]),adapt_hx:new Ii("float32",new Float32Array(128),[1,128])}:{}}async runInference(e){if(!this.session)throw new Error("OnnxModule not initialized.");const t={};for(let a=0;a<this.inKeys.length;a++){const o=this.inKeys[a],l=this.session.inputNames[a];if(!l||!e[o])throw new Error(`Missing ONNX input for key: ${o}`);t[l]=e[o]}const r=await this.session.run(t),i={};for(let a=0;a<this.outKeys.length;a++){const o=this.outKeys[a],l=this.session.outputNames[a];l&&r[l]&&(i[o]=r[l])}const s={};return this.isRecurrent&&i["next,adapt_hx"]&&(s.is_init=new Ii("bool",[!1],[1]),s.adapt_hx=i["next,adapt_hx"]),[i,s]}}class Qte{constructor(e,t,r,i){this.mujoco=e,this.mjModel=t,this.mjData=r;const s=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(const a of i){const o=s.indexOf(a);if(o<0)throw new Error(`Joint "${a}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[o]),this.qvelAdr.push(t.jnt_dofadr[o]),this.jointIndices.push(o)}this.numActions=i.length,this.ctrlAdr=this.buildCtrlAdr()}build(){const e=this.mjData.qpos,t=this.mjData.qvel,r=new Float32Array(this.numActions),i=new Float32Array(this.numActions);for(let c=0;c<this.numActions;c++)r[c]=e[this.qposAdr[c]],i[c]=t[this.qvelAdr[c]];const s=new Float32Array([e[0],e[1],e[2]]),a=new Float32Array([e[3],e[4],e[5],e[6]]),o=new Float32Array([t[0],t[1],t[2]]),l=new Float32Array([t[3],t[4],t[5]]);return{jointPos:r,jointVel:i,rootPos:s,rootQuat:a,rootLinVel:o,rootAngVel:l}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}getControlMappingFor(e,t){if(!this.ctrlAdr)return null;const r=e.map(c=>new RegExp(`^(?:${c})$`)),i=c=>r.some(d=>d.test(c)),s=[],a=[],o=[],l=[];for(let c=0;c<t.length;c++)i(t[c])&&(s.push(this.ctrlAdr[c]),a.push(this.qposAdr[c]),o.push(this.qvelAdr[c]),l.push(c));return s.length===0?null:{ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l}}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;const e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let i=0;i<this.mjModel.nu;i++){const s=this.mjModel.actuator_trntype[i];e===void 0||s===e?t.push(this.mjModel.actuator_trnid[2*i]):t.push(-1)}const r=[];for(const i of this.jointIndices){const s=t.findIndex(a=>a===i);if(s<0)return null;r.push(s)}return r}getJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;let l=r.decode(t.subarray(a,o));!l&&s===0&&(l="floating_base_joint"),i.push(l)}return i}}class Pz{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class Pte{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName="default",this.currentDone=!0}reset(e){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName="default"}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}}class Lte extends Pz{constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.tracking=new Pte(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class Fte{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName="default",this.currentDone=!0}reset(e){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName="default"}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}}class zte extends Pz{constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.locomotion=new Fte(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class Ute{constructor(e,t){this.terms=[];for(const r of e){const i=t[r.name];if(!i){console.warn(`[EventManager] Unknown event type: ${r.name}`);continue}this.terms.push(new i(r))}}onReset(e){for(const t of this.terms)t.onReset(e)}get size(){return this.terms.length}}class Lz{constructor(e){this.config=e}}const Ote={};class Fz extends Lz{constructor(e){super(e),this.poseRange=e.params?.pose_range??{}}onReset(e){const{mjModel:t,mjData:r}=e;if(!t||!r)return;const i=this._findFreeJoint(t);if(i===-1)return;const s=t.jnt_qposadr[i],a=l=>{const c=this.poseRange[l];return c?c[0]+Math.random()*(c[1]-c[0]):0};r.qpos[s+0]+=a("x"),r.qpos[s+1]+=a("y"),r.qpos[s+2]+=a("z");const o=a("yaw");o!==0&&this._applyYawRotation(r.qpos,s+3,o)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}class $te extends Lz{constructor(e){super(e),this.patchName=e.params?.patch_name??"spawn",this.fallback=new Fz(e)}onReset(e){const{mjModel:t,mjData:r,terrainData:i}=e;if(!t||!r)return;const s=i?.flat_patches?.[this.patchName];if(!s||s.length===0){this.fallback.onReset(e);return}const a=this._findFreeJoint(t);if(a===-1)return;const o=t.jnt_qposadr[a],l=s[Math.floor(Math.random()*s.length)],c=r.qpos[o+2];r.qpos[o+0]=l[0],r.qpos[o+1]=l[1],r.qpos[o+2]=l[2]+c;const h=(this.config.params?.pose_range??{}).yaw??[-Math.PI,Math.PI],p=h[0]+Math.random()*(h[1]-h[0]);this._applyYawRotation(r.qpos,o+3,p)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}const Gte={ResetRootStateUniform:Fz,ResetRootStateFromFlatPatches:$te},Hte={...Gte,...Ote};class zz extends Error{constructor(){super("This scene cannot be loaded because it exceeds the browser's WebAssembly 2 GB memory limit. Try closing other browser tabs or reloading the page to free memory."),this.name="WasmMemoryLimitError"}}function NR(n){const e=n instanceof Error?n.message:String(n);return e.includes("MjModel loading returned null")||e.includes("Could not allocate memory")||e.includes("memory allocation failed")||e.includes("bad_alloc")}class Vte{constructor(e,t,r={}){this.render=()=>{if(Zr().updateDebugVisuals(),this.mjData&&BZ(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){S3(this.camera,this.lights);for(const[o,l]of this.lastSimState.bodies){const c=this.bodies[o];c&&(c.position.copy(l.position),c.quaternion.copy(l.quaternion))}I3(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&K7({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{const{width:o,height:l}=this.getSize();this.camera.aspect=o/l,this.camera.updateProjectionMatrix(),this.renderer.setSize(o,l)},this.mujoco=e,this.container=t,this.baseUrl=r.baseUrl||"/";const i="/working";try{this.mujoco.FS.mkdir(i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&console.warn("Failed to create /working directory:",o)}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:"."},i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&o.code!=="EBUSY"&&console.warn("Failed to mount MEMFS at /working:",o)}const{width:s,height:a}=this.getSize();this.scene=new VV,this.scene.name="scene",this.camera=new Fr(45,s/a,.001,1e3),this.camera.name="PerspectiveCamera",this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new C7({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(s,a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=bN,this.renderer.outputColorSpace=ri,this.renderer.toneMapping=wN,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported("immersive-vr").then(o=>{o&&(this.vrButton=_C.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new S7(this.camera,this.renderer.domElement),this.controls.target.set(0,.2,0),this.controls.panSpeed=2,this.controls.zoomSpeed=1,this.controls.enableDamping=!0,this.controls.dampingFactor=.1,this.controls.screenSpacePanning=!0,this.controls.update(),this.renderer.setAnimationLoop(this.render),window.addEventListener("resize",this.onWindowResize),"ResizeObserver"in window?(this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),this.resizeObserver.observe(this.container)):this.resizeObserver=null,this.lastSimState={bodies:new Map,tendons:Z7()},this.dynamicBodyIds=null,this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.loopPromise=null,this.running=!1,this.timestep=.001,this.decimation=1,this.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.terminationManager=null,this.eventManager=null,this.terrainData=null,this.splatMesh=null,this.colliderMesh=null,this.cameraState={trackBodyId:null,prevBodyPos:null},this.sceneCacheManager=mw.getInstance(this.mujoco),this.resourceTracker=new MZ,this.memoryMonitor=new TZ}async loadEnvironment(e,t=null,r=null,i=null,s=null,a=null){this.terrainData=a,s&&s.length>0?(this.eventManager=new Ute(s,Hte),console.log(`[EventManager] ${this.eventManager.size} reset event(s) loaded`)):this.eventManager=null,await this.stop(),this.splatMesh&&(V3(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(K3(this.colliderMesh,this.scene),this.colliderMesh=null);const o=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const l=performance.now()-o;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:l})}else this.memoryMonitor.logCacheOperation("miss",e),await this.sceneCacheManager.prepareForNewScene(),this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.resourceTracker.startTracking(this.mujoco),await lX(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);r&&(this.splatMesh=H3(r,this.scene),r.colliderUrl&&(this.colliderMesh=await J3(this.resolveAssetUrl(r.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.applyViewerConfig(i),this.running=!0,this.startLoop()}initializeCommands(){const e=Zr();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e,t){Zr().initialize(e,t),console.log("[mjswanRuntime] Commands loaded from policy config:",Object.keys(e))}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){const e=this.policyStateBuilder.build();this.policyRunner.reset(e)}console.log("[mjswanRuntime] Simulation reset")}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{const t=this.scene.getObjectByName("MuJoCo Root");t&&this.scene.remove(t);const r={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await aX(this.mujoco,e,r),!this.mjModel||!this.mjData)throw new Error("Failed to load MuJoCo model.");this.mujocoRoot=this.scene.getObjectByName("MuJoCo Root"),this.mujoco.mj_forward(this.mjModel,this.mjData),I3(this.mujoco,this.mjData,this.lights),S3(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new Z3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds}),this.loadingScene=null})(),await this.loadingScene}async loadSceneWithOomRetry(e){try{await this.loadScene(e)}catch(t){if(!NR(t))throw t;console.warn("[mjswanRuntime] OOM — clearing cache and retrying..."),this.loadingScene=null,await this.sceneCacheManager.clear();try{await this.loadScene(e)}catch(r){throw this.loadingScene=null,NR(r)?new zz:r}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&(V3(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(K3(this.colliderMesh,this.scene),this.colliderMesh=null),e&&(this.splatMesh=H3(e,this.scene),e.colliderUrl&&(this.colliderMesh=await J3(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&qQ(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}async stop(){this.running=!1;const e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){const e=performance.now(),t=this.timestep*this.decimation;if(this.mjModel&&this.mjData){if(Zr().update(t),this.mujoco.mj_forward(this.mjModel,this.mjData),this.policyRunner&&this.policyStateBuilder){const s=this.policyStateBuilder.build(),a=this.policyRunner.collectObservationsByKey(s);if(await this.runOnnxInference(a),this.policyDebugCounter%60===0){const o="policy"in a?"policy":"observation"in a?"observation":Object.keys(a)[0],l=o?a[o]:null,c=l?Array.from(l.slice(0,8)):[];console.log("[PolicyRunner] obs",{key:o,size:l?l.length:0,sample:c})}this.policyDebugCounter+=1}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){const s=this.policyStateBuilder.build();if(this.terminationManager.evaluate(s).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){const o=this.policyStateBuilder.build();this.policyRunner.reset(o)}}}const r=(performance.now()-e)/1e3,i=Math.max(0,t-r);i>0&&await new Promise(s=>setTimeout(s,i*1e3))}this.loopPromise=null}async loadPolicyConfig(e){const t=this.policyConfigPath;this.policyConfigPath=e,this.policyRunner=null,this.policyStateBuilder=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.terminationManager=null;const r=Zr();if(r.clear(),r.setResetCallback(()=>this.resetSimulation()),!!e){if(!this.mjModel||!this.mjData){console.warn("Policy config loaded before MuJoCo model is ready.");return}e!==t&&this.resetSimulationState();try{const{config:i}=await this.fetchPolicyConfig(e);if(this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),i.commands&&typeof i.commands=="object"&&(this.initializeCommandsFromConfig(i.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),Zr().resetTerms(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()),!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new kte(i,{policyModules:{tracking:Lte,locomotion:zte},observations:see});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),this.policyRunner=s,this.policyStateBuilder=new Qte(this.mujoco,this.mjModel,this.mjData,s.getPolicyJointNames());const a=this.policyStateBuilder.build();if(this.policyRunner.reset(a),this.policyControl=this.buildPolicyControl(i,s,this.policyStateBuilder),i.terminations&&Object.keys(i.terminations).length>0&&(this.terminationManager=new aee(i.terminations,hee),console.log(`[TerminationManager] ${this.terminationManager.size} termination term(s) loaded`)),i.onnx?.path){const o=this.resolvePolicyAssetPath(e,i.onnx.path),l=this.resolveAssetUrl(o),c={...i.onnx,path:l},d=new Nte(c);await d.init(),this.onnxModule=d,this.onnxInputDict=d.initInput()}console.log("[PolicyRunner] config loaded",{obsSize:s.getObservationSize(),obsLayout:s.getObservationLayout(),pdEnabled:this.policyControl!==null})}catch(i){console.warn("Failed to load policy config:",i)}}}async fetchPolicyConfig(e){const t=this.resolveAssetUrl(e),r=await fetch(t,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch policy config: ${r.status}`);return{config:await r.json(),resolvedUrl:t}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;const t=(this.baseUrl||"/").replace(/\/+$/,"/"),r=new URL(t,window.location.origin+"/").toString();return new URL(e.replace(/^\/+/,""),r).toString()}resolvePolicyAssetPath(e,t){const r=e.replace(/\\/g,"/"),i=r.lastIndexOf("/");return i>=0?`${r.slice(0,i+1)}${t}`.replace(/\/+/g,"/"):t}buildPolicyControl(e,t,r){const i=t.getPolicyJointNames(),s=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(c,d,h,p,A,g,m,x)=>{const y=h.qposAdr.length,_=h.actionIndices.map(B=>i[B]),b=this.normalizeControlArray(p,y,1,_),w=this.normalizeControlArray(A,y,0,_),C=x?t.getDefaultJointPos():new Float32Array(i.length),S=new Float32Array(y);for(let B=0;B<y;B++)S[B]=C[h.actionIndices[B]];const M=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(i.length),T=new Float32Array(y);for(let B=0;B<y;B++)T[B]=M[h.actionIndices[B]]??0;const R=this.normalizeControlArray(g,y,0,_),k=this.normalizeControlArray(m,y,0,_),V=h.ctrlAdr.map(B=>B<0||!this.mjModel?!1:this.mjModel.actuator_biastype[B]===s),P=V.some(Boolean),H=V.some(B=>!B);return P&&H&&console.warn(`[PolicyRunner] Action term "${c}": mixed actuator types detected.`),console.log(`[PolicyRunner] Action term "${c}" (${d}): ${y} joint(s), mode: ${P?"position (ctrl=target_pos)":"motor (ctrl=torque, external PD)"}`),{controlType:d,ctrlAdr:h.ctrlAdr,qposAdr:h.qposAdr,qvelAdr:h.qvelAdr,actionIndices:h.actionIndices,actionScale:b,actionOffset:w,defaultJointPos:S,encoderBias:T,positionActuator:V,kp:R,kd:k}},o=e.actions;if(!o||Object.keys(o).length===0){const c=e.control_type??"joint_position";if(c!=="joint_position"&&c!=="torque")return console.warn(`[PolicyRunner] Unsupported control_type: ${c}`),null;const d=r.getControlMapping();if(!d)return console.warn("[PolicyRunner] Failed to build control mapping."),null;const h={...d,actionIndices:Array.from({length:d.qposAdr.length},(p,A)=>A)};return[a("legacy",c,h,e.action_scale,void 0,e.stiffness,e.damping,!0)]}const l=[];for(const[c,d]of Object.entries(o)){const h=d.type??"joint_position";if(h!=="joint_position"&&h!=="torque"){console.warn(`[PolicyRunner] Action term "${c}": unsupported type "${h}", skipping.`);continue}const p=d.actuator_names??[".*"],A=p.length===1&&p[0]===".*";let g;if(A){const x=r.getControlMapping();if(!x){console.warn(`[PolicyRunner] Action term "${c}": failed to build control mapping, skipping.`);continue}g={...x,actionIndices:Array.from({length:x.qposAdr.length},(y,_)=>_)}}else if(g=r.getControlMappingFor(p,i),!g){console.warn(`[PolicyRunner] Action term "${c}": no joints matched patterns [${p.join(", ")}], skipping.`);continue}const m=d.use_default_offset!==void 0?d.use_default_offset:h==="joint_position";l.push(a(c,h,g,d.scale,d.offset,d.stiffness,d.damping,m))}return l.length===0?(console.warn("[PolicyRunner] No valid action terms found in config.actions."),null):l}normalizeControlArray(e,t,r,i){const s=new Float32Array(t);if(s.fill(r),typeof e=="number")return s.fill(e),s;if(Array.isArray(e)){for(let a=0;a<t;a++)s[a]=typeof e[a]=="number"?e[a]:r;return s}if(e!==null&&typeof e=="object"&&i){for(const[a,o]of Object.entries(e)){const l=i.indexOf(a);l>=0&&l<t?s[l]=o:console.warn(`[PolicyRunner] Joint name "${a}" not found in policy_joint_names; skipping.`)}return s}return s}resetSimulationState(){!this.mjModel||!this.mjData||(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),Zr().resetTerms(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.lastSimState.bodies.clear(),this.updateCachedState())}executeSimulationSteps(){if(!(!this.mjModel||!this.mjData)){this.applyDragForces();for(let e=0;e<this.decimation;e++)this.applyPolicyControl(),this.mujoco.mj_step(this.mjModel,this.mjData)}}applyPolicyControl(){if(!this.policyControl||!this.mjData)return;const e=this.mjData.ctrl;e.fill(0);const t=this.policyRunner?.getLastActions()??new Float32Array(0);for(const r of this.policyControl){const{controlType:i,ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l,actionScale:c,actionOffset:d,defaultJointPos:h,encoderBias:p,positionActuator:A,kp:g,kd:m}=r,x=s.length;if(i==="joint_position")for(let y=0;y<x;y++){const _=s[y];if(_<0)continue;const b=t[l[y]]??0,w=h[y]+d[y]+c[y]*b-p[y];if(A[y])e[_]=w;else{const C=this.mjData.qpos[a[y]],S=this.mjData.qvel[o[y]];e[_]=g[y]*(w-C)+m[y]*(0-S)}}else if(i==="torque")for(let y=0;y<x;y++){const _=s[y];_>=0&&(e[_]=c[y]*(t[l[y]]??0))}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||(this.onnxInputDict=this.onnxModule.initInput());const t={...this.onnxInputDict};for(const[d,h]of Object.entries(e))t[d]=new Ii("float32",h,[1,h.length]);for(const d of this.onnxModule.inKeys)if(!t[d]){console.warn("[PolicyRunner] Missing ONNX input:",{key:d,available:Object.keys(t)});return}const[r,i]=await this.onnxModule.runInference(t);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i});const s=this.onnxModule.outKeys[0],a=r.action??(s?r[s]:null)??r.policy??null;if(!a)return;const o=a.data,l=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&l.length!==c){console.warn("[PolicyRunner] Action size mismatch:",{expected:c,got:l.length});return}this.policyRunner.setLastActions(l)}catch(t){console.warn("[PolicyRunner] ONNX inference failed:",t)}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let p=0;p<this.mjData.xfrc_applied.length;p++)this.mjData.xfrc_applied[p]=0;const e=this.dragStateManager.physicsObject;if(!e||!("bodyID"in e)||typeof e.bodyID!="number"||e.bodyID<=0)return;const t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(Bd(this.mjData.xpos,p,this.bodies[p].position),fg(this.mjData.xquat,p,this.bodies[p].quaternion),this.bodies[p].updateWorldMatrix(!0,!1));this.dragStateManager.update();const r=this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale),i=C3(r),s=this.dragStateManager.worldHit.clone(),a=C3(s),o=new he(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),l=new he(a.x-o.x,a.y-o.y,a.z-o.z),c=new he(i.x,i.y,i.z),d=new he().crossVectors(l,c),h=t*6;this.mjData.xfrc_applied[h+0]=i.x,this.mjData.xfrc_applied[h+1]=i.y,this.mjData.xfrc_applied[h+2]=i.z,this.mjData.xfrc_applied[h+3]=d.x,this.mjData.xfrc_applied[h+4]=d.y,this.mjData.xfrc_applied[h+5]=d.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++)if(!(e&&!e.has(t))&&this.bodies[t]){this.lastSimState.bodies.has(t)||this.lastSimState.bodies.set(t,{position:new he,quaternion:new Cn});const r=this.lastSimState.bodies.get(t);Bd(this.mjData.xpos,t,r.position),fg(this.mjData.xquat,t,r.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&J7(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=SZ(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){const t=new Set;for(let r=1;r<e.nbody;r++){let i=r;for(;i>0;){if(e.body_jntnum[i]>0){t.add(r);break}i=e.body_parentid[i]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;const r=this.bodies[t];r&&(Bd(this.mjData.xpos,t,r.position),fg(this.mjData.xquat,t,r.quaternion))}}dispose(){this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.dragStateManager&&(this.dragStateManager.dispose(),this.dragStateManager=null),this.mjData=null,this.mjModel=null,window.removeEventListener("resize",this.onWindowResize),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.controls.dispose(),this.renderer.setAnimationLoop(null),this.renderer.dispose(),this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.vrButton?.parentElement&&(this.vrButton.parentElement.removeChild(this.vrButton),this.vrButton=null),this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.lastSimState.bodies.clear()}disposeThreeJSResources(){if(this.scene)for(this.scene.traverse(e=>{"geometry"in e&&e.geometry&&e.geometry.dispose(),"material"in e&&e.material&&(Array.isArray(e.material)?e.material.forEach(t=>this.disposeMaterial(t)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),e.dispose()}getSize(){const e=this.container.clientWidth||window.innerWidth,t=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,t)}}async restoreFromCache(e){const t=this.sceneCacheManager.get(e);if(!t)throw new Error(`Scene ${e} not found in cache`);const r=this.scene.getObjectByName("MuJoCo Root");r&&this.scene.remove(r),this.mjModel=t.mjModel,this.mjData=t.mjData,this.bodies=t.bodies,this.lights=t.lights,this.mujocoRoot=t.mujocoRoot,this.scene.add(this.mujocoRoot),this.scene.background=t.skybox,this.mujoco.mj_forward(this.mjModel,this.mjData),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new Z3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds})}async captureAndCacheResources(e){const t=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot){console.warn("[SceneCache] Cannot cache scene: missing resources");return}const r=this.resourceTracker.estimateSceneMemory({mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,meshes:{},mujocoRoot:this.mujocoRoot});await this.sceneCacheManager.set(e,{scenePath:e,lastAccessed:Date.now(),loadedAt:Date.now(),mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,lights:this.lights,meshes:{},mujocoRoot:this.mujocoRoot,skybox:this.scene.background instanceof uh?this.scene.background:null,fsFiles:t,estimatedMemoryBytes:r});const i=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation("load",e,{memoryMB:r/1048576,totalScenes:i.totalScenes,totalMemoryMB:i.totalMemoryBytes/1048576})}}const Zm="mjswan_oom_reload_scene",jte=({scenePath:n,baseUrl:e,policyConfigPath:t,splatConfig:r,cameraConfig:i,eventsConfig:s,terrainData:a,onStatusChange:o,onError:l,onReady:c,onRuntimeReady:d})=>{const h=U.useRef(null),p=U.useRef(null),A=U.useRef(null),g=U.useRef(r);return g.current=r,U.useEffect(()=>{let m=!1;const x=_=>{o?.(_)};return(async()=>{if(x("Loading MuJoCo..."),!A.current){const w=await gH(()=>import("./mujoco-BK4bzMF-.js"),[]);A.current=await w.default()}if(m)return;const _=h.current;if(!_)throw new Error("Failed to find viewer container.");const b=A.current;if(!b)throw new Error("MuJoCo not loaded.");p.current||(p.current=new Vte(b,_,{baseUrl:e}),d?.(p.current)),x("Loading scene assets..."),await p.current.loadEnvironment(n,t??null,g.current??null,i??null,s??null,a??null),!m&&(sessionStorage.removeItem(Zm),x("Running simulation"),c?.())})().catch(_=>{if(!m){if(_ instanceof zz){if(sessionStorage.getItem(Zm)!==n){console.warn("[MjswanViewer] OOM — reloading page to free memory..."),sessionStorage.setItem(Zm,n),window.location.reload();return}sessionStorage.removeItem(Zm)}console.error("Failed to initialize MuJoCo viewer:",_),l?.(_ instanceof Error?_:new Error(String(_))),x("Failed to load scene")}}),()=>{m=!0,p.current?.dispose(),p.current=null}},[n,e,t,i,s,a,o,l,c]),W.jsx("div",{ref:h,className:"viewer"})};var Wte={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}};const cI=(n,e,t,r)=>{const i=U.forwardRef(({color:s="currentColor",size:a=24,stroke:o=2,title:l,className:c,children:d,...h},p)=>U.createElement("svg",{ref:p,...Wte[n],width:a,height:a,className:["tabler-icon",`tabler-icon-${e}`,c].join(" "),strokeWidth:o,stroke:s,...h},[l&&U.createElement("title",{key:"svg-title"},l),...r.map(([A,g])=>U.createElement(A,g)),...Array.isArray(d)?d:[d]]));return i.displayName=`${t}`,i};const qte=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],Uz=cI("outline","chevron-down","ChevronDown",qte);const Yte=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],Xte=cI("outline","chevron-up","ChevronUp",Yte);const Jte=[["path",{d:"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4",key:"svg-0"}],["path",{d:"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4",key:"svg-1"}]],Kte=cI("outline","refresh","Refresh",Jte),QR="0.4.1",PR=[{login:"ttktjmt",html_url:"https://github.com/ttktjmt"},{login:"claude",html_url:"https://github.com/claude"},{login:"julien-blanchon",html_url:"https://github.com/julien-blanchon"},{login:"unmoyai",html_url:"https://github.com/unmoyai"},{login:"brentyi",html_url:"https://github.com/brentyi"},{login:"Axellwppr",html_url:"https://github.com/Axellwppr"},{login:"CharlieLeee",html_url:"https://github.com/CharlieLeee"}],Zte={move:"touchmove",end:"touchend"},ene={move:"mousemove",end:"mouseup"};function tne(n){return n.type==="touchmove"}function nne(n){return n.type==="mousemove"}const Up=On.createContext(null);function ho({children:n,width:e}){const t=On.useRef(null),[r,{toggle:i}]=Kg(!0),[s,a]=On.useState(800),o=On.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),l=On.useRef({}),c=(A,g,m)=>Math.abs(A+g/2)<Math.abs(A-m+g/2)?A:A-m,d=15;function h(A,g){const m=t.current;if(m===null)return[A,g];const x=m.parentElement;if(x===null)return[A,g];let y=A,_=g;return y=Math.min(y,x.clientWidth-m.clientWidth-d),y=Math.max(y,d),_=Math.min(_,x.clientHeight-m.clientHeight-d),_=Math.max(_,d),m.style.top=`${_.toString()}px`,m.style.left=`${y.toString()}px`,[c(y,m.clientWidth,x.clientWidth),c(_,m.clientHeight,x.clientHeight)]}On.useEffect(()=>{const A=t.current;if(A===null)return;const g=A.parentElement;if(g===null)return;const m=new ResizeObserver(()=>{l.current.x===void 0&&(l.current.x=c(A.offsetLeft,A.clientWidth,g.clientWidth)),l.current.y===void 0&&(l.current.y=c(A.offsetTop,A.clientHeight,g.clientHeight));const x=g.clientHeight-d*2;s!==x&&a(x);let y=l.current.x,_=l.current.y;for(;y<0;)y+=g.clientWidth;for(;_<0;)_+=g.clientHeight;h(y,_)});return m.observe(A),m.observe(g),()=>{m.disconnect()}});const p=A=>{const g=o.current,m=t.current;if(!m)return;A.type=="touchstart"?(A=A,g.startClientX=A.touches[0].clientX,g.startClientY=A.touches[0].clientY):(A=A,g.startClientX=A.clientX,g.startClientY=A.clientY),g.startPosX=m.offsetLeft,g.startPosY=m.offsetTop;const x=A.type=="touchstart"?Zte:ene;function y(_){let b=0,w=0;if(tne(_)?(_=_,b=_.touches[0].clientX-g.startClientX,w=_.touches[0].clientY-g.startClientY):nne(_)&&(_=_,b=_.clientX-g.startClientX,w=_.clientY-g.startClientY),Math.abs(b)<=3&&Math.abs(w)<=3)return;g.dragging=!0;const C=g.startPosX+b,S=g.startPosY+w;[l.current.x,l.current.y]=h(C,S)}window.addEventListener(x.move,y),window.addEventListener(x.end,()=>{A.type=="touchstart"&&(g.dragging=!1),window.removeEventListener(x.move,y)},{once:!0})};return W.jsx(Up.Provider,{value:{wrapperRef:t,expanded:r,width:e,maxHeight:s,toggleExpanded:i,dragHandler:p,dragInfo:o},children:W.jsx(Gc,{radius:"xs",shadow:"0.1em 0 1em 0 rgba(0,0,0,0.1)",style:{boxSizing:"border-box",width:e,zIndex:10,position:"absolute",top:"1em",right:"1em",margin:0,"& .expandIcon":{transform:"rotate(0)"},overflow:"hidden"},ref:t,children:n})})}ho.Handle=function({children:e}){const t=On.useContext(Up);return W.jsx(W.Fragment,{children:W.jsx(nt,{style:{borderRadius:"0.2em 0.2em 0 0",lineHeight:"1.5em",cursor:"pointer",position:"relative",fontWeight:400,userSelect:"none",display:"flex",alignItems:"center",padding:"0 0.75em",height:"2.75em"},onClick:()=>{const r=t.dragInfo.current;if(r.dragging){r.dragging=!1;return}t.toggleExpanded()},onTouchStart:r=>{t.dragHandler(r)},onMouseDown:r=>{t.dragHandler(r)},children:e})})};ho.Contents=function({children:e}){const t=On.useContext(Up);return W.jsxs(bg,{in:t.expanded,children:[W.jsx(wd,{mx:"xs"}),W.jsx(Kc.Autosize,{mah:t.maxHeight,children:W.jsx(nt,{style:{width:t.width},children:e})})]})};ho.HideWhenCollapsed=function({children:e}){return On.useContext(Up)?.expanded??!0?e:null};ho.HideWhenExpanded=function({children:e}){return On.useContext(Up)?.expanded??!0?null:e};function z_({id:n,label:e,children:t}){return W.jsx(nt,{pb:"0.5em",px:"xs",children:W.jsxs(pE,{align:"center",children:[W.jsx(nt,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:W.jsx("label",{htmlFor:n,children:e})})}),W.jsx(nt,{style:{flexGrow:1},children:t})]})})}function Oz({label:n,expandByDefault:e=!0,children:t}){const[r,{toggle:i}]=Kg(e),s=r?Xte:Uz;return W.jsxs(Gc,{withBorder:!0,style:{borderWidth:"1px",position:"relative",marginLeft:"var(--mantine-spacing-xs)",marginRight:"var(--mantine-spacing-xs)",marginTop:"var(--mantine-spacing-xs)",marginBottom:"var(--mantine-spacing-xs)",paddingBottom:"calc(var(--mantine-spacing-xs) - 0.5em)"},children:[W.jsxs(Gc,{onClick:i,style:{fontSize:"0.875em",position:"absolute",padding:"0 0.375em",top:0,left:"0.375em",transform:"translateY(-50%)",userSelect:"none",fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center"},children:[n,W.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),W.jsx(bg,{in:r,children:W.jsx(nt,{pt:"1em",children:t})}),W.jsx(bg,{in:!r,children:W.jsx(nt,{p:"xs"})})]})}const $z={fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"4.5em",flexShrink:0},rne={root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}},ine={flex:1,minWidth:0,height:"1.75em",fontSize:"0.8em",fontFamily:"inherit",border:"1px solid var(--mantine-color-default-border)",borderRadius:"var(--mantine-radius-sm)",background:"var(--mantine-color-default)",color:"var(--mantine-color-text)",textAlign:"right",padding:"0 0.4em",outline:"none",cursor:"ns-resize",touchAction:"none"};function U_({axis:n,value:e,min:t=-1/0,max:r=1/0,step:i,onChange:s}){const a=U.useRef(null),o=U.useRef(null);U.useEffect(()=>{const g=a.current;g&&document.activeElement!==g&&(g.value=e.toFixed(2))},[e]);const l=g=>Math.max(t,Math.min(r,parseFloat((Math.round(g/i)*i).toFixed(10)))),c=g=>{g.preventDefault(),g.currentTarget.setPointerCapture(g.pointerId),o.current={startY:g.clientY,startValue:e,moved:!1}},d=g=>{if(!o.current||!(g.buttons&1))return;const m=o.current.startY-g.clientY;if(Math.abs(m)>3&&(o.current.moved=!0),!o.current.moved)return;const x=l(o.current.startValue+m*i);s(x),a.current&&(a.current.value=x.toFixed(2))},h=()=>{if(o.current&&!o.current.moved){const g=a.current;g&&(g.focus(),g.select())}o.current=null},p=g=>{const m=parseFloat(g.target.value);isNaN(m)||s(l(m)),g.target.value=e.toFixed(2)},A=g=>{g.key==="Enter"&&g.currentTarget.blur(),g.key==="Escape"&&(a.current&&(a.current.value=e.toFixed(2)),a.current?.blur())};return W.jsxs(nt,{style:{display:"flex",alignItems:"center",gap:"0.25em",flex:1},children:[W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,letterSpacing:"-0.75px",flexShrink:0},children:n}),W.jsx("input",{ref:a,size:1,defaultValue:e.toFixed(2),onPointerDown:c,onPointerMove:d,onPointerUp:h,onBlur:p,onKeyDown:A,onFocus:g=>g.currentTarget.style.outline="2px solid var(--mantine-color-blue-5)",onBlurCapture:g=>g.currentTarget.style.outline="none",style:ine})]})}function LR({label:n,x:e,y:t,z:r,step:i,xLabel:s="X",yLabel:a="Y",zLabel:o="Z",onX:l,onY:c,onZ:d}){return W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[W.jsx(qs,{c:"dimmed",style:$z,children:n}),W.jsx(U_,{axis:s,value:e,step:i,onChange:l}),W.jsx(U_,{axis:a,value:t,step:i,onChange:c}),W.jsx(U_,{axis:o,value:r,step:i,onChange:d})]})}function sne({scale:n,xOffset:e,yOffset:t,zOffset:r,roll:i,pitch:s,yaw:a,onCalibrate:o}){const[l,c]=U.useState(n),[d,h]=U.useState(e),[p,A]=U.useState(t),[g,m]=U.useState(r),[x,y]=U.useState(i),[_,b]=U.useState(s),[w,C]=U.useState(a);U.useEffect(()=>{c(n)},[n]),U.useEffect(()=>{h(e)},[e]),U.useEffect(()=>{A(t)},[t]),U.useEffect(()=>{m(r)},[r]),U.useEffect(()=>{y(i)},[i]),U.useEffect(()=>{b(s)},[s]),U.useEffect(()=>{C(a)},[a]);const S=(M,T,R,k,V,P,H)=>o(M,T,R,k,V,P,H);return W.jsxs(Oz,{label:"Control",expandByDefault:!0,children:[W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[W.jsx(qs,{c:"dimmed",style:$z,children:"Scale"}),W.jsx(nt,{style:{flex:1},children:W.jsx(M0,{value:l,onChange:M=>{c(M),S(M,d,p,g,x,_,w)},min:.1,max:5,step:.05,size:"xs",label:M=>M.toFixed(2),styles:rne})})]}),W.jsx(LR,{label:"Position",x:d,y:p,z:g,step:.05,onX:M=>{h(M),S(l,M,p,g,x,_,w)},onY:M=>{A(M),S(l,d,M,g,x,_,w)},onZ:M=>{m(M),S(l,d,p,M,x,_,w)}}),W.jsx(LR,{label:"Rotation",x,y:_,z:w,step:.5,xLabel:"R",yLabel:"P",zLabel:"Y",onX:M=>{y(M),S(l,d,p,g,M,_,w)},onY:M=>{b(M),S(l,d,p,g,x,M,w)},onZ:M=>{C(M),S(l,d,p,g,x,_,M)}})]})}function ane(n){return n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function one({command:n,value:e,onChange:t,disabled:r}){const i=n.config;return W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:i.label}),W.jsx(nt,{style:{width:"50%"},children:W.jsx(M0,{value:e,onChange:s=>t(n.id,s),min:i.min,max:i.max,step:i.step,size:"xs",disabled:r,styles:{root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}}})})]})}function lne(n){const{projects:e,projectValue:t,projectLabel:r,onProjectChange:i,scenes:s,sceneValue:a,onSceneChange:o,splats:l,splatSection:c=!1,splatValue:d,onSplatChange:h,splatConfig:p,onCalibrateSplat:A,onSplatUrlLoad:g,policies:m,policyValue:x,onPolicyChange:y,commandsEnabled:_=!1,onReset:b}=n,[w,{open:C,close:S}]=Kg(!1),[M,T]=U.useState(""),[R,k]=U.useState(null),[V,P]=U.useState(!1),H=U.useCallback(async le=>{if(le.key!=="Enter"||!g)return;const oe=M.trim();if(l.some(ue=>ue.label===oe||ue.value===oe))return;if(!oe.toLowerCase().endsWith(".spz")){k("URL must end with .spz");return}await g(oe)?(k(null),P(!0)):k("File not found at the specified URL")},[g,M,l]),[B,j]=U.useState([]),[J,X]=U.useState([]),[$,Y]=U.useState({});U.useEffect(()=>{const le=Zr(),oe=()=>{j(le.getCommands()),X(le.getCommandGroups()),Y(le.getValues())};return oe(),le.addEventListener(oe),()=>{le.removeEventListener(oe)}},[]);const ne=U.useCallback((le,oe)=>{Zr().setValue(le,oe),Y(ue=>({...ue,[le]:oe}))},[]),L=U.useCallback(()=>{Zr().triggerButton("_system:reset"),b&&b()},[b]),G=le=>B.filter(oe=>oe.groupName===le&&oe.config.type==="slider");return!e.length&&!s.length&&!m.length?null:W.jsxs(W.Fragment,{children:[W.jsx(ra,{opened:w,onClose:S,size:"lg",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:W.jsxs(YE,{gap:"md",align:"center",children:[W.jsx(Mg,{src:"./logo-color.svg",style:{width:"8em",height:"auto"}}),W.jsx(qs,{size:"xl",fw:700,children:"powered by mjswan"}),W.jsxs(qs,{size:"sm",c:"dimmed",children:["version ",QR]}),W.jsx(qs,{size:"sm",c:"dimmed",children:"MuJoco Simulation on Web Assembly with Neural netwroks"}),W.jsx(wd,{w:"100%"}),W.jsxs(nt,{children:[W.jsx(sp,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"}),"  •  ",W.jsx(sp,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]}),W.jsx(wd,{w:"100%"}),W.jsxs(nt,{style:{textAlign:"left",maxHeight:"120px",overflowY:"auto",lineHeight:"1",fontSize:"0.8rem",opacity:"0.75"},px:"md",children:["Thanks to our contributors! ",W.jsx("br",{}),PR.map((le,oe)=>W.jsxs("span",{children:[W.jsx(sp,{href:le.html_url,target:"_blank",style:{textDecoration:"none",fontSize:"0.75rem"},children:le.login}),oe<PR.length-1&&", "]},le.login))]})]})}),W.jsxs(ho,{width:"20em",children:[W.jsxs(ho.Handle,{children:[W.jsx(Pd,{label:`mjswan ${QR}`,children:W.jsx(nt,{component:"a",onClick:le=>{le.stopPropagation(),C()},style:{position:"absolute",cursor:"pointer",display:"flex",top:"0.8em",left:"0.9em"},children:W.jsx(Mg,{src:"./logo.svg",style:{width:"1.2em",height:"auto"}})})}),W.jsx("div",{style:{width:"1.1em"}}),W.jsx(ho.HideWhenCollapsed,{children:W.jsxs(nt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[W.jsx("span",{style:{flexGrow:1},children:r}),e.length>1&&W.jsxs(fi,{position:"bottom-start",offset:5,children:[W.jsx(fi.Target,{children:W.jsx(nt,{onClick:le=>le.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center"},children:W.jsx(Uz,{size:16})})}),W.jsx(fi.Dropdown,{onClick:le=>le.stopPropagation(),children:e.map(le=>W.jsx(fi.Item,{onClick:oe=>{oe.stopPropagation(),i(le.value)},style:{fontWeight:le.value===t?600:400,backgroundColor:le.value===t?"rgba(34, 139, 230, 0.1)":void 0},children:le.label},le.value))})]})]})}),W.jsx(ho.HideWhenExpanded,{children:W.jsx(nt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:r})})]}),W.jsx(ho.Contents,{children:W.jsxs(nt,{pt:"0.375em",children:[s.length>0&&W.jsx(z_,{id:"scene-select",label:"Scene",children:W.jsx(Ed,{id:"scene-select",placeholder:"Select scene",data:s,value:a,onChange:o,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),(l.length>0||c)&&W.jsx(z_,{id:"splat-select",label:"Splat",children:W.jsx(Pd,{label:R??"",color:"red",position:"bottom",opened:R!==null,withArrow:!0,children:W.jsx(Ed,{id:"splat-select",placeholder:g!==void 0?"Select splat or paste .spz URL":"Select splat",data:l,value:d,onChange:le=>{h(le),k(null),P(!1)},searchable:g!==void 0,searchValue:M,onSearchChange:le=>{T(le),le&&k(null)},onKeyDown:H,size:"xs",radius:"xs",clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})})}),(p?.control&&d!==null||V)&&A&&W.jsx(sne,{scale:p?.scale??1,xOffset:p?.xOffset??0,yOffset:p?.yOffset??0,zOffset:p?.zOffset??0,roll:p?.roll??0,pitch:p?.pitch??0,yaw:p?.yaw??0,onCalibrate:A}),m.length>0&&W.jsx(z_,{id:"policy-select",label:"Policy",children:W.jsx(Ed,{id:"policy-select",placeholder:"Select policy",data:m,value:x,onChange:y,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),J.length>0&&B.filter(le=>le.config.type==="slider").length>0&&W.jsx(W.Fragment,{children:J.map(le=>{const oe=G(le);return oe.length===0?null:W.jsx(Oz,{label:ane(le),expandByDefault:!0,children:oe.map(Ae=>W.jsx(one,{command:Ae,value:$[Ae.id]??0,onChange:ne,disabled:!_},Ae.id))},le)})}),W.jsx(wd,{mb:"xs",mx:"xs"}),W.jsx(nt,{px:"xs",pb:"xs",children:W.jsx(ih,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:W.jsx(Kte,{size:14}),onClick:L,children:"Reset"})})]})})]})]})}function jf(n,e,t){return Object.keys(n[e]).reduce((r,i)=>(r[i]=`var(--mantine-${t}-${i})`,r),{})}function FR(n,e){return n in e.breakpoints?e.breakpoints[n]:G_(n)}function cne(n){const e=uD(n0,n),t=jf(e,"fontSizes","font-size"),r=jf(e,"lineHeights","line-height"),i=jf(e,"shadows","shadow"),s=jf(e,"radius","radius"),a=jf(e,"spacing","spacing"),o=Object.keys(e.headings.sizes).reduce((c,d)=>(c[d]={fontSize:`var(--mantine-${d}-font-size)`,lineHeight:`var(--mantine-${d}-line-height)`,fontWeight:`var(--mantine-${d}-font-weight)`},c),{}),l=Object.keys(e.colors).reduce((c,d)=>(c[d]={0:`var(--mantine-color-${d}-0)`,1:`var(--mantine-color-${d}-1)`,2:`var(--mantine-color-${d}-2)`,3:`var(--mantine-color-${d}-3)`,4:`var(--mantine-color-${d}-4)`,5:`var(--mantine-color-${d}-5)`,6:`var(--mantine-color-${d}-6)`,7:`var(--mantine-color-${d}-7)`,8:`var(--mantine-color-${d}-8)`,9:`var(--mantine-color-${d}-9)`,filled:`var(--mantine-color-${d}-filled)`,filledHover:`var(--mantine-color-${d}-filled-hover)`,light:`var(--mantine-color-${d}-light)`,lightHover:`var(--mantine-color-${d}-light-hover)`,lightColor:`var(--mantine-color-${d}-light-color)`,outline:`var(--mantine-color-${d}-outline)`,outlineHover:`var(--mantine-color-${d}-outline-hover)`},c),{primary:"var(--mantine-primary-color-filled)",primaryColors:{0:"var(--mantine-primary-color-0)",1:"var(--mantine-primary-color-1)",2:"var(--mantine-primary-color-2)",3:"var(--mantine-primary-color-3)",4:"var(--mantine-primary-color-4)",5:"var(--mantine-primary-color-5)",6:"var(--mantine-primary-color-6)",7:"var(--mantine-primary-color-7)",8:"var(--mantine-primary-color-8)",9:"var(--mantine-primary-color-9)",filled:"var(--mantine-primary-color-filled)",filledHover:"var(--mantine-primary-color-filled-hover)",light:"var(--mantine-primary-color-light)",lightHover:"var(--mantine-primary-color-light-hover)",lightColor:"var(--mantine-primary-color-light-color)",outline:"var(--mantine-primary-color-outline)",outlineHover:"var(--mantine-primary-color-outline-hover)"},white:"var(--mantine-color-white)",black:"var(--mantine-color-black)",text:"var(--mantine-color-text)",body:"var(--mantine-color-body)",error:"var(--mantine-color-error)",placeholder:"var(--mantine-color-placeholder)",anchor:"var(--mantine-color-anchor)",default:"var(--mantine-color-default)",defaultHover:"var(--mantine-color-default-hover)",defaultColor:"var(--mantine-color-default-color)",defaultBorder:"var(--mantine-color-default-border)",dimmed:"var(--mantine-color-dimmed)",disabledBody:"var(--mantine-color-disabled)",disabledText:"var(--mantine-color-disabled-color)",disabledBorder:"var(--mantine-color-disabled-border)"});return{scale:"var(--mantine-scale)",cursorType:"var(--mantine-cursor-type)",webkitFontSmoothing:"var(--mantine-webkit-font-smoothing)",mozFontSmoothing:"var(--mantine-moz-font-smoothing)",lineHeight:"var(--mantine-line-height)",fontFamily:"var(--mantine-font-family)",fontFamilyMonospace:"var(--mantine-font-family-monospace)",fontFamilyHeadings:"var(--mantine-font-family-headings)",headingFontWeight:"var(--mantine-heading-font-weight)",radiusDefault:"var(--mantine-radius-default)",breakpoints:e.breakpoints,fontSizes:t,lineHeights:r,shadows:i,radius:s,headings:o,spacing:a,colors:l,rtlSelector:'[dir="rtl"] &',darkSelector:'[data-mantine-color-scheme="dark"] &',lightSelector:'[data-mantine-color-scheme="light"] &',smallerThan:c=>`(max-width: ${FR(c,e)})`,largerThan:c=>`(min-width: ${FR(c,e)})`}}const kw={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:nh.extend({defaultProps:{radius:"xs"}}),ColorInput:PE.extend({defaultProps:{radius:"xs"}}),Select:Ed.extend({defaultProps:{radius:"sm"}}),Textarea:FE.extend({defaultProps:{radius:"xs"}}),TextInput:XE.extend({defaultProps:{radius:"xs"}}),NumberInput:jE.extend({defaultProps:{radius:"xs"}}),Paper:Gc.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:th.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:ih.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};cne(kw);const Gz=U.createContext(void 0),Hz=()=>{const n=U.useContext(Gz);if(!n)throw new Error("useLoading must be used within a LoadingProvider");return n},une=({children:n})=>{const[e,t]=U.useState(!1),r=U.useRef(0),i=U.useCallback(()=>{r.current+=1,r.current>0&&t(!0)},[]),s=U.useCallback(()=>{r.current=Math.max(0,r.current-1),r.current===0&&t(!1)},[]);return W.jsx(Gz.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:n})},dne=()=>{const{isLoading:n}=Hz();return n?W.jsx("div",{className:"loader-overlay",children:W.jsx("div",{className:"loader-content",children:W.jsx(Zd,{size:64,type:"bars"})})}):null};function hne(){const n="/".replace(/\/+$/,"/");let t=window.location.pathname.replace(/^\/+|\/+$/g,"");const r=n.replace(/^\/+|\/+$/g,"");if(r&&(t===r?t="":t.startsWith(`${r}/`)&&(t=t.slice(r.length+1))),!t)return null;const i=t.split("/")[0];return i==="main"||i.includes(".")||i==="assets"?null:i}function uI(n){return n.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function fne(n,e){const t=n.replace(/\/+$/,"/"),r=new Set,i=(h,p)=>{if(h)try{const A=new URL(h,p||window.location.href).toString();r.add(A)}catch{r.add(h.replace(/\/+/g,"/"))}},s=`${window.location.origin}/`,a=new URL(t,s).toString();i("assets/config.json",a);const l=window.location.pathname.split("/").filter(Boolean);l.length>0&&l[l.length-1]==="index.html"&&l.pop(),l.length>0&&l[l.length-1]===(e??"main")&&l.pop();const c=`/${l.join("/")}${l.length?"/":""}`,d=`${window.location.origin}${c}`;return i("assets/config.json",d),i("assets/config.json"),i("../assets/config.json"),i("../../assets/config.json"),Array.from(r)}async function pne(n,e){const r=new URLSearchParams(window.location.search).get("config"),i=fne(n,e);if(r)try{i.unshift(new URL(r,window.location.href).toString())}catch{i.unshift(r)}let s=null;for(const a of i)try{const o=await fetch(a,{cache:"no-store"});if(!o.ok)throw new Error(`Failed to fetch ${a}: ${o.status}`);const l=await o.text(),c=l.trim();if((o.headers.get("content-type")||"").includes("text/html")||c.startsWith("<!doctype")||c.startsWith("<html"))throw new Error(`Received HTML from ${a}`);try{return JSON.parse(l)}catch(h){throw new Error(`Invalid JSON from ${a}: ${h instanceof Error?h.message:String(h)}`)}}catch(o){s=o instanceof Error?o:new Error(String(o))}throw s??new Error("Failed to load config.json.")}function zR(n,e){if(!n.scenes.length)return null;if(!e)return n.scenes[0];const t=e.trim().toLowerCase();return n.scenes.find(r=>r.name.toLowerCase()===t)||n.scenes.find(r=>uI(r.name)===t)||n.scenes[0]}function UR(n,e){if(!n.policies.length)return null;const t=n.policies.find(s=>s.default)??n.policies[0];if(!e)return t.name;const r=e.trim().toLowerCase();return(n.policies.find(s=>s.name.toLowerCase()===r)||n.policies.find(s=>uI(s.name)===r))?.name??t.name}function O_(n,e,t){const i="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let s=i?`/${i}/`:"/";n&&n!=="main"&&(s+=`${n}/`);const a=new URLSearchParams;e&&a.set("scene",e),t&&a.set("policy",t);const o=s+(a.toString()?"?"+a.toString():"");window.history.replaceState({},"",o)}function Ane(){const[n,e]=U.useState(null),[t,r]=U.useState(null),[i,s]=U.useState(null),[a,o]=U.useState(null),[l,c]=U.useState(null),[d,h]=U.useState(null),[p,A]=U.useState(null),g=U.useRef(null),{showLoading:m,hideLoading:x}=Hz(),y=U.useMemo(()=>hne(),[]),_=U.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),b=U.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);U.useEffect(()=>{m(),pne("/",y).then(oe=>{e(oe);const Ae=oe.projects.find(be=>y===null?be.id===null:be.id===y);if(!Ae)throw new Error(`Project "${y??"(main)"}" not found in config.json.`);r(Ae);const ue=zR(Ae,_);s(ue);const pe=ue?UR(ue,b):null;o(pe)}).catch(oe=>{console.error("Failed to load config:",oe),c(oe.message||"Failed to load config."),x()})},[y,_,b,m,x]);const w=U.useMemo(()=>{if(!t||!i)return null;const oe=t.id?t.id:"main",Ae=i.path?i.path:`scene/${uI(i.name)}/scene.xml`;return`${oe}/assets/${Ae}`.replace(/\/+/g,"/")},[t,i]),C=U.useMemo(()=>!i||!a?null:i.policies.find(oe=>oe.name===a)??null,[i,a]),S=U.useMemo(()=>!t||!C?.config?null:`${t.id?t.id:"main"}/assets/${C.config}`.replace(/\/+/g,"/"),[t,C]),M=U.useMemo(()=>{if(!t||!i?.splats?.length)return[];const oe=t.id?t.id:"main";return i.splats.map(Ae=>{if(Ae.path){const ue=`${oe}/assets/${Ae.path}`.replace(/\/+/g,"/");return{...Ae,url:ue}}return Ae})},[t,i?.splats]),T=U.useMemo(()=>d?M.find(oe=>oe.name===d)??null:p?{name:"Custom",url:p}:null,[M,d,p]),R=U.useMemo(()=>n?n.projects.map(oe=>({value:oe.id??"main",label:oe.name||(oe.id??"Main")})):[],[n]),k=U.useMemo(()=>t?t.scenes.map(oe=>({value:oe.name,label:oe.name})):[],[t]),V=U.useMemo(()=>!i||!i.policies?[]:i.policies.map(oe=>({value:oe.name,label:oe.name})),[i]),P=t?t.id??"main":null,H=i?.name??null,B=U.useCallback(oe=>{c(oe.message),x()},[x]),j=U.useCallback(()=>{x()},[x]);U.useEffect(()=>{const oe=i?.splats?.[0];h(oe?oe.name:null),A(null)},[i]);const J=U.useCallback(oe=>{g.current=oe},[]),X=U.useMemo(()=>i?.splats?.length?i.splats.map(oe=>({value:oe.name,label:oe.name})):[],[i?.splats]),$=U.useCallback(oe=>{if(oe===null)g.current?.setSplat(null);else{const Ae=M.find(ue=>ue.name===oe);Ae&&g.current?.setSplat(Ae)}h(oe),A(null)},[M]),Y=U.useCallback(async oe=>{try{if(!(await fetch(oe,{method:"HEAD"})).ok)return!1}catch{return!1}return g.current?.setSplat({name:"Custom",url:oe}),A(oe),!0},[]),ne=U.useCallback((oe,Ae,ue,pe,be,Te,ke)=>{const Oe=T??(p?{name:"Custom",url:p}:null);Oe&&g.current?.calibrateSplat({...Oe,scale:oe,xOffset:Ae,yOffset:ue,zOffset:pe,roll:be,pitch:Te,yaw:ke})},[T,p]),L=U.useCallback(oe=>{if(!n||!oe)return;const Ae=oe==="main"?null:oe,ue=n.projects.find(Te=>(Te.id??"main")===(Ae??"main"));if(!ue)return;m(),r(ue);const pe=zR(ue,null);s(pe);const be=pe?.policies?.[0]?.name??null;o(be),O_(ue.id,pe?.name??null,be)},[n,m]),G=U.useCallback(oe=>{if(!t||!oe)return;const Ae=t.scenes.find(pe=>pe.name===oe);if(!Ae)return;m(),s(Ae);const ue=UR(Ae,null);o(ue),O_(t.id,oe,ue)},[t,m]),le=U.useCallback(oe=>{oe!==a&&m(),o(oe),O_(t?.id??null,i?.name??null,oe)},[t,i,a,m]);return l?W.jsx(W_,{theme:kw,defaultColorScheme:"auto",children:W.jsx("div",{className:"app",children:W.jsxs("div",{className:"hud hud-error",children:[W.jsx("h1",{className:"hud-title",children:"mjswan"}),W.jsx("p",{className:"hud-message",children:l})]})})}):!t||!i||!w?null:W.jsx(W_,{theme:kw,defaultColorScheme:"auto",children:W.jsxs("div",{className:"app",children:[W.jsx(dne,{}),W.jsx(lne,{projects:R,projectValue:P,projectLabel:t?.name??"mjswan",onProjectChange:L,scenes:k,sceneValue:H,onSceneChange:G,splats:X,splatSection:i?.splatSection??!1,splatValue:d,onSplatChange:$,splatConfig:T,onCalibrateSplat:ne,onSplatUrlLoad:Y,policies:V,policyValue:a,onPolicyChange:le,commandsEnabled:!!S}),W.jsx(jte,{scenePath:w,baseUrl:"/",policyConfigPath:S,splatConfig:T,cameraConfig:i?.camera,eventsConfig:i?.events,terrainData:i?.terrainData,onError:B,onReady:j,onRuntimeReady:J})]})})}function mne(){return W.jsx(une,{children:W.jsx(Ane,{})})}const OR=document.getElementById("root");OR&&k4.createRoot(OR).render(W.jsx(On.StrictMode,{children:W.jsx(mne,{})}));export{gH as _};
15613
+ ${s}`,o=t.createShaderModule({code:a,label:n.name});un("verbose",()=>`[WebGPU] ${n.name} shader code: ${a}`);let l=t.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:n.name});return Js(n.name),{programInfo:n,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(n){let e=typeof n=="number"?n:n.x,t=typeof n=="number"?1:n.y||1,r=typeof n=="number"?1:n.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=i&&t<=i&&r<=i)return[e,t,r];let s=e*t*r,a=Math.ceil(Math.sqrt(s));if(a>i){if(a=Math.ceil(Math.cbrt(s)),a>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),xz={};mh(xz,{WebGpuBackend:()=>vz});var IR,SR,BR,vz,Bte=Ze(()=>{ms(),Lt(),Ro(),RP(),Fee(),Ite(),Ste(),IR=(n,e)=>{if(e.length!==n.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${n.length}.`);let t=[];for(let r=0;r<n.length;++r){let i=n[r].dataType;switch(e[r]){case"none":{t.push("");break}case"type":{t.push(`${i}`);break}case"rank":{let s=n[r].dims.length;t.push(`${i};${s}`);break}case"dims":{let s=n[r].dims.join(",");t.push(`${i};${s}`);break}default:throw new Error(`unsupported input dependency: ${e[r]}`)}}return t.join("|")},SR=(n,e,t)=>{let r=n.name;return n.shaderCache?.hint&&(r+="["+n.shaderCache.hint+"]"),r+=":"+t+`:${IR(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},BR=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},vz=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let n=this.kernelCustomData.get(this.currentKernelId);return n||(n={},this.kernelCustomData.set(this.currentKernelId,n)),n}async initialize(n,e){this.env=n;let t=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxBufferSize:e.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:e.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:e.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:e.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:e.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},i=s=>e.features.has(s)&&t.push(s)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await e.requestDevice(r),this.adapterInfo=new BR(e.info||await e.requestAdapterInfo()),this.gpuDataManager=NP(this),this.programManager=new yz(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,HC(n.logLevel,!!n.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let n=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Qa(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(n.getMappedRange()),t=this.pendingQueries.get(n);for(let r=0;r<e.length/2;r++){let i=t[r],s=i.kernelId,a=this.kernels.get(s),o=a.kernelType,l=a.kernelName,c=i.programName,d=i.inputTensorViews,h=i.outputTensorViews,p=e[r*2],A=e[r*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=p);let g=Number(p-this.queryTimeBase),m=Number(A-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(m))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(x=>({dims:x.dims,dataType:uo(x.dataType)})),outputsMetadata:h.map(x=>({dims:x.dims,dataType:uo(x.dataType)})),kernelId:s,kernelType:o,kernelName:l,programName:c,startTime:g,endTime:m});else{let x="";d.forEach((_,b)=>{x+=`input[${b}]: [${_.dims}] | ${uo(_.dataType)}, `});let y="";h.forEach((_,b)=>{y+=`output[${b}]: [${_.dims}] | ${uo(_.dataType)}, `}),console.log(`[profiling] kernel "${s}|${o}|${l}|${c}" ${x}${y}start time: ${g} ns, execution time: ${m-g} ns`)}Og("GPU",`${c}::${p}::${A}`)}n.unmap(),this.pendingQueries.delete(n)}),Js()}run(n,e,t,r,i,s){Qa(n.name);let a=[];for(let _=0;_<e.length;++_){let b=e[_].data;if(b===0)continue;let w=this.gpuDataManager.get(b);if(!w)throw new Error(`no GPU data for input: ${b}`);a.push(w)}let{outputs:o,dispatchGroup:l,programUniforms:c}=n.getRunData(e),d=t.length===0?o.map((_,b)=>b):t;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let h=[],p=[];for(let _=0;_<o.length;++_){if(!Number.isInteger(d[_])||d[_]<-3||d[_]>=s)throw new Error(`Invalid output index: ${d[_]}`);if(d[_]===-3)continue;let b=d[_]===-1,w=d[_]===-2,C=b||w?i(o[_].dataType,o[_].dims):r(d[_],o[_].dataType,o[_].dims);if(h.push(C),C.data===0)continue;let S=this.gpuDataManager.get(C.data);if(!S)throw new Error(`no GPU data for output: ${C.data}`);if(b&&this.temporaryData.push(S),w){let M=this.kernelPersistentData.get(this.currentKernelId);M||(M=[],this.kernelPersistentData.set(this.currentKernelId,M)),M.push(S)}p.push(S)}if(a.length!==e.length||p.length!==h.length){if(p.length===0)return Js(n.name),h;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let A;if(c){let _=0,b=[];c.forEach(M=>{let T=typeof M.data=="number"?[M.data]:M.data;if(T.length===0)return;let R=M.type===10?2:4,k,V;M.type===10?(V=T.length>4?16:T.length>2?8:T.length*R,k=T.length>4?16:R*T.length):(V=T.length<=2?T.length*R:16,k=16),_=Math.ceil(_/V)*V,b.push(_);let P=M.type===10?8:4;_+=T.length>4?Math.ceil(T.length/P)*k:T.length*R});let w=16;_=Math.ceil(_/w)*w;let C=new ArrayBuffer(_);c.forEach((M,T)=>{let R=b[T],k=typeof M.data=="number"?[M.data]:M.data;if(M.type===6)new Int32Array(C,R,k.length).set(k);else if(M.type===12)new Uint32Array(C,R,k.length).set(k);else if(M.type===10)new Uint16Array(C,R,k.length).set(k);else if(M.type===1)new Float32Array(C,R,k.length).set(k);else throw new Error(`Unsupported uniform type: ${uo(M.type)}`)});let S=this.gpuDataManager.create(_,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(S.buffer,0,C,0,_),this.gpuDataManager.release(S.id),A={offset:0,size:_,buffer:S.buffer}}let g=this.programManager.normalizeDispatchGroupSize(l),m=g[1]===1&&g[2]===1,x=SR(n,e,m),y=this.programManager.getArtifact(x);if(y||(y=this.programManager.build(n,g),this.programManager.setArtifact(x,y),un("info",()=>`[artifact] key: ${x}, programName: ${n.name}`)),c&&y.uniformVariablesInfo){if(c.length!==y.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${y.uniformVariablesInfo.length}, got ${c.length} in program "${y.programInfo.name}".`);for(let _=0;_<c.length;_++){let b=c[_],w=b.type,C=typeof b.data=="number"?1:b.data.length,[S,M]=y.uniformVariablesInfo[_];if(w!==S||C!==M)throw new Error(`Uniform variable ${_} mismatch: expect type ${S} with size ${M}, got type ${w} with size ${C} in program "${y.programInfo.name}".`)}}if(un("info",()=>`[ProgramManager] run "${n.name}" (key=${x}) with ${g[0]}x${g[1]}x${g[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let _={kernelId:this.currentKernelId,programName:y.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(_),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(_)}return this.programManager.run(y,a,p,g,A),Js(n.name),h}upload(n,e){this.gpuDataManager.upload(n,e)}memcpy(n,e){this.gpuDataManager.memcpy(n,e)}async download(n,e){await this.gpuDataManager.download(n,e)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,e,t,r){let i=gz.get(n);if(!i)throw new Error(`kernel not implemented: ${n}`);let s={kernelType:n,kernelName:r,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(e,s)}releaseKernel(n){let e=this.kernelPersistentData.get(n);if(e){for(let t of e)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,e,t){let r=this.kernels.get(n);if(!r)throw new Error(`kernel not created: ${n}`);let i=r.kernelType,s=r.kernelName,a=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${s}" is not allowed to be called recursively`);this.currentKernelId=n,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),un("info",()=>`[WebGPU] Start to run kernel "[${i}] ${s}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(e,o[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${s}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${i}] ${s}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,e,t,r){let i=this.sessionExternalDataMapping.get(n);i||(i=new Map,this.sessionExternalDataMapping.set(n,i));let s=i.get(e),a=this.gpuDataManager.registerExternalBuffer(t,r,s);return i.set(e,[a,t]),a}unregisterBuffers(n){let e=this.sessionExternalDataMapping.get(n);e&&(e.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let e=this.gpuDataManager.get(n);if(!e)throw new Error(`no GPU data for buffer: ${n}`);return e.buffer}createDownloader(n,e,t){return async()=>{let r=await vw(this,n,e);return VC(r.buffer,t)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){un("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){un("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){un("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),t=n.length;this.pendingKernels=[];for(let r=0;r<t;r++){let i=this.getComputePassEncoder(),s=n[r];this.writeTimestamp(this.pendingDispatchNumber*2),i.setPipeline(s.computePipeline),i.setBindGroup(0,s.bindGroup),i.dispatchWorkgroups(...s.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(e[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),_z={};mh(_z,{init:()=>bz});var Xm,MR,bz,Mte=Ze(()=>{Lt(),Ro(),jt(),Lee(),Xm=class wz{constructor(e,t,r,i){this.module=e,this.dataType=t,this.data=r,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=Pe.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=Pe.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=Pe.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let e=Pe.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Pe.size(e)!==Pe.size(this.dims))throw new Error("Invalid new shape");return new wz(this.module,this.dataType,this.data,e)}},MR=class{constructor(n,e,t){this.module=n,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let r=n.PTR_SIZE,i=t/n.PTR_SIZE,s=r===4?"i32":"i64";this.opKernelContext=Number(n.getValue(r*i++,s));let a=Number(n.getValue(r*i++,s));this.outputCount=Number(n.getValue(r*i++,s)),this.customDataOffset=Number(n.getValue(r*i++,"*")),this.customDataSize=Number(n.getValue(r*i++,s));let o=[];for(let l=0;l<a;l++){let c=Number(n.getValue(r*i++,s)),d=Number(n.getValue(r*i++,"*")),h=Number(n.getValue(r*i++,s)),p=[];for(let A=0;A<h;A++)p.push(Number(n.getValue(r*i++,s)));o.push(new Xm(n,c,d,p))}this.inputs=o}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(n,e){let t=e?.inputs?.map(a=>typeof a=="number"?this.inputs[a]:a)??this.inputs,r=e?.outputs??[],i=(a,o,l)=>new Xm(this.module,o,this.output(a,l),l),s=(a,o)=>{let l=Rc(a,o);if(!l)throw new Error(`Unsupported data type: ${a}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new Xm(this.module,a,c,o)};return this.backend.run(n,t,r,i,s,this.outputCount)}output(n,e){let t=this.module.stackSave();try{let r=this.module.PTR_SIZE,i=r===4?"i32":"i64",s=this.module.stackAlloc((1+e.length)*r);this.module.setValue(s,e.length,i);for(let a=0;a<e.length;a++)this.module.setValue(s+r*(a+1),e[a],i);return this.module._JsepOutput(this.opKernelContext,n,s)}catch(r){throw new Error(`Failed to generate kernel's output[${n}] with dims [${e}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${r}`)}finally{this.module.stackRestore(t)}}},bz=async(n,e,t,r)=>{let i=e.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(n==="webgpu"){let s=(Bte(),Rp(xz)).WebGpuBackend,a=new s;await a.initialize(t,r),i("webgpu",[a,o=>a.alloc(Number(o)),o=>a.free(o),(o,l,c,d=!1)=>{if(d)un("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(l)}, size=${Number(c)}`),a.memcpy(Number(o),Number(l));else{un("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let h=e.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(c));a.upload(Number(l),h)}},async(o,l,c)=>{un("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${l}, size=${c}`),await a.download(Number(o),()=>e.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(o,l,c)=>a.createKernel(o,Number(l),c,e.UTF8ToString(e._JsepGetNodeName(Number(l)))),o=>a.releaseKernel(o),(o,l,c,d)=>{un("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${o}, contextDataOffset=${l}`);let h=new MR(e,a,Number(l));return a.computeKernel(Number(o),h,d)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let s=new kP(t);i("webnn",[s,()=>s.reserveTensorId(),a=>s.releaseTensorId(a),async(a,o,l,c,d)=>s.ensureTensor(a,o,l,c,d),(a,o)=>{s.uploadTensor(a,o)},async(a,o)=>s.downloadTensor(a,o),(a,o)=>s.registerMLContext(a,o),!!t.trace])}}}),TR,nI,rI,wl,RR,Q_,qg,iI,sI,P_,aI,oI,lI,Ez=Ze(()=>{ms(),Nee(),Qee(),Lt(),tu(),UC(),SP(),TR=(n,e)=>{kn()._OrtInit(n,e)!==0&&wn("Can't initialize onnxruntime.")},nI=async n=>{TR(n.wasm.numThreads,Gg(n.logLevel))},rI=async(n,e)=>{kn().asyncInit?.();let t=n.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(t){if(typeof t.limits!="object"||typeof t.features!="object"||typeof t.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let r=n.webgpu.powerPreference;if(r!==void 0&&r!=="low-power"&&r!=="high-performance")throw new Error(`Invalid powerPreference setting: "${r}"`);let i=n.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:r,forceFallbackAdapter:i}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let r=(Mte(),Rp(_z)).init;e==="webgpu"&&await r("webgpu",kn(),n,t),e==="webnn"&&await r("webnn",kn(),n)}},wl=new Map,RR=n=>{let e=kn(),t=e.stackSave();try{let r=e.PTR_SIZE,i=e.stackAlloc(2*r);e._OrtGetInputOutputCount(n,i,i+r)!==0&&wn("Can't get session input/output count.");let s=r===4?"i32":"i64";return[Number(e.getValue(i,s)),Number(e.getValue(i+r,s))]}finally{e.stackRestore(t)}},Q_=(n,e)=>{let t=kn(),r=t.stackSave(),i=0;try{let s=t.PTR_SIZE,a=t.stackAlloc(2*s);t._OrtGetInputOutputMetadata(n,e,a,a+s)!==0&&wn("Can't get session input/output metadata.");let o=Number(t.getValue(a,"*"));i=Number(t.getValue(a+s,"*"));let l=t.HEAP32[i/4];if(l===0)return[o,0];let c=t.HEAPU32[i/4+1],d=[];for(let h=0;h<c;h++){let p=Number(t.getValue(i+8+h*s,"*"));d.push(p!==0?t.UTF8ToString(p):Number(t.getValue(i+8+(h+c)*s,"*")))}return[o,l,d]}finally{t.stackRestore(r),i!==0&&t._OrtFree(i)}},qg=n=>{let e=kn(),t=e._malloc(n.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return e.HEAPU8.set(n,t),[t,n.byteLength]},iI=async(n,e)=>{let t,r,i=kn();Array.isArray(n)?[t,r]=n:n.buffer===i.HEAPU8.buffer?[t,r]=[n.byteOffset,n.byteLength]:[t,r]=qg(n);let s=0,a=0,o=0,l=[],c=[],d=[];try{if([a,l]=await IP(e),e?.externalData&&i.mountExternalData){let w=[];for(let C of e.externalData){let S=typeof C=="string"?C:C.path;w.push(GC(typeof C=="string"?C:C.data).then(M=>{i.mountExternalData(S,M)}))}await Promise.all(w)}for(let w of e?.executionProviders??[])if((typeof w=="string"?w:w.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof w!="string"){let C=w,S=C?.context,M=C?.gpuDevice,T=C?.deviceType,R=C?.powerPreference;S?i.currentContext=S:M?i.currentContext=await i.webnnCreateMLContext(M):i.currentContext=await i.webnnCreateMLContext({deviceType:T,powerPreference:R})}else i.currentContext=await i.webnnCreateMLContext();break}s=await i._OrtCreateSession(t,r,a),i.webgpuOnCreateSession?.(s),s===0&&wn("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(s,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[h,p]=RR(s),A=!!e?.enableGraphCapture,g=[],m=[],x=[],y=[],_=[];for(let w=0;w<h;w++){let[C,S,M]=Q_(s,w);C===0&&wn("Can't get an input name."),c.push(C);let T=i.UTF8ToString(C);g.push(T),x.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:uo(S),shape:M})}for(let w=0;w<p;w++){let[C,S,M]=Q_(s,w+h);C===0&&wn("Can't get an output name."),d.push(C);let T=i.UTF8ToString(C);m.push(T),y.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:uo(S),shape:M});{if(A&&e?.preferredOutputLocation===void 0){_.push("gpu-buffer");continue}let R=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[T]??"cpu",k=i.webnnIsGraphOutput;if(R==="cpu"&&k&&k(s,T)){_.push("ml-tensor-cpu-output");continue}if(R!=="cpu"&&R!=="cpu-pinned"&&R!=="gpu-buffer"&&R!=="ml-tensor")throw new Error(`Not supported preferred output location: ${R}.`);if(A&&R!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${R}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(R)}}let b=null;return _.some(w=>w==="gpu-buffer"||w==="ml-tensor"||w==="ml-tensor-cpu-output")&&(o=i._OrtCreateBinding(s),o===0&&wn("Can't create IO binding."),b={handle:o,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(w=>w==="ml-tensor-cpu-output"?"ml-tensor":w).map(w=>yw(w))}),wl.set(s,[s,c,d,b,A,!1]),[s,g,m,x,y]}catch(h){throw c.forEach(p=>i._OrtFree(p)),d.forEach(p=>i._OrtFree(p)),o!==0&&i._OrtReleaseBinding(o)!==0&&wn("Can't release IO binding."),s!==0&&i._OrtReleaseSession(s)!==0&&wn("Can't release session."),h}finally{i._free(t),a!==0&&i._OrtReleaseSessionOptions(a)!==0&&wn("Can't release session options."),l.forEach(h=>i._free(h)),i.unmountExternalData?.()}},sI=n=>{let e=kn(),t=wl.get(n);if(!t)throw new Error(`cannot release session. invalid session id: ${n}`);let[r,i,s,a,o]=t;a&&(o&&e._OrtClearBoundOutputs(a.handle)!==0&&wn("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&wn("Can't release IO binding.")),e.jsepOnReleaseSession?.(n),e.webnnOnReleaseSession?.(n),e.webgpuOnReleaseSession?.(n),i.forEach(l=>e._OrtFree(l)),s.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(r)!==0&&wn("Can't release session."),wl.delete(n)},P_=async(n,e,t,r,i,s,a=!1)=>{if(!n){e.push(0);return}let o=kn(),l=o.PTR_SIZE,c=n[0],d=n[1],h=n[3],p=h,A,g;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let y=n[2].gpuBuffer;g=Rc(Tc(c),d);{let _=o.jsepRegisterBuffer;if(!_)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=_(r,s,y,g)}}else if(h==="ml-tensor"){let y=n[2].mlTensor;g=Rc(Tc(c),d);let _=o.webnnRegisterMLTensor;if(!_)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=_(r,y,Tc(c),d)}else{let y=n[2];if(Array.isArray(y)){g=l*y.length,A=o._malloc(g),t.push(A);for(let _=0;_<y.length;_++){if(typeof y[_]!="string")throw new TypeError(`tensor data at index ${_} is not a string`);o.setValue(A+_*l,Us(y[_],t),"*")}}else{let _=o.webnnIsGraphInput,b=o.webnnIsGraphOutput;if(c!=="string"&&_&&b){let w=o.UTF8ToString(i);if(_(r,w)||b(r,w)){let C=Tc(c);g=Rc(C,d),p="ml-tensor";let S=o.webnnCreateTemporaryTensor,M=o.webnnUploadTensor;if(!S||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let T=await S(r,C,d);M(T,new Uint8Array(y.buffer,y.byteOffset,y.byteLength)),A=T}else g=y.byteLength,A=o._malloc(g),t.push(A),o.HEAPU8.set(new Uint8Array(y.buffer,y.byteOffset,g),A)}else g=y.byteLength,A=o._malloc(g),t.push(A),o.HEAPU8.set(new Uint8Array(y.buffer,y.byteOffset,g),A)}}let m=o.stackSave(),x=o.stackAlloc(4*d.length);try{d.forEach((_,b)=>o.setValue(x+b*l,_,l===4?"i32":"i64"));let y=o._OrtCreateTensor(Tc(c),A,g,x,d.length,yw(p));y===0&&wn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(y)}finally{o.stackRestore(m)}},aI=async(n,e,t,r,i,s)=>{let a=kn(),o=a.PTR_SIZE,l=wl.get(n);if(!l)throw new Error(`cannot run inference. invalid session id: ${n}`);let c=l[0],d=l[1],h=l[2],p=l[3],A=l[4],g=l[5],m=e.length,x=r.length,y=0,_=[],b=[],w=[],C=[],S=[],M=a.stackSave(),T=a.stackAlloc(m*o),R=a.stackAlloc(m*o),k=a.stackAlloc(x*o),V=a.stackAlloc(x*o);try{[y,_]=CP(s),Uc("wasm prepareInputOutputTensor");for(let j=0;j<m;j++)await P_(t[j],b,C,n,d[e[j]],e[j],A);for(let j=0;j<x;j++)await P_(i[j],w,C,n,h[r[j]],m+r[j],A);Oc("wasm prepareInputOutputTensor");for(let j=0;j<m;j++)a.setValue(T+j*o,b[j],"*"),a.setValue(R+j*o,d[e[j]],"*");for(let j=0;j<x;j++)a.setValue(k+j*o,w[j],"*"),a.setValue(V+j*o,h[r[j]],"*");if(p&&!g){let{handle:j,outputPreferredLocations:J,outputPreferredLocationsEncoded:X}=p;if(d.length!==m)throw new Error(`input count from feeds (${m}) is expected to be always equal to model's input count (${d.length}).`);Uc("wasm bindInputsOutputs");for(let $=0;$<m;$++){let Y=e[$];await a._OrtBindInput(j,d[Y],b[$])!==0&&wn(`Can't bind input[${$}] for session=${n}.`)}for(let $=0;$<x;$++){let Y=r[$];i[$]?.[3]?(S.push(w[$]),a._OrtBindOutput(j,h[Y],w[$],0)!==0&&wn(`Can't bind pre-allocated output[${$}] for session=${n}.`)):a._OrtBindOutput(j,h[Y],0,X[Y])!==0&&wn(`Can't bind output[${$}] to ${J[$]} for session=${n}.`)}Oc("wasm bindInputsOutputs"),wl.set(n,[c,d,h,p,A,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let P;p?P=await a._OrtRunWithBinding(c,p.handle,x,k,y):P=await a._OrtRun(c,R,T,m,V,x,k,y),P!==0&&wn("failed to call OrtRun().");let H=[],B=[];Uc("wasm ProcessOutputTensor");for(let j=0;j<x;j++){let J=Number(a.getValue(k+j*o,"*"));if(J===w[j]||S.includes(w[j])){H.push(i[j]),J!==w[j]&&a._OrtReleaseTensor(J)!==0&&wn("Can't release tensor.");continue}let X=a.stackSave(),$=a.stackAlloc(4*o),Y=!1,ne,L=0;try{a._OrtGetTensorData(J,$,$+o,$+2*o,$+3*o)!==0&&wn(`Can't access output tensor data on index ${j}.`);let G=o===4?"i32":"i64",le=Number(a.getValue($,G));L=a.getValue($+o,"*");let oe=a.getValue($+o*2,"*"),Ae=Number(a.getValue($+o*3,G)),ue=[];for(let Te=0;Te<Ae;Te++)ue.push(Number(a.getValue(oe+Te*o,G)));a._OrtFree(oe)!==0&&wn("Can't free memory for tensor dims.");let pe=ue.reduce((Te,ke)=>Te*ke,1);ne=uo(le);let be=p?.outputPreferredLocations[r[j]];if(ne==="string"){if(be==="gpu-buffer"||be==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Te=[];for(let ke=0;ke<pe;ke++){let Oe=a.getValue(L+ke*o,"*"),ft=a.getValue(L+(ke+1)*o,"*"),He=ke===pe-1?void 0:ft-Oe;Te.push(a.UTF8ToString(Oe,He))}H.push([ne,ue,Te,"cpu"])}else if(be==="gpu-buffer"&&pe>0){let Te=a.jsepGetBuffer;if(!Te)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ke=Te(L),Oe=Rc(le,pe);if(Oe===void 0||!OC(ne))throw new Error(`Unsupported data type: ${ne}`);Y=!0,H.push([ne,ue,{gpuBuffer:ke,download:a.jsepCreateDownloader(ke,Oe,ne),dispose:()=>{a._OrtReleaseTensor(J)!==0&&wn("Can't release tensor.")}},"gpu-buffer"])}else if(be==="ml-tensor"&&pe>0){let Te=a.webnnEnsureTensor,ke=a.webnnIsGraphInputOutputTypeSupported;if(!Te||!ke)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Rc(le,pe)===void 0||!$C(ne))throw new Error(`Unsupported data type: ${ne}`);if(!ke(n,ne,!1))throw new Error(`preferredLocation "ml-tensor" for ${ne} output is not supported by current WebNN Context.`);let Oe=await Te(n,L,le,ue,!1);Y=!0,H.push([ne,ue,{mlTensor:Oe,download:a.webnnCreateMLTensorDownloader(L,ne),dispose:()=>{a.webnnReleaseTensorId(L),a._OrtReleaseTensor(J)}},"ml-tensor"])}else if(be==="ml-tensor-cpu-output"&&pe>0){let Te=a.webnnCreateMLTensorDownloader(L,ne)(),ke=H.length;Y=!0,B.push((async()=>{let Oe=[ke,await Te];return a.webnnReleaseTensorId(L),a._OrtReleaseTensor(J),Oe})()),H.push([ne,ue,[],"cpu"])}else{let Te=j0(ne),ke=new Te(pe);new Uint8Array(ke.buffer,ke.byteOffset,ke.byteLength).set(a.HEAPU8.subarray(L,L+ke.byteLength)),H.push([ne,ue,ke,"cpu"])}}finally{a.stackRestore(X),ne==="string"&&L&&a._free(L),Y||a._OrtReleaseTensor(J)}}p&&!A&&(a._OrtClearBoundOutputs(p.handle)!==0&&wn("Can't clear bound outputs."),wl.set(n,[c,d,h,p,A,!1]));for(let[j,J]of await Promise.all(B))H[j][2]=J;return Oc("wasm ProcessOutputTensor"),H}finally{a.webnnOnRunEnd?.(c),a.stackRestore(M),b.forEach(P=>a._OrtReleaseTensor(P)),w.forEach(P=>a._OrtReleaseTensor(P)),C.forEach(P=>a._free(P)),y!==0&&a._OrtReleaseRunOptions(y),_.forEach(P=>a._free(P))}},oI=n=>{let e=kn(),t=wl.get(n);if(!t)throw new Error("invalid session id");let r=t[0],i=e._OrtEndProfiling(r);i===0&&wn("Can't get an profile file name."),e._OrtFree(i)},lI=n=>{let e=[];for(let t of n){let r=t[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),El,es,Ad,Hf,Vf,Jm,L_,Km,_c,bc,DR,Cz,Iz,Sz,Bz,Mz,Tz,Rz,Dz=Ze(()=>{ms(),Ez(),tu(),FC(),El=()=>!!Dn.wasm.proxy&&typeof document<"u",Ad=!1,Hf=!1,Vf=!1,Km=new Map,_c=(n,e)=>{let t=Km.get(n);t?t.push(e):Km.set(n,[e])},bc=()=>{if(Ad||!Hf||Vf||!es)throw new Error("worker not ready")},DR=n=>{switch(n.data.type){case"init-wasm":Ad=!1,n.data.err?(Vf=!0,L_[1](n.data.err)):(Hf=!0,L_[0]()),Jm&&(URL.revokeObjectURL(Jm),Jm=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Km.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},Cz=async()=>{if(!Hf){if(Ad)throw new Error("multiple calls to 'initWasm()' detected.");if(Vf)throw new Error("previous call to 'initWasm()' failed.");if(Ad=!0,El())return new Promise((n,e)=>{es?.terminate(),wP().then(([t,r])=>{try{es=r,es.onerror=s=>e(s),es.onmessage=DR,L_=[n,e];let i={type:"init-wasm",in:Dn};!i.in.wasm.wasmPaths&&(t||gw)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm",import.meta.url).href}),es.postMessage(i),Jm=t}catch(i){e(i)}},e)});try{await zC(Dn.wasm),await nI(Dn),Hf=!0}catch(n){throw Vf=!0,n}finally{Ad=!1}}},Iz=async n=>{if(El())return bc(),new Promise((e,t)=>{_c("init-ep",[e,t]);let r={type:"init-ep",in:{epName:n,env:Dn}};es.postMessage(r)});await rI(Dn,n)},Sz=async n=>El()?(bc(),new Promise((e,t)=>{_c("copy-from",[e,t]);let r={type:"copy-from",in:{buffer:n}};es.postMessage(r,[n.buffer])})):qg(n),Bz=async(n,e)=>{if(El()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return bc(),new Promise((t,r)=>{_c("create",[t,r]);let i={type:"create",in:{model:n,options:{...e}}},s=[];n instanceof Uint8Array&&s.push(n.buffer),es.postMessage(i,s)})}else return iI(n,e)},Mz=async n=>{if(El())return bc(),new Promise((e,t)=>{_c("release",[e,t]);let r={type:"release",in:n};es.postMessage(r)});sI(n)},Tz=async(n,e,t,r,i,s)=>{if(El()){if(t.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return bc(),new Promise((a,o)=>{_c("run",[a,o]);let l=t,c={type:"run",in:{sessionId:n,inputIndices:e,inputs:l,outputIndices:r,options:s}};es.postMessage(c,lI(l))})}else return aI(n,e,t,r,i,s)},Rz=async n=>{if(El())return bc(),new Promise((e,t)=>{_c("end-profiling",[e,t]);let r={type:"end-profiling",in:n};es.postMessage(r)});oI(n)}}),F_,kR,kz,Tte=Ze(()=>{ms(),Dz(),Lt(),LC(),SP(),F_=(n,e)=>{switch(n.location){case"cpu":return[n.type,n.dims,n.data,"cpu"];case"gpu-buffer":return[n.type,n.dims,{gpuBuffer:n.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[n.type,n.dims,{mlTensor:n.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${n.location} for ${e()}`)}},kR=n=>{switch(n[3]){case"cpu":return new Ii(n[0],n[2],n[1]);case"gpu-buffer":{let e=n[0];if(!OC(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:t,download:r,dispose:i}=n[2];return Ii.fromGpuBuffer(t,{dataType:e,dims:n[1],download:r,dispose:i})}case"ml-tensor":{let e=n[0];if(!$C(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:r,dispose:i}=n[2];return Ii.fromMLTensor(t,{dataType:e,dims:n[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},kz=class{async fetchModelAndCopyToWasmMemory(n){return Sz(await GC(n))}async loadModel(n,e){Qa();let t;typeof n=="string"?t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Bz(t,e),Js()}async dispose(){return Mz(this.sessionId)}async run(n,e,t){Qa();let r=[],i=[];Object.entries(n).forEach(h=>{let p=h[0],A=h[1],g=this.inputNames.indexOf(p);if(g===-1)throw new Error(`invalid input '${p}'`);r.push(A),i.push(g)});let s=[],a=[];Object.entries(e).forEach(h=>{let p=h[0],A=h[1],g=this.outputNames.indexOf(p);if(g===-1)throw new Error(`invalid output '${p}'`);s.push(A),a.push(g)});let o=r.map((h,p)=>F_(h,()=>`input "${this.inputNames[i[p]]}"`)),l=s.map((h,p)=>h?F_(h,()=>`output "${this.outputNames[a[p]]}"`):null),c=await Tz(this.sessionId,i,o,a,l,t),d={};for(let h=0;h<c.length;h++)d[this.outputNames[a[h]]]=s[h]??kR(c[h]);return Js(),d}startProfiling(){}endProfiling(){Rz(this.sessionId)}}}),Nz={};mh(Nz,{OnnxruntimeWebAssemblyBackend:()=>Dw,initializeFlags:()=>Rw,wasmBackend:()=>Qz});var Rw,Dw,Qz,Rte=Ze(()=>{ms(),Dz(),Tte(),Rw=()=>{(typeof Dn.wasm.initTimeout!="number"||Dn.wasm.initTimeout<0)&&(Dn.wasm.initTimeout=0);let n=Dn.wasm.simd;if(typeof n!="boolean"&&n!==void 0&&n!=="fixed"&&n!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${n}". Reset it to \`false\` and ignore SIMD feature checking.`),Dn.wasm.simd=!1),typeof Dn.wasm.proxy!="boolean"&&(Dn.wasm.proxy=!1),typeof Dn.wasm.trace!="boolean"&&(Dn.wasm.trace=!1),typeof Dn.wasm.numThreads!="number"||!Number.isInteger(Dn.wasm.numThreads)||Dn.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Dn.wasm.numThreads=1;else{let e=typeof navigator>"u"?mee("node:os").cpus().length:navigator.hardwareConcurrency;Dn.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Dw=class{async init(n){Rw(),await Cz(),await Iz(n)}async createInferenceSessionHandler(n,e){let t=new kz;return await t.loadModel(n,e),t}},Qz=new Dw});ms();ms();ms();var Dte="1.24.3";{let n=(Rte(),Rp(Nz)).wasmBackend;xd("webgpu",n,5),xd("webnn",n,5),xd("cpu",n,10),xd("wasm",n,10)}Object.defineProperty(Dn.versions,"web",{value:Dte,enumerable:!0});class kte{constructor(e,t={}){this.config=e,this.options=t,this.policyModule=null,this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null,this.context=null,this.policyJointNames=(e.policy_joint_names??[]).slice(),this.numActions=this.policyJointNames.length,this.lastActions=new Float32Array(this.numActions),this.defaultJointPos=this.normalizeArray(e.default_joint_pos??[],this.numActions,0)}async init(e){this.context=e,this.policyModule=await this.buildPolicyModule(e),this.buildObservationGroups()}reset(e){this.lastActions.fill(0),this.policyModule?.reset();for(const t of Object.values(this.obsGroups))for(const r of t)r.reset&&r.reset(e);if(e){for(const[t,r]of Object.entries(this.historyConfig))if(r.steps>1){const i=this.buildFrame(this.obsGroups[t]??[],e),s=this.historyBuffers[t];for(let a=0;a<r.steps;a++)s.set(i,a*i.length)}}}update(e){this.policyModule?.update();for(const t of Object.values(this.obsGroups))for(const r of t)r.update&&r.update(e)}collectObservationsByKey(e){this.update(e);const t={};for(const[r,i]of Object.entries(this.obsGroups)){const s=this.historyConfig[r];if(s&&s.steps>1){const a=this.buildFrame(i,e),o=this.historyBuffers[r];for(let l=o.length-1;l>=a.length;l--)o[l]=o[l-a.length];o.set(a,0),t[r]=new Float32Array(o)}else t[r]=this.buildFrame(i,e)}return t}collectObservations(e){const t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];const r=Object.keys(t)[0];return r?t[r]:new Float32Array(0)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];const e=Object.keys(this.obsSizes)[0];return e?this.obsSizes[e]:0}getObservationLayout(){if(this.defaultObsKey&&this.obsLayouts[this.defaultObsKey])return this.obsLayouts[this.defaultObsKey].map(t=>({...t}));const e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(t=>({...t})):[]}getPolicyModuleContext(){return this.policyModule?.getContext()??{}}getPolicyModule(){return this.policyModule}getContext(){return this.context}getPolicyJointNames(){return this.policyJointNames.slice()}getNumActions(){return this.numActions}getDefaultJointPos(){return new Float32Array(this.defaultJointPos)}getLastActions(){return new Float32Array(this.lastActions)}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){const t=this.options.policyModules??{},r=this.config.policy_module,i=r?t[r]:t.default;if(r&&!i)throw new Error(`Unknown policy module: ${r}`);if(!i)return null;const s=new i(this.config);return await s.init(e),s}buildObservationGroups(){const e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;for(const[r,i]of Object.entries(t)){if(Array.isArray(i)){const s=i.map(a=>{const o=e[a.name];if(!o)throw new Error(`Unknown observation type: ${a.name}`);return new o(this,a)});this.registerGroup(r,s,i);continue}if(i&&typeof i=="object"){const s=i;if(Array.isArray(s.components)){const a=s.components.map(c=>{const d=e[c.name];if(!d)throw new Error(`Unknown observation type: ${c.name}`);const h={...c,history_steps:1};return new d(this,h)}),o=Math.max(1,Math.floor(s.history_steps??1)),l=!!s.interleaved;this.registerGroup(r,a,s.components,{steps:o,interleaved:l})}}}this.obsGroups.policy?this.defaultObsKey="policy":this.obsGroups.observation?this.defaultObsKey="observation":this.obsGroups.obs_history?this.defaultObsKey="obs_history":this.defaultObsKey=Object.keys(this.obsGroups)[0]??null}registerGroup(e,t,r,i){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((a,o)=>({name:r[o]?.name??`obs_${o}`,size:a.size}));const s=this.obsLayouts[e].reduce((a,o)=>a+o.size,0);i&&i.steps>1?(this.historyConfig[e]=i,this.historyBuffers[e]=new Float32Array(s*i.steps),this.obsSizes[e]=s*i.steps):this.obsSizes[e]=s}buildFrame(e,t){const r=e.reduce((a,o)=>a+o.size,0),i=new Float32Array(r);let s=0;for(const a of e){const o=a.compute(t),l=o instanceof Float32Array?o:Float32Array.from(o);if(l.length!==a.size)throw new Error(`Observation size mismatch: expected ${a.size}, got ${l.length}`);i.set(l,s),s+=l.length}return i}normalizeArray(e,t,r){const i=new Float32Array(t);for(let s=0;s<t;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}}Dn.wasm.proxy=!1;Dn.wasm.numThreads=1;class Nte{constructor(e){if(!e?.path)throw new Error("OnnxModule requires a path.");this.config=e,this.session=null;const t=e.meta?.in_keys??["policy"],r=e.meta?.out_keys??["action"];this.inKeys=t.map(i=>Array.isArray(i)?i.join(","):i),this.outKeys=r.map(i=>Array.isArray(i)?i.join(","):i),this.isRecurrent=this.inKeys.includes("adapt_hx")}async init(){const e=await fetch(this.config.path);if(!e.ok)throw new Error(`Failed to fetch ONNX model: ${e.status}`);const t=await e.arrayBuffer();this.session=await PC.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"})}initInput(){return this.isRecurrent?{is_init:new Ii("bool",[!0],[1]),adapt_hx:new Ii("float32",new Float32Array(128),[1,128])}:{}}async runInference(e){if(!this.session)throw new Error("OnnxModule not initialized.");const t={};for(let a=0;a<this.inKeys.length;a++){const o=this.inKeys[a],l=this.session.inputNames[a];if(!l||!e[o])throw new Error(`Missing ONNX input for key: ${o}`);t[l]=e[o]}const r=await this.session.run(t),i={};for(let a=0;a<this.outKeys.length;a++){const o=this.outKeys[a],l=this.session.outputNames[a];l&&r[l]&&(i[o]=r[l])}const s={};return this.isRecurrent&&i["next,adapt_hx"]&&(s.is_init=new Ii("bool",[!1],[1]),s.adapt_hx=i["next,adapt_hx"]),[i,s]}}class Qte{constructor(e,t,r,i){this.mujoco=e,this.mjModel=t,this.mjData=r;const s=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(const a of i){const o=s.indexOf(a);if(o<0)throw new Error(`Joint "${a}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[o]),this.qvelAdr.push(t.jnt_dofadr[o]),this.jointIndices.push(o)}this.numActions=i.length,this.ctrlAdr=this.buildCtrlAdr()}build(){const e=this.mjData.qpos,t=this.mjData.qvel,r=new Float32Array(this.numActions),i=new Float32Array(this.numActions);for(let c=0;c<this.numActions;c++)r[c]=e[this.qposAdr[c]],i[c]=t[this.qvelAdr[c]];const s=new Float32Array([e[0],e[1],e[2]]),a=new Float32Array([e[3],e[4],e[5],e[6]]),o=new Float32Array([t[0],t[1],t[2]]),l=new Float32Array([t[3],t[4],t[5]]);return{jointPos:r,jointVel:i,rootPos:s,rootQuat:a,rootLinVel:o,rootAngVel:l}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}getControlMappingFor(e,t){if(!this.ctrlAdr)return null;const r=e.map(c=>new RegExp(`^(?:${c})$`)),i=c=>r.some(d=>d.test(c)),s=[],a=[],o=[],l=[];for(let c=0;c<t.length;c++)i(t[c])&&(s.push(this.ctrlAdr[c]),a.push(this.qposAdr[c]),o.push(this.qvelAdr[c]),l.push(c));return s.length===0?null:{ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l}}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;const e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let i=0;i<this.mjModel.nu;i++){const s=this.mjModel.actuator_trntype[i];e===void 0||s===e?t.push(this.mjModel.actuator_trnid[2*i]):t.push(-1)}const r=[];for(const i of this.jointIndices){const s=t.findIndex(a=>a===i);if(s<0)return null;r.push(s)}return r}getJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;let l=r.decode(t.subarray(a,o));!l&&s===0&&(l="floating_base_joint"),i.push(l)}return i}}class Pz{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class Pte{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName="default",this.currentDone=!0}reset(e){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName="default"}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}}class Lte extends Pz{constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.tracking=new Pte(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class Fte{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName="default",this.currentDone=!0}reset(e){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName="default"}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}}class zte extends Pz{constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.locomotion=new Fte(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class Ute{constructor(e,t){this.terms=[];for(const r of e){const i=t[r.name];if(!i){console.warn(`[EventManager] Unknown event type: ${r.name}`);continue}this.terms.push(new i(r))}}onReset(e){for(const t of this.terms)t.onReset(e)}get size(){return this.terms.length}}class Lz{constructor(e){this.config=e}}const Ote={};class Fz extends Lz{constructor(e){super(e),this.poseRange=e.params?.pose_range??{}}onReset(e){const{mjModel:t,mjData:r}=e;if(!t||!r)return;const i=this._findFreeJoint(t);if(i===-1)return;const s=t.jnt_qposadr[i],a=l=>{const c=this.poseRange[l];return c?c[0]+Math.random()*(c[1]-c[0]):0};r.qpos[s+0]+=a("x"),r.qpos[s+1]+=a("y"),r.qpos[s+2]+=a("z");const o=a("yaw");o!==0&&this._applyYawRotation(r.qpos,s+3,o)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}class $te extends Lz{constructor(e){super(e),this.patchName=e.params?.patch_name??"spawn",this.fallback=new Fz(e)}onReset(e){const{mjModel:t,mjData:r,terrainData:i}=e;if(!t||!r)return;const s=i?.flat_patches?.[this.patchName];if(!s||s.length===0){this.fallback.onReset(e);return}const a=this._findFreeJoint(t);if(a===-1)return;const o=t.jnt_qposadr[a],l=s[Math.floor(Math.random()*s.length)],c=r.qpos[o+2];r.qpos[o+0]=l[0],r.qpos[o+1]=l[1],r.qpos[o+2]=l[2]+c;const h=(this.config.params?.pose_range??{}).yaw??[-Math.PI,Math.PI],p=h[0]+Math.random()*(h[1]-h[0]);this._applyYawRotation(r.qpos,o+3,p)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}const Gte={ResetRootStateUniform:Fz,ResetRootStateFromFlatPatches:$te},Hte={...Gte,...Ote};class zz extends Error{constructor(){super("This scene cannot be loaded because it exceeds the browser's WebAssembly 2 GB memory limit. Try closing other browser tabs or reloading the page to free memory."),this.name="WasmMemoryLimitError"}}function NR(n){const e=n instanceof Error?n.message:String(n);return e.includes("MjModel loading returned null")||e.includes("Could not allocate memory")||e.includes("memory allocation failed")||e.includes("bad_alloc")}class Vte{constructor(e,t,r={}){this.render=()=>{if(Zr().updateDebugVisuals(),this.mjData&&BZ(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){S3(this.camera,this.lights);for(const[o,l]of this.lastSimState.bodies){const c=this.bodies[o];c&&(c.position.copy(l.position),c.quaternion.copy(l.quaternion))}I3(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&K7({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{const{width:o,height:l}=this.getSize();this.camera.aspect=o/l,this.camera.updateProjectionMatrix(),this.renderer.setSize(o,l)},this.mujoco=e,this.container=t,this.baseUrl=r.baseUrl||"/";const i="/working";try{this.mujoco.FS.mkdir(i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&console.warn("Failed to create /working directory:",o)}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:"."},i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&o.code!=="EBUSY"&&console.warn("Failed to mount MEMFS at /working:",o)}const{width:s,height:a}=this.getSize();this.scene=new VV,this.scene.name="scene",this.camera=new Fr(45,s/a,.001,1e3),this.camera.name="PerspectiveCamera",this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new C7({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(s,a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=bN,this.renderer.outputColorSpace=ri,this.renderer.toneMapping=wN,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported("immersive-vr").then(o=>{o&&(this.vrButton=_C.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new S7(this.camera,this.renderer.domElement),this.controls.target.set(0,.2,0),this.controls.panSpeed=2,this.controls.zoomSpeed=1,this.controls.enableDamping=!0,this.controls.dampingFactor=.1,this.controls.screenSpacePanning=!0,this.controls.update(),this.renderer.setAnimationLoop(this.render),window.addEventListener("resize",this.onWindowResize),"ResizeObserver"in window?(this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),this.resizeObserver.observe(this.container)):this.resizeObserver=null,this.lastSimState={bodies:new Map,tendons:Z7()},this.dynamicBodyIds=null,this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.loopPromise=null,this.running=!1,this.timestep=.001,this.decimation=1,this.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.terminationManager=null,this.eventManager=null,this.terrainData=null,this.splatMesh=null,this.colliderMesh=null,this.cameraState={trackBodyId:null,prevBodyPos:null},this.sceneCacheManager=mw.getInstance(this.mujoco),this.resourceTracker=new MZ,this.memoryMonitor=new TZ}async loadEnvironment(e,t=null,r=null,i=null,s=null,a=null){this.terrainData=a,s&&s.length>0?(this.eventManager=new Ute(s,Hte),console.log(`[EventManager] ${this.eventManager.size} reset event(s) loaded`)):this.eventManager=null,await this.stop(),this.splatMesh&&(V3(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(K3(this.colliderMesh,this.scene),this.colliderMesh=null);const o=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const l=performance.now()-o;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:l})}else this.memoryMonitor.logCacheOperation("miss",e),await this.sceneCacheManager.prepareForNewScene(),this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.resourceTracker.startTracking(this.mujoco),await lX(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);r&&(this.splatMesh=H3(r,this.scene),r.colliderUrl&&(this.colliderMesh=await J3(this.resolveAssetUrl(r.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.applyViewerConfig(i),this.running=!0,this.startLoop()}initializeCommands(){const e=Zr();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e,t){Zr().initialize(e,t),console.log("[mjswanRuntime] Commands loaded from policy config:",Object.keys(e))}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){const e=this.policyStateBuilder.build();this.policyRunner.reset(e)}console.log("[mjswanRuntime] Simulation reset")}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{const t=this.scene.getObjectByName("MuJoCo Root");t&&this.scene.remove(t);const r={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await aX(this.mujoco,e,r),!this.mjModel||!this.mjData)throw new Error("Failed to load MuJoCo model.");this.mujocoRoot=this.scene.getObjectByName("MuJoCo Root"),this.mujoco.mj_forward(this.mjModel,this.mjData),I3(this.mujoco,this.mjData,this.lights),S3(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new Z3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds}),this.loadingScene=null})(),await this.loadingScene}async loadSceneWithOomRetry(e){try{await this.loadScene(e)}catch(t){if(!NR(t))throw t;console.warn("[mjswanRuntime] OOM — clearing cache and retrying..."),this.loadingScene=null,await this.sceneCacheManager.clear();try{await this.loadScene(e)}catch(r){throw this.loadingScene=null,NR(r)?new zz:r}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&(V3(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(K3(this.colliderMesh,this.scene),this.colliderMesh=null),e&&(this.splatMesh=H3(e,this.scene),e.colliderUrl&&(this.colliderMesh=await J3(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&qQ(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}async stop(){this.running=!1;const e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){const e=performance.now(),t=this.timestep*this.decimation;if(this.mjModel&&this.mjData){if(Zr().update(t),this.mujoco.mj_forward(this.mjModel,this.mjData),this.policyRunner&&this.policyStateBuilder){const s=this.policyStateBuilder.build(),a=this.policyRunner.collectObservationsByKey(s);if(await this.runOnnxInference(a),this.policyDebugCounter%60===0){const o="policy"in a?"policy":"observation"in a?"observation":Object.keys(a)[0],l=o?a[o]:null,c=l?Array.from(l.slice(0,8)):[];console.log("[PolicyRunner] obs",{key:o,size:l?l.length:0,sample:c})}this.policyDebugCounter+=1}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){const s=this.policyStateBuilder.build();if(this.terminationManager.evaluate(s).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){const o=this.policyStateBuilder.build();this.policyRunner.reset(o)}}}const r=(performance.now()-e)/1e3,i=Math.max(0,t-r);i>0&&await new Promise(s=>setTimeout(s,i*1e3))}this.loopPromise=null}async loadPolicyConfig(e){const t=this.policyConfigPath;this.policyConfigPath=e,this.policyRunner=null,this.policyStateBuilder=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.terminationManager=null;const r=Zr();if(r.clear(),r.setResetCallback(()=>this.resetSimulation()),!!e){if(!this.mjModel||!this.mjData){console.warn("Policy config loaded before MuJoCo model is ready.");return}e!==t&&this.resetSimulationState();try{const{config:i}=await this.fetchPolicyConfig(e);if(this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),i.commands&&typeof i.commands=="object"&&(this.initializeCommandsFromConfig(i.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),Zr().resetTerms(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()),!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new kte(i,{policyModules:{tracking:Lte,locomotion:zte},observations:see});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),this.policyRunner=s,this.policyStateBuilder=new Qte(this.mujoco,this.mjModel,this.mjData,s.getPolicyJointNames());const a=this.policyStateBuilder.build();if(this.policyRunner.reset(a),this.policyControl=this.buildPolicyControl(i,s,this.policyStateBuilder),i.terminations&&Object.keys(i.terminations).length>0&&(this.terminationManager=new aee(i.terminations,hee),console.log(`[TerminationManager] ${this.terminationManager.size} termination term(s) loaded`)),i.onnx?.path){const o=this.resolvePolicyAssetPath(e,i.onnx.path),l=this.resolveAssetUrl(o),c={...i.onnx,path:l},d=new Nte(c);await d.init(),this.onnxModule=d,this.onnxInputDict=d.initInput()}console.log("[PolicyRunner] config loaded",{obsSize:s.getObservationSize(),obsLayout:s.getObservationLayout(),pdEnabled:this.policyControl!==null})}catch(i){console.warn("Failed to load policy config:",i)}}}async fetchPolicyConfig(e){const t=this.resolveAssetUrl(e),r=await fetch(t,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch policy config: ${r.status}`);return{config:await r.json(),resolvedUrl:t}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;const t=(this.baseUrl||"/").replace(/\/+$/,"/"),r=new URL(t,window.location.origin+"/").toString();return new URL(e.replace(/^\/+/,""),r).toString()}resolvePolicyAssetPath(e,t){const r=e.replace(/\\/g,"/"),i=r.lastIndexOf("/");return i>=0?`${r.slice(0,i+1)}${t}`.replace(/\/+/g,"/"):t}buildPolicyControl(e,t,r){const i=t.getPolicyJointNames(),s=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(c,d,h,p,A,g,m,x)=>{const y=h.qposAdr.length,_=h.actionIndices.map(B=>i[B]),b=this.normalizeControlArray(p,y,1,_),w=this.normalizeControlArray(A,y,0,_),C=x?t.getDefaultJointPos():new Float32Array(i.length),S=new Float32Array(y);for(let B=0;B<y;B++)S[B]=C[h.actionIndices[B]];const M=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(i.length),T=new Float32Array(y);for(let B=0;B<y;B++)T[B]=M[h.actionIndices[B]]??0;const R=this.normalizeControlArray(g,y,0,_),k=this.normalizeControlArray(m,y,0,_),V=h.ctrlAdr.map(B=>B<0||!this.mjModel?!1:this.mjModel.actuator_biastype[B]===s),P=V.some(Boolean),H=V.some(B=>!B);return P&&H&&console.warn(`[PolicyRunner] Action term "${c}": mixed actuator types detected.`),console.log(`[PolicyRunner] Action term "${c}" (${d}): ${y} joint(s), mode: ${P?"position (ctrl=target_pos)":"motor (ctrl=torque, external PD)"}`),{controlType:d,ctrlAdr:h.ctrlAdr,qposAdr:h.qposAdr,qvelAdr:h.qvelAdr,actionIndices:h.actionIndices,actionScale:b,actionOffset:w,defaultJointPos:S,encoderBias:T,positionActuator:V,kp:R,kd:k}},o=e.actions;if(!o||Object.keys(o).length===0){const c=e.control_type??"joint_position";if(c!=="joint_position"&&c!=="torque")return console.warn(`[PolicyRunner] Unsupported control_type: ${c}`),null;const d=r.getControlMapping();if(!d)return console.warn("[PolicyRunner] Failed to build control mapping."),null;const h={...d,actionIndices:Array.from({length:d.qposAdr.length},(p,A)=>A)};return[a("legacy",c,h,e.action_scale,void 0,e.stiffness,e.damping,!0)]}const l=[];for(const[c,d]of Object.entries(o)){const h=d.type??"joint_position";if(h!=="joint_position"&&h!=="torque"){console.warn(`[PolicyRunner] Action term "${c}": unsupported type "${h}", skipping.`);continue}const p=d.actuator_names??[".*"],A=p.length===1&&p[0]===".*";let g;if(A){const x=r.getControlMapping();if(!x){console.warn(`[PolicyRunner] Action term "${c}": failed to build control mapping, skipping.`);continue}g={...x,actionIndices:Array.from({length:x.qposAdr.length},(y,_)=>_)}}else if(g=r.getControlMappingFor(p,i),!g){console.warn(`[PolicyRunner] Action term "${c}": no joints matched patterns [${p.join(", ")}], skipping.`);continue}const m=d.use_default_offset!==void 0?d.use_default_offset:h==="joint_position";l.push(a(c,h,g,d.scale,d.offset,d.stiffness,d.damping,m))}return l.length===0?(console.warn("[PolicyRunner] No valid action terms found in config.actions."),null):l}normalizeControlArray(e,t,r,i){const s=new Float32Array(t);if(s.fill(r),typeof e=="number")return s.fill(e),s;if(Array.isArray(e)){for(let a=0;a<t;a++)s[a]=typeof e[a]=="number"?e[a]:r;return s}if(e!==null&&typeof e=="object"&&i){for(const[a,o]of Object.entries(e)){const l=i.indexOf(a);l>=0&&l<t?s[l]=o:console.warn(`[PolicyRunner] Joint name "${a}" not found in policy_joint_names; skipping.`)}return s}return s}resetSimulationState(){!this.mjModel||!this.mjData||(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),Zr().resetTerms(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.lastSimState.bodies.clear(),this.updateCachedState())}executeSimulationSteps(){if(!(!this.mjModel||!this.mjData)){this.applyDragForces();for(let e=0;e<this.decimation;e++)this.applyPolicyControl(),this.mujoco.mj_step(this.mjModel,this.mjData)}}applyPolicyControl(){if(!this.policyControl||!this.mjData)return;const e=this.mjData.ctrl;e.fill(0);const t=this.policyRunner?.getLastActions()??new Float32Array(0);for(const r of this.policyControl){const{controlType:i,ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l,actionScale:c,actionOffset:d,defaultJointPos:h,encoderBias:p,positionActuator:A,kp:g,kd:m}=r,x=s.length;if(i==="joint_position")for(let y=0;y<x;y++){const _=s[y];if(_<0)continue;const b=t[l[y]]??0,w=h[y]+d[y]+c[y]*b-p[y];if(A[y])e[_]=w;else{const C=this.mjData.qpos[a[y]],S=this.mjData.qvel[o[y]];e[_]=g[y]*(w-C)+m[y]*(0-S)}}else if(i==="torque")for(let y=0;y<x;y++){const _=s[y];_>=0&&(e[_]=c[y]*(t[l[y]]??0))}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||(this.onnxInputDict=this.onnxModule.initInput());const t={...this.onnxInputDict};for(const[d,h]of Object.entries(e))t[d]=new Ii("float32",h,[1,h.length]);for(const d of this.onnxModule.inKeys)if(!t[d]){console.warn("[PolicyRunner] Missing ONNX input:",{key:d,available:Object.keys(t)});return}const[r,i]=await this.onnxModule.runInference(t);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i});const s=this.onnxModule.outKeys[0],a=r.action??(s?r[s]:null)??r.policy??null;if(!a)return;const o=a.data,l=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&l.length!==c){console.warn("[PolicyRunner] Action size mismatch:",{expected:c,got:l.length});return}this.policyRunner.setLastActions(l)}catch(t){console.warn("[PolicyRunner] ONNX inference failed:",t)}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let p=0;p<this.mjData.xfrc_applied.length;p++)this.mjData.xfrc_applied[p]=0;const e=this.dragStateManager.physicsObject;if(!e||!("bodyID"in e)||typeof e.bodyID!="number"||e.bodyID<=0)return;const t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(Bd(this.mjData.xpos,p,this.bodies[p].position),fg(this.mjData.xquat,p,this.bodies[p].quaternion),this.bodies[p].updateWorldMatrix(!0,!1));this.dragStateManager.update();const r=this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale),i=C3(r),s=this.dragStateManager.worldHit.clone(),a=C3(s),o=new he(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),l=new he(a.x-o.x,a.y-o.y,a.z-o.z),c=new he(i.x,i.y,i.z),d=new he().crossVectors(l,c),h=t*6;this.mjData.xfrc_applied[h+0]=i.x,this.mjData.xfrc_applied[h+1]=i.y,this.mjData.xfrc_applied[h+2]=i.z,this.mjData.xfrc_applied[h+3]=d.x,this.mjData.xfrc_applied[h+4]=d.y,this.mjData.xfrc_applied[h+5]=d.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++)if(!(e&&!e.has(t))&&this.bodies[t]){this.lastSimState.bodies.has(t)||this.lastSimState.bodies.set(t,{position:new he,quaternion:new Cn});const r=this.lastSimState.bodies.get(t);Bd(this.mjData.xpos,t,r.position),fg(this.mjData.xquat,t,r.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&J7(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=SZ(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){const t=new Set;for(let r=1;r<e.nbody;r++){let i=r;for(;i>0;){if(e.body_jntnum[i]>0){t.add(r);break}i=e.body_parentid[i]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;const r=this.bodies[t];r&&(Bd(this.mjData.xpos,t,r.position),fg(this.mjData.xquat,t,r.quaternion))}}dispose(){this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.dragStateManager&&(this.dragStateManager.dispose(),this.dragStateManager=null),this.mjData=null,this.mjModel=null,window.removeEventListener("resize",this.onWindowResize),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.controls.dispose(),this.renderer.setAnimationLoop(null),this.renderer.dispose(),this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.vrButton?.parentElement&&(this.vrButton.parentElement.removeChild(this.vrButton),this.vrButton=null),this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.lastSimState.bodies.clear()}disposeThreeJSResources(){if(this.scene)for(this.scene.traverse(e=>{"geometry"in e&&e.geometry&&e.geometry.dispose(),"material"in e&&e.material&&(Array.isArray(e.material)?e.material.forEach(t=>this.disposeMaterial(t)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),e.dispose()}getSize(){const e=this.container.clientWidth||window.innerWidth,t=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,t)}}async restoreFromCache(e){const t=this.sceneCacheManager.get(e);if(!t)throw new Error(`Scene ${e} not found in cache`);const r=this.scene.getObjectByName("MuJoCo Root");r&&this.scene.remove(r),this.mjModel=t.mjModel,this.mjData=t.mjData,this.bodies=t.bodies,this.lights=t.lights,this.mujocoRoot=t.mujocoRoot,this.scene.add(this.mujocoRoot),this.scene.background=t.skybox,this.mujoco.mj_forward(this.mjModel,this.mjData),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new Z3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds})}async captureAndCacheResources(e){const t=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot){console.warn("[SceneCache] Cannot cache scene: missing resources");return}const r=this.resourceTracker.estimateSceneMemory({mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,meshes:{},mujocoRoot:this.mujocoRoot});await this.sceneCacheManager.set(e,{scenePath:e,lastAccessed:Date.now(),loadedAt:Date.now(),mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,lights:this.lights,meshes:{},mujocoRoot:this.mujocoRoot,skybox:this.scene.background instanceof uh?this.scene.background:null,fsFiles:t,estimatedMemoryBytes:r});const i=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation("load",e,{memoryMB:r/1048576,totalScenes:i.totalScenes,totalMemoryMB:i.totalMemoryBytes/1048576})}}const Zm="mjswan_oom_reload_scene",jte=({scenePath:n,baseUrl:e,policyConfigPath:t,splatConfig:r,cameraConfig:i,eventsConfig:s,terrainData:a,onStatusChange:o,onError:l,onReady:c,onRuntimeReady:d})=>{const h=U.useRef(null),p=U.useRef(null),A=U.useRef(null),g=U.useRef(r);return g.current=r,U.useEffect(()=>{let m=!1;const x=_=>{o?.(_)};return(async()=>{if(x("Loading MuJoCo..."),!A.current){const w=await gH(()=>import("./mujoco-lvuvscK6.js"),[]);A.current=await w.default()}if(m)return;const _=h.current;if(!_)throw new Error("Failed to find viewer container.");const b=A.current;if(!b)throw new Error("MuJoCo not loaded.");p.current||(p.current=new Vte(b,_,{baseUrl:e}),d?.(p.current)),x("Loading scene assets..."),await p.current.loadEnvironment(n,t??null,g.current??null,i??null,s??null,a??null),!m&&(sessionStorage.removeItem(Zm),x("Running simulation"),c?.())})().catch(_=>{if(!m){if(_ instanceof zz){if(sessionStorage.getItem(Zm)!==n){console.warn("[MjswanViewer] OOM — reloading page to free memory..."),sessionStorage.setItem(Zm,n),window.location.reload();return}sessionStorage.removeItem(Zm)}console.error("Failed to initialize MuJoCo viewer:",_),l?.(_ instanceof Error?_:new Error(String(_))),x("Failed to load scene")}}),()=>{m=!0,p.current?.dispose(),p.current=null}},[n,e,t,i,s,a,o,l,c]),W.jsx("div",{ref:h,className:"viewer"})};var Wte={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}};const cI=(n,e,t,r)=>{const i=U.forwardRef(({color:s="currentColor",size:a=24,stroke:o=2,title:l,className:c,children:d,...h},p)=>U.createElement("svg",{ref:p,...Wte[n],width:a,height:a,className:["tabler-icon",`tabler-icon-${e}`,c].join(" "),strokeWidth:o,stroke:s,...h},[l&&U.createElement("title",{key:"svg-title"},l),...r.map(([A,g])=>U.createElement(A,g)),...Array.isArray(d)?d:[d]]));return i.displayName=`${t}`,i};const qte=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],Uz=cI("outline","chevron-down","ChevronDown",qte);const Yte=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],Xte=cI("outline","chevron-up","ChevronUp",Yte);const Jte=[["path",{d:"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4",key:"svg-0"}],["path",{d:"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4",key:"svg-1"}]],Kte=cI("outline","refresh","Refresh",Jte),QR="0.4.3",PR=[{login:"ttktjmt",html_url:"https://github.com/ttktjmt"},{login:"claude",html_url:"https://github.com/claude"},{login:"julien-blanchon",html_url:"https://github.com/julien-blanchon"},{login:"unmoyai",html_url:"https://github.com/unmoyai"},{login:"brentyi",html_url:"https://github.com/brentyi"},{login:"Axellwppr",html_url:"https://github.com/Axellwppr"},{login:"CharlieLeee",html_url:"https://github.com/CharlieLeee"}],Zte={move:"touchmove",end:"touchend"},ene={move:"mousemove",end:"mouseup"};function tne(n){return n.type==="touchmove"}function nne(n){return n.type==="mousemove"}const Up=On.createContext(null);function ho({children:n,width:e}){const t=On.useRef(null),[r,{toggle:i}]=Kg(!0),[s,a]=On.useState(800),o=On.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),l=On.useRef({}),c=(A,g,m)=>Math.abs(A+g/2)<Math.abs(A-m+g/2)?A:A-m,d=15;function h(A,g){const m=t.current;if(m===null)return[A,g];const x=m.parentElement;if(x===null)return[A,g];let y=A,_=g;return y=Math.min(y,x.clientWidth-m.clientWidth-d),y=Math.max(y,d),_=Math.min(_,x.clientHeight-m.clientHeight-d),_=Math.max(_,d),m.style.top=`${_.toString()}px`,m.style.left=`${y.toString()}px`,[c(y,m.clientWidth,x.clientWidth),c(_,m.clientHeight,x.clientHeight)]}On.useEffect(()=>{const A=t.current;if(A===null)return;const g=A.parentElement;if(g===null)return;const m=new ResizeObserver(()=>{l.current.x===void 0&&(l.current.x=c(A.offsetLeft,A.clientWidth,g.clientWidth)),l.current.y===void 0&&(l.current.y=c(A.offsetTop,A.clientHeight,g.clientHeight));const x=g.clientHeight-d*2;s!==x&&a(x);let y=l.current.x,_=l.current.y;for(;y<0;)y+=g.clientWidth;for(;_<0;)_+=g.clientHeight;h(y,_)});return m.observe(A),m.observe(g),()=>{m.disconnect()}});const p=A=>{const g=o.current,m=t.current;if(!m)return;A.type=="touchstart"?(A=A,g.startClientX=A.touches[0].clientX,g.startClientY=A.touches[0].clientY):(A=A,g.startClientX=A.clientX,g.startClientY=A.clientY),g.startPosX=m.offsetLeft,g.startPosY=m.offsetTop;const x=A.type=="touchstart"?Zte:ene;function y(_){let b=0,w=0;if(tne(_)?(_=_,b=_.touches[0].clientX-g.startClientX,w=_.touches[0].clientY-g.startClientY):nne(_)&&(_=_,b=_.clientX-g.startClientX,w=_.clientY-g.startClientY),Math.abs(b)<=3&&Math.abs(w)<=3)return;g.dragging=!0;const C=g.startPosX+b,S=g.startPosY+w;[l.current.x,l.current.y]=h(C,S)}window.addEventListener(x.move,y),window.addEventListener(x.end,()=>{A.type=="touchstart"&&(g.dragging=!1),window.removeEventListener(x.move,y)},{once:!0})};return W.jsx(Up.Provider,{value:{wrapperRef:t,expanded:r,width:e,maxHeight:s,toggleExpanded:i,dragHandler:p,dragInfo:o},children:W.jsx(Gc,{radius:"xs",shadow:"0.1em 0 1em 0 rgba(0,0,0,0.1)",style:{boxSizing:"border-box",width:e,zIndex:10,position:"absolute",top:"1em",right:"1em",margin:0,"& .expandIcon":{transform:"rotate(0)"},overflow:"hidden"},ref:t,children:n})})}ho.Handle=function({children:e}){const t=On.useContext(Up);return W.jsx(W.Fragment,{children:W.jsx(nt,{style:{borderRadius:"0.2em 0.2em 0 0",lineHeight:"1.5em",cursor:"pointer",position:"relative",fontWeight:400,userSelect:"none",display:"flex",alignItems:"center",padding:"0 0.75em",height:"2.75em"},onClick:()=>{const r=t.dragInfo.current;if(r.dragging){r.dragging=!1;return}t.toggleExpanded()},onTouchStart:r=>{t.dragHandler(r)},onMouseDown:r=>{t.dragHandler(r)},children:e})})};ho.Contents=function({children:e}){const t=On.useContext(Up);return W.jsxs(bg,{in:t.expanded,children:[W.jsx(wd,{mx:"xs"}),W.jsx(Kc.Autosize,{mah:t.maxHeight,children:W.jsx(nt,{style:{width:t.width},children:e})})]})};ho.HideWhenCollapsed=function({children:e}){return On.useContext(Up)?.expanded??!0?e:null};ho.HideWhenExpanded=function({children:e}){return On.useContext(Up)?.expanded??!0?null:e};function z_({id:n,label:e,children:t}){return W.jsx(nt,{pb:"0.5em",px:"xs",children:W.jsxs(pE,{align:"center",children:[W.jsx(nt,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:W.jsx("label",{htmlFor:n,children:e})})}),W.jsx(nt,{style:{flexGrow:1},children:t})]})})}function Oz({label:n,expandByDefault:e=!0,children:t}){const[r,{toggle:i}]=Kg(e),s=r?Xte:Uz;return W.jsxs(Gc,{withBorder:!0,style:{borderWidth:"1px",position:"relative",marginLeft:"var(--mantine-spacing-xs)",marginRight:"var(--mantine-spacing-xs)",marginTop:"var(--mantine-spacing-xs)",marginBottom:"var(--mantine-spacing-xs)",paddingBottom:"calc(var(--mantine-spacing-xs) - 0.5em)"},children:[W.jsxs(Gc,{onClick:i,style:{fontSize:"0.875em",position:"absolute",padding:"0 0.375em",top:0,left:"0.375em",transform:"translateY(-50%)",userSelect:"none",fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center"},children:[n,W.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),W.jsx(bg,{in:r,children:W.jsx(nt,{pt:"1em",children:t})}),W.jsx(bg,{in:!r,children:W.jsx(nt,{p:"xs"})})]})}const $z={fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"4.5em",flexShrink:0},rne={root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}},ine={flex:1,minWidth:0,height:"1.75em",fontSize:"0.8em",fontFamily:"inherit",border:"1px solid var(--mantine-color-default-border)",borderRadius:"var(--mantine-radius-sm)",background:"var(--mantine-color-default)",color:"var(--mantine-color-text)",textAlign:"right",padding:"0 0.4em",outline:"none",cursor:"ns-resize",touchAction:"none"};function U_({axis:n,value:e,min:t=-1/0,max:r=1/0,step:i,onChange:s}){const a=U.useRef(null),o=U.useRef(null);U.useEffect(()=>{const g=a.current;g&&document.activeElement!==g&&(g.value=e.toFixed(2))},[e]);const l=g=>Math.max(t,Math.min(r,parseFloat((Math.round(g/i)*i).toFixed(10)))),c=g=>{g.preventDefault(),g.currentTarget.setPointerCapture(g.pointerId),o.current={startY:g.clientY,startValue:e,moved:!1}},d=g=>{if(!o.current||!(g.buttons&1))return;const m=o.current.startY-g.clientY;if(Math.abs(m)>3&&(o.current.moved=!0),!o.current.moved)return;const x=l(o.current.startValue+m*i);s(x),a.current&&(a.current.value=x.toFixed(2))},h=()=>{if(o.current&&!o.current.moved){const g=a.current;g&&(g.focus(),g.select())}o.current=null},p=g=>{const m=parseFloat(g.target.value);isNaN(m)||s(l(m)),g.target.value=e.toFixed(2)},A=g=>{g.key==="Enter"&&g.currentTarget.blur(),g.key==="Escape"&&(a.current&&(a.current.value=e.toFixed(2)),a.current?.blur())};return W.jsxs(nt,{style:{display:"flex",alignItems:"center",gap:"0.25em",flex:1},children:[W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,letterSpacing:"-0.75px",flexShrink:0},children:n}),W.jsx("input",{ref:a,size:1,defaultValue:e.toFixed(2),onPointerDown:c,onPointerMove:d,onPointerUp:h,onBlur:p,onKeyDown:A,onFocus:g=>g.currentTarget.style.outline="2px solid var(--mantine-color-blue-5)",onBlurCapture:g=>g.currentTarget.style.outline="none",style:ine})]})}function LR({label:n,x:e,y:t,z:r,step:i,xLabel:s="X",yLabel:a="Y",zLabel:o="Z",onX:l,onY:c,onZ:d}){return W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[W.jsx(qs,{c:"dimmed",style:$z,children:n}),W.jsx(U_,{axis:s,value:e,step:i,onChange:l}),W.jsx(U_,{axis:a,value:t,step:i,onChange:c}),W.jsx(U_,{axis:o,value:r,step:i,onChange:d})]})}function sne({scale:n,xOffset:e,yOffset:t,zOffset:r,roll:i,pitch:s,yaw:a,onCalibrate:o}){const[l,c]=U.useState(n),[d,h]=U.useState(e),[p,A]=U.useState(t),[g,m]=U.useState(r),[x,y]=U.useState(i),[_,b]=U.useState(s),[w,C]=U.useState(a);U.useEffect(()=>{c(n)},[n]),U.useEffect(()=>{h(e)},[e]),U.useEffect(()=>{A(t)},[t]),U.useEffect(()=>{m(r)},[r]),U.useEffect(()=>{y(i)},[i]),U.useEffect(()=>{b(s)},[s]),U.useEffect(()=>{C(a)},[a]);const S=(M,T,R,k,V,P,H)=>o(M,T,R,k,V,P,H);return W.jsxs(Oz,{label:"Control",expandByDefault:!0,children:[W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[W.jsx(qs,{c:"dimmed",style:$z,children:"Scale"}),W.jsx(nt,{style:{flex:1},children:W.jsx(M0,{value:l,onChange:M=>{c(M),S(M,d,p,g,x,_,w)},min:.1,max:5,step:.05,size:"xs",label:M=>M.toFixed(2),styles:rne})})]}),W.jsx(LR,{label:"Position",x:d,y:p,z:g,step:.05,onX:M=>{h(M),S(l,M,p,g,x,_,w)},onY:M=>{A(M),S(l,d,M,g,x,_,w)},onZ:M=>{m(M),S(l,d,p,M,x,_,w)}}),W.jsx(LR,{label:"Rotation",x,y:_,z:w,step:.5,xLabel:"R",yLabel:"P",zLabel:"Y",onX:M=>{y(M),S(l,d,p,g,M,_,w)},onY:M=>{b(M),S(l,d,p,g,x,M,w)},onZ:M=>{C(M),S(l,d,p,g,x,_,M)}})]})}function ane(n){return n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function one({command:n,value:e,onChange:t,disabled:r}){const i=n.config;return W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:i.label}),W.jsx(nt,{style:{width:"50%"},children:W.jsx(M0,{value:e,onChange:s=>t(n.id,s),min:i.min,max:i.max,step:i.step,size:"xs",disabled:r,styles:{root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}}})})]})}function lne(n){const{projects:e,projectValue:t,projectLabel:r,onProjectChange:i,scenes:s,sceneValue:a,onSceneChange:o,splats:l,splatSection:c=!1,splatValue:d,onSplatChange:h,splatConfig:p,onCalibrateSplat:A,onSplatUrlLoad:g,policies:m,policyValue:x,onPolicyChange:y,commandsEnabled:_=!1,onReset:b}=n,[w,{open:C,close:S}]=Kg(!1),[M,T]=U.useState(""),[R,k]=U.useState(null),[V,P]=U.useState(!1),H=U.useCallback(async le=>{if(le.key!=="Enter"||!g)return;const oe=M.trim();if(l.some(ue=>ue.label===oe||ue.value===oe))return;if(!oe.toLowerCase().endsWith(".spz")){k("URL must end with .spz");return}await g(oe)?(k(null),P(!0)):k("File not found at the specified URL")},[g,M,l]),[B,j]=U.useState([]),[J,X]=U.useState([]),[$,Y]=U.useState({});U.useEffect(()=>{const le=Zr(),oe=()=>{j(le.getCommands()),X(le.getCommandGroups()),Y(le.getValues())};return oe(),le.addEventListener(oe),()=>{le.removeEventListener(oe)}},[]);const ne=U.useCallback((le,oe)=>{Zr().setValue(le,oe),Y(ue=>({...ue,[le]:oe}))},[]),L=U.useCallback(()=>{Zr().triggerButton("_system:reset"),b&&b()},[b]),G=le=>B.filter(oe=>oe.groupName===le&&oe.config.type==="slider");return!e.length&&!s.length&&!m.length?null:W.jsxs(W.Fragment,{children:[W.jsx(ra,{opened:w,onClose:S,size:"lg",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:W.jsxs(YE,{gap:"md",align:"center",children:[W.jsx(Mg,{src:"./logo-color.svg",style:{width:"8em",height:"auto"}}),W.jsx(qs,{size:"xl",fw:700,children:"powered by mjswan"}),W.jsxs(qs,{size:"sm",c:"dimmed",children:["version ",QR]}),W.jsx(qs,{size:"sm",c:"dimmed",children:"MuJoco Simulation on Web Assembly with Neural netwroks"}),W.jsx(wd,{w:"100%"}),W.jsxs(nt,{children:[W.jsx(sp,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"}),"  •  ",W.jsx(sp,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]}),W.jsx(wd,{w:"100%"}),W.jsxs(nt,{style:{textAlign:"left",maxHeight:"120px",overflowY:"auto",lineHeight:"1",fontSize:"0.8rem",opacity:"0.75"},px:"md",children:["Thanks to our contributors! ",W.jsx("br",{}),PR.map((le,oe)=>W.jsxs("span",{children:[W.jsx(sp,{href:le.html_url,target:"_blank",style:{textDecoration:"none",fontSize:"0.75rem"},children:le.login}),oe<PR.length-1&&", "]},le.login))]})]})}),W.jsxs(ho,{width:"20em",children:[W.jsxs(ho.Handle,{children:[W.jsx(Pd,{label:`mjswan ${QR}`,children:W.jsx(nt,{component:"a",onClick:le=>{le.stopPropagation(),C()},style:{position:"absolute",cursor:"pointer",display:"flex",top:"0.8em",left:"0.9em"},children:W.jsx(Mg,{src:"./logo.svg",style:{width:"1.2em",height:"auto"}})})}),W.jsx("div",{style:{width:"1.1em"}}),W.jsx(ho.HideWhenCollapsed,{children:W.jsxs(nt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[W.jsx("span",{style:{flexGrow:1},children:r}),e.length>1&&W.jsxs(fi,{position:"bottom-start",offset:5,children:[W.jsx(fi.Target,{children:W.jsx(nt,{onClick:le=>le.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center"},children:W.jsx(Uz,{size:16})})}),W.jsx(fi.Dropdown,{onClick:le=>le.stopPropagation(),children:e.map(le=>W.jsx(fi.Item,{onClick:oe=>{oe.stopPropagation(),i(le.value)},style:{fontWeight:le.value===t?600:400,backgroundColor:le.value===t?"rgba(34, 139, 230, 0.1)":void 0},children:le.label},le.value))})]})]})}),W.jsx(ho.HideWhenExpanded,{children:W.jsx(nt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:r})})]}),W.jsx(ho.Contents,{children:W.jsxs(nt,{pt:"0.375em",children:[s.length>0&&W.jsx(z_,{id:"scene-select",label:"Scene",children:W.jsx(Ed,{id:"scene-select",placeholder:"Select scene",data:s,value:a,onChange:o,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),(l.length>0||c)&&W.jsx(z_,{id:"splat-select",label:"Splat",children:W.jsx(Pd,{label:R??"",color:"red",position:"bottom",opened:R!==null,withArrow:!0,children:W.jsx(Ed,{id:"splat-select",placeholder:g!==void 0?"Select splat or paste .spz URL":"Select splat",data:l,value:d,onChange:le=>{h(le),k(null),P(!1)},searchable:g!==void 0,searchValue:M,onSearchChange:le=>{T(le),le&&k(null)},onKeyDown:H,size:"xs",radius:"xs",clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})})}),(p?.control&&d!==null||V)&&A&&W.jsx(sne,{scale:p?.scale??1,xOffset:p?.xOffset??0,yOffset:p?.yOffset??0,zOffset:p?.zOffset??0,roll:p?.roll??0,pitch:p?.pitch??0,yaw:p?.yaw??0,onCalibrate:A}),m.length>0&&W.jsx(z_,{id:"policy-select",label:"Policy",children:W.jsx(Ed,{id:"policy-select",placeholder:"Select policy",data:m,value:x,onChange:y,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),J.length>0&&B.filter(le=>le.config.type==="slider").length>0&&W.jsx(W.Fragment,{children:J.map(le=>{const oe=G(le);return oe.length===0?null:W.jsx(Oz,{label:ane(le),expandByDefault:!0,children:oe.map(Ae=>W.jsx(one,{command:Ae,value:$[Ae.id]??0,onChange:ne,disabled:!_},Ae.id))},le)})}),W.jsx(wd,{mb:"xs",mx:"xs"}),W.jsx(nt,{px:"xs",pb:"xs",children:W.jsx(ih,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:W.jsx(Kte,{size:14}),onClick:L,children:"Reset"})})]})})]})]})}function jf(n,e,t){return Object.keys(n[e]).reduce((r,i)=>(r[i]=`var(--mantine-${t}-${i})`,r),{})}function FR(n,e){return n in e.breakpoints?e.breakpoints[n]:G_(n)}function cne(n){const e=uD(n0,n),t=jf(e,"fontSizes","font-size"),r=jf(e,"lineHeights","line-height"),i=jf(e,"shadows","shadow"),s=jf(e,"radius","radius"),a=jf(e,"spacing","spacing"),o=Object.keys(e.headings.sizes).reduce((c,d)=>(c[d]={fontSize:`var(--mantine-${d}-font-size)`,lineHeight:`var(--mantine-${d}-line-height)`,fontWeight:`var(--mantine-${d}-font-weight)`},c),{}),l=Object.keys(e.colors).reduce((c,d)=>(c[d]={0:`var(--mantine-color-${d}-0)`,1:`var(--mantine-color-${d}-1)`,2:`var(--mantine-color-${d}-2)`,3:`var(--mantine-color-${d}-3)`,4:`var(--mantine-color-${d}-4)`,5:`var(--mantine-color-${d}-5)`,6:`var(--mantine-color-${d}-6)`,7:`var(--mantine-color-${d}-7)`,8:`var(--mantine-color-${d}-8)`,9:`var(--mantine-color-${d}-9)`,filled:`var(--mantine-color-${d}-filled)`,filledHover:`var(--mantine-color-${d}-filled-hover)`,light:`var(--mantine-color-${d}-light)`,lightHover:`var(--mantine-color-${d}-light-hover)`,lightColor:`var(--mantine-color-${d}-light-color)`,outline:`var(--mantine-color-${d}-outline)`,outlineHover:`var(--mantine-color-${d}-outline-hover)`},c),{primary:"var(--mantine-primary-color-filled)",primaryColors:{0:"var(--mantine-primary-color-0)",1:"var(--mantine-primary-color-1)",2:"var(--mantine-primary-color-2)",3:"var(--mantine-primary-color-3)",4:"var(--mantine-primary-color-4)",5:"var(--mantine-primary-color-5)",6:"var(--mantine-primary-color-6)",7:"var(--mantine-primary-color-7)",8:"var(--mantine-primary-color-8)",9:"var(--mantine-primary-color-9)",filled:"var(--mantine-primary-color-filled)",filledHover:"var(--mantine-primary-color-filled-hover)",light:"var(--mantine-primary-color-light)",lightHover:"var(--mantine-primary-color-light-hover)",lightColor:"var(--mantine-primary-color-light-color)",outline:"var(--mantine-primary-color-outline)",outlineHover:"var(--mantine-primary-color-outline-hover)"},white:"var(--mantine-color-white)",black:"var(--mantine-color-black)",text:"var(--mantine-color-text)",body:"var(--mantine-color-body)",error:"var(--mantine-color-error)",placeholder:"var(--mantine-color-placeholder)",anchor:"var(--mantine-color-anchor)",default:"var(--mantine-color-default)",defaultHover:"var(--mantine-color-default-hover)",defaultColor:"var(--mantine-color-default-color)",defaultBorder:"var(--mantine-color-default-border)",dimmed:"var(--mantine-color-dimmed)",disabledBody:"var(--mantine-color-disabled)",disabledText:"var(--mantine-color-disabled-color)",disabledBorder:"var(--mantine-color-disabled-border)"});return{scale:"var(--mantine-scale)",cursorType:"var(--mantine-cursor-type)",webkitFontSmoothing:"var(--mantine-webkit-font-smoothing)",mozFontSmoothing:"var(--mantine-moz-font-smoothing)",lineHeight:"var(--mantine-line-height)",fontFamily:"var(--mantine-font-family)",fontFamilyMonospace:"var(--mantine-font-family-monospace)",fontFamilyHeadings:"var(--mantine-font-family-headings)",headingFontWeight:"var(--mantine-heading-font-weight)",radiusDefault:"var(--mantine-radius-default)",breakpoints:e.breakpoints,fontSizes:t,lineHeights:r,shadows:i,radius:s,headings:o,spacing:a,colors:l,rtlSelector:'[dir="rtl"] &',darkSelector:'[data-mantine-color-scheme="dark"] &',lightSelector:'[data-mantine-color-scheme="light"] &',smallerThan:c=>`(max-width: ${FR(c,e)})`,largerThan:c=>`(min-width: ${FR(c,e)})`}}const kw={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:nh.extend({defaultProps:{radius:"xs"}}),ColorInput:PE.extend({defaultProps:{radius:"xs"}}),Select:Ed.extend({defaultProps:{radius:"sm"}}),Textarea:FE.extend({defaultProps:{radius:"xs"}}),TextInput:XE.extend({defaultProps:{radius:"xs"}}),NumberInput:jE.extend({defaultProps:{radius:"xs"}}),Paper:Gc.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:th.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:ih.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};cne(kw);const Gz=U.createContext(void 0),Hz=()=>{const n=U.useContext(Gz);if(!n)throw new Error("useLoading must be used within a LoadingProvider");return n},une=({children:n})=>{const[e,t]=U.useState(!1),r=U.useRef(0),i=U.useCallback(()=>{r.current+=1,r.current>0&&t(!0)},[]),s=U.useCallback(()=>{r.current=Math.max(0,r.current-1),r.current===0&&t(!1)},[]);return W.jsx(Gz.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:n})},dne=()=>{const{isLoading:n}=Hz();return n?W.jsx("div",{className:"loader-overlay",children:W.jsx("div",{className:"loader-content",children:W.jsx(Zd,{size:64,type:"bars"})})}):null};function hne(){const n="/".replace(/\/+$/,"/");let t=window.location.pathname.replace(/^\/+|\/+$/g,"");const r=n.replace(/^\/+|\/+$/g,"");if(r&&(t===r?t="":t.startsWith(`${r}/`)&&(t=t.slice(r.length+1))),!t)return null;const i=t.split("/")[0];return i==="main"||i.includes(".")||i==="assets"?null:i}function uI(n){return n.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function fne(n,e){const t=n.replace(/\/+$/,"/"),r=new Set,i=(h,p)=>{if(h)try{const A=new URL(h,p||window.location.href).toString();r.add(A)}catch{r.add(h.replace(/\/+/g,"/"))}},s=`${window.location.origin}/`,a=new URL(t,s).toString();i("assets/config.json",a);const l=window.location.pathname.split("/").filter(Boolean);l.length>0&&l[l.length-1]==="index.html"&&l.pop(),l.length>0&&l[l.length-1]===(e??"main")&&l.pop();const c=`/${l.join("/")}${l.length?"/":""}`,d=`${window.location.origin}${c}`;return i("assets/config.json",d),i("assets/config.json"),i("../assets/config.json"),i("../../assets/config.json"),Array.from(r)}async function pne(n,e){const r=new URLSearchParams(window.location.search).get("config"),i=fne(n,e);if(r)try{i.unshift(new URL(r,window.location.href).toString())}catch{i.unshift(r)}let s=null;for(const a of i)try{const o=await fetch(a,{cache:"no-store"});if(!o.ok)throw new Error(`Failed to fetch ${a}: ${o.status}`);const l=await o.text(),c=l.trim();if((o.headers.get("content-type")||"").includes("text/html")||c.startsWith("<!doctype")||c.startsWith("<html"))throw new Error(`Received HTML from ${a}`);try{return JSON.parse(l)}catch(h){throw new Error(`Invalid JSON from ${a}: ${h instanceof Error?h.message:String(h)}`)}}catch(o){s=o instanceof Error?o:new Error(String(o))}throw s??new Error("Failed to load config.json.")}function zR(n,e){if(!n.scenes.length)return null;if(!e)return n.scenes[0];const t=e.trim().toLowerCase();return n.scenes.find(r=>r.name.toLowerCase()===t)||n.scenes.find(r=>uI(r.name)===t)||n.scenes[0]}function UR(n,e){if(!n.policies.length)return null;const t=n.policies.find(s=>s.default)??n.policies[0];if(!e)return t.name;const r=e.trim().toLowerCase();return(n.policies.find(s=>s.name.toLowerCase()===r)||n.policies.find(s=>uI(s.name)===r))?.name??t.name}function O_(n,e,t){const i="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let s=i?`/${i}/`:"/";n&&n!=="main"&&(s+=`${n}/`);const a=new URLSearchParams;e&&a.set("scene",e),t&&a.set("policy",t);const o=s+(a.toString()?"?"+a.toString():"");window.history.replaceState({},"",o)}function Ane(){const[n,e]=U.useState(null),[t,r]=U.useState(null),[i,s]=U.useState(null),[a,o]=U.useState(null),[l,c]=U.useState(null),[d,h]=U.useState(null),[p,A]=U.useState(null),g=U.useRef(null),{showLoading:m,hideLoading:x}=Hz(),y=U.useMemo(()=>hne(),[]),_=U.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),b=U.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);U.useEffect(()=>{m(),pne("/",y).then(oe=>{e(oe);const Ae=oe.projects.find(be=>y===null?be.id===null:be.id===y);if(!Ae)throw new Error(`Project "${y??"(main)"}" not found in config.json.`);r(Ae);const ue=zR(Ae,_);s(ue);const pe=ue?UR(ue,b):null;o(pe)}).catch(oe=>{console.error("Failed to load config:",oe),c(oe.message||"Failed to load config."),x()})},[y,_,b,m,x]);const w=U.useMemo(()=>{if(!t||!i)return null;const oe=t.id?t.id:"main",Ae=i.path?i.path:`scene/${uI(i.name)}/scene.xml`;return`${oe}/assets/${Ae}`.replace(/\/+/g,"/")},[t,i]),C=U.useMemo(()=>!i||!a?null:i.policies.find(oe=>oe.name===a)??null,[i,a]),S=U.useMemo(()=>!t||!C?.config?null:`${t.id?t.id:"main"}/assets/${C.config}`.replace(/\/+/g,"/"),[t,C]),M=U.useMemo(()=>{if(!t||!i?.splats?.length)return[];const oe=t.id?t.id:"main";return i.splats.map(Ae=>{if(Ae.path){const ue=`${oe}/assets/${Ae.path}`.replace(/\/+/g,"/");return{...Ae,url:ue}}return Ae})},[t,i?.splats]),T=U.useMemo(()=>d?M.find(oe=>oe.name===d)??null:p?{name:"Custom",url:p}:null,[M,d,p]),R=U.useMemo(()=>n?n.projects.map(oe=>({value:oe.id??"main",label:oe.name||(oe.id??"Main")})):[],[n]),k=U.useMemo(()=>t?t.scenes.map(oe=>({value:oe.name,label:oe.name})):[],[t]),V=U.useMemo(()=>!i||!i.policies?[]:i.policies.map(oe=>({value:oe.name,label:oe.name})),[i]),P=t?t.id??"main":null,H=i?.name??null,B=U.useCallback(oe=>{c(oe.message),x()},[x]),j=U.useCallback(()=>{x()},[x]);U.useEffect(()=>{const oe=i?.splats?.[0];h(oe?oe.name:null),A(null)},[i]);const J=U.useCallback(oe=>{g.current=oe},[]),X=U.useMemo(()=>i?.splats?.length?i.splats.map(oe=>({value:oe.name,label:oe.name})):[],[i?.splats]),$=U.useCallback(oe=>{if(oe===null)g.current?.setSplat(null);else{const Ae=M.find(ue=>ue.name===oe);Ae&&g.current?.setSplat(Ae)}h(oe),A(null)},[M]),Y=U.useCallback(async oe=>{try{if(!(await fetch(oe,{method:"HEAD"})).ok)return!1}catch{return!1}return g.current?.setSplat({name:"Custom",url:oe}),A(oe),!0},[]),ne=U.useCallback((oe,Ae,ue,pe,be,Te,ke)=>{const Oe=T??(p?{name:"Custom",url:p}:null);Oe&&g.current?.calibrateSplat({...Oe,scale:oe,xOffset:Ae,yOffset:ue,zOffset:pe,roll:be,pitch:Te,yaw:ke})},[T,p]),L=U.useCallback(oe=>{if(!n||!oe)return;const Ae=oe==="main"?null:oe,ue=n.projects.find(Te=>(Te.id??"main")===(Ae??"main"));if(!ue)return;m(),r(ue);const pe=zR(ue,null);s(pe);const be=pe?.policies?.[0]?.name??null;o(be),O_(ue.id,pe?.name??null,be)},[n,m]),G=U.useCallback(oe=>{if(!t||!oe)return;const Ae=t.scenes.find(pe=>pe.name===oe);if(!Ae)return;m(),s(Ae);const ue=UR(Ae,null);o(ue),O_(t.id,oe,ue)},[t,m]),le=U.useCallback(oe=>{oe!==a&&m(),o(oe),O_(t?.id??null,i?.name??null,oe)},[t,i,a,m]);return l?W.jsx(W_,{theme:kw,defaultColorScheme:"auto",children:W.jsx("div",{className:"app",children:W.jsxs("div",{className:"hud hud-error",children:[W.jsx("h1",{className:"hud-title",children:"mjswan"}),W.jsx("p",{className:"hud-message",children:l})]})})}):!t||!i||!w?null:W.jsx(W_,{theme:kw,defaultColorScheme:"auto",children:W.jsxs("div",{className:"app",children:[W.jsx(dne,{}),W.jsx(lne,{projects:R,projectValue:P,projectLabel:t?.name??"mjswan",onProjectChange:L,scenes:k,sceneValue:H,onSceneChange:G,splats:X,splatSection:i?.splatSection??!1,splatValue:d,onSplatChange:$,splatConfig:T,onCalibrateSplat:ne,onSplatUrlLoad:Y,policies:V,policyValue:a,onPolicyChange:le,commandsEnabled:!!S}),W.jsx(jte,{scenePath:w,baseUrl:"/",policyConfigPath:S,splatConfig:T,cameraConfig:i?.camera,eventsConfig:i?.events,terrainData:i?.terrainData,onError:B,onReady:j,onRuntimeReady:J})]})})}function mne(){return W.jsx(une,{children:W.jsx(Ane,{})})}const OR=document.getElementById("root");OR&&k4.createRoot(OR).render(W.jsx(On.StrictMode,{children:W.jsx(mne,{})}));export{gH as _};
@@ -1,4 +1,4 @@
1
- import{_ as Gn}from"./index-BSeAJBAd.js";const Yn=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));var tc=(async function(De={}){var Tr,v=De,Ke=typeof window=="object",Z=typeof WorkerGlobalScope<"u",V=typeof process=="object"&&process.versions?.node&&process.type!="renderer",ct=!Ke&&!V&&!Z,A=Z&&self.name?.startsWith("em-pthread");if(A&&(p(!globalThis.moduleLoaded,"module should only be loaded once on each pthread worker"),globalThis.moduleLoaded=!0),V){const{createRequire:e}=await Gn(async()=>{const{createRequire:r}=await Promise.resolve().then(()=>Yn);return{createRequire:r}},void 0);var ve=e(import.meta.url),Xe=ve("worker_threads");global.Worker=Xe.Worker,Z=!Xe.isMainThread,A=Z&&Xe.workerData=="em-pthread"}var Fr="./this.program",Pr=(e,r)=>{throw r},Ar=import.meta.url,Je="";function Kn(e){return v.locateFile?v.locateFile(e,Je):Je+e}var Ze,Oe;if(V){if(!(typeof process=="object"&&process.versions?.node&&process.type!="renderer"))throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");var lt=process.versions.node,Ie=lt.split(".").slice(0,3);if(Ie=Ie[0]*1e4+Ie[1]*100+Ie[2].split("-")[0]*1,Ie<160400)throw new Error("This emscripten-generated code requires node v16.04.4.0 (detected v"+lt+")");var Me=ve("fs");Ar.startsWith("file:")&&(Je=ve("path").dirname(ve("url").fileURLToPath(Ar))+"/"),Oe=r=>{r=Ne(r)?new URL(r):r;var t=Me.readFileSync(r);return p(Buffer.isBuffer(t)),t},Ze=async(r,t=!0)=>{r=Ne(r)?new URL(r):r;var n=Me.readFileSync(r,t?void 0:"utf8");return p(t?Buffer.isBuffer(n):typeof n=="string"),n},process.argv.length>1&&(Fr=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),Pr=(r,t)=>{throw process.exitCode=r,t}}else if(ct){if(typeof process=="object"&&process.versions?.node&&process.type!="renderer"||typeof window=="object"||typeof WorkerGlobalScope<"u")throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)")}else if(Ke||Z){try{Je=new URL(".",Ar).href}catch{}if(!(typeof window=="object"||typeof WorkerGlobalScope<"u"))throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");V||(Z&&(Oe=e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),Ze=async e=>{if(Ne(e))return new Promise((t,n)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{if(i.status==200||i.status==0&&i.response){t(i.response);return}n(i.status)},i.onerror=n,i.send(null)});var r=await fetch(e,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)})}else throw new Error("environment detection error");var ut=console.log.bind(console),dt=console.error.bind(console);if(V){var Xn=ve("util"),ft=e=>typeof e=="object"?Xn.inspect(e):e;ut=(...e)=>Me.writeSync(1,e.map(ft).join(" ")+`
1
+ import{_ as Gn}from"./index-C6iGKiGz.js";const Yn=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));var tc=(async function(De={}){var Tr,v=De,Ke=typeof window=="object",Z=typeof WorkerGlobalScope<"u",V=typeof process=="object"&&process.versions?.node&&process.type!="renderer",ct=!Ke&&!V&&!Z,A=Z&&self.name?.startsWith("em-pthread");if(A&&(p(!globalThis.moduleLoaded,"module should only be loaded once on each pthread worker"),globalThis.moduleLoaded=!0),V){const{createRequire:e}=await Gn(async()=>{const{createRequire:r}=await Promise.resolve().then(()=>Yn);return{createRequire:r}},void 0);var ve=e(import.meta.url),Xe=ve("worker_threads");global.Worker=Xe.Worker,Z=!Xe.isMainThread,A=Z&&Xe.workerData=="em-pthread"}var Fr="./this.program",Pr=(e,r)=>{throw r},Ar=import.meta.url,Je="";function Kn(e){return v.locateFile?v.locateFile(e,Je):Je+e}var Ze,Oe;if(V){if(!(typeof process=="object"&&process.versions?.node&&process.type!="renderer"))throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");var lt=process.versions.node,Ie=lt.split(".").slice(0,3);if(Ie=Ie[0]*1e4+Ie[1]*100+Ie[2].split("-")[0]*1,Ie<160400)throw new Error("This emscripten-generated code requires node v16.04.4.0 (detected v"+lt+")");var Me=ve("fs");Ar.startsWith("file:")&&(Je=ve("path").dirname(ve("url").fileURLToPath(Ar))+"/"),Oe=r=>{r=Ne(r)?new URL(r):r;var t=Me.readFileSync(r);return p(Buffer.isBuffer(t)),t},Ze=async(r,t=!0)=>{r=Ne(r)?new URL(r):r;var n=Me.readFileSync(r,t?void 0:"utf8");return p(t?Buffer.isBuffer(n):typeof n=="string"),n},process.argv.length>1&&(Fr=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),Pr=(r,t)=>{throw process.exitCode=r,t}}else if(ct){if(typeof process=="object"&&process.versions?.node&&process.type!="renderer"||typeof window=="object"||typeof WorkerGlobalScope<"u")throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)")}else if(Ke||Z){try{Je=new URL(".",Ar).href}catch{}if(!(typeof window=="object"||typeof WorkerGlobalScope<"u"))throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");V||(Z&&(Oe=e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),Ze=async e=>{if(Ne(e))return new Promise((t,n)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{if(i.status==200||i.status==0&&i.response){t(i.response);return}n(i.status)},i.onerror=n,i.send(null)});var r=await fetch(e,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)})}else throw new Error("environment detection error");var ut=console.log.bind(console),dt=console.error.bind(console);if(V){var Xn=ve("util"),ft=e=>typeof e=="object"?Xn.inspect(e):e;ut=(...e)=>Me.writeSync(1,e.map(ft).join(" ")+`
2
2
  `),dt=(...e)=>Me.writeSync(2,e.map(ft).join(" ")+`
3
3
  `)}var ue=ut,C=dt;p(Ke||Z||V,"Pthreads do not work in this environment yet (need Web Workers, or an alternative to them)"),p(!ct,"shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.");var xe;typeof WebAssembly!="object"&&C("no native wasm support detected");var Cr,ke=!1,Se;function p(e,r){e||z("Assertion failed"+(r?": "+r:""))}var Ne=e=>e.startsWith("file://");function vt(){var e=tt();p((e&3)==0),e==0&&(e+=4),(d(),T)[e>>2]=34821223,(d(),T)[e+4>>2]=2310721022,(d(),T)[0]=1668509029}function Le(){if(!ke){var e=tt();e==0&&(e+=4);var r=(d(),T)[e>>2],t=(d(),T)[e+4>>2];(r!=34821223||t!=2310721022)&&z(`Stack overflow! Stack cookie has been overwritten at ${he(e)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${he(t)} ${he(r)}`),(d(),T)[0]!=1668509029&&z("Runtime error: The application has corrupted its heap memory area (address zero)!")}}class b extends Error{}class Jn extends b{}class $r extends b{constructor(r){super(r),this.excPtr=r;const t=Pn(r);this.name=t[0],this.message=t[1]}}(()=>{var e=new Int16Array(1),r=new Int8Array(e.buffer);if(e[0]=25459,r[0]!==115||r[1]!==99)throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"})();function Qe(e){Object.getOwnPropertyDescriptor(v,e)||Object.defineProperty(v,e,{configurable:!0,set(){z(`Attempt to set \`Module.${e}\` after it has already been processed. This can happen, for example, when code is injected via '--post-js' rather than '--pre-js'`)}})}function M(e){return()=>p(!1,`call to '${e}' via reference taken before Wasm module initialization`)}function Zn(e){Object.getOwnPropertyDescriptor(v,e)&&z(`\`Module.${e}\` was supplied but \`${e}\` not included in INCOMING_MODULE_JS_API`)}function _t(e){return e==="FS_createPath"||e==="FS_createDataFile"||e==="FS_createPreloadedFile"||e==="FS_unlink"||e==="addRunDependency"||e==="FS_createLazyFile"||e==="FS_createDevice"||e==="removeRunDependency"}function pt(e,r){typeof globalThis<"u"&&!Object.getOwnPropertyDescriptor(globalThis,e)&&Object.defineProperty(globalThis,e,{configurable:!0,get(){r()}})}function ht(e,r){pt(e,()=>{ae(`\`${e}\` is not longer defined by emscripten. ${r}`)})}ht("buffer","Please use HEAP8.buffer or wasmMemory.buffer"),ht("asm","Please use wasmExports instead");function Qn(e){pt(e,()=>{var r=`\`${e}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`,t=e;t.startsWith("_")||(t="$"+e),r+=` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${t}')`,_t(e)&&(r+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),ae(r)}),mt(e)}function mt(e){A||Object.getOwnPropertyDescriptor(v,e)||Object.defineProperty(v,e,{configurable:!0,get(){var r=`'${e}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;_t(e)&&(r+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),z(r)}})}function d(){Q.buffer!=B.buffer&&er()}var Rr,Dr,gt;if(V&&A){var yt=Xe.parentPort;yt.on("message",e=>global.onmessage?.({data:e})),Object.assign(globalThis,{self:global,postMessage:e=>yt.postMessage(e)})}var ei=0;if(A){let e=function(r){try{var t=r.data,n=t.cmd;if(n==="load"){ei=t.workerID;let i=[];self.onmessage=a=>i.push(a),self.startWorker=a=>{postMessage({cmd:"loaded"});for(let s of i)e(s);self.onmessage=e};for(const a of t.handlers)(!v[a]||v[a].proxy)&&(v[a]=(...s)=>{postMessage({cmd:"callHandler",handler:a,args:s})},a=="print"&&(ue=v[a]),a=="printErr"&&(C=v[a]));Q=t.wasmMemory,er(),gt(t.wasmModule)}else if(n==="run"){p(t.pthread_ptr),vi(t.pthread_ptr),rt(t.pthread_ptr,0,0,1,0,0),$.threadInitTLS(),Yr(t.pthread_ptr),Or||(Cn(),Or=!0);try{_i(t.start_routine,t.arg)}catch(i){if(i!="unwind")throw i}}else t.target==="setimmediate"||(n==="checkMailbox"?Or&&wr():n&&(C(`worker: received unknown command ${n}`),C(t)))}catch(i){throw C(`worker: onmessage() captured an uncaught exception: ${i}`),i?.stack&&C(i.stack),$n(),i}};var Or=!1;self.onunhandledrejection=r=>{throw r.reason||r},self.onmessage=e}var Q,B,K,de,ie,S,T,wt,Ue,Y,Et,We=!1;function er(){var e=Q.buffer;B=new Int8Array(e),de=new Int16Array(e),K=new Uint8Array(e),ie=new Uint16Array(e),S=new Int32Array(e),T=new Uint32Array(e),wt=new Float32Array(e),Ue=new Float64Array(e),Y=new BigInt64Array(e),Et=new BigUint64Array(e)}function ri(){if(!A){if(v.wasmMemory)Q=v.wasmMemory;else{var e=v.INITIAL_MEMORY||16777216;p(e>=65536,"INITIAL_MEMORY should be larger than STACK_SIZE, was "+e+"! (STACK_SIZE=65536)"),Q=new WebAssembly.Memory({initial:e/65536,maximum:32768,shared:!0})}er()}}p(typeof Int32Array<"u"&&typeof Float64Array<"u"&&Int32Array.prototype.subarray!=null&&Int32Array.prototype.set!=null,"JS engine does not provide full typed array support");function ti(){if(p(!A),v.preRun)for(typeof v.preRun=="function"&&(v.preRun=[v.preRun]);v.preRun.length;)Ct(v.preRun.shift());Qe("preRun"),Pt(At)}function bt(){if(p(!We),We=!0,A)return startWorker(v);Le(),!v.noFSInit&&!o.initialized&&o.init(),Ee.__wasm_call_ctors(),o.ignorePermissions=!1}function ni(){if(Le(),!A){if(v.postRun)for(typeof v.postRun=="function"&&(v.postRun=[v.postRun]);v.postRun.length;)fi(v.postRun.shift());Qe("postRun"),Pt(Rt)}}var _e=0,je=null,Te={},pe=null;function rr(e){_e++,v.monitorRunDependencies?.(_e),e?(p(!Te[e]),Te[e]=1,pe===null&&typeof setInterval<"u"&&(pe=setInterval(()=>{if(ke){clearInterval(pe),pe=null;return}var r=!1;for(var t in Te)r||(r=!0,C("still waiting on run dependencies:")),C(`dependency: ${t}`);r&&C("(end of list)")},1e4))):C("warning: run dependency added without ID")}function Be(e){if(_e--,v.monitorRunDependencies?.(_e),e?(p(Te[e]),delete Te[e]):C("warning: run dependency removed without ID"),_e==0&&(pe!==null&&(clearInterval(pe),pe=null),je)){var r=je;je=null,r()}}function z(e){v.onAbort?.(e),e="Aborted("+e+")",C(e),ke=!0;var r=new WebAssembly.RuntimeError(e);throw Dr?.(r),r}function U(e,r){return(...t)=>{p(We,`native function \`${e}\` called before runtime initialization`);var n=Ee[e];return p(n,`exported native function \`${e}\` not found`),p(t.length<=r,`native function \`${e}\` called with ${t.length} args but expects ${r}`),n(...t)}}var ze;function ii(){return v.locateFile?Kn("mujoco.wasm"):new URL("/assets/mujoco-BrqJA_5D.wasm",import.meta.url).href}function ai(e){if(e==ze&&xe)return new Uint8Array(xe);if(Oe)return Oe(e);throw"both async and sync fetching of the wasm failed"}async function oi(e){if(!xe)try{var r=await Ze(e);return new Uint8Array(r)}catch{}return ai(e)}async function si(e,r){try{var t=await oi(e),n=await WebAssembly.instantiate(t,r);return n}catch(i){C(`failed to asynchronously prepare wasm: ${i}`),Ne(ze)&&C(`warning: Loading from a file URI (${ze}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`),z(i)}}async function ci(e,r,t){if(!e&&typeof WebAssembly.instantiateStreaming=="function"&&!Ne(r)&&!V)try{var n=fetch(r,{credentials:"same-origin"}),i=await WebAssembly.instantiateStreaming(n,t);return i}catch(a){C(`wasm streaming compile failed: ${a}`),C("falling back to ArrayBuffer instantiation")}return si(r,t)}function kt(){return zo(),{env:ot,wasi_snapshot_preview1:ot}}async function li(){function e(s,c){return Ee=s.exports,pi(Ee._emscripten_tls_init),nr=Ee.__indirect_function_table,p(nr,"table not found in wasm exports"),Cr=c,Bo(Ee),Be("wasm-instantiate"),Ee}rr("wasm-instantiate");var r=v;function t(s){return p(v===r,"the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"),r=null,e(s.instance,s.module)}var n=kt();if(v.instantiateWasm)return new Promise((s,c)=>{try{v.instantiateWasm(n,(l,u)=>{s(e(l,u))})}catch(l){C(`Module.instantiateWasm callback failed with error: ${l}`),c(l)}});if(A)return new Promise(s=>{gt=c=>{var l=new WebAssembly.Instance(c,kt());s(e(l,c))}});ze??=ii();var i=await ci(xe,ze,n),a=t(i);return a}class St{name="ExitStatus";constructor(r){this.message=`Program terminated with exit(${r})`,this.status=r}}var Tt=e=>{e.terminate(),e.onmessage=r=>{var t=r.data.cmd;C(`received "${t}" command from terminated worker: ${e.workerID}`)}},Ft=e=>{p(!A,"Internal Error! cleanupThread() can only ever be called from main application thread!"),p(e,"Internal Error! Null pthread_ptr in cleanupThread!");var r=$.pthreads[e];p(r),$.returnWorkerToPool(r)},Pt=e=>{for(;e.length>0;)e.shift()(v)},At=[],Ct=e=>At.push(e),ui=e=>{p(!A,"Internal Error! spawnThread() can only ever be called from main application thread!"),p(e.pthread_ptr,"Internal error, no pthread ptr!");var r=$.getNewWorker();if(!r)return 6;p(!r.pthread_ptr,"Internal error!"),$.runningWorkers.push(r),$.pthreads[e.pthread_ptr]=r,r.pthread_ptr=e.pthread_ptr;var t={cmd:"run",start_routine:e.startRoutine,arg:e.arg,pthread_ptr:e.pthread_ptr};return V&&r.unref(),r.postMessage(t,e.transferList),0},He=0,tr=()=>ir||He>0,w=()=>it(),y=e=>Un(e),Ve=e=>Wn(e),G=(e,r,t,...n)=>{for(var i=n.length*2,a=w(),s=Ve(i*8),c=s>>3,l=0;l<n.length;l++){var u=n[l];typeof u=="bigint"?((d(),Y)[c+2*l]=1n,(d(),Y)[c+2*l+1]=u):((d(),Y)[c+2*l]=0n,(d(),Ue)[c+2*l+1]=u)}var f=Rn(e,r,i,s,t);return y(a),f};function Ir(e){if(A)return G(0,0,1,e);Se=e,tr()||($.terminateAllThreads(),v.onExit?.(e),ke=!0),Pr(e,new St(e))}function $t(e){if(A)return G(1,0,0,e);Mr(e)}var di=(e,r)=>{if(Se=e,ec(),A)throw p(!r),$t(e),"unwind";if(tr()&&!r){var t=`program exited (with status: ${e}), but keepRuntimeAlive() is set (counter=${He}) due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)`;Dr?.(t),C(t)}Ir(e)},Mr=di,he=e=>(p(typeof e=="number"),e>>>=0,"0x"+e.toString(16).padStart(8,"0")),$={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},nextWorkerID:1,init(){A||$.initMainThread()},initMainThread(){Ct(()=>{rr("loading-workers"),$.loadWasmModuleToAllWorkers(()=>Be("loading-workers"))})},terminateAllThreads:()=>{p(!A,"Internal Error! terminateAllThreads() can only ever be called from main application thread!");for(var e of $.runningWorkers)Tt(e);for(var e of $.unusedWorkers)Tt(e);$.unusedWorkers=[],$.runningWorkers=[],$.pthreads={}},returnWorkerToPool:e=>{var r=e.pthread_ptr;delete $.pthreads[r],$.unusedWorkers.push(e),$.runningWorkers.splice($.runningWorkers.indexOf(e),1),e.pthread_ptr=0,Dn(r)},threadInitTLS(){$.tlsInitFunctions.forEach(e=>e())},loadWasmModuleToWorker:e=>new Promise(r=>{e.onmessage=a=>{var s=a.data,c=s.cmd;if(s.targetThread&&s.targetThread!=Zr()){var l=$.pthreads[s.targetThread];l?l.postMessage(s,s.transferList):C(`Internal error! Worker sent a message "${c}" to target pthread ${s.targetThread}, but that thread no longer exists!`);return}c==="checkMailbox"?wr():c==="spawnThread"?ui(s):c==="cleanupThread"?Ft(s.thread):c==="loaded"?(e.loaded=!0,r(e)):s.target==="setimmediate"?e.postMessage(s):c==="callHandler"?v[s.handler](...s.args):c&&C(`worker sent an unknown command ${c}`)},e.onerror=a=>{var s="worker sent an error!";throw e.pthread_ptr&&(s=`Pthread ${he(e.pthread_ptr)} sent an error!`),C(`${s} ${a.filename}:${a.lineno}: ${a.message}`),a},V&&(e.on("message",a=>e.onmessage({data:a})),e.on("error",a=>e.onerror(a))),p(Q instanceof WebAssembly.Memory,"WebAssembly memory should have been loaded by now!"),p(Cr instanceof WebAssembly.Module,"WebAssembly Module should have been loaded by now!");var t=[],n=["onExit","onAbort","print","printErr"];for(var i of n)v.propertyIsEnumerable(i)&&t.push(i);e.postMessage({cmd:"load",handlers:t,wasmMemory:Q,wasmModule:Cr,workerID:e.workerID})}),loadWasmModuleToAllWorkers(e){e()},allocateUnusedWorker(){var e;if(v.mainScriptUrlOrBlob){var r=v.mainScriptUrlOrBlob;typeof r!="string"&&(r=URL.createObjectURL(r)),e=new Worker(r,{type:"module",workerData:"em-pthread",name:"em-pthread-"+$.nextWorkerID})}else e=new Worker(new URL("/assets/mujoco-CTy7U9S1.js",import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread-"+$.nextWorkerID});e.workerID=$.nextWorkerID++,$.unusedWorkers.push(e)},getNewWorker(){return $.unusedWorkers.length==0&&(V||C("Tried to spawn a new thread, but the thread pool is exhausted.\nThis might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.\nIf you want to increase the pool size, use setting `-sPTHREAD_POOL_SIZE=...`.\nIf you want to throw an explicit error instead of the risk of deadlocking in those cases, use setting `-sPTHREAD_POOL_SIZE_STRICT=2`."),$.allocateUnusedWorker(),$.loadWasmModuleToWorker($.unusedWorkers[0])),$.unusedWorkers.pop()}},Rt=[],fi=e=>Rt.push(e);function vi(e){var r=(d(),T)[e+52>>2],t=(d(),T)[e+56>>2],n=r-t;p(r!=0),p(n!=0),p(r>n,"stackHigh must be higher then stackLow"),Ln(r,n),y(r),vt()}var Dt=[],nr,E=e=>{var r=Dt[e];return r||(Dt[e]=r=nr.get(e)),p(nr.get(e)==r,"JavaScript-side Wasm function table mirror is out of date!"),r},_i=(e,r)=>{He=0,ir=0;var t=E(e)(r);Le();function n(i){tr()?Se=i:nt(i)}n(t)},ir=!0,pi=e=>$.tlsInitFunctions.push(e),ae=e=>{ae.shown||={},ae.shown[e]||(ae.shown[e]=1,V&&(e="warning: "+e),C(e))},Ot=typeof TextDecoder<"u"?new TextDecoder:void 0,Fe=(e,r=0,t=NaN)=>{for(var n=r+t,i=r;e[i]&&!(i>=n);)++i;if(i-r>16&&e.buffer&&Ot)return Ot.decode(e.buffer instanceof ArrayBuffer?e.subarray(r,i):e.slice(r,i));for(var a="";r<i;){var s=e[r++];if(!(s&128)){a+=String.fromCharCode(s);continue}var c=e[r++]&63;if((s&224)==192){a+=String.fromCharCode((s&31)<<6|c);continue}var l=e[r++]&63;if((s&240)==224?s=(s&15)<<12|c<<6|l:((s&248)!=240&&ae("Invalid UTF-8 leading byte "+he(s)+" encountered when deserializing a UTF-8 string in wasm memory to a JS string!"),s=(s&7)<<18|c<<12|l<<6|e[r++]&63),s<65536)a+=String.fromCharCode(s);else{var u=s-65536;a+=String.fromCharCode(55296|u>>10,56320|u&1023)}}return a},oe=(e,r)=>(p(typeof e=="number",`UTF8ToString expects a number (got ${typeof e})`),e?Fe((d(),K),e,r):""),hi=(e,r,t,n)=>z(`Assertion failed: ${oe(e)}, at: `+[r?oe(r):"unknown filename",t,n?oe(n):"unknown function"]),mi=(e,r)=>E(e)(r),se=[],ar=0,gi=e=>{var r=new or(e);return r.get_caught()||(r.set_caught(!0),ar--),r.set_rethrown(!1),se.push(r),Sr(e),zn(e)},yi=()=>{if(!se.length)return 0;var e=se[se.length-1];return Sr(e.excPtr),e.excPtr},ce=0,wi=()=>{k(0,0),p(se.length>0);var e=se.pop();at(e.excPtr),ce=0};class or{constructor(r){this.excPtr=r,this.ptr=r-24}set_type(r){(d(),T)[this.ptr+4>>2]=r}get_type(){return(d(),T)[this.ptr+4>>2]}set_destructor(r){(d(),T)[this.ptr+8>>2]=r}get_destructor(){return(d(),T)[this.ptr+8>>2]}set_caught(r){r=r?1:0,(d(),B)[this.ptr+12]=r}get_caught(){return(d(),B)[this.ptr+12]!=0}set_rethrown(r){r=r?1:0,(d(),B)[this.ptr+13]=r}get_rethrown(){return(d(),B)[this.ptr+13]!=0}init(r,t){this.set_adjusted_ptr(0),this.set_type(r),this.set_destructor(t)}set_adjusted_ptr(r){(d(),T)[this.ptr+16>>2]=r}get_adjusted_ptr(){return(d(),T)[this.ptr+16>>2]}}var sr=e=>xn(e),xr=e=>{var r=ce?.excPtr;if(!r)return sr(0),0;var t=new or(r);t.set_adjusted_ptr(r);var n=t.get_type();if(!n)return sr(0),r;for(var i of e){if(i===0||i===n)break;var a=t.ptr+16;if(Bn(i,n,a))return sr(i),r}return sr(n),r},Ei=()=>xr([]),bi=e=>xr([e]),ki=(e,r)=>xr([e,r]),It=()=>{var e=se.pop();e||z("no exception to throw");var r=e.excPtr;throw e.get_rethrown()||(se.push(e),e.set_rethrown(!0),e.set_caught(!1),ar++),ce=new $r(r),ce},Si=e=>{if(e){var r=new or(e);se.push(r),r.set_rethrown(!0),It()}},Ti=(e,r,t)=>{var n=new or(e);throw n.init(r,t),ce=new $r(e),ar++,ce},Fi=()=>ar,Pi=e=>{throw ce||(ce=new $r(e)),ce},O={isAbs:e=>e.charAt(0)==="/",splitPath:e=>{var r=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return r.exec(e).slice(1)},normalizeArray:(e,r)=>{for(var t=0,n=e.length-1;n>=0;n--){var i=e[n];i==="."?e.splice(n,1):i===".."?(e.splice(n,1),t++):t&&(e.splice(n,1),t--)}if(r)for(;t;t--)e.unshift("..");return e},normalize:e=>{var r=O.isAbs(e),t=e.slice(-1)==="/";return e=O.normalizeArray(e.split("/").filter(n=>!!n),!r).join("/"),!e&&!r&&(e="."),e&&t&&(e+="/"),(r?"/":"")+e},dirname:e=>{var r=O.splitPath(e),t=r[0],n=r[1];return!t&&!n?".":(n&&(n=n.slice(0,-1)),t+n)},basename:e=>e&&e.match(/([^\/]+|\/)\/*$/)[1],join:(...e)=>O.normalize(e.join("/")),join2:(e,r)=>O.normalize(e+"/"+r)},Ai=()=>{if(V){var e=ve("crypto");return r=>e.randomFillSync(r)}return r=>r.set(crypto.getRandomValues(new Uint8Array(r.byteLength)))},Mt=e=>{(Mt=Ai())(e)},Pe={resolve:(...e)=>{for(var r="",t=!1,n=e.length-1;n>=-1&&!t;n--){var i=n>=0?e[n]:o.cwd();if(typeof i!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!i)return"";r=i+"/"+r,t=O.isAbs(i)}return r=O.normalizeArray(r.split("/").filter(a=>!!a),!t).join("/"),(t?"/":"")+r||"."},relative:(e,r)=>{e=Pe.resolve(e).slice(1),r=Pe.resolve(r).slice(1);function t(u){for(var f=0;f<u.length&&u[f]==="";f++);for(var h=u.length-1;h>=0&&u[h]==="";h--);return f>h?[]:u.slice(f,h-f+1)}for(var n=t(e.split("/")),i=t(r.split("/")),a=Math.min(n.length,i.length),s=a,c=0;c<a;c++)if(n[c]!==i[c]){s=c;break}for(var l=[],c=s;c<n.length;c++)l.push("..");return l=l.concat(i.slice(s)),l.join("/")}},Nr=[],Ae=e=>{for(var r=0,t=0;t<e.length;++t){var n=e.charCodeAt(t);n<=127?r++:n<=2047?r+=2:n>=55296&&n<=57343?(r+=4,++t):r+=3}return r},xt=(e,r,t,n)=>{if(p(typeof e=="string",`stringToUTF8Array expects a string (got ${typeof e})`),!(n>0))return 0;for(var i=t,a=t+n-1,s=0;s<e.length;++s){var c=e.codePointAt(s);if(c<=127){if(t>=a)break;r[t++]=c}else if(c<=2047){if(t+1>=a)break;r[t++]=192|c>>6,r[t++]=128|c&63}else if(c<=65535){if(t+2>=a)break;r[t++]=224|c>>12,r[t++]=128|c>>6&63,r[t++]=128|c&63}else{if(t+3>=a)break;c>1114111&&ae("Invalid Unicode code point "+he(c)+" encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."),r[t++]=240|c>>18,r[t++]=128|c>>12&63,r[t++]=128|c>>6&63,r[t++]=128|c&63,s++}}return r[t]=0,t-i},Lr=(e,r,t)=>{var n=Ae(e)+1,i=new Array(n),a=xt(e,i,0,i.length);return i.length=a,i},Ci=()=>{if(!Nr.length){var e=null;if(V){var r=256,t=Buffer.alloc(r),n=0,i=process.stdin.fd;try{n=Me.readSync(i,t,0,r)}catch(a){if(a.toString().includes("EOF"))n=0;else throw a}n>0&&(e=t.slice(0,n).toString("utf-8"))}else typeof window<"u"&&typeof window.prompt=="function"&&(e=window.prompt("Input: "),e!==null&&(e+=`
4
4
  `));if(!e)return null;Nr=Lr(e)}return Nr.shift()},fe={ttys:[],init(){},shutdown(){},register(e,r){fe.ttys[e]={input:[],output:[],ops:r},o.registerDevice(e,fe.stream_ops)},stream_ops:{open(e){var r=fe.ttys[e.node.rdev];if(!r)throw new o.ErrnoError(43);e.tty=r,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,r,t,n,i){if(!e.tty||!e.tty.ops.get_char)throw new o.ErrnoError(60);for(var a=0,s=0;s<n;s++){var c;try{c=e.tty.ops.get_char(e.tty)}catch{throw new o.ErrnoError(29)}if(c===void 0&&a===0)throw new o.ErrnoError(6);if(c==null)break;a++,r[t+s]=c}return a&&(e.node.atime=Date.now()),a},write(e,r,t,n,i){if(!e.tty||!e.tty.ops.put_char)throw new o.ErrnoError(60);try{for(var a=0;a<n;a++)e.tty.ops.put_char(e.tty,r[t+a])}catch{throw new o.ErrnoError(29)}return n&&(e.node.mtime=e.node.ctime=Date.now()),a}},default_tty_ops:{get_char(e){return Ci()},put_char(e,r){r===null||r===10?(ue(Fe(e.output)),e.output=[]):r!=0&&e.output.push(r)},fsync(e){e.output?.length>0&&(ue(Fe(e.output)),e.output=[])},ioctl_tcgets(e){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(e,r,t){return 0},ioctl_tiocgwinsz(e){return[24,80]}},default_tty1_ops:{put_char(e,r){r===null||r===10?(C(Fe(e.output)),e.output=[]):r!=0&&e.output.push(r)},fsync(e){e.output?.length>0&&(C(Fe(e.output)),e.output=[])}}},Nt=e=>{z("internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported")},P={ops_table:null,mount(e){return P.createNode(null,"/",16895,0)},createNode(e,r,t,n){if(o.isBlkdev(t)||o.isFIFO(t))throw new o.ErrnoError(63);P.ops_table||={dir:{node:{getattr:P.node_ops.getattr,setattr:P.node_ops.setattr,lookup:P.node_ops.lookup,mknod:P.node_ops.mknod,rename:P.node_ops.rename,unlink:P.node_ops.unlink,rmdir:P.node_ops.rmdir,readdir:P.node_ops.readdir,symlink:P.node_ops.symlink},stream:{llseek:P.stream_ops.llseek}},file:{node:{getattr:P.node_ops.getattr,setattr:P.node_ops.setattr},stream:{llseek:P.stream_ops.llseek,read:P.stream_ops.read,write:P.stream_ops.write,mmap:P.stream_ops.mmap,msync:P.stream_ops.msync}},link:{node:{getattr:P.node_ops.getattr,setattr:P.node_ops.setattr,readlink:P.node_ops.readlink},stream:{}},chrdev:{node:{getattr:P.node_ops.getattr,setattr:P.node_ops.setattr},stream:o.chrdev_stream_ops}};var i=o.createNode(e,r,t,n);return o.isDir(i.mode)?(i.node_ops=P.ops_table.dir.node,i.stream_ops=P.ops_table.dir.stream,i.contents={}):o.isFile(i.mode)?(i.node_ops=P.ops_table.file.node,i.stream_ops=P.ops_table.file.stream,i.usedBytes=0,i.contents=null):o.isLink(i.mode)?(i.node_ops=P.ops_table.link.node,i.stream_ops=P.ops_table.link.stream):o.isChrdev(i.mode)&&(i.node_ops=P.ops_table.chrdev.node,i.stream_ops=P.ops_table.chrdev.stream),i.atime=i.mtime=i.ctime=Date.now(),e&&(e.contents[r]=i,e.atime=e.mtime=e.ctime=i.atime),i},getFileDataAsTypedArray(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage(e,r){var t=e.contents?e.contents.length:0;if(!(t>=r)){var n=1024*1024;r=Math.max(r,t*(t<n?2:1.125)>>>0),t!=0&&(r=Math.max(r,256));var i=e.contents;e.contents=new Uint8Array(r),e.usedBytes>0&&e.contents.set(i.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,r){if(e.usedBytes!=r)if(r==0)e.contents=null,e.usedBytes=0;else{var t=e.contents;e.contents=new Uint8Array(r),t&&e.contents.set(t.subarray(0,Math.min(r,e.usedBytes))),e.usedBytes=r}},node_ops:{getattr(e){var r={};return r.dev=o.isChrdev(e.mode)?e.id:1,r.ino=e.id,r.mode=e.mode,r.nlink=1,r.uid=0,r.gid=0,r.rdev=e.rdev,o.isDir(e.mode)?r.size=4096:o.isFile(e.mode)?r.size=e.usedBytes:o.isLink(e.mode)?r.size=e.link.length:r.size=0,r.atime=new Date(e.atime),r.mtime=new Date(e.mtime),r.ctime=new Date(e.ctime),r.blksize=4096,r.blocks=Math.ceil(r.size/r.blksize),r},setattr(e,r){for(const t of["mode","atime","mtime","ctime"])r[t]!=null&&(e[t]=r[t]);r.size!==void 0&&P.resizeFileStorage(e,r.size)},lookup(e,r){throw new o.ErrnoError(44)},mknod(e,r,t,n){return P.createNode(e,r,t,n)},rename(e,r,t){var n;try{n=o.lookupNode(r,t)}catch{}if(n){if(o.isDir(e.mode))for(var i in n.contents)throw new o.ErrnoError(55);o.hashRemoveNode(n)}delete e.parent.contents[e.name],r.contents[t]=e,e.name=t,r.ctime=r.mtime=e.parent.ctime=e.parent.mtime=Date.now()},unlink(e,r){delete e.contents[r],e.ctime=e.mtime=Date.now()},rmdir(e,r){var t=o.lookupNode(e,r);for(var n in t.contents)throw new o.ErrnoError(55);delete e.contents[r],e.ctime=e.mtime=Date.now()},readdir(e){return[".","..",...Object.keys(e.contents)]},symlink(e,r,t){var n=P.createNode(e,r,41471,0);return n.link=t,n},readlink(e){if(!o.isLink(e.mode))throw new o.ErrnoError(28);return e.link}},stream_ops:{read(e,r,t,n,i){var a=e.node.contents;if(i>=e.node.usedBytes)return 0;var s=Math.min(e.node.usedBytes-i,n);if(p(s>=0),s>8&&a.subarray)r.set(a.subarray(i,i+s),t);else for(var c=0;c<s;c++)r[t+c]=a[i+c];return s},write(e,r,t,n,i,a){if(p(!(r instanceof ArrayBuffer)),r.buffer===(d(),B).buffer&&(a=!1),!n)return 0;var s=e.node;if(s.mtime=s.ctime=Date.now(),r.subarray&&(!s.contents||s.contents.subarray)){if(a)return p(i===0,"canOwn must imply no weird position inside the file"),s.contents=r.subarray(t,t+n),s.usedBytes=n,n;if(s.usedBytes===0&&i===0)return s.contents=r.slice(t,t+n),s.usedBytes=n,n;if(i+n<=s.usedBytes)return s.contents.set(r.subarray(t,t+n),i),n}if(P.expandFileStorage(s,i+n),s.contents.subarray&&r.subarray)s.contents.set(r.subarray(t,t+n),i);else for(var c=0;c<n;c++)s.contents[i+c]=r[t+c];return s.usedBytes=Math.max(s.usedBytes,i+n),n},llseek(e,r,t){var n=r;if(t===1?n+=e.position:t===2&&o.isFile(e.node.mode)&&(n+=e.node.usedBytes),n<0)throw new o.ErrnoError(28);return n},mmap(e,r,t,n,i){if(!o.isFile(e.node.mode))throw new o.ErrnoError(43);var a,s,c=e.node.contents;if(!(i&2)&&c&&c.buffer===(d(),B).buffer)s=!1,a=c.byteOffset;else{if(s=!0,a=Nt(),!a)throw new o.ErrnoError(48);c&&((t>0||t+r<c.length)&&(c.subarray?c=c.subarray(t,t+r):c=Array.prototype.slice.call(c,t,t+r)),(d(),B).set(c,a))}return{ptr:a,allocated:s}},msync(e,r,t,n,i){return P.stream_ops.write(e,r,0,n,t,!1),0}}},$i=async e=>{var r=await Ze(e);return p(r,`Loading data file "${e}" failed (no arrayBuffer).`),new Uint8Array(r)},Lt=(...e)=>o.createDataFile(...e),Ri=e=>{for(var r=e;;){if(!Te[e])return e;e=r+Math.random()}},Ut=[],Di=(e,r,t,n)=>{typeof Browser<"u"&&Browser.init();var i=!1;return Ut.forEach(a=>{i||a.canHandle(r)&&(a.handle(e,r,t,n),i=!0)}),i},Wt=(e,r,t,n,i,a,s,c,l,u)=>{var f=r?Pe.resolve(O.join2(e,r)):e,h=Ri(`cp ${f}`);function m(_){function g(F){u?.(),c||Lt(e,r,F,n,i,l),a?.(),Be(h)}Di(_,f,g,()=>{s?.(),Be(h)})||g(_)}rr(h),typeof t=="string"?$i(t).then(m,s):m(t)},Oi=e=>{var r={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},t=r[e];if(typeof t>"u")throw new Error(`Unknown file open mode: ${e}`);return t},Ur=(e,r)=>{var t=0;return e&&(t|=365),r&&(t|=146),t},Ii=e=>oe(In(e)),jt={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135},o={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class extends Error{name="ErrnoError";constructor(e){super(We?Ii(e):""),this.errno=e;for(var r in jt)if(jt[r]===e){this.code=r;break}}},FSStream:class{shared={};get object(){return this.node}set object(e){this.node=e}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(e){this.shared.flags=e}get position(){return this.shared.position}set position(e){this.shared.position=e}},FSNode:class{node_ops={};stream_ops={};readMode=365;writeMode=146;mounted=null;constructor(e,r,t,n){e||(e=this),this.parent=e,this.mount=e.mount,this.id=o.nextInode++,this.name=r,this.mode=t,this.rdev=n,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(e){e?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(e){e?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return o.isDir(this.mode)}get isDevice(){return o.isChrdev(this.mode)}},lookupPath(e,r={}){if(!e)throw new o.ErrnoError(44);r.follow_mount??=!0,O.isAbs(e)||(e=o.cwd()+"/"+e);e:for(var t=0;t<40;t++){for(var n=e.split("/").filter(u=>!!u),i=o.root,a="/",s=0;s<n.length;s++){var c=s===n.length-1;if(c&&r.parent)break;if(n[s]!=="."){if(n[s]===".."){if(a=O.dirname(a),o.isRoot(i)){e=a+"/"+n.slice(s+1).join("/");continue e}else i=i.parent;continue}a=O.join2(a,n[s]);try{i=o.lookupNode(i,n[s])}catch(u){if(u?.errno===44&&c&&r.noent_okay)return{path:a};throw u}if(o.isMountpoint(i)&&(!c||r.follow_mount)&&(i=i.mounted.root),o.isLink(i.mode)&&(!c||r.follow)){if(!i.node_ops.readlink)throw new o.ErrnoError(52);var l=i.node_ops.readlink(i);O.isAbs(l)||(l=O.dirname(a)+"/"+l),e=l+"/"+n.slice(s+1).join("/");continue e}}}return{path:a,node:i}}throw new o.ErrnoError(32)},getPath(e){for(var r;;){if(o.isRoot(e)){var t=e.mount.mountpoint;return r?t[t.length-1]!=="/"?`${t}/${r}`:t+r:t}r=r?`${e.name}/${r}`:e.name,e=e.parent}},hashName(e,r){for(var t=0,n=0;n<r.length;n++)t=(t<<5)-t+r.charCodeAt(n)|0;return(e+t>>>0)%o.nameTable.length},hashAddNode(e){var r=o.hashName(e.parent.id,e.name);e.name_next=o.nameTable[r],o.nameTable[r]=e},hashRemoveNode(e){var r=o.hashName(e.parent.id,e.name);if(o.nameTable[r]===e)o.nameTable[r]=e.name_next;else for(var t=o.nameTable[r];t;){if(t.name_next===e){t.name_next=e.name_next;break}t=t.name_next}},lookupNode(e,r){var t=o.mayLookup(e);if(t)throw new o.ErrnoError(t);for(var n=o.hashName(e.id,r),i=o.nameTable[n];i;i=i.name_next){var a=i.name;if(i.parent.id===e.id&&a===r)return i}return o.lookup(e,r)},createNode(e,r,t,n){p(typeof e=="object");var i=new o.FSNode(e,r,t,n);return o.hashAddNode(i),i},destroyNode(e){o.hashRemoveNode(e)},isRoot(e){return e===e.parent},isMountpoint(e){return!!e.mounted},isFile(e){return(e&61440)===32768},isDir(e){return(e&61440)===16384},isLink(e){return(e&61440)===40960},isChrdev(e){return(e&61440)===8192},isBlkdev(e){return(e&61440)===24576},isFIFO(e){return(e&61440)===4096},isSocket(e){return(e&49152)===49152},flagsToPermissionString(e){var r=["r","w","rw"][e&3];return e&512&&(r+="w"),r},nodePermissions(e,r){return o.ignorePermissions?0:r.includes("r")&&!(e.mode&292)||r.includes("w")&&!(e.mode&146)||r.includes("x")&&!(e.mode&73)?2:0},mayLookup(e){if(!o.isDir(e.mode))return 54;var r=o.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate(e,r){if(!o.isDir(e.mode))return 54;try{var t=o.lookupNode(e,r);return 20}catch{}return o.nodePermissions(e,"wx")},mayDelete(e,r,t){var n;try{n=o.lookupNode(e,r)}catch(a){return a.errno}var i=o.nodePermissions(e,"wx");if(i)return i;if(t){if(!o.isDir(n.mode))return 54;if(o.isRoot(n)||o.getPath(n)===o.cwd())return 10}else if(o.isDir(n.mode))return 31;return 0},mayOpen(e,r){return e?o.isLink(e.mode)?32:o.isDir(e.mode)&&(o.flagsToPermissionString(r)!=="r"||r&576)?31:o.nodePermissions(e,o.flagsToPermissionString(r)):44},checkOpExists(e,r){if(!e)throw new o.ErrnoError(r);return e},MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=o.MAX_OPEN_FDS;e++)if(!o.streams[e])return e;throw new o.ErrnoError(33)},getStreamChecked(e){var r=o.getStream(e);if(!r)throw new o.ErrnoError(8);return r},getStream:e=>o.streams[e],createStream(e,r=-1){return p(r>=-1),e=Object.assign(new o.FSStream,e),r==-1&&(r=o.nextfd()),e.fd=r,o.streams[r]=e,e},closeStream(e){o.streams[e]=null},dupStream(e,r=-1){var t=o.createStream(e,r);return t.stream_ops?.dup?.(t),t},doSetAttr(e,r,t){var n=e?.stream_ops.setattr,i=n?e:r;n??=r.node_ops.setattr,o.checkOpExists(n,63),n(i,t)},chrdev_stream_ops:{open(e){var r=o.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,e.stream_ops.open?.(e)},llseek(){throw new o.ErrnoError(70)}},major:e=>e>>8,minor:e=>e&255,makedev:(e,r)=>e<<8|r,registerDevice(e,r){o.devices[e]={stream_ops:r}},getDevice:e=>o.devices[e],getMounts(e){for(var r=[],t=[e];t.length;){var n=t.pop();r.push(n),t.push(...n.mounts)}return r},syncfs(e,r){typeof e=="function"&&(r=e,e=!1),o.syncFSRequests++,o.syncFSRequests>1&&C(`warning: ${o.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var t=o.getMounts(o.root.mount),n=0;function i(s){return p(o.syncFSRequests>0),o.syncFSRequests--,r(s)}function a(s){if(s)return a.errored?void 0:(a.errored=!0,i(s));++n>=t.length&&i(null)}t.forEach(s=>{if(!s.type.syncfs)return a(null);s.type.syncfs(s,e,a)})},mount(e,r,t){if(typeof e=="string")throw e;var n=t==="/",i=!t,a;if(n&&o.root)throw new o.ErrnoError(10);if(!n&&!i){var s=o.lookupPath(t,{follow_mount:!1});if(t=s.path,a=s.node,o.isMountpoint(a))throw new o.ErrnoError(10);if(!o.isDir(a.mode))throw new o.ErrnoError(54)}var c={type:e,opts:r,mountpoint:t,mounts:[]},l=e.mount(c);return l.mount=c,c.root=l,n?o.root=l:a&&(a.mounted=c,a.mount&&a.mount.mounts.push(c)),l},unmount(e){var r=o.lookupPath(e,{follow_mount:!1});if(!o.isMountpoint(r.node))throw new o.ErrnoError(28);var t=r.node,n=t.mounted,i=o.getMounts(n);Object.keys(o.nameTable).forEach(s=>{for(var c=o.nameTable[s];c;){var l=c.name_next;i.includes(c.mount)&&o.destroyNode(c),c=l}}),t.mounted=null;var a=t.mount.mounts.indexOf(n);p(a!==-1),t.mount.mounts.splice(a,1)},lookup(e,r){return e.node_ops.lookup(e,r)},mknod(e,r,t){var n=o.lookupPath(e,{parent:!0}),i=n.node,a=O.basename(e);if(!a)throw new o.ErrnoError(28);if(a==="."||a==="..")throw new o.ErrnoError(20);var s=o.mayCreate(i,a);if(s)throw new o.ErrnoError(s);if(!i.node_ops.mknod)throw new o.ErrnoError(63);return i.node_ops.mknod(i,a,r,t)},statfs(e){return o.statfsNode(o.lookupPath(e,{follow:!0}).node)},statfsStream(e){return o.statfsNode(e.node)},statfsNode(e){var r={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:o.nextInode,ffree:o.nextInode-1,fsid:42,flags:2,namelen:255};return e.node_ops.statfs&&Object.assign(r,e.node_ops.statfs(e.mount.opts.root)),r},create(e,r=438){return r&=4095,r|=32768,o.mknod(e,r,0)},mkdir(e,r=511){return r&=1023,r|=16384,o.mknod(e,r,0)},mkdirTree(e,r){var t=e.split("/"),n="";for(var i of t)if(i){(n||O.isAbs(e))&&(n+="/"),n+=i;try{o.mkdir(n,r)}catch(a){if(a.errno!=20)throw a}}},mkdev(e,r,t){return typeof t>"u"&&(t=r,r=438),r|=8192,o.mknod(e,r,t)},symlink(e,r){if(!Pe.resolve(e))throw new o.ErrnoError(44);var t=o.lookupPath(r,{parent:!0}),n=t.node;if(!n)throw new o.ErrnoError(44);var i=O.basename(r),a=o.mayCreate(n,i);if(a)throw new o.ErrnoError(a);if(!n.node_ops.symlink)throw new o.ErrnoError(63);return n.node_ops.symlink(n,i,e)},rename(e,r){var t=O.dirname(e),n=O.dirname(r),i=O.basename(e),a=O.basename(r),s,c,l;if(s=o.lookupPath(e,{parent:!0}),c=s.node,s=o.lookupPath(r,{parent:!0}),l=s.node,!c||!l)throw new o.ErrnoError(44);if(c.mount!==l.mount)throw new o.ErrnoError(75);var u=o.lookupNode(c,i),f=Pe.relative(e,n);if(f.charAt(0)!==".")throw new o.ErrnoError(28);if(f=Pe.relative(r,t),f.charAt(0)!==".")throw new o.ErrnoError(55);var h;try{h=o.lookupNode(l,a)}catch{}if(u!==h){var m=o.isDir(u.mode),_=o.mayDelete(c,i,m);if(_)throw new o.ErrnoError(_);if(_=h?o.mayDelete(l,a,m):o.mayCreate(l,a),_)throw new o.ErrnoError(_);if(!c.node_ops.rename)throw new o.ErrnoError(63);if(o.isMountpoint(u)||h&&o.isMountpoint(h))throw new o.ErrnoError(10);if(l!==c&&(_=o.nodePermissions(c,"w"),_))throw new o.ErrnoError(_);o.hashRemoveNode(u);try{c.node_ops.rename(u,l,a),u.parent=l}catch(g){throw g}finally{o.hashAddNode(u)}}},rmdir(e){var r=o.lookupPath(e,{parent:!0}),t=r.node,n=O.basename(e),i=o.lookupNode(t,n),a=o.mayDelete(t,n,!0);if(a)throw new o.ErrnoError(a);if(!t.node_ops.rmdir)throw new o.ErrnoError(63);if(o.isMountpoint(i))throw new o.ErrnoError(10);t.node_ops.rmdir(t,n),o.destroyNode(i)},readdir(e){var r=o.lookupPath(e,{follow:!0}),t=r.node,n=o.checkOpExists(t.node_ops.readdir,54);return n(t)},unlink(e){var r=o.lookupPath(e,{parent:!0}),t=r.node;if(!t)throw new o.ErrnoError(44);var n=O.basename(e),i=o.lookupNode(t,n),a=o.mayDelete(t,n,!1);if(a)throw new o.ErrnoError(a);if(!t.node_ops.unlink)throw new o.ErrnoError(63);if(o.isMountpoint(i))throw new o.ErrnoError(10);t.node_ops.unlink(t,n),o.destroyNode(i)},readlink(e){var r=o.lookupPath(e),t=r.node;if(!t)throw new o.ErrnoError(44);if(!t.node_ops.readlink)throw new o.ErrnoError(28);return t.node_ops.readlink(t)},stat(e,r){var t=o.lookupPath(e,{follow:!r}),n=t.node,i=o.checkOpExists(n.node_ops.getattr,63);return i(n)},fstat(e){var r=o.getStreamChecked(e),t=r.node,n=r.stream_ops.getattr,i=n?r:t;return n??=t.node_ops.getattr,o.checkOpExists(n,63),n(i)},lstat(e){return o.stat(e,!0)},doChmod(e,r,t,n){o.doSetAttr(e,r,{mode:t&4095|r.mode&-4096,ctime:Date.now(),dontFollow:n})},chmod(e,r,t){var n;if(typeof e=="string"){var i=o.lookupPath(e,{follow:!t});n=i.node}else n=e;o.doChmod(null,n,r,t)},lchmod(e,r){o.chmod(e,r,!0)},fchmod(e,r){var t=o.getStreamChecked(e);o.doChmod(t,t.node,r,!1)},doChown(e,r,t){o.doSetAttr(e,r,{timestamp:Date.now(),dontFollow:t})},chown(e,r,t,n){var i;if(typeof e=="string"){var a=o.lookupPath(e,{follow:!n});i=a.node}else i=e;o.doChown(null,i,n)},lchown(e,r,t){o.chown(e,r,t,!0)},fchown(e,r,t){var n=o.getStreamChecked(e);o.doChown(n,n.node,!1)},doTruncate(e,r,t){if(o.isDir(r.mode))throw new o.ErrnoError(31);if(!o.isFile(r.mode))throw new o.ErrnoError(28);var n=o.nodePermissions(r,"w");if(n)throw new o.ErrnoError(n);o.doSetAttr(e,r,{size:t,timestamp:Date.now()})},truncate(e,r){if(r<0)throw new o.ErrnoError(28);var t;if(typeof e=="string"){var n=o.lookupPath(e,{follow:!0});t=n.node}else t=e;o.doTruncate(null,t,r)},ftruncate(e,r){var t=o.getStreamChecked(e);if(r<0||(t.flags&2097155)===0)throw new o.ErrnoError(28);o.doTruncate(t,t.node,r)},utime(e,r,t){var n=o.lookupPath(e,{follow:!0}),i=n.node,a=o.checkOpExists(i.node_ops.setattr,63);a(i,{atime:r,mtime:t})},open(e,r,t=438){if(e==="")throw new o.ErrnoError(44);r=typeof r=="string"?Oi(r):r,r&64?t=t&4095|32768:t=0;var n,i;if(typeof e=="object")n=e;else{i=e.endsWith("/");var a=o.lookupPath(e,{follow:!(r&131072),noent_okay:!0});n=a.node,e=a.path}var s=!1;if(r&64)if(n){if(r&128)throw new o.ErrnoError(20)}else{if(i)throw new o.ErrnoError(31);n=o.mknod(e,t|511,0),s=!0}if(!n)throw new o.ErrnoError(44);if(o.isChrdev(n.mode)&&(r&=-513),r&65536&&!o.isDir(n.mode))throw new o.ErrnoError(54);if(!s){var c=o.mayOpen(n,r);if(c)throw new o.ErrnoError(c)}r&512&&!s&&o.truncate(n,0),r&=-131713;var l=o.createStream({node:n,path:o.getPath(n),flags:r,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return l.stream_ops.open&&l.stream_ops.open(l),s&&o.chmod(n,t&511),v.logReadFiles&&!(r&1)&&(e in o.readFiles||(o.readFiles[e]=1)),l},close(e){if(o.isClosed(e))throw new o.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(r){throw r}finally{o.closeStream(e.fd)}e.fd=null},isClosed(e){return e.fd===null},llseek(e,r,t){if(o.isClosed(e))throw new o.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new o.ErrnoError(70);if(t!=0&&t!=1&&t!=2)throw new o.ErrnoError(28);return e.position=e.stream_ops.llseek(e,r,t),e.ungotten=[],e.position},read(e,r,t,n,i){if(p(t>=0),n<0||i<0)throw new o.ErrnoError(28);if(o.isClosed(e))throw new o.ErrnoError(8);if((e.flags&2097155)===1)throw new o.ErrnoError(8);if(o.isDir(e.node.mode))throw new o.ErrnoError(31);if(!e.stream_ops.read)throw new o.ErrnoError(28);var a=typeof i<"u";if(!a)i=e.position;else if(!e.seekable)throw new o.ErrnoError(70);var s=e.stream_ops.read(e,r,t,n,i);return a||(e.position+=s),s},write(e,r,t,n,i,a){if(p(t>=0),n<0||i<0)throw new o.ErrnoError(28);if(o.isClosed(e))throw new o.ErrnoError(8);if((e.flags&2097155)===0)throw new o.ErrnoError(8);if(o.isDir(e.node.mode))throw new o.ErrnoError(31);if(!e.stream_ops.write)throw new o.ErrnoError(28);e.seekable&&e.flags&1024&&o.llseek(e,0,2);var s=typeof i<"u";if(!s)i=e.position;else if(!e.seekable)throw new o.ErrnoError(70);var c=e.stream_ops.write(e,r,t,n,i,a);return s||(e.position+=c),c},mmap(e,r,t,n,i){if((n&2)!==0&&(i&2)===0&&(e.flags&2097155)!==2)throw new o.ErrnoError(2);if((e.flags&2097155)===1)throw new o.ErrnoError(2);if(!e.stream_ops.mmap)throw new o.ErrnoError(43);if(!r)throw new o.ErrnoError(28);return e.stream_ops.mmap(e,r,t,n,i)},msync(e,r,t,n,i){return p(t>=0),e.stream_ops.msync?e.stream_ops.msync(e,r,t,n,i):0},ioctl(e,r,t){if(!e.stream_ops.ioctl)throw new o.ErrnoError(59);return e.stream_ops.ioctl(e,r,t)},readFile(e,r={}){if(r.flags=r.flags||0,r.encoding=r.encoding||"binary",r.encoding!=="utf8"&&r.encoding!=="binary")throw new Error(`Invalid encoding type "${r.encoding}"`);var t=o.open(e,r.flags),n=o.stat(e),i=n.size,a=new Uint8Array(i);return o.read(t,a,0,i,0),r.encoding==="utf8"&&(a=Fe(a)),o.close(t),a},writeFile(e,r,t={}){t.flags=t.flags||577;var n=o.open(e,t.flags,t.mode);if(typeof r=="string"&&(r=new Uint8Array(Lr(r))),ArrayBuffer.isView(r))o.write(n,r,0,r.byteLength,void 0,t.canOwn);else throw new Error("Unsupported data type");o.close(n)},cwd:()=>o.currentPath,chdir(e){var r=o.lookupPath(e,{follow:!0});if(r.node===null)throw new o.ErrnoError(44);if(!o.isDir(r.node.mode))throw new o.ErrnoError(54);var t=o.nodePermissions(r.node,"x");if(t)throw new o.ErrnoError(t);o.currentPath=r.path},createDefaultDirectories(){o.mkdir("/tmp"),o.mkdir("/home"),o.mkdir("/home/web_user")},createDefaultDevices(){o.mkdir("/dev"),o.registerDevice(o.makedev(1,3),{read:()=>0,write:(n,i,a,s,c)=>s,llseek:()=>0}),o.mkdev("/dev/null",o.makedev(1,3)),fe.register(o.makedev(5,0),fe.default_tty_ops),fe.register(o.makedev(6,0),fe.default_tty1_ops),o.mkdev("/dev/tty",o.makedev(5,0)),o.mkdev("/dev/tty1",o.makedev(6,0));var e=new Uint8Array(1024),r=0,t=()=>(r===0&&(Mt(e),r=e.byteLength),e[--r]);o.createDevice("/dev","random",t),o.createDevice("/dev","urandom",t),o.mkdir("/dev/shm"),o.mkdir("/dev/shm/tmp")},createSpecialDirectories(){o.mkdir("/proc");var e=o.mkdir("/proc/self");o.mkdir("/proc/self/fd"),o.mount({mount(){var r=o.createNode(e,"fd",16895,73);return r.stream_ops={llseek:P.stream_ops.llseek},r.node_ops={lookup(t,n){var i=+n,a=o.getStreamChecked(i),s={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>a.path},id:i+1};return s.parent=s,s},readdir(){return Array.from(o.streams.entries()).filter(([t,n])=>n).map(([t,n])=>t.toString())}},r}},{},"/proc/self/fd")},createStandardStreams(e,r,t){e?o.createDevice("/dev","stdin",e):o.symlink("/dev/tty","/dev/stdin"),r?o.createDevice("/dev","stdout",null,r):o.symlink("/dev/tty","/dev/stdout"),t?o.createDevice("/dev","stderr",null,t):o.symlink("/dev/tty1","/dev/stderr");var n=o.open("/dev/stdin",0),i=o.open("/dev/stdout",1),a=o.open("/dev/stderr",1);p(n.fd===0,`invalid handle for stdin (${n.fd})`),p(i.fd===1,`invalid handle for stdout (${i.fd})`),p(a.fd===2,`invalid handle for stderr (${a.fd})`)},staticInit(){o.nameTable=new Array(4096),o.mount(P,{},"/"),o.createDefaultDirectories(),o.createDefaultDevices(),o.createSpecialDirectories(),o.filesystems={MEMFS:P}},init(e,r,t){p(!o.initialized,"FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"),o.initialized=!0,e??=v.stdin,r??=v.stdout,t??=v.stderr,o.createStandardStreams(e,r,t)},quit(){o.initialized=!1,et(0);for(var e of o.streams)e&&o.close(e)},findObject(e,r){var t=o.analyzePath(e,r);return t.exists?t.object:null},analyzePath(e,r){try{var t=o.lookupPath(e,{follow:!r});e=t.path}catch{}var n={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var t=o.lookupPath(e,{parent:!0});n.parentExists=!0,n.parentPath=t.path,n.parentObject=t.node,n.name=O.basename(e),t=o.lookupPath(e,{follow:!r}),n.exists=!0,n.path=t.path,n.object=t.node,n.name=t.node.name,n.isRoot=t.path==="/"}catch(i){n.error=i.errno}return n},createPath(e,r,t,n){e=typeof e=="string"?e:o.getPath(e);for(var i=r.split("/").reverse();i.length;){var a=i.pop();if(a){var s=O.join2(e,a);try{o.mkdir(s)}catch(c){if(c.errno!=20)throw c}e=s}}return s},createFile(e,r,t,n,i){var a=O.join2(typeof e=="string"?e:o.getPath(e),r),s=Ur(n,i);return o.create(a,s)},createDataFile(e,r,t,n,i,a){var s=r;e&&(e=typeof e=="string"?e:o.getPath(e),s=r?O.join2(e,r):e);var c=Ur(n,i),l=o.create(s,c);if(t){if(typeof t=="string"){for(var u=new Array(t.length),f=0,h=t.length;f<h;++f)u[f]=t.charCodeAt(f);t=u}o.chmod(l,c|146);var m=o.open(l,577);o.write(m,t,0,t.length,0,a),o.close(m),o.chmod(l,c)}},createDevice(e,r,t,n){var i=O.join2(typeof e=="string"?e:o.getPath(e),r),a=Ur(!!t,!!n);o.createDevice.major??=64;var s=o.makedev(o.createDevice.major++,0);return o.registerDevice(s,{open(c){c.seekable=!1},close(c){n?.buffer?.length&&n(10)},read(c,l,u,f,h){for(var m=0,_=0;_<f;_++){var g;try{g=t()}catch{throw new o.ErrnoError(29)}if(g===void 0&&m===0)throw new o.ErrnoError(6);if(g==null)break;m++,l[u+_]=g}return m&&(c.node.atime=Date.now()),m},write(c,l,u,f,h){for(var m=0;m<f;m++)try{n(l[u+m])}catch{throw new o.ErrnoError(29)}return f&&(c.node.mtime=c.node.ctime=Date.now()),m}}),o.mkdev(i,a,s)},forceLoadFile(e){if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if(typeof XMLHttpRequest<"u")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.");try{e.contents=Oe(e.url),e.usedBytes=e.contents.length}catch{throw new o.ErrnoError(29)}},createLazyFile(e,r,t,n,i){class a{lengthKnown=!1;chunks=[];get(_){if(!(_>this.length-1||_<0)){var g=_%this.chunkSize,F=_/this.chunkSize|0;return this.getter(F)[g]}}setDataGetter(_){this.getter=_}cacheLength(){var _=new XMLHttpRequest;if(_.open("HEAD",t,!1),_.send(null),!(_.status>=200&&_.status<300||_.status===304))throw new Error("Couldn't load "+t+". Status: "+_.status);var g=Number(_.getResponseHeader("Content-length")),F,I=(F=_.getResponseHeader("Accept-Ranges"))&&F==="bytes",D=(F=_.getResponseHeader("Content-Encoding"))&&F==="gzip",H=1024*1024;I||(H=g);var x=(q,le)=>{if(q>le)throw new Error("invalid range ("+q+", "+le+") or no bytes requested!");if(le>g-1)throw new Error("only "+g+" bytes available! programmer error!");var L=new XMLHttpRequest;if(L.open("GET",t,!1),g!==H&&L.setRequestHeader("Range","bytes="+q+"-"+le),L.responseType="arraybuffer",L.overrideMimeType&&L.overrideMimeType("text/plain; charset=x-user-defined"),L.send(null),!(L.status>=200&&L.status<300||L.status===304))throw new Error("Couldn't load "+t+". Status: "+L.status);return L.response!==void 0?new Uint8Array(L.response||[]):Lr(L.responseText||"")},be=this;be.setDataGetter(q=>{var le=q*H,L=(q+1)*H-1;if(L=Math.min(L,g-1),typeof be.chunks[q]>"u"&&(be.chunks[q]=x(le,L)),typeof be.chunks[q]>"u")throw new Error("doXHR failed!");return be.chunks[q]}),(D||!g)&&(H=g=1,g=this.getter(0).length,H=g,ue("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=g,this._chunkSize=H,this.lengthKnown=!0}get length(){return this.lengthKnown||this.cacheLength(),this._length}get chunkSize(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}if(typeof XMLHttpRequest<"u"){if(!Z)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s=new a,c={isDevice:!1,contents:s}}else var c={isDevice:!1,url:t};var l=o.createFile(e,r,c,n,i);c.contents?l.contents=c.contents:c.url&&(l.contents=null,l.url=c.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var u={},f=Object.keys(l.stream_ops);f.forEach(m=>{var _=l.stream_ops[m];u[m]=(...g)=>(o.forceLoadFile(l),_(...g))});function h(m,_,g,F,I){var D=m.node.contents;if(I>=D.length)return 0;var H=Math.min(D.length-I,F);if(p(H>=0),D.slice)for(var x=0;x<H;x++)_[g+x]=D[I+x];else for(var x=0;x<H;x++)_[g+x]=D.get(I+x);return H}return u.read=(m,_,g,F,I)=>(o.forceLoadFile(l),h(m,_,g,F,I)),u.mmap=(m,_,g,F,I)=>{o.forceLoadFile(l);var D=Nt();if(!D)throw new o.ErrnoError(48);return h(m,(d(),B),D,_,g),{ptr:D,allocated:!0}},l.stream_ops=u,l},absolutePath(){z("FS.absolutePath has been removed; use PATH_FS.resolve instead")},createFolder(){z("FS.createFolder has been removed; use FS.mkdir instead")},createLink(){z("FS.createLink has been removed; use FS.symlink instead")},joinPath(){z("FS.joinPath has been removed; use PATH.join instead")},mmapAlloc(){z("FS.mmapAlloc has been replaced by the top level function mmapAlloc")},standardizePath(){z("FS.standardizePath has been removed; use PATH.normalize instead")}},N={DEFAULT_POLLMASK:5,calculateAt(e,r,t){if(O.isAbs(r))return r;var n;if(e===-100)n=o.cwd();else{var i=N.getStreamFromFD(e);n=i.path}if(r.length==0){if(!t)throw new o.ErrnoError(44);return n}return n+"/"+r},writeStat(e,r){(d(),S)[e>>2]=r.dev,(d(),S)[e+4>>2]=r.mode,(d(),T)[e+8>>2]=r.nlink,(d(),S)[e+12>>2]=r.uid,(d(),S)[e+16>>2]=r.gid,(d(),S)[e+20>>2]=r.rdev,(d(),Y)[e+24>>3]=BigInt(r.size),(d(),S)[e+32>>2]=4096,(d(),S)[e+36>>2]=r.blocks;var t=r.atime.getTime(),n=r.mtime.getTime(),i=r.ctime.getTime();return(d(),Y)[e+40>>3]=BigInt(Math.floor(t/1e3)),(d(),T)[e+48>>2]=t%1e3*1e3*1e3,(d(),Y)[e+56>>3]=BigInt(Math.floor(n/1e3)),(d(),T)[e+64>>2]=n%1e3*1e3*1e3,(d(),Y)[e+72>>3]=BigInt(Math.floor(i/1e3)),(d(),T)[e+80>>2]=i%1e3*1e3*1e3,(d(),Y)[e+88>>3]=BigInt(r.ino),0},writeStatFs(e,r){(d(),S)[e+4>>2]=r.bsize,(d(),S)[e+40>>2]=r.bsize,(d(),S)[e+8>>2]=r.blocks,(d(),S)[e+12>>2]=r.bfree,(d(),S)[e+16>>2]=r.bavail,(d(),S)[e+20>>2]=r.files,(d(),S)[e+24>>2]=r.ffree,(d(),S)[e+28>>2]=r.fsid,(d(),S)[e+44>>2]=r.flags,(d(),S)[e+36>>2]=r.namelen},doMsync(e,r,t,n,i){if(!o.isFile(r.node.mode))throw new o.ErrnoError(43);if(n&2)return 0;var a=(d(),K).slice(e,e+t);o.msync(r,a,i,t,n)},getStreamFromFD(e){var r=o.getStreamChecked(e);return r},varargs:void 0,getStr(e){var r=oe(e);return r}};function Bt(e,r,t){if(A)return G(2,0,1,e,r,t);try{var n=N.getStreamFromFD(e);if(p(!t),n.fd===r)return-28;if(r<0||r>=o.MAX_OPEN_FDS)return-8;var i=o.getStream(r);return i&&o.close(i),o.dupStream(n,r).fd}catch(a){if(typeof o>"u"||a.name!=="ErrnoError")throw a;return-a.errno}}var cr=()=>{p(N.varargs!=null);var e=(d(),S)[+N.varargs>>2];return N.varargs+=4,e},Ce=cr;function zt(e,r,t){if(A)return G(3,0,1,e,r,t);N.varargs=t;try{var n=N.getStreamFromFD(e);switch(r){case 0:{var i=cr();if(i<0)return-28;for(;o.streams[i];)i++;var a;return a=o.dupStream(n,i),a.fd}case 1:case 2:return 0;case 3:return n.flags;case 4:{var i=cr();return n.flags|=i,0}case 12:{var i=Ce(),s=0;return(d(),de)[i+s>>1]=2,0}case 13:case 14:return 0}return-28}catch(c){if(typeof o>"u"||c.name!=="ErrnoError")throw c;return-c.errno}}function Ht(e,r){if(A)return G(4,0,1,e,r);try{return N.writeStat(r,o.fstat(e))}catch(t){if(typeof o>"u"||t.name!=="ErrnoError")throw t;return-t.errno}}function Vt(e,r,t){if(A)return G(5,0,1,e,r,t);N.varargs=t;try{var n=N.getStreamFromFD(e);switch(r){case 21509:return n.tty?0:-59;case 21505:{if(!n.tty)return-59;if(n.tty.ops.ioctl_tcgets){var i=n.tty.ops.ioctl_tcgets(n),a=Ce();(d(),S)[a>>2]=i.c_iflag||0,(d(),S)[a+4>>2]=i.c_oflag||0,(d(),S)[a+8>>2]=i.c_cflag||0,(d(),S)[a+12>>2]=i.c_lflag||0;for(var s=0;s<32;s++)(d(),B)[a+s+17]=i.c_cc[s]||0;return 0}return 0}case 21510:case 21511:case 21512:return n.tty?0:-59;case 21506:case 21507:case 21508:{if(!n.tty)return-59;if(n.tty.ops.ioctl_tcsets){for(var a=Ce(),c=(d(),S)[a>>2],l=(d(),S)[a+4>>2],u=(d(),S)[a+8>>2],f=(d(),S)[a+12>>2],h=[],s=0;s<32;s++)h.push((d(),B)[a+s+17]);return n.tty.ops.ioctl_tcsets(n.tty,r,{c_iflag:c,c_oflag:l,c_cflag:u,c_lflag:f,c_cc:h})}return 0}case 21519:{if(!n.tty)return-59;var a=Ce();return(d(),S)[a>>2]=0,0}case 21520:return n.tty?-28:-59;case 21531:{var a=Ce();return o.ioctl(n,r,a)}case 21523:{if(!n.tty)return-59;if(n.tty.ops.ioctl_tiocgwinsz){var m=n.tty.ops.ioctl_tiocgwinsz(n.tty),a=Ce();(d(),de)[a>>1]=m[0],(d(),de)[a+2>>1]=m[1]}return 0}case 21524:return n.tty?0:-59;case 21515:return n.tty?0:-59;default:return-28}}catch(_){if(typeof o>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function Gt(e,r){if(A)return G(6,0,1,e,r);try{return e=N.getStr(e),N.writeStat(r,o.lstat(e))}catch(t){if(typeof o>"u"||t.name!=="ErrnoError")throw t;return-t.errno}}function Yt(e,r,t,n){if(A)return G(7,0,1,e,r,t,n);try{r=N.getStr(r);var i=n&256,a=n&4096;return n=n&-6401,p(!n,`unknown flags in __syscall_newfstatat: ${n}`),r=N.calculateAt(e,r,a),N.writeStat(t,i?o.lstat(r):o.stat(r))}catch(s){if(typeof o>"u"||s.name!=="ErrnoError")throw s;return-s.errno}}function qt(e,r,t,n){if(A)return G(8,0,1,e,r,t,n);N.varargs=n;try{r=N.getStr(r),r=N.calculateAt(e,r);var i=n?cr():0;return o.open(r,t,i).fd}catch(a){if(typeof o>"u"||a.name!=="ErrnoError")throw a;return-a.errno}}function Kt(e,r){if(A)return G(9,0,1,e,r);try{return e=N.getStr(e),N.writeStat(r,o.stat(e))}catch(t){if(typeof o>"u"||t.name!=="ErrnoError")throw t;return-t.errno}}var Mi=()=>z("native code called abort()"),W=e=>{for(var r="";;){var t=(d(),K)[e++];if(!t)return r;r+=String.fromCharCode(t)}},$e={},me={},lr={},Ge=class extends Error{constructor(r){super(r),this.name="BindingError"}},R=e=>{throw new Ge(e)};function xi(e,r,t={}){var n=r.name;if(e||R(`type "${n}" must have a positive integer typeid pointer`),me.hasOwnProperty(e)){if(t.ignoreDuplicateRegistrations)return;R(`Cannot register type '${n}' twice`)}if(me[e]=r,delete lr[e],$e.hasOwnProperty(e)){var i=$e[e];delete $e[e],i.forEach(a=>a())}}function X(e,r,t={}){if(r.argPackAdvance===void 0)throw new TypeError("registerType registeredInstance requires argPackAdvance");return xi(e,r,t)}var Xt=(e,r,t)=>{switch(r){case 1:return t?n=>(d(),B)[n]:n=>(d(),K)[n];case 2:return t?n=>(d(),de)[n>>1]:n=>(d(),ie)[n>>1];case 4:return t?n=>(d(),S)[n>>2]:n=>(d(),T)[n>>2];case 8:return t?n=>(d(),Y)[n>>3]:n=>(d(),Et)[n>>3];default:throw new TypeError(`invalid integer width (${r}): ${e}`)}},ge=e=>{if(e===null)return"null";var r=typeof e;return r==="object"||r==="array"||r==="function"?e.toString():""+e},Jt=(e,r,t,n)=>{if(r<t||r>n)throw new TypeError(`Passing a number "${ge(r)}" from JS side to C/C++ side to an argument of type "${e}", which is outside the valid range [${t}, ${n}]!`)},Ni=(e,r,t,n,i)=>{r=W(r);const a=n===0n;let s=c=>c;if(a){const c=t*8;s=l=>BigInt.asUintN(c,l),i=s(i)}X(e,{name:r,fromWireType:s,toWireType:(c,l)=>{if(typeof l=="number")l=BigInt(l);else if(typeof l!="bigint")throw new TypeError(`Cannot convert "${ge(l)}" to ${this.name}`);return Jt(r,l,n,i),l},argPackAdvance:ee,readValueFromPointer:Xt(r,t,!a),destructorFunction:null})},ee=8,Li=(e,r,t,n)=>{r=W(r),X(e,{name:r,fromWireType:function(i){return!!i},toWireType:function(i,a){return a?t:n},argPackAdvance:ee,readValueFromPointer:function(i){return this.fromWireType((d(),K)[i])},destructorFunction:null})},Ui=e=>({count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType}),Wr=e=>{function r(t){return t.$$.ptrType.registeredClass.name}R(r(e)+" instance already deleted")},jr=!1,Zt=e=>{},Wi=e=>{e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)},Qt=e=>{e.count.value-=1;var r=e.count.value===0;r&&Wi(e)},en=(e,r,t)=>{if(r===t)return e;if(t.baseClass===void 0)return null;var n=en(e,r,t.baseClass);return n===null?null:t.downcast(n)},rn={},ji={},Bi=(e,r)=>{for(r===void 0&&R("ptr should not be undefined");e.baseClass;)r=e.upcast(r),e=e.baseClass;return r},zi=(e,r)=>(r=Bi(e,r),ji[r]),Hi=class extends Error{constructor(r){super(r),this.name="InternalError"}},ur=e=>{throw new Hi(e)},dr=(e,r)=>{(!r.ptrType||!r.ptr)&&ur("makeClassHandle requires ptr and ptrType");var t=!!r.smartPtrType,n=!!r.smartPtr;return t!==n&&ur("Both smartPtrType and smartPtr must be specified"),r.count={value:1},Ye(Object.create(e,{$$:{value:r,writable:!0}}))};function tn(e){var r=this.getPointee(e);if(!r)return this.destructor(e),null;var t=zi(this.registeredClass,r);if(t!==void 0){if(t.$$.count.value===0)return t.$$.ptr=r,t.$$.smartPtr=e,t.clone();var n=t.clone();return this.destructor(e),n}function i(){return this.isSmartPointer?dr(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:e}):dr(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var a=this.registeredClass.getActualType(r),s=rn[a];if(!s)return i.call(this);var c;this.isConst?c=s.constPointerType:c=s.pointerType;var l=en(r,this.registeredClass,c.registeredClass);return l===null?i.call(this):this.isSmartPointer?dr(c.registeredClass.instancePrototype,{ptrType:c,ptr:l,smartPtrType:this,smartPtr:e}):dr(c.registeredClass.instancePrototype,{ptrType:c,ptr:l})}var Ye=e=>typeof FinalizationRegistry>"u"?(Ye=r=>r,e):(jr=new FinalizationRegistry(r=>{console.warn(r.leakWarning),Qt(r.$$)}),Ye=r=>{var t=r.$$,n=!!t.smartPtr;if(n){var i={$$:t},a=t.ptrType.registeredClass,s=new Error(`Embind found a leaked C++ instance ${a.name} <${he(t.ptr)}>.
package/dist/index.html CHANGED
@@ -11,7 +11,7 @@
11
11
  />
12
12
  <link rel="manifest" href="manifest.json" />
13
13
  <title>mjswan</title>
14
- <script type="module" crossorigin src="/assets/index-BSeAJBAd.js"></script>
14
+ <script type="module" crossorigin src="/assets/index-C6iGKiGz.js"></script>
15
15
  <link rel="stylesheet" crossorigin href="/assets/index-B4SJqdSr.css">
16
16
  </head>
17
17
  <body>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mjswan",
3
3
  "type": "module",
4
- "version": "0.4.1",
4
+ "version": "0.4.3",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/ttktjmt/mjswan.git"