hytopia 0.9.2 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server.js CHANGED
@@ -88,7 +88,7 @@ For example, you can use the \`pathToFileURL()\` method of the \`url\` core modu
88
88
  Instead, \`yield\` should either be called with a value, or not be called at all. For example:
89
89
  if (condition) { yield value; }`)};import{Buffer as GW5}from"node:buffer";import{StringDecoder as VW5}from"node:string_decoder";var t3=(Z,J,X)=>{if(X)return;if(Z)return{transform:HW5.bind(void 0,new TextEncoder)};let $=new VW5(J);return{transform:qW5.bind(void 0,$),final:zW5.bind(void 0,$)}},HW5=function*(Z,J){if(GW5.isBuffer(J))yield yJ(J);else if(typeof J==="string")yield Z.encode(J);else yield J},qW5=function*(Z,J){yield A8(J)?Z.write(J):J},zW5=function*(Z){let J=Z.end();if(J!=="")yield J};import{callbackify as Xm}from"node:util";var vM=Xm(async(Z,J,X,$)=>{J.currentIterable=Z(...X);try{for await(let Y of J.currentIterable)$.push(Y)}finally{delete J.currentIterable}}),e3=async function*(Z,J,X){if(X===J.length){yield Z;return}let{transform:$=UW5}=J[X];for await(let Y of $(Z))yield*e3(Y,J,X+1)},$m=async function*(Z){for(let[J,{final:X}]of Object.entries(Z))yield*FW5(X,Number(J),Z)},FW5=async function*(Z,J,X){if(Z===void 0)return;for await(let $ of Z())yield*e3($,X,J+1)},Ym=Xm(async({currentIterable:Z},J)=>{if(Z!==void 0){await(J?Z.throw(J):Z.return());return}if(J)throw J}),UW5=function*(Z){yield Z};var SM=(Z,J,X,$)=>{try{for(let Y of Z(...J))X.push(Y);$()}catch(Y){$(Y)}},Qm=(Z,J)=>[...J.flatMap((X)=>[...l$(X,Z,0)]),...$G(Z)],l$=function*(Z,J,X){if(X===J.length){yield Z;return}let{transform:$=LW5}=J[X];for(let Y of $(Z))yield*l$(Y,J,X+1)},$G=function*(Z){for(let[J,{final:X}]of Object.entries(Z))yield*BW5(X,Number(J),Z)},BW5=function*(Z,J,X){if(Z===void 0)return;for(let $ of Z())yield*l$($,X,J+1)},LW5=function*(Z){yield Z};var _M=({value:Z,value:{transform:J,final:X,writableObjectMode:$,readableObjectMode:Y},optionName:Q},{encoding:W})=>{let K={},G=Km(Z,W,Q),V=c$(J),H=c$(X),q=V?vM.bind(void 0,e3,K):SM.bind(void 0,l$),z=V||H?vM.bind(void 0,$m,K):SM.bind(void 0,$G),F=V||H?Ym.bind(void 0,K):void 0;return{stream:new wW5({writableObjectMode:$,writableHighWaterMark:Wm($),readableObjectMode:Y,readableHighWaterMark:Wm(Y),transform(L,B,w){q([L,G,0],this,w)},flush(L){z([G],this,L)},destroy:F})}},ZF=(Z,J,X,$)=>{let Y=J.filter(({type:W})=>W==="generator"),Q=$?Y.reverse():Y;for(let{value:W,optionName:K}of Q){let G=Km(W,X,K);Z=Qm(G,Z)}return Z},Km=({transform:Z,final:J,binary:X,writableObjectMode:$,readableObjectMode:Y,preserveNewlines:Q},W,K)=>{let G={};return[{transform:eg($,K)},t3(X,W,$),o3(X,Q,$,G),{transform:Z,final:J},{transform:Zm(Y,K)},tg({binary:X,preserveNewlines:Q,readableObjectMode:Y,state:G})].filter(Boolean)};var Gm=(Z,J)=>{for(let X of OW5(Z))NW5(Z,X,J)},OW5=(Z)=>new Set(Object.entries(Z).filter(([,{direction:J}])=>J==="input").map(([J])=>Number(J))),NW5=(Z,J,X)=>{let{stdioItems:$}=Z[J],Y=$.filter(({contents:K})=>K!==void 0);if(Y.length===0)return;if(J!==0){let[{type:K,optionName:G}]=Y;throw new TypeError(`Only the \`stdin\` option, not \`${G}\`, can be ${o1[K]} with synchronous methods.`)}let W=Y.map(({contents:K})=>K).map((K)=>jW5(K,$));X.input=a4(W)},jW5=(Z,J)=>{let X=ZF(Z,J,"utf8",!0);return MW5(X),a4(X)},MW5=(Z)=>{let J=Z.find((X)=>typeof X!=="string"&&!A8(X));if(J!==void 0)throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${J}.`)};import{writeFileSync as CW5,appendFileSync as TW5}from"node:fs";var JF=({stdioItems:Z,encoding:J,verboseInfo:X,fdNumber:$})=>$!=="all"&&QW(X,$)&&!k7.has(J)&&RW5($)&&(Z.some(({type:Y,value:Q})=>Y==="native"&&DW5.has(Q))||Z.every(({type:Y})=>Q9.has(Y))),RW5=(Z)=>Z===1||Z===2,DW5=new Set(["pipe","overlapped"]),Vm=async(Z,J,X,$)=>{for await(let Y of Z)if(!PW5(J))qm(Y,X,$)},Hm=(Z,J,X)=>{for(let $ of Z)qm($,J,X)},PW5=(Z)=>Z._readableState.pipes.length>0,qm=(Z,J,X)=>{let $=z3(Z);gZ({type:"output",verboseMessage:$,fdNumber:J,verboseInfo:X})};var zm=({fileDescriptors:Z,syncResult:{output:J},options:X,isMaxBuffer:$,verboseInfo:Y})=>{if(J===null)return{output:Array.from({length:3})};let Q={},W=new Set([]);return{output:J.map((G,V)=>kW5({result:G,fileDescriptors:Z,fdNumber:V,state:Q,outputFiles:W,isMaxBuffer:$,verboseInfo:Y},X)),...Q}},kW5=({result:Z,fileDescriptors:J,fdNumber:X,state:$,outputFiles:Y,isMaxBuffer:Q,verboseInfo:W},{buffer:K,encoding:G,lines:V,stripFinalNewline:H,maxBuffer:q})=>{if(Z===null)return;let z=Fg(Z,Q,q),F=yJ(z),{stdioItems:U,objectMode:L}=J[X],B=EW5([F],U,G,$),{serializedResult:w,finalResult:O=w}=IW5({chunks:B,objectMode:L,encoding:G,lines:V,stripFinalNewline:H,fdNumber:X});vW5({serializedResult:w,fdNumber:X,state:$,verboseInfo:W,encoding:G,stdioItems:U,objectMode:L});let M=K[X]?O:void 0;try{if($.error===void 0)SW5(w,U,Y);return M}catch(N){return $.error=N,M}},EW5=(Z,J,X,$)=>{try{return ZF(Z,J,X,!1)}catch(Y){return $.error=Y,Z}},IW5=({chunks:Z,objectMode:J,encoding:X,lines:$,stripFinalNewline:Y,fdNumber:Q})=>{if(J)return{serializedResult:Z};if(X==="buffer")return{serializedResult:a4(Z)};let W=kh(Z,X);if($[Q])return{serializedResult:W,finalResult:IM(W,!Y[Q],J)};return{serializedResult:W}},vW5=({serializedResult:Z,fdNumber:J,state:X,verboseInfo:$,encoding:Y,stdioItems:Q,objectMode:W})=>{if(!JF({stdioItems:Q,encoding:Y,verboseInfo:$,fdNumber:J}))return;let K=IM(Z,!1,W);try{Hm(K,J,$)}catch(G){X.error??=G}},SW5=(Z,J,X)=>{for(let{path:$,append:Y}of J.filter(({type:Q})=>a3.has(Q))){let Q=typeof $==="string"?$:$.toString();if(Y||X.has(Q))TW5($,Z);else X.add(Q),CW5($,Z)}};var Fm=([,Z,J],X)=>{if(!X.all)return;if(Z===void 0)return J;if(J===void 0)return Z;if(Array.isArray(Z))return Array.isArray(J)?[...Z,...J]:[...Z,uJ(J,X,"all")];if(Array.isArray(J))return[uJ(Z,X,"all"),...J];if(A8(Z)&&A8(J))return yj([Z,J]);return`${Z}${J}`};import{once as AM}from"node:events";var Um=async(Z,J)=>{let[X,$]=await _W5(Z);return J.isForcefullyTerminated??=!1,[X,$]},_W5=async(Z)=>{let[J,X]=await Promise.allSettled([AM(Z,"spawn"),AM(Z,"exit")]);if(J.status==="rejected")return[];return X.status==="rejected"?Bm(Z):X.value},Bm=async(Z)=>{try{return await AM(Z,"exit")}catch{return Bm(Z)}},Lm=async(Z)=>{let[J,X]=await Z;if(!AW5(J,X)&&xM(J,X))throw new mZ;return[J,X]},AW5=(Z,J)=>Z===void 0&&J===void 0,xM=(Z,J)=>Z!==0||J!==null;var wm=({error:Z,status:J,signal:X,output:$},{maxBuffer:Y})=>{let Q=xW5(Z,J,X),W=Q?.code==="ETIMEDOUT",K=zg(Q,$,Y);return{resultError:Q,exitCode:J,signal:X,timedOut:W,isMaxBuffer:K}},xW5=(Z,J,X)=>{if(Z!==void 0)return Z;return xM(J,X)?new mZ:void 0};var Om=(Z,J,X)=>{let{file:$,commandArguments:Y,command:Q,escapedCommand:W,startTime:K,verboseInfo:G,options:V,fileDescriptors:H}=hW5(Z,J,X),q=gW5({file:$,commandArguments:Y,options:V,command:Q,escapedCommand:W,verboseInfo:G,fileDescriptors:H,startTime:K});return UW(q,G,V)},hW5=(Z,J,X)=>{let{command:$,escapedCommand:Y,startTime:Q,verboseInfo:W}=U3(Z,J,X),K=bW5(X),{file:G,commandArguments:V,options:H}=b3(Z,J,K);yW5(H);let q=sg(H,W);return{file:G,commandArguments:V,command:$,escapedCommand:Y,startTime:Q,verboseInfo:W,options:H,fileDescriptors:q}},bW5=(Z)=>Z.node&&!Z.ipc?{...Z,ipc:!1}:Z,yW5=({ipc:Z,ipcInput:J,detached:X,cancelSignal:$})=>{if(J)XF("ipcInput");if(Z)XF("ipc: true");if(X)XF("detached: true");if($)XF("cancelSignal")},XF=(Z)=>{throw new TypeError(`The "${Z}" option cannot be used with synchronous methods.`)},gW5=({file:Z,commandArguments:J,options:X,command:$,escapedCommand:Y,verboseInfo:Q,fileDescriptors:W,startTime:K})=>{let G=mW5({file:Z,commandArguments:J,options:X,command:$,escapedCommand:Y,fileDescriptors:W,startTime:K});if(G.failed)return G;let{resultError:V,exitCode:H,signal:q,timedOut:z,isMaxBuffer:F}=wm(G,X),{output:U,error:L=V}=zm({fileDescriptors:W,syncResult:G,options:X,isMaxBuffer:F,verboseInfo:Q}),B=U.map((O,M)=>uJ(O,X,M)),w=uJ(Fm(U,X),X,"all");return uW5({error:L,exitCode:H,signal:q,timedOut:z,isMaxBuffer:F,stdio:B,all:w,options:X,command:$,escapedCommand:Y,startTime:K})},mW5=({file:Z,commandArguments:J,options:X,command:$,escapedCommand:Y,fileDescriptors:Q,startTime:W})=>{try{Gm(Q,X);let K=dW5(X);return fW5(Z,J,K)}catch(K){return FW({error:K,command:$,escapedCommand:Y,fileDescriptors:Q,options:X,startTime:W,isSync:!0})}},dW5=({encoding:Z,maxBuffer:J,...X})=>({...X,encoding:"buffer",maxBuffer:p3(J)}),uW5=({error:Z,exitCode:J,signal:X,timedOut:$,isMaxBuffer:Y,stdio:Q,all:W,options:K,command:G,escapedCommand:V,startTime:H})=>Z===void 0?i3({command:G,escapedCommand:V,stdio:Q,all:W,ipcOutput:[],options:K,startTime:H}):XG({error:Z,command:G,escapedCommand:V,timedOut:$,isCanceled:!1,isGracefullyCanceled:!1,isMaxBuffer:Y,isForcefullyTerminated:!1,exitCode:J,signal:X,stdio:Q,all:W,ipcOutput:[],options:K,startTime:H,isSync:!0});import{setMaxListeners as I45}from"node:events";import{spawn as v45}from"node:child_process";import Dm from"node:process";import{once as fM,on as cW5}from"node:events";var Nm=({anyProcess:Z,channel:J,isSubprocess:X,ipc:$},{reference:Y=!0,filter:Q}={})=>{return GW({methodName:"getOneMessage",isSubprocess:X,ipc:$,isConnected:S3(Z)}),lW5({anyProcess:Z,channel:J,isSubprocess:X,filter:Q,reference:Y})},lW5=async({anyProcess:Z,channel:J,isSubprocess:X,filter:$,reference:Y})=>{k3(J,Y);let Q=r1(Z,J,X),W=new AbortController;try{return await Promise.race([pW5(Q,$,W),iW5(Q,X,W),nW5(Q,X,W)])}catch(K){throw VW(Z),K}finally{W.abort(),E3(J,Y)}},pW5=async(Z,J,{signal:X})=>{if(J===void 0){let[$]=await fM(Z,"message",{signal:X});return $}for await(let[$]of cW5(Z,"message",{signal:X}))if(J($))return $},iW5=async(Z,J,{signal:X})=>{await fM(Z,"disconnect",{signal:X}),Yy(J)},nW5=async(Z,J,{signal:X})=>{let[$]=await fM(Z,"strict:error",{signal:X});throw P3($,J)};import{once as Mm,on as sW5}from"node:events";var Rm=({anyProcess:Z,channel:J,isSubprocess:X,ipc:$},{reference:Y=!0}={})=>hM({anyProcess:Z,channel:J,isSubprocess:X,ipc:$,shouldAwait:!X,reference:Y}),hM=({anyProcess:Z,channel:J,isSubprocess:X,ipc:$,shouldAwait:Y,reference:Q})=>{GW({methodName:"getEachMessage",isSubprocess:X,ipc:$,isConnected:S3(Z)}),k3(J,Q);let W=r1(Z,J,X),K=new AbortController,G={};return aW5(Z,W,K),rW5({ipcEmitter:W,isSubprocess:X,controller:K,state:G}),oW5({anyProcess:Z,channel:J,ipcEmitter:W,isSubprocess:X,shouldAwait:Y,controller:K,state:G,reference:Q})},aW5=async(Z,J,X)=>{try{await Mm(J,"disconnect",{signal:X.signal}),X.abort()}catch{}},rW5=async({ipcEmitter:Z,isSubprocess:J,controller:X,state:$})=>{try{let[Y]=await Mm(Z,"strict:error",{signal:X.signal});$.error=P3(Y,J),X.abort()}catch{}},oW5=async function*({anyProcess:Z,channel:J,ipcEmitter:X,isSubprocess:$,shouldAwait:Y,controller:Q,state:W,reference:K}){try{for await(let[G]of sW5(X,"message",{signal:Q.signal}))jm(W),yield G}catch{jm(W)}finally{if(Q.abort(),E3(J,K),!$)VW(Z);if(Y)await Z}},jm=({error:Z})=>{if(Z)throw Z};var Pm=(Z,{ipc:J})=>{Object.assign(Z,Tm(Z,!1,J))},Cm=()=>{let Z=Dm,J=!0,X=Dm.channel!==void 0;return{...Tm(Z,!0,X),getCancelSignal:Sy.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:!0,ipc:X})}},Tm=(Z,J,X)=>({sendMessage:f3.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X}),getOneMessage:Nm.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X}),getEachMessage:Rm.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X})});import{ChildProcess as tW5}from"node:child_process";import{PassThrough as eW5,Readable as ZK5,Writable as JK5,Duplex as XK5}from"node:stream";var km=({error:Z,command:J,escapedCommand:X,fileDescriptors:$,options:Y,startTime:Q,verboseInfo:W})=>{TM($);let K=new tW5;$K5(K,$),Object.assign(K,{readable:YK5,writable:QK5,duplex:WK5});let G=FW({error:Z,command:J,escapedCommand:X,fileDescriptors:$,options:Y,startTime:Q,isSync:!1}),V=KK5(G,W,Y);return{subprocess:K,promise:V}},$K5=(Z,J)=>{let X=YG(),$=YG(),Y=YG(),Q=Array.from({length:J.length-3},YG),W=YG(),K=[X,$,Y,...Q];Object.assign(Z,{stdin:X,stdout:$,stderr:Y,all:W,stdio:K})},YG=()=>{let Z=new eW5;return Z.end(),Z},YK5=()=>new ZK5({read(){}}),QK5=()=>new JK5({write(){}}),WK5=()=>new XK5({read(){},write(){}}),KK5=async(Z,J,X)=>UW(Z,J,X);import{createReadStream as Em,createWriteStream as Im}from"node:fs";import{Buffer as GK5}from"node:buffer";import{Readable as QG,Writable as VK5,Duplex as HK5}from"node:stream";var Sm=(Z,J)=>r3(qK5,Z,J,!1),WG=({type:Z,optionName:J})=>{throw new TypeError(`The \`${J}\` option cannot be ${o1[Z]}.`)},vm={fileNumber:WG,generator:_M,asyncGenerator:_M,nodeStream:({value:Z})=>({stream:Z}),webTransform({value:{transform:Z,writableObjectMode:J,readableObjectMode:X}}){let $=J||X;return{stream:HK5.fromWeb(Z,{objectMode:$})}},duplex:({value:{transform:Z}})=>({stream:Z}),native(){}},qK5={input:{...vm,fileUrl:({value:Z})=>({stream:Em(Z)}),filePath:({value:{file:Z}})=>({stream:Em(Z)}),webStream:({value:Z})=>({stream:QG.fromWeb(Z)}),iterable:({value:Z})=>({stream:QG.from(Z)}),asyncIterable:({value:Z})=>({stream:QG.from(Z)}),string:({value:Z})=>({stream:QG.from(Z)}),uint8Array:({value:Z})=>({stream:QG.from(GK5.from(Z))})},output:{...vm,fileUrl:({value:Z})=>({stream:Im(Z)}),filePath:({value:{file:Z,append:J}})=>({stream:Im(Z,J?{flags:"a"}:{})}),webStream:({value:Z})=>({stream:VK5.fromWeb(Z)}),iterable:WG,asyncIterable:WG,string:WG,uint8Array:WG}};import{on as zK5,once as _m}from"node:events";import{PassThrough as FK5,getDefaultHighWaterMark as UK5}from"node:stream";import{finished as fm}from"node:stream/promises";function p$(Z){if(!Array.isArray(Z))throw new TypeError(`Expected an array, got \`${typeof Z}\`.`);for(let Y of Z)bM(Y);let J=Z.some(({readableObjectMode:Y})=>Y),X=BK5(Z,J),$=new hm({objectMode:J,writableHighWaterMark:X,readableHighWaterMark:X});for(let Y of Z)$.add(Y);return $}var BK5=(Z,J)=>{if(Z.length===0)return UK5(J);let X=Z.filter(({readableObjectMode:$})=>$===J).map(({readableHighWaterMark:$})=>$);return Math.max(...X)};class hm extends FK5{#Z=new Set([]);#X=new Set([]);#J=new Set([]);#$;#Y=Symbol("unpipe");#Q=new WeakMap;add(Z){if(bM(Z),this.#Z.has(Z))return;this.#Z.add(Z),this.#$??=LK5(this,this.#Z,this.#Y);let J=NK5({passThroughStream:this,stream:Z,streams:this.#Z,ended:this.#X,aborted:this.#J,onFinished:this.#$,unpipeEvent:this.#Y});this.#Q.set(Z,J),Z.pipe(this,{end:!1})}async remove(Z){if(bM(Z),!this.#Z.has(Z))return!1;let J=this.#Q.get(Z);if(J===void 0)return!1;return this.#Q.delete(Z),Z.unpipe(this),await J,!0}}var LK5=async(Z,J,X)=>{$F(Z,Am);let $=new AbortController;try{await Promise.race([wK5(Z,$),OK5(Z,J,X,$)])}finally{$.abort(),$F(Z,-Am)}},wK5=async(Z,{signal:J})=>{try{await fm(Z,{signal:J,cleanup:!0})}catch(X){throw bm(Z,X),X}},OK5=async(Z,J,X,{signal:$})=>{for await(let[Y]of zK5(Z,"unpipe",{signal:$}))if(J.has(Y))Y.emit(X)},bM=(Z)=>{if(typeof Z?.pipe!=="function")throw new TypeError(`Expected a readable stream, got: \`${typeof Z}\`.`)},NK5=async({passThroughStream:Z,stream:J,streams:X,ended:$,aborted:Y,onFinished:Q,unpipeEvent:W})=>{$F(Z,xm);let K=new AbortController;try{await Promise.race([jK5(Q,J,K),MK5({passThroughStream:Z,stream:J,streams:X,ended:$,aborted:Y,controller:K}),RK5({stream:J,streams:X,ended:$,aborted:Y,unpipeEvent:W,controller:K})])}finally{K.abort(),$F(Z,-xm)}if(X.size>0&&X.size===$.size+Y.size)if($.size===0&&Y.size>0)yM(Z);else DK5(Z)},jK5=async(Z,J,{signal:X})=>{try{if(await Z,!X.aborted)yM(J)}catch($){if(!X.aborted)bm(J,$)}},MK5=async({passThroughStream:Z,stream:J,streams:X,ended:$,aborted:Y,controller:{signal:Q}})=>{try{if(await fm(J,{signal:Q,cleanup:!0,readable:!0,writable:!1}),X.has(J))$.add(J)}catch(W){if(Q.aborted||!X.has(J))return;if(ym(W))Y.add(J);else gm(Z,W)}},RK5=async({stream:Z,streams:J,ended:X,aborted:$,unpipeEvent:Y,controller:{signal:Q}})=>{if(await _m(Z,Y,{signal:Q}),!Z.readable)return _m(Q,"abort",{signal:Q});J.delete(Z),X.delete(Z),$.delete(Z)},DK5=(Z)=>{if(Z.writable)Z.end()},bm=(Z,J)=>{if(ym(J))yM(Z);else gm(Z,J)},ym=(Z)=>Z?.code==="ERR_STREAM_PREMATURE_CLOSE",yM=(Z)=>{if(Z.readable||Z.writable)Z.destroy()},gm=(Z,J)=>{if(!Z.destroyed)Z.once("error",PK5),Z.destroy(J)},PK5=()=>{},$F=(Z,J)=>{let X=Z.getMaxListeners();if(X!==0&&X!==Number.POSITIVE_INFINITY)Z.setMaxListeners(X+J)},Am=2,xm=1;import{finished as mm}from"node:stream/promises";var LW=(Z,J)=>{Z.pipe(J),CK5(Z,J),TK5(Z,J)},CK5=async(Z,J)=>{if(ZZ(Z)||ZZ(J))return;try{await mm(Z,{cleanup:!0,readable:!0,writable:!1})}catch{}gM(J)},gM=(Z)=>{if(Z.writable)Z.end()},TK5=async(Z,J)=>{if(ZZ(Z)||ZZ(J))return;try{await mm(J,{cleanup:!0,readable:!1,writable:!0})}catch{}mM(Z)},mM=(Z)=>{if(Z.readable)Z.destroy()};var dm=(Z,J,X)=>{let $=new Map;for(let[Y,{stdioItems:Q,direction:W}]of Object.entries(J)){for(let{stream:K}of Q.filter(({type:G})=>Q9.has(G)))kK5(Z,K,W,Y);for(let{stream:K}of Q.filter(({type:G})=>!Q9.has(G)))IK5({subprocess:Z,stream:K,direction:W,fdNumber:Y,pipeGroups:$,controller:X})}for(let[Y,Q]of $.entries()){let W=Q.length===1?Q[0]:p$(Q);LW(W,Y)}},kK5=(Z,J,X,$)=>{if(X==="output")LW(Z.stdio[$],J);else LW(J,Z.stdio[$]);let Y=EK5[$];if(Y!==void 0)Z[Y]=J;Z.stdio[$]=J},EK5=["stdin","stdout","stderr"],IK5=({subprocess:Z,stream:J,direction:X,fdNumber:$,pipeGroups:Y,controller:Q})=>{if(J===void 0)return;vK5(J,Q);let[W,K]=X==="output"?[J,Z.stdio[$]]:[Z.stdio[$],J],G=Y.get(W)??[];Y.set(W,[...G,K])},vK5=(Z,{signal:J})=>{if(ZZ(Z))d$(Z,SK5,J)},SK5=2;import{addAbortListener as xK5}from"node:events";var i$=[];i$.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")i$.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")i$.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var YF=(Z)=>!!Z&&typeof Z==="object"&&typeof Z.removeListener==="function"&&typeof Z.emit==="function"&&typeof Z.reallyExit==="function"&&typeof Z.listeners==="function"&&typeof Z.kill==="function"&&typeof Z.pid==="number"&&typeof Z.on==="function",dM=Symbol.for("signal-exit emitter"),uM=globalThis,_K5=Object.defineProperty.bind(Object);class um{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(uM[dM])return uM[dM];_K5(uM,dM,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(Z,J){this.listeners[Z].push(J)}removeListener(Z,J){let X=this.listeners[Z],$=X.indexOf(J);if($===-1)return;if($===0&&X.length===1)X.length=0;else X.splice($,1)}emit(Z,J,X){if(this.emitted[Z])return!1;this.emitted[Z]=!0;let $=!1;for(let Y of this.listeners[Z])$=Y(J,X)===!0||$;if(Z==="exit")$=this.emit("afterExit",J,X)||$;return $}}class lM{}var AK5=(Z)=>{return{onExit(J,X){return Z.onExit(J,X)},load(){return Z.load()},unload(){return Z.unload()}}};class cm extends lM{onExit(){return()=>{}}load(){}unload(){}}class lm extends lM{#Z=cM.platform==="win32"?"SIGINT":"SIGHUP";#X=new um;#J;#$;#Y;#Q={};#W=!1;constructor(Z){super();this.#J=Z,this.#Q={};for(let J of i$)this.#Q[J]=()=>{let X=this.#J.listeners(J),{count:$}=this.#X,Y=Z;if(typeof Y.__signal_exit_emitter__==="object"&&typeof Y.__signal_exit_emitter__.count==="number")$+=Y.__signal_exit_emitter__.count;if(X.length===$){this.unload();let Q=this.#X.emit("exit",null,J),W=J==="SIGHUP"?this.#Z:J;if(!Q)Z.kill(Z.pid,W)}};this.#Y=Z.reallyExit,this.#$=Z.emit}onExit(Z,J){if(!YF(this.#J))return()=>{};if(this.#W===!1)this.load();let X=J?.alwaysLast?"afterExit":"exit";return this.#X.on(X,Z),()=>{if(this.#X.removeListener(X,Z),this.#X.listeners.exit.length===0&&this.#X.listeners.afterExit.length===0)this.unload()}}load(){if(this.#W)return;this.#W=!0,this.#X.count+=1;for(let Z of i$)try{let J=this.#Q[Z];if(J)this.#J.on(Z,J)}catch(J){}this.#J.emit=(Z,...J)=>{return this.#G(Z,...J)},this.#J.reallyExit=(Z)=>{return this.#K(Z)}}unload(){if(!this.#W)return;this.#W=!1,i$.forEach((Z)=>{let J=this.#Q[Z];if(!J)throw new Error("Listener not defined for signal: "+Z);try{this.#J.removeListener(Z,J)}catch(X){}}),this.#J.emit=this.#$,this.#J.reallyExit=this.#Y,this.#X.count-=1}#K(Z){if(!YF(this.#J))return 0;return this.#J.exitCode=Z||0,this.#X.emit("exit",this.#J.exitCode,null),this.#Y.call(this.#J,this.#J.exitCode)}#G(Z,...J){let X=this.#$;if(Z==="exit"&&YF(this.#J)){if(typeof J[0]==="number")this.#J.exitCode=J[0];let $=X.call(this.#J,Z,...J);return this.#X.emit("exit",this.#J.exitCode,null),$}else return X.call(this.#J,Z,...J)}}var cM=globalThis.process,{onExit:pm,load:qQ6,unload:zQ6}=AK5(YF(cM)?new lm(cM):new cm);var im=(Z,{cleanup:J,detached:X},{signal:$})=>{if(!J||X)return;let Y=pm(()=>{Z.kill()});xK5($,()=>{Y()})};var sm=({source:Z,sourcePromise:J,boundOptions:X,createNested:$},...Y)=>{let Q=F3(),{destination:W,destinationStream:K,destinationError:G,from:V,unpipeSignal:H}=fK5(X,$,Y),{sourceStream:q,sourceError:z}=bK5(Z,V),{options:F,fileDescriptors:U}=uZ.get(Z);return{sourcePromise:J,sourceStream:q,sourceOptions:F,sourceError:z,destination:W,destinationStream:K,destinationError:G,unpipeSignal:H,fileDescriptors:U,startTime:Q}},fK5=(Z,J,X)=>{try{let{destination:$,pipeOptions:{from:Y,to:Q,unpipeSignal:W}={}}=hK5(Z,J,...X),K=T3($,Q);return{destination:$,destinationStream:K,from:Y,unpipeSignal:W}}catch($){return{destinationError:$}}},hK5=(Z,J,X,...$)=>{if(Array.isArray(X))return{destination:J(nm,Z)(X,...$),pipeOptions:Z};if(typeof X==="string"||X instanceof URL||hj(X)){if(Object.keys(Z).length>0)throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)("file", ...).');let[Y,Q,W]=$3(X,...$);return{destination:J(nm)(Y,Q,W),pipeOptions:W}}if(uZ.has(X)){if(Object.keys(Z).length>0)throw new TypeError("Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).");return{destination:X,pipeOptions:$[0]}}throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${X}`)},nm=({options:Z})=>({options:{...Z,stdin:"pipe",piped:!0}}),bK5=(Z,J)=>{try{return{sourceStream:HW(Z,J)}}catch(X){return{sourceError:X}}};var rm=({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:$,fileDescriptors:Y,sourceOptions:Q,startTime:W})=>{let K=yK5({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:$});if(K!==void 0)throw pM({error:K,fileDescriptors:Y,sourceOptions:Q,startTime:W})},yK5=({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:$})=>{if(J!==void 0&&$!==void 0)return $;if($!==void 0)return mM(Z),$;if(J!==void 0)return gM(X),J},pM=({error:Z,fileDescriptors:J,sourceOptions:X,startTime:$})=>FW({error:Z,command:am,escapedCommand:am,fileDescriptors:J,options:X,startTime:$,isSync:!1}),am="source.pipe(destination)";var om=async(Z)=>{let[{status:J,reason:X,value:$=X},{status:Y,reason:Q,value:W=Q}]=await Z;if(!W.pipedFrom.includes($))W.pipedFrom.push($);if(Y==="rejected")throw W;if(J==="rejected")throw $;return W};import{finished as gK5}from"node:stream/promises";var tm=(Z,J,X)=>{let $=QF.has(J)?dK5(Z,J):mK5(Z,J);return d$(Z,cK5,X.signal),d$(J,lK5,X.signal),uK5(J),$},mK5=(Z,J)=>{let X=p$([Z]);return LW(X,J),QF.set(J,X),X},dK5=(Z,J)=>{let X=QF.get(J);return X.add(Z),X},uK5=async(Z)=>{try{await gK5(Z,{cleanup:!0,readable:!1,writable:!0})}catch{}QF.delete(Z)},QF=new WeakMap,cK5=2,lK5=1;import{aborted as pK5}from"node:util";var em=(Z,J)=>Z===void 0?[]:[iK5(Z,J)],iK5=async(Z,{sourceStream:J,mergedStream:X,fileDescriptors:$,sourceOptions:Y,startTime:Q})=>{await pK5(Z,J),await X.remove(J);let W=new Error("Pipe canceled by `unpipeSignal` option.");throw pM({error:W,fileDescriptors:$,sourceOptions:Y,startTime:Q})};var WF=(Z,...J)=>{if(L8(J[0]))return WF.bind(void 0,{...Z,boundOptions:{...Z.boundOptions,...J[0]}});let{destination:X,...$}=sm(Z,...J),Y=nK5({...$,destination:X});return Y.pipe=WF.bind(void 0,{...Z,source:X,sourcePromise:Y,boundOptions:{}}),Y},nK5=async({sourcePromise:Z,sourceStream:J,sourceOptions:X,sourceError:$,destination:Y,destinationStream:Q,destinationError:W,unpipeSignal:K,fileDescriptors:G,startTime:V})=>{let H=sK5(Z,Y);rm({sourceStream:J,sourceError:$,destinationStream:Q,destinationError:W,fileDescriptors:G,sourceOptions:X,startTime:V});let q=new AbortController;try{let z=tm(J,Q,q);return await Promise.race([om(H),...em(K,{sourceStream:J,mergedStream:z,sourceOptions:X,fileDescriptors:G,startTime:V})])}finally{q.abort()}},sK5=(Z,J)=>Promise.allSettled([Z,J]);import{setImmediate as J45}from"node:timers/promises";import{on as aK5}from"node:events";import{getDefaultHighWaterMark as rK5}from"node:stream";var KF=({subprocessStdout:Z,subprocess:J,binary:X,shouldEncode:$,encoding:Y,preserveNewlines:Q})=>{let W=new AbortController;return oK5(J,W),Jd({stream:Z,controller:W,binary:X,shouldEncode:!Z.readableObjectMode&&$,encoding:Y,shouldSplit:!Z.readableObjectMode,preserveNewlines:Q})},oK5=async(Z,J)=>{try{await Z}catch{}finally{J.abort()}},iM=({stream:Z,onStreamEnd:J,lines:X,encoding:$,stripFinalNewline:Y,allMixed:Q})=>{let W=new AbortController;tK5(J,W,Z);let K=Z.readableObjectMode&&!Q;return Jd({stream:Z,controller:W,binary:$==="buffer",shouldEncode:!K,encoding:$,shouldSplit:!K&&X,preserveNewlines:!Y})},tK5=async(Z,J,X)=>{try{await Z}catch{X.destroy()}finally{J.abort()}},Jd=({stream:Z,controller:J,binary:X,shouldEncode:$,encoding:Y,shouldSplit:Q,preserveNewlines:W})=>{let K=aK5(Z,"data",{signal:J.signal,highWaterMark:Zd,highWatermark:Zd});return eK5({onStdoutChunk:K,controller:J,binary:X,shouldEncode:$,encoding:Y,shouldSplit:Q,preserveNewlines:W})},nM=rK5(!0),Zd=nM,eK5=async function*({onStdoutChunk:Z,controller:J,binary:X,shouldEncode:$,encoding:Y,shouldSplit:Q,preserveNewlines:W}){let K=Z45({binary:X,shouldEncode:$,encoding:Y,shouldSplit:Q,preserveNewlines:W});try{for await(let[G]of Z)yield*l$(G,K,0)}catch(G){if(!J.signal.aborted)throw G}finally{yield*$G(K)}},Z45=({binary:Z,shouldEncode:J,encoding:X,shouldSplit:$,preserveNewlines:Y})=>[t3(Z,X,!J),o3(Z,Y,!$,{})].filter(Boolean);var Xd=async({stream:Z,onStreamEnd:J,fdNumber:X,encoding:$,buffer:Y,maxBuffer:Q,lines:W,allMixed:K,stripFinalNewline:G,verboseInfo:V,streamInfo:H})=>{let q=X45({stream:Z,onStreamEnd:J,fdNumber:X,encoding:$,allMixed:K,verboseInfo:V,streamInfo:H});if(!Y){await Promise.all([$45(Z),q]);return}let z=kM(G,X),F=iM({stream:Z,onStreamEnd:J,lines:W,encoding:$,stripFinalNewline:z,allMixed:K}),[U]=await Promise.all([Y45({stream:Z,iterable:F,fdNumber:X,encoding:$,maxBuffer:Q,lines:W}),q]);return U},X45=async({stream:Z,onStreamEnd:J,fdNumber:X,encoding:$,allMixed:Y,verboseInfo:Q,streamInfo:{fileDescriptors:W}})=>{if(!JF({stdioItems:W[X]?.stdioItems,encoding:$,verboseInfo:Q,fdNumber:X}))return;let K=iM({stream:Z,onStreamEnd:J,lines:!0,encoding:$,stripFinalNewline:!0,allMixed:Y});await Vm(K,Z,X,Q)},$45=async(Z)=>{if(await J45(),Z.readableFlowing===null)Z.resume()},Y45=async({stream:Z,stream:{readableObjectMode:J},iterable:X,fdNumber:$,encoding:Y,maxBuffer:Q,lines:W})=>{try{if(J||W)return await d3(X,{maxBuffer:Q});if(Y==="buffer")return new Uint8Array(await u3(X,{maxBuffer:Q}));return await l3(X,{maxBuffer:Q})}catch(K){return $d(Vg({error:K,stream:Z,readableObjectMode:J,lines:W,encoding:Y,fdNumber:$}))}},sM=async(Z)=>{try{return await Z}catch(J){return $d(J)}},$d=({bufferedData:Z})=>Ch(Z)?new Uint8Array(Z):Z;import{finished as Q45}from"node:stream/promises";var KG=async(Z,J,X,{isSameDirection:$,stopOnExit:Y=!1}={})=>{let Q=W45(Z,X),W=new AbortController;try{await Promise.race([...Y?[X.exitPromise]:[],Q45(Z,{cleanup:!0,signal:W.signal})])}catch(K){if(!Q.stdinCleanedUp)V45(K,J,X,$)}finally{W.abort()}},W45=(Z,{originalStreams:[J],subprocess:X})=>{let $={stdinCleanedUp:!1};if(Z===J)K45(Z,X,$);return $},K45=(Z,J,X)=>{let{_destroy:$}=Z;Z._destroy=(...Y)=>{G45(J,X),$.call(Z,...Y)}},G45=({exitCode:Z,signalCode:J},X)=>{if(Z!==null||J!==null)X.stdinCleanedUp=!0},V45=(Z,J,X,$)=>{if(!H45(Z,J,X,$))throw Z},H45=(Z,J,X,$=!0)=>{if(X.propagating)return Yd(Z)||GF(Z);return X.propagating=!0,aM(X,J)===$?Yd(Z):GF(Z)},aM=({fileDescriptors:Z},J)=>J!=="all"&&Z[J].direction==="input",GF=(Z)=>Z?.code==="ERR_STREAM_PREMATURE_CLOSE",Yd=(Z)=>Z?.code==="EPIPE";var Qd=({subprocess:Z,encoding:J,buffer:X,maxBuffer:$,lines:Y,stripFinalNewline:Q,verboseInfo:W,streamInfo:K})=>Z.stdio.map((G,V)=>rM({stream:G,fdNumber:V,encoding:J,buffer:X[V],maxBuffer:$[V],lines:Y[V],allMixed:!1,stripFinalNewline:Q,verboseInfo:W,streamInfo:K})),rM=async({stream:Z,fdNumber:J,encoding:X,buffer:$,maxBuffer:Y,lines:Q,allMixed:W,stripFinalNewline:K,verboseInfo:G,streamInfo:V})=>{if(!Z)return;let H=KG(Z,J,V);if(aM(V,J)){await H;return}let[q]=await Promise.all([Xd({stream:Z,onStreamEnd:H,fdNumber:J,encoding:X,buffer:$,maxBuffer:Y,lines:Q,allMixed:W,stripFinalNewline:K,verboseInfo:G,streamInfo:V}),H]);return q};var Wd=({stdout:Z,stderr:J},{all:X})=>X&&(Z||J)?p$([Z,J].filter(Boolean)):void 0,Kd=({subprocess:Z,encoding:J,buffer:X,maxBuffer:$,lines:Y,stripFinalNewline:Q,verboseInfo:W,streamInfo:K})=>rM({...q45(Z,X),fdNumber:"all",encoding:J,maxBuffer:$[1]+$[2],lines:Y[1]||Y[2],allMixed:z45(Z),stripFinalNewline:Q,verboseInfo:W,streamInfo:K}),q45=({stdout:Z,stderr:J,all:X},[,$,Y])=>{let Q=$||Y;if(!Q)return{stream:X,buffer:Q};if(!$)return{stream:J,buffer:Q};if(!Y)return{stream:Z,buffer:Q};return{stream:X,buffer:Q}},z45=({all:Z,stdout:J,stderr:X})=>Z&&J&&X&&J.readableObjectMode!==X.readableObjectMode;import{once as F45}from"node:events";var Gd=(Z)=>QW(Z,"ipc"),Vd=(Z,J)=>{let X=z3(Z);gZ({type:"ipc",verboseMessage:X,fdNumber:"ipc",verboseInfo:J})};var Hd=async({subprocess:Z,buffer:J,maxBuffer:X,ipc:$,ipcOutput:Y,verboseInfo:Q})=>{if(!$)return Y;let W=Gd(Q),K=gJ(J,"ipc"),G=gJ(X,"ipc");for await(let V of hM({anyProcess:Z,channel:Z.channel,isSubprocess:!1,ipc:$,shouldAwait:!1,reference:!0})){if(K)Hg(Z,Y,G),Y.push(V);if(W)Vd(V,Q)}return Y},qd=async(Z,J)=>{return await Promise.allSettled([Z]),J};var zd=async({subprocess:Z,options:{encoding:J,buffer:X,maxBuffer:$,lines:Y,timeoutDuration:Q,cancelSignal:W,gracefulCancel:K,forceKillAfterDelay:G,stripFinalNewline:V,ipc:H,ipcInput:q},context:z,verboseInfo:F,fileDescriptors:U,originalStreams:L,onInternalError:B,controller:w})=>{let O=Um(Z,z),M={originalStreams:L,fileDescriptors:U,subprocess:Z,exitPromise:O,propagating:!1},N=Qd({subprocess:Z,encoding:J,buffer:X,maxBuffer:$,lines:Y,stripFinalNewline:V,verboseInfo:F,streamInfo:M}),P=Kd({subprocess:Z,encoding:J,buffer:X,maxBuffer:$,lines:Y,stripFinalNewline:V,verboseInfo:F,streamInfo:M}),D=[],C=Hd({subprocess:Z,buffer:X,maxBuffer:$,ipc:H,ipcOutput:D,verboseInfo:F}),T=U45(L,Z,M),k=B45(U,M);try{return await Promise.race([Promise.all([{},Lm(O),Promise.all(N),P,C,dy(Z,q),...T,...k]),B,L45(Z,w),...hy(Z,Q,z,w),...$y({subprocess:Z,cancelSignal:W,gracefulCancel:K,context:z,controller:w}),...xy({subprocess:Z,cancelSignal:W,gracefulCancel:K,forceKillAfterDelay:G,context:z,controller:w})])}catch(A){return z.terminationReason??="other",Promise.all([{error:A},O,Promise.all(N.map((v)=>sM(v))),sM(P),qd(C,D),Promise.allSettled(T),Promise.allSettled(k)])}},U45=(Z,J,X)=>Z.map(($,Y)=>$===J.stdio[Y]?void 0:KG($,Y,X)),B45=(Z,J)=>Z.flatMap(({stdioItems:X},$)=>X.filter(({value:Y,stream:Q=Y})=>XZ(Q,{checkOpen:!1})&&!ZZ(Q)).map(({type:Y,value:Q,stream:W=Q})=>KG(W,$,J,{isSameDirection:Q9.has(Y),stopOnExit:Y==="native"}))),L45=async(Z,{signal:J})=>{let[X]=await F45(Z,"error",{signal:J});throw X};var Fd=()=>({readableDestroy:new WeakMap,writableFinal:new WeakMap,writableDestroy:new WeakMap}),GG=(Z,J,X)=>{let $=Z[X];if(!$.has(J))$.set(J,[]);let Y=$.get(J),Q=dZ();return Y.push(Q),{resolve:Q.resolve.bind(Q),promises:Y}},wW=async({resolve:Z,promises:J},X)=>{Z();let[$]=await Promise.race([Promise.allSettled([!0,X]),Promise.all([!1,...J])]);return!$};import{Readable as w45}from"node:stream";import{callbackify as O45}from"node:util";import{finished as Ud}from"node:stream/promises";var oM=async(Z)=>{if(Z===void 0)return;try{await tM(Z)}catch{}},Bd=async(Z)=>{if(Z===void 0)return;try{await eM(Z)}catch{}},tM=async(Z)=>{await Ud(Z,{cleanup:!0,readable:!1,writable:!0})},eM=async(Z)=>{await Ud(Z,{cleanup:!0,readable:!0,writable:!1})},VF=async(Z,J)=>{if(await Z,J)throw J},HF=(Z,J,X)=>{if(X&&!GF(X))Z.destroy(X);else if(J)Z.destroy()};var Ld=({subprocess:Z,concurrentStreams:J,encoding:X},{from:$,binary:Y=!0,preserveNewlines:Q=!0}={})=>{let W=Y||k7.has(X),{subprocessStdout:K,waitReadableDestroy:G}=ZR(Z,$,J),{readableEncoding:V,readableObjectMode:H,readableHighWaterMark:q}=JR(K,W),{read:z,onStdoutDataDone:F}=XR({subprocessStdout:K,subprocess:Z,binary:W,encoding:X,preserveNewlines:Q}),U=new w45({read:z,destroy:O45(YR.bind(void 0,{subprocessStdout:K,subprocess:Z,waitReadableDestroy:G})),highWaterMark:q,objectMode:H,encoding:V});return $R({subprocessStdout:K,onStdoutDataDone:F,readable:U,subprocess:Z}),U},ZR=(Z,J,X)=>{let $=HW(Z,J),Y=GG(X,$,"readableDestroy");return{subprocessStdout:$,waitReadableDestroy:Y}},JR=({readableEncoding:Z,readableObjectMode:J,readableHighWaterMark:X},$)=>$?{readableEncoding:Z,readableObjectMode:J,readableHighWaterMark:X}:{readableEncoding:Z,readableObjectMode:!0,readableHighWaterMark:nM},XR=({subprocessStdout:Z,subprocess:J,binary:X,encoding:$,preserveNewlines:Y})=>{let Q=dZ(),W=KF({subprocessStdout:Z,subprocess:J,binary:X,shouldEncode:!X,encoding:$,preserveNewlines:Y});return{read(){N45(this,W,Q)},onStdoutDataDone:Q}},N45=async(Z,J,X)=>{try{let{value:$,done:Y}=await J.next();if(Y)X.resolve();else Z.push($)}catch{}},$R=async({subprocessStdout:Z,onStdoutDataDone:J,readable:X,subprocess:$,subprocessStdin:Y})=>{try{if(await eM(Z),await $,await oM(Y),await J,X.readable)X.push(null)}catch(Q){await oM(Y),wd(X,Q)}},YR=async({subprocessStdout:Z,subprocess:J,waitReadableDestroy:X},$)=>{if(await wW(X,J))wd(Z,$),await VF(J,$)},wd=(Z,J)=>{HF(Z,Z.readable,J)};import{Writable as j45}from"node:stream";import{callbackify as Od}from"node:util";var Nd=({subprocess:Z,concurrentStreams:J},{to:X}={})=>{let{subprocessStdin:$,waitWritableFinal:Y,waitWritableDestroy:Q}=QR(Z,X,J),W=new j45({...WR($,Z,Y),destroy:Od(GR.bind(void 0,{subprocessStdin:$,subprocess:Z,waitWritableFinal:Y,waitWritableDestroy:Q})),highWaterMark:$.writableHighWaterMark,objectMode:$.writableObjectMode});return KR($,W),W},QR=(Z,J,X)=>{let $=T3(Z,J),Y=GG(X,$,"writableFinal"),Q=GG(X,$,"writableDestroy");return{subprocessStdin:$,waitWritableFinal:Y,waitWritableDestroy:Q}},WR=(Z,J,X)=>({write:M45.bind(void 0,Z),final:Od(R45.bind(void 0,Z,J,X))}),M45=(Z,J,X,$)=>{if(Z.write(J,X))$();else Z.once("drain",$)},R45=async(Z,J,X)=>{if(await wW(X,J)){if(Z.writable)Z.end();await J}},KR=async(Z,J,X)=>{try{if(await tM(Z),J.writable)J.end()}catch($){await Bd(X),jd(J,$)}},GR=async({subprocessStdin:Z,subprocess:J,waitWritableFinal:X,waitWritableDestroy:$},Y)=>{if(await wW(X,J),await wW($,J))jd(Z,Y),await VF(J,Y)},jd=(Z,J)=>{HF(Z,Z.writable,J)};import{Duplex as D45}from"node:stream";import{callbackify as P45}from"node:util";var Md=({subprocess:Z,concurrentStreams:J,encoding:X},{from:$,to:Y,binary:Q=!0,preserveNewlines:W=!0}={})=>{let K=Q||k7.has(X),{subprocessStdout:G,waitReadableDestroy:V}=ZR(Z,$,J),{subprocessStdin:H,waitWritableFinal:q,waitWritableDestroy:z}=QR(Z,Y,J),{readableEncoding:F,readableObjectMode:U,readableHighWaterMark:L}=JR(G,K),{read:B,onStdoutDataDone:w}=XR({subprocessStdout:G,subprocess:Z,binary:K,encoding:X,preserveNewlines:W}),O=new D45({read:B,...WR(H,Z,q),destroy:P45(C45.bind(void 0,{subprocessStdout:G,subprocessStdin:H,subprocess:Z,waitReadableDestroy:V,waitWritableFinal:q,waitWritableDestroy:z})),readableHighWaterMark:L,writableHighWaterMark:H.writableHighWaterMark,readableObjectMode:U,writableObjectMode:H.writableObjectMode,encoding:F});return $R({subprocessStdout:G,onStdoutDataDone:w,readable:O,subprocess:Z,subprocessStdin:H}),KR(H,O,G),O},C45=async({subprocessStdout:Z,subprocessStdin:J,subprocess:X,waitReadableDestroy:$,waitWritableFinal:Y,waitWritableDestroy:Q},W)=>{await Promise.all([YR({subprocessStdout:Z,subprocess:X,waitReadableDestroy:$},W),GR({subprocessStdin:J,subprocess:X,waitWritableFinal:Y,waitWritableDestroy:Q},W)])};var VR=(Z,J,{from:X,binary:$=!1,preserveNewlines:Y=!1}={})=>{let Q=$||k7.has(J),W=HW(Z,X),K=KF({subprocessStdout:W,subprocess:Z,binary:Q,shouldEncode:!0,encoding:J,preserveNewlines:Y});return T45(K,W,Z)},T45=async function*(Z,J,X){try{yield*Z}finally{if(J.readable)J.destroy();await X}};var Rd=(Z,{encoding:J})=>{let X=Fd();Z.readable=Ld.bind(void 0,{subprocess:Z,concurrentStreams:X,encoding:J}),Z.writable=Nd.bind(void 0,{subprocess:Z,concurrentStreams:X}),Z.duplex=Md.bind(void 0,{subprocess:Z,concurrentStreams:X,encoding:J}),Z.iterable=VR.bind(void 0,Z,J),Z[Symbol.asyncIterator]=VR.bind(void 0,Z,J,{})};var Dd=(Z,J)=>{for(let[X,$]of E45){let Y=$.value.bind(J);Reflect.defineProperty(Z,X,{...$,value:Y})}},k45=(async()=>{})().constructor.prototype,E45=["then","catch","finally"].map((Z)=>[Z,Reflect.getOwnPropertyDescriptor(k45,Z)]);var Pd=(Z,J,X,$)=>{let{file:Y,commandArguments:Q,command:W,escapedCommand:K,startTime:G,verboseInfo:V,options:H,fileDescriptors:q}=S45(Z,J,X),{subprocess:z,promise:F}=A45({file:Y,commandArguments:Q,options:H,startTime:G,verboseInfo:V,command:W,escapedCommand:K,fileDescriptors:q});return z.pipe=WF.bind(void 0,{source:z,sourcePromise:F,boundOptions:{},createNested:$}),Dd(z,F),uZ.set(z,{options:H,fileDescriptors:q}),z},S45=(Z,J,X)=>{let{command:$,escapedCommand:Y,startTime:Q,verboseInfo:W}=U3(Z,J,X),{file:K,commandArguments:G,options:V}=b3(Z,J,X),H=_45(V),q=Sm(H,W);return{file:K,commandArguments:G,command:$,escapedCommand:Y,startTime:Q,verboseInfo:W,options:H,fileDescriptors:q}},_45=({timeout:Z,signal:J,...X})=>{if(J!==void 0)throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');return{...X,timeoutDuration:Z}},A45=({file:Z,commandArguments:J,options:X,startTime:$,verboseInfo:Y,command:Q,escapedCommand:W,fileDescriptors:K})=>{let G;try{G=v45(Z,J,X)}catch(U){return km({error:U,command:Q,escapedCommand:W,fileDescriptors:K,options:X,startTime:$,verboseInfo:Y})}let V=new AbortController;I45(Number.POSITIVE_INFINITY,V.signal);let H=[...G.stdio];dm(G,K,V),im(G,X,V);let q={},z=dZ();G.kill=Jy.bind(void 0,{kill:G.kill.bind(G),options:X,onInternalError:z,context:q,controller:V}),G.all=Wd(G,X),Rd(G,X),Pm(G,X);let F=x45({subprocess:G,options:X,startTime:$,verboseInfo:Y,fileDescriptors:K,originalStreams:H,command:Q,escapedCommand:W,context:q,onInternalError:z,controller:V});return{subprocess:G,promise:F}},x45=async({subprocess:Z,options:J,startTime:X,verboseInfo:$,fileDescriptors:Y,originalStreams:Q,command:W,escapedCommand:K,context:G,onInternalError:V,controller:H})=>{let[q,[z,F],U,L,B]=await zd({subprocess:Z,options:J,context:G,verboseInfo:$,fileDescriptors:Y,originalStreams:Q,onInternalError:V,controller:H});H.abort(),V.resolve();let w=U.map((N,P)=>uJ(N,J,P)),O=uJ(L,J,"all"),M=f45({errorInfo:q,exitCode:z,signal:F,stdio:w,all:O,ipcOutput:B,context:G,options:J,command:W,escapedCommand:K,startTime:X});return UW(M,$,J)},f45=({errorInfo:Z,exitCode:J,signal:X,stdio:$,all:Y,ipcOutput:Q,context:W,options:K,command:G,escapedCommand:V,startTime:H})=>("error"in Z)?XG({error:Z.error,command:G,escapedCommand:V,timedOut:W.terminationReason==="timeout",isCanceled:W.terminationReason==="cancel"||W.terminationReason==="gracefulCancel",isGracefullyCanceled:W.terminationReason==="gracefulCancel",isMaxBuffer:Z.error instanceof mJ,isForcefullyTerminated:W.isForcefullyTerminated,exitCode:J,signal:X,stdio:$,all:Y,ipcOutput:Q,options:K,startTime:H,isSync:!1}):i3({command:G,escapedCommand:V,stdio:$,all:Y,ipcOutput:Q,options:K,startTime:H});var qF=(Z,J)=>{let X=Object.fromEntries(Object.entries(J).map(([$,Y])=>[$,h45($,Z[$],Y)]));return{...Z,...X}},h45=(Z,J,X)=>{if(b45.has(Z)&&L8(J)&&L8(X))return{...J,...X};return X},b45=new Set(["env",...uj]);var t1=(Z,J,X,$)=>{let Y=(W,K,G)=>t1(W,K,X,G),Q=(...W)=>y45({mapArguments:Z,deepOptions:X,boundOptions:J,setBoundExeca:$,createNested:Y},...W);if($!==void 0)$(Q,Y,J);return Q},y45=({mapArguments:Z,deepOptions:J={},boundOptions:X={},setBoundExeca:$,createNested:Y},Q,...W)=>{if(L8(Q))return Y(Z,qF(X,Q),$);let{file:K,commandArguments:G,options:V,isSync:H}=g45({mapArguments:Z,firstArgument:Q,nextArguments:W,deepOptions:J,boundOptions:X});return H?Om(K,G,V):Pd(K,G,V,Y)},g45=({mapArguments:Z,firstArgument:J,nextArguments:X,deepOptions:$,boundOptions:Y})=>{let Q=Sh(J)?_h(J,X):[J,...X],[W,K,G]=$3(...Q),V=qF(qF($,Y),G),{file:H=W,commandArguments:q=K,options:z=V,isSync:F=!1}=Z({file:W,commandArguments:K,options:V});return{file:H,commandArguments:q,options:z,isSync:F}};var Cd=({file:Z,commandArguments:J})=>kd(Z,J),Td=({file:Z,commandArguments:J})=>({...kd(Z,J),isSync:!0}),kd=(Z,J)=>{if(J.length>0)throw new TypeError(`The command and its arguments must be passed as a single string: ${Z} ${J}.`);let[X,...$]=m45(Z);return{file:X,commandArguments:$}},m45=(Z)=>{if(typeof Z!=="string")throw new TypeError(`The command must be a string: ${String(Z)}.`);let J=Z.trim();if(J==="")return[];let X=[];for(let $ of J.split(d45)){let Y=X.at(-1);if(Y&&Y.endsWith("\\"))X[X.length-1]=`${Y.slice(0,-1)} ${$}`;else X.push($)}return X},d45=/ +/g;var Ed=(Z,J,X)=>{Z.sync=J(u45,X),Z.s=Z.sync},Id=({options:Z})=>vd(Z),u45=({options:Z})=>({...vd(Z),isSync:!0}),vd=(Z)=>({options:{...c45(Z),...Z}}),c45=({input:Z,inputFile:J,stdio:X})=>Z===void 0&&J===void 0&&X===void 0?{stdin:"inherit"}:{},Sd={preferLocal:!0};var _d=t1(()=>({})),Z46=t1(()=>({isSync:!0})),J46=t1(Cd),X46=t1(Td),$46=t1(yy),Y46=t1(Id,{},Sd,Ed),{sendMessage:Q46,getOneMessage:W46,getEachMessage:K46,getCancelSignal:G46}=Cm();var td=e(ld(),1);var HG=(Z)=>{if(typeof Z!=="string")throw new TypeError("invalid pattern");if(Z.length>65536)throw new TypeError("pattern is too long")};var o45={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},qG=(Z)=>Z.replace(/[[\]\\-]/g,"\\$&"),t45=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),pd=(Z)=>Z.join(""),id=(Z,J)=>{let X=J;if(Z.charAt(X)!=="[")throw new Error("not in a brace expression");let $=[],Y=[],Q=X+1,W=!1,K=!1,G=!1,V=!1,H=X,q="";Z:while(Q<Z.length){let L=Z.charAt(Q);if((L==="!"||L==="^")&&Q===X+1){V=!0,Q++;continue}if(L==="]"&&W&&!G){H=Q+1;break}if(W=!0,L==="\\"){if(!G){G=!0,Q++;continue}}if(L==="["&&!G){for(let[B,[w,O,M]]of Object.entries(o45))if(Z.startsWith(B,Q)){if(q)return["$.",!1,Z.length-X,!0];if(Q+=B.length,M)Y.push(w);else $.push(w);K=K||O;continue Z}}if(G=!1,q){if(L>q)$.push(qG(q)+"-"+qG(L));else if(L===q)$.push(qG(L));q="",Q++;continue}if(Z.startsWith("-]",Q+1)){$.push(qG(L+"-")),Q+=2;continue}if(Z.startsWith("-",Q+1)){q=L,Q+=2;continue}$.push(qG(L)),Q++}if(H<Q)return["",!1,0,!1];if(!$.length&&!Y.length)return["$.",!1,Z.length-X,!0];if(Y.length===0&&$.length===1&&/^\\?.$/.test($[0])&&!V){let L=$[0].length===2?$[0].slice(-1):$[0];return[t45(L),!1,H-X,!1]}let z="["+(V?"^":"")+pd($)+"]",F="["+(V?"":"^")+pd(Y)+"]";return[$.length&&Y.length?"("+z+"|"+F+")":$.length?z:F,K,H-X,!0]};var $Z=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/\[([^\/\\])\]/g,"$1"):Z.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")};var e45=new Set(["!","?","+","*","@"]),nd=(Z)=>e45.has(Z),ZG5="(?!(?:^|/)\\.\\.?(?:$|/))",zF="(?!\\.)",JG5=new Set(["[","."]),XG5=new Set(["..","."]),$G5=new Set("().*{}+?[]^$\\!"),YG5=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),FR="[^/]",sd=FR+"*?",ad=FR+"+?";class Z6{type;#Z;#X;#J=!1;#$=[];#Y;#Q;#W;#K=!1;#G;#H;#z=!1;constructor(Z,J,X={}){if(this.type=Z,Z)this.#X=!0;if(this.#Y=J,this.#Z=this.#Y?this.#Y.#Z:this,this.#G=this.#Z===this?X:this.#Z.#G,this.#W=this.#Z===this?[]:this.#Z.#W,Z==="!"&&!this.#Z.#K)this.#W.push(this);this.#Q=this.#Y?this.#Y.#$.length:0}get hasMagic(){if(this.#X!==void 0)return this.#X;for(let Z of this.#$){if(typeof Z==="string")continue;if(Z.type||Z.hasMagic)return this.#X=!0}return this.#X}toString(){if(this.#H!==void 0)return this.#H;if(!this.type)return this.#H=this.#$.map((Z)=>String(Z)).join("");else return this.#H=this.type+"("+this.#$.map((Z)=>String(Z)).join("|")+")"}#V(){if(this!==this.#Z)throw new Error("should only call on root");if(this.#K)return this;this.toString(),this.#K=!0;let Z;while(Z=this.#W.pop()){if(Z.type!=="!")continue;let J=Z,X=J.#Y;while(X){for(let $=J.#Q+1;!X.type&&$<X.#$.length;$++)for(let Y of Z.#$){if(typeof Y==="string")throw new Error("string part in extglob AST??");Y.copyIn(X.#$[$])}J=X,X=J.#Y}}return this}push(...Z){for(let J of Z){if(J==="")continue;if(typeof J!=="string"&&!(J instanceof Z6&&J.#Y===this))throw new Error("invalid part: "+J);this.#$.push(J)}}toJSON(){let Z=this.type===null?this.#$.slice().map((J)=>typeof J==="string"?J:J.toJSON()):[this.type,...this.#$.map((J)=>J.toJSON())];if(this.isStart()&&!this.type)Z.unshift([]);if(this.isEnd()&&(this===this.#Z||this.#Z.#K&&this.#Y?.type==="!"))Z.push({});return Z}isStart(){if(this.#Z===this)return!0;if(!this.#Y?.isStart())return!1;if(this.#Q===0)return!0;let Z=this.#Y;for(let J=0;J<this.#Q;J++){let X=Z.#$[J];if(!(X instanceof Z6&&X.type==="!"))return!1}return!0}isEnd(){if(this.#Z===this)return!0;if(this.#Y?.type==="!")return!0;if(!this.#Y?.isEnd())return!1;if(!this.type)return this.#Y?.isEnd();let Z=this.#Y?this.#Y.#$.length:0;return this.#Q===Z-1}copyIn(Z){if(typeof Z==="string")this.push(Z);else this.push(Z.clone(this))}clone(Z){let J=new Z6(this.type,Z);for(let X of this.#$)J.copyIn(X);return J}static#U(Z,J,X,$){let Y=!1,Q=!1,W=-1,K=!1;if(J.type===null){let z=X,F="";while(z<Z.length){let U=Z.charAt(z++);if(Y||U==="\\"){Y=!Y,F+=U;continue}if(Q){if(z===W+1){if(U==="^"||U==="!")K=!0}else if(U==="]"&&!(z===W+2&&K))Q=!1;F+=U;continue}else if(U==="["){Q=!0,W=z,K=!1,F+=U;continue}if(!$.noext&&nd(U)&&Z.charAt(z)==="("){J.push(F),F="";let L=new Z6(U,J);z=Z6.#U(Z,L,z,$),J.push(L);continue}F+=U}return J.push(F),z}let G=X+1,V=new Z6(null,J),H=[],q="";while(G<Z.length){let z=Z.charAt(G++);if(Y||z==="\\"){Y=!Y,q+=z;continue}if(Q){if(G===W+1){if(z==="^"||z==="!")K=!0}else if(z==="]"&&!(G===W+2&&K))Q=!1;q+=z;continue}else if(z==="["){Q=!0,W=G,K=!1,q+=z;continue}if(nd(z)&&Z.charAt(G)==="("){V.push(q),q="";let F=new Z6(z,V);V.push(F),G=Z6.#U(Z,F,G,$);continue}if(z==="|"){V.push(q),q="",H.push(V),V=new Z6(null,J);continue}if(z===")"){if(q===""&&J.#$.length===0)J.#z=!0;return V.push(q),q="",J.push(...H,V),G}q+=z}return J.type=null,J.#X=void 0,J.#$=[Z.substring(X-1)],G}static fromGlob(Z,J={}){let X=new Z6(null,void 0,J);return Z6.#U(Z,X,0,J),X}toMMPattern(){if(this!==this.#Z)return this.#Z.toMMPattern();let Z=this.toString(),[J,X,$,Y]=this.toRegExpSource();if(!($||this.#X||this.#G.nocase&&!this.#G.nocaseMagicOnly&&Z.toUpperCase()!==Z.toLowerCase()))return X;let W=(this.#G.nocase?"i":"")+(Y?"u":"");return Object.assign(new RegExp(`^${J}$`,W),{_src:J,_glob:Z})}get options(){return this.#G}toRegExpSource(Z){let J=Z??!!this.#G.dot;if(this.#Z===this)this.#V();if(!this.type){let K=this.isStart()&&this.isEnd(),G=this.#$.map((z)=>{let[F,U,L,B]=typeof z==="string"?Z6.#B(z,this.#X,K):z.toRegExpSource(Z);return this.#X=this.#X||L,this.#J=this.#J||B,F}).join(""),V="";if(this.isStart()){if(typeof this.#$[0]==="string"){if(!(this.#$.length===1&&XG5.has(this.#$[0]))){let F=JG5,U=J&&F.has(G.charAt(0))||G.startsWith("\\.")&&F.has(G.charAt(2))||G.startsWith("\\.\\.")&&F.has(G.charAt(4)),L=!J&&!Z&&F.has(G.charAt(0));V=U?ZG5:L?zF:""}}}let H="";if(this.isEnd()&&this.#Z.#K&&this.#Y?.type==="!")H="(?:$|\\/)";return[V+G+H,$Z(G),this.#X=!!this.#X,this.#J]}let X=this.type==="*"||this.type==="+",$=this.type==="!"?"(?:(?!(?:":"(?:",Y=this.#L(J);if(this.isStart()&&this.isEnd()&&!Y&&this.type!=="!"){let K=this.toString();return this.#$=[K],this.type=null,this.#X=void 0,[K,$Z(this.toString()),!1,!1]}let Q=!X||Z||J||!zF?"":this.#L(!0);if(Q===Y)Q="";if(Q)Y=`(?:${Y})(?:${Q})*?`;let W="";if(this.type==="!"&&this.#z)W=(this.isStart()&&!J?zF:"")+ad;else{let K=this.type==="!"?"))"+(this.isStart()&&!J&&!Z?zF:"")+sd+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&Q?")":this.type==="*"&&Q?")?":`)${this.type}`;W=$+Y+K}return[W,$Z(Y),this.#X=!!this.#X,this.#J]}#L(Z){return this.#$.map((J)=>{if(typeof J==="string")throw new Error("string type in extglob ast??");let[X,$,Y,Q]=J.toRegExpSource(Z);return this.#J=this.#J||Q,X}).filter((J)=>!(this.isStart()&&this.isEnd())||!!J).join("|")}static#B(Z,J,X=!1){let $=!1,Y="",Q=!1;for(let W=0;W<Z.length;W++){let K=Z.charAt(W);if($){$=!1,Y+=($G5.has(K)?"\\":"")+K;continue}if(K==="\\"){if(W===Z.length-1)Y+="\\\\";else $=!0;continue}if(K==="["){let[G,V,H,q]=id(Z,W);if(H){Y+=G,Q=Q||V,W+=H-1,J=J||q;continue}}if(K==="*"){if(X&&Z==="*")Y+=ad;else Y+=sd;J=!0;continue}if(K==="?"){Y+=FR,J=!0;continue}Y+=YG5(K)}return[Y,$Z(Z),!!J,Q]}}var OW=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/[?*()[\]]/g,"[$&]"):Z.replace(/[?*()[\]\\]/g,"\\$&")};var v6=(Z,J,X={})=>{if(HG(J),!X.nocomment&&J.charAt(0)==="#")return!1;return new K9(J,X).match(Z)},QG5=/^\*+([^+@!?\*\[\(]*)$/,WG5=(Z)=>(J)=>!J.startsWith(".")&&J.endsWith(Z),KG5=(Z)=>(J)=>J.endsWith(Z),GG5=(Z)=>{return Z=Z.toLowerCase(),(J)=>!J.startsWith(".")&&J.toLowerCase().endsWith(Z)},VG5=(Z)=>{return Z=Z.toLowerCase(),(J)=>J.toLowerCase().endsWith(Z)},HG5=/^\*+\.\*+$/,qG5=(Z)=>!Z.startsWith(".")&&Z.includes("."),zG5=(Z)=>Z!=="."&&Z!==".."&&Z.includes("."),FG5=/^\.\*+$/,UG5=(Z)=>Z!=="."&&Z!==".."&&Z.startsWith("."),BG5=/^\*+$/,LG5=(Z)=>Z.length!==0&&!Z.startsWith("."),wG5=(Z)=>Z.length!==0&&Z!=="."&&Z!=="..",OG5=/^\?+([^+@!?\*\[\(]*)?$/,NG5=([Z,J=""])=>{let X=ed([Z]);if(!J)return X;return J=J.toLowerCase(),($)=>X($)&&$.toLowerCase().endsWith(J)},jG5=([Z,J=""])=>{let X=Zu([Z]);if(!J)return X;return J=J.toLowerCase(),($)=>X($)&&$.toLowerCase().endsWith(J)},MG5=([Z,J=""])=>{let X=Zu([Z]);return!J?X:($)=>X($)&&$.endsWith(J)},RG5=([Z,J=""])=>{let X=ed([Z]);return!J?X:($)=>X($)&&$.endsWith(J)},ed=([Z])=>{let J=Z.length;return(X)=>X.length===J&&!X.startsWith(".")},Zu=([Z])=>{let J=Z.length;return(X)=>X.length===J&&X!=="."&&X!==".."},Ju=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",rd={win32:{sep:"\\"},posix:{sep:"/"}},DG5=Ju==="win32"?rd.win32.sep:rd.posix.sep;v6.sep=DG5;var J6=Symbol("globstar **");v6.GLOBSTAR=J6;var PG5="[^/]",CG5=PG5+"*?",TG5="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",kG5="(?:(?!(?:\\/|^)\\.).)*?",EG5=(Z,J={})=>(X)=>v6(X,Z,J);v6.filter=EG5;var W9=(Z,J={})=>Object.assign({},Z,J),IG5=(Z)=>{if(!Z||typeof Z!=="object"||!Object.keys(Z).length)return v6;let J=v6;return Object.assign(($,Y,Q={})=>J($,Y,W9(Z,Q)),{Minimatch:class $ extends J.Minimatch{constructor(Y,Q={}){super(Y,W9(Z,Q))}static defaults(Y){return J.defaults(W9(Z,Y)).Minimatch}},AST:class $ extends J.AST{constructor(Y,Q,W={}){super(Y,Q,W9(Z,W))}static fromGlob(Y,Q={}){return J.AST.fromGlob(Y,W9(Z,Q))}},unescape:($,Y={})=>J.unescape($,W9(Z,Y)),escape:($,Y={})=>J.escape($,W9(Z,Y)),filter:($,Y={})=>J.filter($,W9(Z,Y)),defaults:($)=>J.defaults(W9(Z,$)),makeRe:($,Y={})=>J.makeRe($,W9(Z,Y)),braceExpand:($,Y={})=>J.braceExpand($,W9(Z,Y)),match:($,Y,Q={})=>J.match($,Y,W9(Z,Q)),sep:J.sep,GLOBSTAR:J6})};v6.defaults=IG5;var Xu=(Z,J={})=>{if(HG(Z),J.nobrace||!/\{(?:(?!\{).)*\}/.test(Z))return[Z];return td.default(Z)};v6.braceExpand=Xu;var vG5=(Z,J={})=>new K9(Z,J).makeRe();v6.makeRe=vG5;var SG5=(Z,J,X={})=>{let $=new K9(J,X);if(Z=Z.filter((Y)=>$.match(Y)),$.options.nonull&&!Z.length)Z.push(J);return Z};v6.match=SG5;var od=/[?*]|[+@!]\(.*?\)|\[|\]/,_G5=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class K9{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(Z,J={}){if(HG(Z),J=J||{},this.options=J,this.pattern=Z,this.platform=J.platform||Ju,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!J.windowsPathsNoEscape||J.allowWindowsEscape===!1,this.windowsPathsNoEscape)this.pattern=this.pattern.replace(/\\/g,"/");this.preserveMultipleSlashes=!!J.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!J.nonegate,this.comment=!1,this.empty=!1,this.partial=!!J.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=J.windowsNoMagicRoot!==void 0?J.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let Z of this.set)for(let J of Z)if(typeof J!=="string")return!0;return!1}debug(...Z){}make(){let Z=this.pattern,J=this.options;if(!J.nocomment&&Z.charAt(0)==="#"){this.comment=!0;return}if(!Z){this.empty=!0;return}if(this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],J.debug)this.debug=(...Y)=>console.error(...Y);this.debug(this.pattern,this.globSet);let X=this.globSet.map((Y)=>this.slashSplit(Y));this.globParts=this.preprocess(X),this.debug(this.pattern,this.globParts);let $=this.globParts.map((Y,Q,W)=>{if(this.isWindows&&this.windowsNoMagicRoot){let K=Y[0]===""&&Y[1]===""&&(Y[2]==="?"||!od.test(Y[2]))&&!od.test(Y[3]),G=/^[a-z]:/i.test(Y[0]);if(K)return[...Y.slice(0,4),...Y.slice(4).map((V)=>this.parse(V))];else if(G)return[Y[0],...Y.slice(1).map((V)=>this.parse(V))]}return Y.map((K)=>this.parse(K))});if(this.debug(this.pattern,$),this.set=$.filter((Y)=>Y.indexOf(!1)===-1),this.isWindows)for(let Y=0;Y<this.set.length;Y++){let Q=this.set[Y];if(Q[0]===""&&Q[1]===""&&this.globParts[Y][2]==="?"&&typeof Q[3]==="string"&&/^[a-z]:$/i.test(Q[3]))Q[2]="?"}this.debug(this.pattern,this.set)}preprocess(Z){if(this.options.noglobstar){for(let X=0;X<Z.length;X++)for(let $=0;$<Z[X].length;$++)if(Z[X][$]==="**")Z[X][$]="*"}let{optimizationLevel:J=1}=this.options;if(J>=2)Z=this.firstPhasePreProcess(Z),Z=this.secondPhasePreProcess(Z);else if(J>=1)Z=this.levelOneOptimize(Z);else Z=this.adjascentGlobstarOptimize(Z);return Z}adjascentGlobstarOptimize(Z){return Z.map((J)=>{let X=-1;while((X=J.indexOf("**",X+1))!==-1){let $=X;while(J[$+1]==="**")$++;if($!==X)J.splice(X,$-X)}return J})}levelOneOptimize(Z){return Z.map((J)=>{return J=J.reduce((X,$)=>{let Y=X[X.length-1];if($==="**"&&Y==="**")return X;if($===".."){if(Y&&Y!==".."&&Y!=="."&&Y!=="**")return X.pop(),X}return X.push($),X},[]),J.length===0?[""]:J})}levelTwoFileOptimize(Z){if(!Array.isArray(Z))Z=this.slashSplit(Z);let J=!1;do{if(J=!1,!this.preserveMultipleSlashes){for(let $=1;$<Z.length-1;$++){let Y=Z[$];if($===1&&Y===""&&Z[0]==="")continue;if(Y==="."||Y==="")J=!0,Z.splice($,1),$--}if(Z[0]==="."&&Z.length===2&&(Z[1]==="."||Z[1]===""))J=!0,Z.pop()}let X=0;while((X=Z.indexOf("..",X+1))!==-1){let $=Z[X-1];if($&&$!=="."&&$!==".."&&$!=="**")J=!0,Z.splice(X-1,2),X-=2}}while(J);return Z.length===0?[""]:Z}firstPhasePreProcess(Z){let J=!1;do{J=!1;for(let X of Z){let $=-1;while(($=X.indexOf("**",$+1))!==-1){let Q=$;while(X[Q+1]==="**")Q++;if(Q>$)X.splice($+1,Q-$);let W=X[$+1],K=X[$+2],G=X[$+3];if(W!=="..")continue;if(!K||K==="."||K===".."||!G||G==="."||G==="..")continue;J=!0,X.splice($,1);let V=X.slice(0);V[$]="**",Z.push(V),$--}if(!this.preserveMultipleSlashes){for(let Q=1;Q<X.length-1;Q++){let W=X[Q];if(Q===1&&W===""&&X[0]==="")continue;if(W==="."||W==="")J=!0,X.splice(Q,1),Q--}if(X[0]==="."&&X.length===2&&(X[1]==="."||X[1]===""))J=!0,X.pop()}let Y=0;while((Y=X.indexOf("..",Y+1))!==-1){let Q=X[Y-1];if(Q&&Q!=="."&&Q!==".."&&Q!=="**"){J=!0;let K=Y===1&&X[Y+1]==="**"?["."]:[];if(X.splice(Y-1,2,...K),X.length===0)X.push("");Y-=2}}}}while(J);return Z}secondPhasePreProcess(Z){for(let J=0;J<Z.length-1;J++)for(let X=J+1;X<Z.length;X++){let $=this.partsMatch(Z[J],Z[X],!this.preserveMultipleSlashes);if($){Z[J]=[],Z[X]=$;break}}return Z.filter((J)=>J.length)}partsMatch(Z,J,X=!1){let $=0,Y=0,Q=[],W="";while($<Z.length&&Y<J.length)if(Z[$]===J[Y])Q.push(W==="b"?J[Y]:Z[$]),$++,Y++;else if(X&&Z[$]==="**"&&J[Y]===Z[$+1])Q.push(Z[$]),$++;else if(X&&J[Y]==="**"&&Z[$]===J[Y+1])Q.push(J[Y]),Y++;else if(Z[$]==="*"&&J[Y]&&(this.options.dot||!J[Y].startsWith("."))&&J[Y]!=="**"){if(W==="b")return!1;W="a",Q.push(Z[$]),$++,Y++}else if(J[Y]==="*"&&Z[$]&&(this.options.dot||!Z[$].startsWith("."))&&Z[$]!=="**"){if(W==="a")return!1;W="b",Q.push(J[Y]),$++,Y++}else return!1;return Z.length===J.length&&Q}parseNegate(){if(this.nonegate)return;let Z=this.pattern,J=!1,X=0;for(let $=0;$<Z.length&&Z.charAt($)==="!";$++)J=!J,X++;if(X)this.pattern=Z.slice(X);this.negate=J}matchOne(Z,J,X=!1){let $=this.options;if(this.isWindows){let U=typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0]),L=!U&&Z[0]===""&&Z[1]===""&&Z[2]==="?"&&/^[a-z]:$/i.test(Z[3]),B=typeof J[0]==="string"&&/^[a-z]:$/i.test(J[0]),w=!B&&J[0]===""&&J[1]===""&&J[2]==="?"&&typeof J[3]==="string"&&/^[a-z]:$/i.test(J[3]),O=L?3:U?0:void 0,M=w?3:B?0:void 0;if(typeof O==="number"&&typeof M==="number"){let[N,P]=[Z[O],J[M]];if(N.toLowerCase()===P.toLowerCase()){if(J[M]=N,M>O)J=J.slice(M);else if(O>M)Z=Z.slice(O)}}}let{optimizationLevel:Y=1}=this.options;if(Y>=2)Z=this.levelTwoFileOptimize(Z);this.debug("matchOne",this,{file:Z,pattern:J}),this.debug("matchOne",Z.length,J.length);for(var Q=0,W=0,K=Z.length,G=J.length;Q<K&&W<G;Q++,W++){this.debug("matchOne loop");var V=J[W],H=Z[Q];if(this.debug(J,V,H),V===!1)return!1;if(V===J6){this.debug("GLOBSTAR",[J,V,H]);var q=Q,z=W+1;if(z===G){this.debug("** at the end");for(;Q<K;Q++)if(Z[Q]==="."||Z[Q]===".."||!$.dot&&Z[Q].charAt(0)===".")return!1;return!0}while(q<K){var F=Z[q];if(this.debug(`
90
90
  globstar while`,Z,q,J,z,F),this.matchOne(Z.slice(q),J.slice(z),X))return this.debug("globstar found match!",q,K,F),!0;else{if(F==="."||F===".."||!$.dot&&F.charAt(0)==="."){this.debug("dot detected!",Z,q,J,z);break}this.debug("globstar swallow a segment, and continue"),q++}}if(X){if(this.debug(`
91
- >>> no match, partial?`,Z,q,J,z),q===K)return!0}return!1}let U;if(typeof V==="string")U=H===V,this.debug("string match",V,H,U);else U=V.test(H),this.debug("pattern match",V,H,U);if(!U)return!1}if(Q===K&&W===G)return!0;else if(Q===K)return X;else if(W===G)return Q===K-1&&Z[Q]==="";else throw new Error("wtf?")}braceExpand(){return Xu(this.pattern,this.options)}parse(Z){HG(Z);let J=this.options;if(Z==="**")return J6;if(Z==="")return"";let X,$=null;if(X=Z.match(BG5))$=J.dot?wG5:LG5;else if(X=Z.match(QG5))$=(J.nocase?J.dot?VG5:GG5:J.dot?KG5:WG5)(X[1]);else if(X=Z.match(OG5))$=(J.nocase?J.dot?jG5:NG5:J.dot?MG5:RG5)(X);else if(X=Z.match(HG5))$=J.dot?zG5:qG5;else if(X=Z.match(FG5))$=UG5;let Y=Z6.fromGlob(Z,this.options).toMMPattern();if($&&typeof Y==="object")Reflect.defineProperty(Y,"test",{value:$});return Y}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Z=this.set;if(!Z.length)return this.regexp=!1,this.regexp;let J=this.options,X=J.noglobstar?CG5:J.dot?TG5:kG5,$=new Set(J.nocase?["i"]:[]),Y=Z.map((K)=>{let G=K.map((V)=>{if(V instanceof RegExp)for(let H of V.flags.split(""))$.add(H);return typeof V==="string"?_G5(V):V===J6?J6:V._src});return G.forEach((V,H)=>{let q=G[H+1],z=G[H-1];if(V!==J6||z===J6)return;if(z===void 0)if(q!==void 0&&q!==J6)G[H+1]="(?:\\/|"+X+"\\/)?"+q;else G[H]=X;else if(q===void 0)G[H-1]=z+"(?:\\/|"+X+")?";else if(q!==J6)G[H-1]=z+"(?:\\/|\\/"+X+"\\/)"+q,G[H+1]=J6}),G.filter((V)=>V!==J6).join("/")}).join("|"),[Q,W]=Z.length>1?["(?:",")"]:["",""];if(Y="^"+Q+Y+W+"$",this.negate)Y="^(?!"+Y+").+$";try{this.regexp=new RegExp(Y,[...$].join(""))}catch(K){this.regexp=!1}return this.regexp}slashSplit(Z){if(this.preserveMultipleSlashes)return Z.split("/");else if(this.isWindows&&/^\/\/[^\/]+/.test(Z))return["",...Z.split(/\/+/)];else return Z.split(/\/+/)}match(Z,J=this.partial){if(this.debug("match",Z,this.pattern),this.comment)return!1;if(this.empty)return Z==="";if(Z==="/"&&J)return!0;let X=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let $=this.slashSplit(Z);this.debug(this.pattern,"split",$);let Y=this.set;this.debug(this.pattern,"set",Y);let Q=$[$.length-1];if(!Q)for(let W=$.length-2;!Q&&W>=0;W--)Q=$[W];for(let W=0;W<Y.length;W++){let K=Y[W],G=$;if(X.matchBase&&K.length===1)G=[Q];if(this.matchOne(G,K,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return v6.defaults(Z).Minimatch}}v6.AST=Z6;v6.Minimatch=K9;v6.escape=OW;v6.unescape=$Z;import{fileURLToPath as HV5}from"node:url";var NW=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,Yu=new Set,UR=typeof process==="object"&&!!process?process:{},Qu=(Z,J,X,$)=>{typeof UR.emitWarning==="function"?UR.emitWarning(Z,J,X,$):console.error(`[${X}] ${J}: ${Z}`)},FF=globalThis.AbortController,$u=globalThis.AbortSignal;if(typeof FF==="undefined"){$u=class X{onabort;_onabort=[];reason;aborted=!1;addEventListener($,Y){this._onabort.push(Y)}},FF=class X{constructor(){J()}signal=new $u;abort($){if(this.signal.aborted)return;this.signal.reason=$,this.signal.aborted=!0;for(let Y of this.signal._onabort)Y($);this.signal.onabort?.($)}};let Z=UR.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",J=()=>{if(!Z)return;Z=!1,Qu("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",J)}}var AG5=(Z)=>!Yu.has(Z),k46=Symbol("type"),e1=(Z)=>Z&&Z===Math.floor(Z)&&Z>0&&isFinite(Z),Wu=(Z)=>!e1(Z)?null:Z<=Math.pow(2,8)?Uint8Array:Z<=Math.pow(2,16)?Uint16Array:Z<=Math.pow(2,32)?Uint32Array:Z<=Number.MAX_SAFE_INTEGER?zG:null;class zG extends Array{constructor(Z){super(Z);this.fill(0)}}class jW{heap;length;static#Z=!1;static create(Z){let J=Wu(Z);if(!J)return[];jW.#Z=!0;let X=new jW(Z,J);return jW.#Z=!1,X}constructor(Z,J){if(!jW.#Z)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new J(Z),this.length=0}push(Z){this.heap[this.length++]=Z}pop(){return this.heap[--this.length]}}class FG{#Z;#X;#J;#$;#Y;#Q;#W;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#K;#G;#H;#z;#V;#U;#L;#B;#O;#k;#N;#E;#R;#M;#j;#C;#w;#v;static unsafeExposeInternals(Z){return{starts:Z.#R,ttls:Z.#M,sizes:Z.#E,keyMap:Z.#H,keyList:Z.#z,valList:Z.#V,next:Z.#U,prev:Z.#L,get head(){return Z.#B},get tail(){return Z.#O},free:Z.#k,isBackgroundFetch:(J)=>Z.#F(J),backgroundFetch:(J,X,$,Y)=>Z.#f(J,X,$,Y),moveToTail:(J)=>Z.#y(J),indexes:(J)=>Z.#T(J),rindexes:(J)=>Z.#I(J),isStale:(J)=>Z.#P(J)}}get max(){return this.#Z}get maxSize(){return this.#X}get calculatedSize(){return this.#G}get size(){return this.#K}get fetchMethod(){return this.#Q}get memoMethod(){return this.#W}get dispose(){return this.#J}get onInsert(){return this.#$}get disposeAfter(){return this.#Y}constructor(Z){let{max:J=0,ttl:X,ttlResolution:$=1,ttlAutopurge:Y,updateAgeOnGet:Q,updateAgeOnHas:W,allowStale:K,dispose:G,onInsert:V,disposeAfter:H,noDisposeOnSet:q,noUpdateTTL:z,maxSize:F=0,maxEntrySize:U=0,sizeCalculation:L,fetchMethod:B,memoMethod:w,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:M,allowStaleOnFetchRejection:N,allowStaleOnFetchAbort:P,ignoreFetchAbort:D}=Z;if(J!==0&&!e1(J))throw new TypeError("max option must be a nonnegative integer");let C=J?Wu(J):Array;if(!C)throw new Error("invalid max value: "+J);if(this.#Z=J,this.#X=F,this.maxEntrySize=U||this.#X,this.sizeCalculation=L,this.sizeCalculation){if(!this.#X&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw new TypeError("sizeCalculation set to non-function")}if(w!==void 0&&typeof w!=="function")throw new TypeError("memoMethod must be a function if defined");if(this.#W=w,B!==void 0&&typeof B!=="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#Q=B,this.#C=!!B,this.#H=new Map,this.#z=new Array(J).fill(void 0),this.#V=new Array(J).fill(void 0),this.#U=new C(J),this.#L=new C(J),this.#B=0,this.#O=0,this.#k=jW.create(J),this.#K=0,this.#G=0,typeof G==="function")this.#J=G;if(typeof V==="function")this.#$=V;if(typeof H==="function")this.#Y=H,this.#N=[];else this.#Y=void 0,this.#N=void 0;if(this.#j=!!this.#J,this.#v=!!this.#$,this.#w=!!this.#Y,this.noDisposeOnSet=!!q,this.noUpdateTTL=!!z,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!N,this.allowStaleOnFetchAbort=!!P,this.ignoreFetchAbort=!!D,this.maxEntrySize!==0){if(this.#X!==0){if(!e1(this.#X))throw new TypeError("maxSize must be a positive integer if specified")}if(!e1(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#m()}if(this.allowStale=!!K,this.noDeleteOnStaleGet=!!M,this.updateAgeOnGet=!!Q,this.updateAgeOnHas=!!W,this.ttlResolution=e1($)||$===0?$:1,this.ttlAutopurge=!!Y,this.ttl=X||0,this.ttl){if(!e1(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#q()}if(this.#Z===0&&this.ttl===0&&this.#X===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#Z&&!this.#X){if(AG5("LRU_CACHE_UNBOUNDED"))Yu.add("LRU_CACHE_UNBOUNDED"),Qu("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",FG)}}getRemainingTTL(Z){return this.#H.has(Z)?1/0:0}#q(){let Z=new zG(this.#Z),J=new zG(this.#Z);this.#M=Z,this.#R=J,this.#S=(Y,Q,W=NW.now())=>{if(J[Y]=Q!==0?W:0,Z[Y]=Q,Q!==0&&this.ttlAutopurge){let K=setTimeout(()=>{if(this.#P(Y))this.#_(this.#z[Y],"expire")},Q+1);if(K.unref)K.unref()}},this.#A=(Y)=>{J[Y]=Z[Y]!==0?NW.now():0},this.#D=(Y,Q)=>{if(Z[Q]){let W=Z[Q],K=J[Q];if(!W||!K)return;Y.ttl=W,Y.start=K,Y.now=X||$();let G=Y.now-K;Y.remainingTTL=W-G}};let X=0,$=()=>{let Y=NW.now();if(this.ttlResolution>0){X=Y;let Q=setTimeout(()=>X=0,this.ttlResolution);if(Q.unref)Q.unref()}return Y};this.getRemainingTTL=(Y)=>{let Q=this.#H.get(Y);if(Q===void 0)return 0;let W=Z[Q],K=J[Q];if(!W||!K)return 1/0;let G=(X||$())-K;return W-G},this.#P=(Y)=>{let Q=J[Y],W=Z[Y];return!!W&&!!Q&&(X||$())-Q>W}}#A=()=>{};#D=()=>{};#S=()=>{};#P=()=>!1;#m(){let Z=new zG(this.#Z);this.#G=0,this.#E=Z,this.#x=(J)=>{this.#G-=Z[J],Z[J]=0},this.#d=(J,X,$,Y)=>{if(this.#F(X))return 0;if(!e1($))if(Y){if(typeof Y!=="function")throw new TypeError("sizeCalculation must be a function");if($=Y(X,J),!e1($))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return $},this.#h=(J,X,$)=>{if(Z[J]=X,this.#X){let Y=this.#X-Z[J];while(this.#G>Y)this.#b(!0)}if(this.#G+=Z[J],$)$.entrySize=X,$.totalCalculatedSize=this.#G}}#x=(Z)=>{};#h=(Z,J,X)=>{};#d=(Z,J,X,$)=>{if(X||$)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#T({allowStale:Z=this.allowStale}={}){if(this.#K)for(let J=this.#O;;){if(!this.#u(J))break;if(Z||!this.#P(J))yield J;if(J===this.#B)break;else J=this.#L[J]}}*#I({allowStale:Z=this.allowStale}={}){if(this.#K)for(let J=this.#B;;){if(!this.#u(J))break;if(Z||!this.#P(J))yield J;if(J===this.#O)break;else J=this.#U[J]}}#u(Z){return Z!==void 0&&this.#H.get(this.#z[Z])===Z}*entries(){for(let Z of this.#T())if(this.#V[Z]!==void 0&&this.#z[Z]!==void 0&&!this.#F(this.#V[Z]))yield[this.#z[Z],this.#V[Z]]}*rentries(){for(let Z of this.#I())if(this.#V[Z]!==void 0&&this.#z[Z]!==void 0&&!this.#F(this.#V[Z]))yield[this.#z[Z],this.#V[Z]]}*keys(){for(let Z of this.#T()){let J=this.#z[Z];if(J!==void 0&&!this.#F(this.#V[Z]))yield J}}*rkeys(){for(let Z of this.#I()){let J=this.#z[Z];if(J!==void 0&&!this.#F(this.#V[Z]))yield J}}*values(){for(let Z of this.#T())if(this.#V[Z]!==void 0&&!this.#F(this.#V[Z]))yield this.#V[Z]}*rvalues(){for(let Z of this.#I())if(this.#V[Z]!==void 0&&!this.#F(this.#V[Z]))yield this.#V[Z]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(Z,J={}){for(let X of this.#T()){let $=this.#V[X],Y=this.#F($)?$.__staleWhileFetching:$;if(Y===void 0)continue;if(Z(Y,this.#z[X],this))return this.get(this.#z[X],J)}}forEach(Z,J=this){for(let X of this.#T()){let $=this.#V[X],Y=this.#F($)?$.__staleWhileFetching:$;if(Y===void 0)continue;Z.call(J,Y,this.#z[X],this)}}rforEach(Z,J=this){for(let X of this.#I()){let $=this.#V[X],Y=this.#F($)?$.__staleWhileFetching:$;if(Y===void 0)continue;Z.call(J,Y,this.#z[X],this)}}purgeStale(){let Z=!1;for(let J of this.#I({allowStale:!0}))if(this.#P(J))this.#_(this.#z[J],"expire"),Z=!0;return Z}info(Z){let J=this.#H.get(Z);if(J===void 0)return;let X=this.#V[J],$=this.#F(X)?X.__staleWhileFetching:X;if($===void 0)return;let Y={value:$};if(this.#M&&this.#R){let Q=this.#M[J],W=this.#R[J];if(Q&&W){let K=Q-(NW.now()-W);Y.ttl=K,Y.start=Date.now()}}if(this.#E)Y.size=this.#E[J];return Y}dump(){let Z=[];for(let J of this.#T({allowStale:!0})){let X=this.#z[J],$=this.#V[J],Y=this.#F($)?$.__staleWhileFetching:$;if(Y===void 0||X===void 0)continue;let Q={value:Y};if(this.#M&&this.#R){Q.ttl=this.#M[J];let W=NW.now()-this.#R[J];Q.start=Math.floor(Date.now()-W)}if(this.#E)Q.size=this.#E[J];Z.unshift([X,Q])}return Z}load(Z){this.clear();for(let[J,X]of Z){if(X.start){let $=Date.now()-X.start;X.start=NW.now()-$}this.set(J,X.value,X)}}set(Z,J,X={}){if(J===void 0)return this.delete(Z),this;let{ttl:$=this.ttl,start:Y,noDisposeOnSet:Q=this.noDisposeOnSet,sizeCalculation:W=this.sizeCalculation,status:K}=X,{noUpdateTTL:G=this.noUpdateTTL}=X,V=this.#d(Z,J,X.size||0,W);if(this.maxEntrySize&&V>this.maxEntrySize){if(K)K.set="miss",K.maxEntrySizeExceeded=!0;return this.#_(Z,"set"),this}let H=this.#K===0?void 0:this.#H.get(Z);if(H===void 0){if(H=this.#K===0?this.#O:this.#k.length!==0?this.#k.pop():this.#K===this.#Z?this.#b(!1):this.#K,this.#z[H]=Z,this.#V[H]=J,this.#H.set(Z,H),this.#U[this.#O]=H,this.#L[H]=this.#O,this.#O=H,this.#K++,this.#h(H,V,K),K)K.set="add";if(G=!1,this.#v)this.#$?.(J,Z,"add")}else{this.#y(H);let q=this.#V[H];if(J!==q){if(this.#C&&this.#F(q)){q.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:z}=q;if(z!==void 0&&!Q){if(this.#j)this.#J?.(z,Z,"set");if(this.#w)this.#N?.push([z,Z,"set"])}}else if(!Q){if(this.#j)this.#J?.(q,Z,"set");if(this.#w)this.#N?.push([q,Z,"set"])}if(this.#x(H),this.#h(H,V,K),this.#V[H]=J,K){K.set="replace";let z=q&&this.#F(q)?q.__staleWhileFetching:q;if(z!==void 0)K.oldValue=z}}else if(K)K.set="update";if(this.#v)this.onInsert?.(J,Z,J===q?"update":"replace")}if($!==0&&!this.#M)this.#q();if(this.#M){if(!G)this.#S(H,$,Y);if(K)this.#D(K,H)}if(!Q&&this.#w&&this.#N){let q=this.#N,z;while(z=q?.shift())this.#Y?.(...z)}return this}pop(){try{while(this.#K){let Z=this.#V[this.#B];if(this.#b(!0),this.#F(Z)){if(Z.__staleWhileFetching)return Z.__staleWhileFetching}else if(Z!==void 0)return Z}}finally{if(this.#w&&this.#N){let Z=this.#N,J;while(J=Z?.shift())this.#Y?.(...J)}}}#b(Z){let J=this.#B,X=this.#z[J],$=this.#V[J];if(this.#C&&this.#F($))$.__abortController.abort(new Error("evicted"));else if(this.#j||this.#w){if(this.#j)this.#J?.($,X,"evict");if(this.#w)this.#N?.push([$,X,"evict"])}if(this.#x(J),Z)this.#z[J]=void 0,this.#V[J]=void 0,this.#k.push(J);if(this.#K===1)this.#B=this.#O=0,this.#k.length=0;else this.#B=this.#U[J];return this.#H.delete(X),this.#K--,J}has(Z,J={}){let{updateAgeOnHas:X=this.updateAgeOnHas,status:$}=J,Y=this.#H.get(Z);if(Y!==void 0){let Q=this.#V[Y];if(this.#F(Q)&&Q.__staleWhileFetching===void 0)return!1;if(!this.#P(Y)){if(X)this.#A(Y);if($)$.has="hit",this.#D($,Y);return!0}else if($)$.has="stale",this.#D($,Y)}else if($)$.has="miss";return!1}peek(Z,J={}){let{allowStale:X=this.allowStale}=J,$=this.#H.get(Z);if($===void 0||!X&&this.#P($))return;let Y=this.#V[$];return this.#F(Y)?Y.__staleWhileFetching:Y}#f(Z,J,X,$){let Y=J===void 0?void 0:this.#V[J];if(this.#F(Y))return Y;let Q=new FF,{signal:W}=X;W?.addEventListener("abort",()=>Q.abort(W.reason),{signal:Q.signal});let K={signal:Q.signal,options:X,context:$},G=(U,L=!1)=>{let{aborted:B}=Q.signal,w=X.ignoreFetchAbort&&U!==void 0;if(X.status)if(B&&!L){if(X.status.fetchAborted=!0,X.status.fetchError=Q.signal.reason,w)X.status.fetchAbortIgnored=!0}else X.status.fetchResolved=!0;if(B&&!w&&!L)return H(Q.signal.reason);let O=z;if(this.#V[J]===z)if(U===void 0)if(O.__staleWhileFetching)this.#V[J]=O.__staleWhileFetching;else this.#_(Z,"fetch");else{if(X.status)X.status.fetchUpdated=!0;this.set(Z,U,K.options)}return U},V=(U)=>{if(X.status)X.status.fetchRejected=!0,X.status.fetchError=U;return H(U)},H=(U)=>{let{aborted:L}=Q.signal,B=L&&X.allowStaleOnFetchAbort,w=B||X.allowStaleOnFetchRejection,O=w||X.noDeleteOnFetchRejection,M=z;if(this.#V[J]===z){if(!O||M.__staleWhileFetching===void 0)this.#_(Z,"fetch");else if(!B)this.#V[J]=M.__staleWhileFetching}if(w){if(X.status&&M.__staleWhileFetching!==void 0)X.status.returnedStale=!0;return M.__staleWhileFetching}else if(M.__returned===M)throw U},q=(U,L)=>{let B=this.#Q?.(Z,Y,K);if(B&&B instanceof Promise)B.then((w)=>U(w===void 0?void 0:w),L);Q.signal.addEventListener("abort",()=>{if(!X.ignoreFetchAbort||X.allowStaleOnFetchAbort){if(U(void 0),X.allowStaleOnFetchAbort)U=(w)=>G(w,!0)}})};if(X.status)X.status.fetchDispatched=!0;let z=new Promise(q).then(G,V),F=Object.assign(z,{__abortController:Q,__staleWhileFetching:Y,__returned:void 0});if(J===void 0)this.set(Z,F,{...K.options,status:void 0}),J=this.#H.get(Z);else this.#V[J]=F;return F}#F(Z){if(!this.#C)return!1;let J=Z;return!!J&&J instanceof Promise&&J.hasOwnProperty("__staleWhileFetching")&&J.__abortController instanceof FF}async fetch(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:$=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,ttl:Q=this.ttl,noDisposeOnSet:W=this.noDisposeOnSet,size:K=0,sizeCalculation:G=this.sizeCalculation,noUpdateTTL:V=this.noUpdateTTL,noDeleteOnFetchRejection:H=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:q=this.allowStaleOnFetchRejection,ignoreFetchAbort:z=this.ignoreFetchAbort,allowStaleOnFetchAbort:F=this.allowStaleOnFetchAbort,context:U,forceRefresh:L=!1,status:B,signal:w}=J;if(!this.#C){if(B)B.fetch="get";return this.get(Z,{allowStale:X,updateAgeOnGet:$,noDeleteOnStaleGet:Y,status:B})}let O={allowStale:X,updateAgeOnGet:$,noDeleteOnStaleGet:Y,ttl:Q,noDisposeOnSet:W,size:K,sizeCalculation:G,noUpdateTTL:V,noDeleteOnFetchRejection:H,allowStaleOnFetchRejection:q,allowStaleOnFetchAbort:F,ignoreFetchAbort:z,status:B,signal:w},M=this.#H.get(Z);if(M===void 0){if(B)B.fetch="miss";let N=this.#f(Z,M,O,U);return N.__returned=N}else{let N=this.#V[M];if(this.#F(N)){let k=X&&N.__staleWhileFetching!==void 0;if(B){if(B.fetch="inflight",k)B.returnedStale=!0}return k?N.__staleWhileFetching:N.__returned=N}let P=this.#P(M);if(!L&&!P){if(B)B.fetch="hit";if(this.#y(M),$)this.#A(M);if(B)this.#D(B,M);return N}let D=this.#f(Z,M,O,U),T=D.__staleWhileFetching!==void 0&&X;if(B){if(B.fetch=P?"stale":"refresh",T&&P)B.returnedStale=!0}return T?D.__staleWhileFetching:D.__returned=D}}async forceFetch(Z,J={}){let X=await this.fetch(Z,J);if(X===void 0)throw new Error("fetch() returned undefined");return X}memo(Z,J={}){let X=this.#W;if(!X)throw new Error("no memoMethod provided to constructor");let{context:$,forceRefresh:Y,...Q}=J,W=this.get(Z,Q);if(!Y&&W!==void 0)return W;let K=X(Z,W,{options:Q,context:$});return this.set(Z,K,Q),K}get(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:$=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,status:Q}=J,W=this.#H.get(Z);if(W!==void 0){let K=this.#V[W],G=this.#F(K);if(Q)this.#D(Q,W);if(this.#P(W)){if(Q)Q.get="stale";if(!G){if(!Y)this.#_(Z,"expire");if(Q&&X)Q.returnedStale=!0;return X?K:void 0}else{if(Q&&X&&K.__staleWhileFetching!==void 0)Q.returnedStale=!0;return X?K.__staleWhileFetching:void 0}}else{if(Q)Q.get="hit";if(G)return K.__staleWhileFetching;if(this.#y(W),$)this.#A(W);return K}}else if(Q)Q.get="miss"}#c(Z,J){this.#L[J]=Z,this.#U[Z]=J}#y(Z){if(Z!==this.#O){if(Z===this.#B)this.#B=this.#U[Z];else this.#c(this.#L[Z],this.#U[Z]);this.#c(this.#O,Z),this.#O=Z}}delete(Z){return this.#_(Z,"delete")}#_(Z,J){let X=!1;if(this.#K!==0){let $=this.#H.get(Z);if($!==void 0)if(X=!0,this.#K===1)this.#g(J);else{this.#x($);let Y=this.#V[$];if(this.#F(Y))Y.__abortController.abort(new Error("deleted"));else if(this.#j||this.#w){if(this.#j)this.#J?.(Y,Z,J);if(this.#w)this.#N?.push([Y,Z,J])}if(this.#H.delete(Z),this.#z[$]=void 0,this.#V[$]=void 0,$===this.#O)this.#O=this.#L[$];else if($===this.#B)this.#B=this.#U[$];else{let Q=this.#L[$];this.#U[Q]=this.#U[$];let W=this.#U[$];this.#L[W]=this.#L[$]}this.#K--,this.#k.push($)}}if(this.#w&&this.#N?.length){let $=this.#N,Y;while(Y=$?.shift())this.#Y?.(...Y)}return X}clear(){return this.#g("delete")}#g(Z){for(let J of this.#I({allowStale:!0})){let X=this.#V[J];if(this.#F(X))X.__abortController.abort(new Error("deleted"));else{let $=this.#z[J];if(this.#j)this.#J?.(X,$,Z);if(this.#w)this.#N?.push([X,$,Z])}}if(this.#H.clear(),this.#V.fill(void 0),this.#z.fill(void 0),this.#M&&this.#R)this.#M.fill(0),this.#R.fill(0);if(this.#E)this.#E.fill(0);if(this.#B=0,this.#O=0,this.#k.length=0,this.#G=0,this.#K=0,this.#w&&this.#N){let J=this.#N,X;while(X=J?.shift())this.#Y?.(...X)}}}import{posix as lG5,win32 as PR}from"node:path";import{fileURLToPath as pG5}from"node:url";import{lstatSync as iG5,readdir as nG5,readdirSync as sG5,readlinkSync as aG5,realpathSync as rG5}from"fs";import*as oG5 from"node:fs";import{lstat as eG5,readdir as ZV5,readlink as JV5,realpath as XV5}from"node:fs/promises";import{EventEmitter as jR}from"node:events";import qu from"node:stream";import{StringDecoder as xG5}from"node:string_decoder";var Ku=typeof process==="object"&&process?process:{stdout:null,stderr:null},fG5=(Z)=>!!Z&&typeof Z==="object"&&(Z instanceof s$||Z instanceof qu||hG5(Z)||bG5(Z)),hG5=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof jR&&typeof Z.pipe==="function"&&Z.pipe!==qu.Writable.prototype.pipe,bG5=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof jR&&typeof Z.write==="function"&&typeof Z.end==="function",cJ=Symbol("EOF"),lJ=Symbol("maybeEmitEnd"),ZX=Symbol("emittedEnd"),UF=Symbol("emittingEnd"),UG=Symbol("emittedError"),BF=Symbol("closed"),Gu=Symbol("read"),LF=Symbol("flush"),Vu=Symbol("flushChunk"),YZ=Symbol("encoding"),MW=Symbol("decoder"),d8=Symbol("flowing"),BG=Symbol("paused"),RW=Symbol("resume"),u8=Symbol("buffer"),S6=Symbol("pipes"),c8=Symbol("bufferLength"),BR=Symbol("bufferPush"),wF=Symbol("bufferShift"),q6=Symbol("objectMode"),w8=Symbol("destroyed"),LR=Symbol("error"),wR=Symbol("emitData"),Hu=Symbol("emitEnd"),OR=Symbol("emitEnd2"),lZ=Symbol("async"),NR=Symbol("abort"),OF=Symbol("aborted"),LG=Symbol("signal"),n$=Symbol("dataListeners"),E7=Symbol("discarded"),wG=(Z)=>Promise.resolve().then(Z),yG5=(Z)=>Z(),gG5=(Z)=>Z==="end"||Z==="finish"||Z==="prefinish",mG5=(Z)=>Z instanceof ArrayBuffer||!!Z&&typeof Z==="object"&&Z.constructor&&Z.constructor.name==="ArrayBuffer"&&Z.byteLength>=0,dG5=(Z)=>!Buffer.isBuffer(Z)&&ArrayBuffer.isView(Z);class MR{src;dest;opts;ondrain;constructor(Z,J,X){this.src=Z,this.dest=J,this.opts=X,this.ondrain=()=>Z[RW](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(Z){}end(){if(this.unpipe(),this.opts.end)this.dest.end()}}class zu extends MR{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(Z,J,X){super(Z,J,X);this.proxyErrors=($)=>J.emit("error",$),Z.on("error",this.proxyErrors)}}var uG5=(Z)=>!!Z.objectMode,cG5=(Z)=>!Z.objectMode&&!!Z.encoding&&Z.encoding!=="buffer";class s$ extends jR{[d8]=!1;[BG]=!1;[S6]=[];[u8]=[];[q6];[YZ];[lZ];[MW];[cJ]=!1;[ZX]=!1;[UF]=!1;[BF]=!1;[UG]=null;[c8]=0;[w8]=!1;[LG];[OF]=!1;[n$]=0;[E7]=!1;writable=!0;readable=!0;constructor(...Z){let J=Z[0]||{};super();if(J.objectMode&&typeof J.encoding==="string")throw new TypeError("Encoding and objectMode may not be used together");if(uG5(J))this[q6]=!0,this[YZ]=null;else if(cG5(J))this[YZ]=J.encoding,this[q6]=!1;else this[q6]=!1,this[YZ]=null;if(this[lZ]=!!J.async,this[MW]=this[YZ]?new xG5(this[YZ]):null,J&&J.debugExposeBuffer===!0)Object.defineProperty(this,"buffer",{get:()=>this[u8]});if(J&&J.debugExposePipes===!0)Object.defineProperty(this,"pipes",{get:()=>this[S6]});let{signal:X}=J;if(X)if(this[LG]=X,X.aborted)this[NR]();else X.addEventListener("abort",()=>this[NR]())}get bufferLength(){return this[c8]}get encoding(){return this[YZ]}set encoding(Z){throw new Error("Encoding must be set at instantiation time")}setEncoding(Z){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[q6]}set objectMode(Z){throw new Error("objectMode must be set at instantiation time")}get["async"](){return this[lZ]}set["async"](Z){this[lZ]=this[lZ]||!!Z}[NR](){this[OF]=!0,this.emit("abort",this[LG]?.reason),this.destroy(this[LG]?.reason)}get aborted(){return this[OF]}set aborted(Z){}write(Z,J,X){if(this[OF])return!1;if(this[cJ])throw new Error("write after end");if(this[w8])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;if(typeof J==="function")X=J,J="utf8";if(!J)J="utf8";let $=this[lZ]?wG:yG5;if(!this[q6]&&!Buffer.isBuffer(Z)){if(dG5(Z))Z=Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength);else if(mG5(Z))Z=Buffer.from(Z);else if(typeof Z!=="string")throw new Error("Non-contiguous data written to non-objectMode stream")}if(this[q6]){if(this[d8]&&this[c8]!==0)this[LF](!0);if(this[d8])this.emit("data",Z);else this[BR](Z);if(this[c8]!==0)this.emit("readable");if(X)$(X);return this[d8]}if(!Z.length){if(this[c8]!==0)this.emit("readable");if(X)$(X);return this[d8]}if(typeof Z==="string"&&!(J===this[YZ]&&!this[MW]?.lastNeed))Z=Buffer.from(Z,J);if(Buffer.isBuffer(Z)&&this[YZ])Z=this[MW].write(Z);if(this[d8]&&this[c8]!==0)this[LF](!0);if(this[d8])this.emit("data",Z);else this[BR](Z);if(this[c8]!==0)this.emit("readable");if(X)$(X);return this[d8]}read(Z){if(this[w8])return null;if(this[E7]=!1,this[c8]===0||Z===0||Z&&Z>this[c8])return this[lJ](),null;if(this[q6])Z=null;if(this[u8].length>1&&!this[q6])this[u8]=[this[YZ]?this[u8].join(""):Buffer.concat(this[u8],this[c8])];let J=this[Gu](Z||null,this[u8][0]);return this[lJ](),J}[Gu](Z,J){if(this[q6])this[wF]();else{let X=J;if(Z===X.length||Z===null)this[wF]();else if(typeof X==="string")this[u8][0]=X.slice(Z),J=X.slice(0,Z),this[c8]-=Z;else this[u8][0]=X.subarray(Z),J=X.subarray(0,Z),this[c8]-=Z}if(this.emit("data",J),!this[u8].length&&!this[cJ])this.emit("drain");return J}end(Z,J,X){if(typeof Z==="function")X=Z,Z=void 0;if(typeof J==="function")X=J,J="utf8";if(Z!==void 0)this.write(Z,J);if(X)this.once("end",X);if(this[cJ]=!0,this.writable=!1,this[d8]||!this[BG])this[lJ]();return this}[RW](){if(this[w8])return;if(!this[n$]&&!this[S6].length)this[E7]=!0;if(this[BG]=!1,this[d8]=!0,this.emit("resume"),this[u8].length)this[LF]();else if(this[cJ])this[lJ]();else this.emit("drain")}resume(){return this[RW]()}pause(){this[d8]=!1,this[BG]=!0,this[E7]=!1}get destroyed(){return this[w8]}get flowing(){return this[d8]}get paused(){return this[BG]}[BR](Z){if(this[q6])this[c8]+=1;else this[c8]+=Z.length;this[u8].push(Z)}[wF](){if(this[q6])this[c8]-=1;else this[c8]-=this[u8][0].length;return this[u8].shift()}[LF](Z=!1){do;while(this[Vu](this[wF]())&&this[u8].length);if(!Z&&!this[u8].length&&!this[cJ])this.emit("drain")}[Vu](Z){return this.emit("data",Z),this[d8]}pipe(Z,J){if(this[w8])return Z;this[E7]=!1;let X=this[ZX];if(J=J||{},Z===Ku.stdout||Z===Ku.stderr)J.end=!1;else J.end=J.end!==!1;if(J.proxyErrors=!!J.proxyErrors,X){if(J.end)Z.end()}else if(this[S6].push(!J.proxyErrors?new MR(this,Z,J):new zu(this,Z,J)),this[lZ])wG(()=>this[RW]());else this[RW]();return Z}unpipe(Z){let J=this[S6].find((X)=>X.dest===Z);if(J){if(this[S6].length===1){if(this[d8]&&this[n$]===0)this[d8]=!1;this[S6]=[]}else this[S6].splice(this[S6].indexOf(J),1);J.unpipe()}}addListener(Z,J){return this.on(Z,J)}on(Z,J){let X=super.on(Z,J);if(Z==="data"){if(this[E7]=!1,this[n$]++,!this[S6].length&&!this[d8])this[RW]()}else if(Z==="readable"&&this[c8]!==0)super.emit("readable");else if(gG5(Z)&&this[ZX])super.emit(Z),this.removeAllListeners(Z);else if(Z==="error"&&this[UG]){let $=J;if(this[lZ])wG(()=>$.call(this,this[UG]));else $.call(this,this[UG])}return X}removeListener(Z,J){return this.off(Z,J)}off(Z,J){let X=super.off(Z,J);if(Z==="data"){if(this[n$]=this.listeners("data").length,this[n$]===0&&!this[E7]&&!this[S6].length)this[d8]=!1}return X}removeAllListeners(Z){let J=super.removeAllListeners(Z);if(Z==="data"||Z===void 0){if(this[n$]=0,!this[E7]&&!this[S6].length)this[d8]=!1}return J}get emittedEnd(){return this[ZX]}[lJ](){if(!this[UF]&&!this[ZX]&&!this[w8]&&this[u8].length===0&&this[cJ]){if(this[UF]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[BF])this.emit("close");this[UF]=!1}}emit(Z,...J){let X=J[0];if(Z!=="error"&&Z!=="close"&&Z!==w8&&this[w8])return!1;else if(Z==="data")return!this[q6]&&!X?!1:this[lZ]?(wG(()=>this[wR](X)),!0):this[wR](X);else if(Z==="end")return this[Hu]();else if(Z==="close"){if(this[BF]=!0,!this[ZX]&&!this[w8])return!1;let Y=super.emit("close");return this.removeAllListeners("close"),Y}else if(Z==="error"){this[UG]=X,super.emit(LR,X);let Y=!this[LG]||this.listeners("error").length?super.emit("error",X):!1;return this[lJ](),Y}else if(Z==="resume"){let Y=super.emit("resume");return this[lJ](),Y}else if(Z==="finish"||Z==="prefinish"){let Y=super.emit(Z);return this.removeAllListeners(Z),Y}let $=super.emit(Z,...J);return this[lJ](),$}[wR](Z){for(let X of this[S6])if(X.dest.write(Z)===!1)this.pause();let J=this[E7]?!1:super.emit("data",Z);return this[lJ](),J}[Hu](){if(this[ZX])return!1;return this[ZX]=!0,this.readable=!1,this[lZ]?(wG(()=>this[OR]()),!0):this[OR]()}[OR](){if(this[MW]){let J=this[MW].end();if(J){for(let X of this[S6])X.dest.write(J);if(!this[E7])super.emit("data",J)}}for(let J of this[S6])J.end();let Z=super.emit("end");return this.removeAllListeners("end"),Z}async collect(){let Z=Object.assign([],{dataLength:0});if(!this[q6])Z.dataLength=0;let J=this.promise();return this.on("data",(X)=>{if(Z.push(X),!this[q6])Z.dataLength+=X.length}),await J,Z}async concat(){if(this[q6])throw new Error("cannot concat in objectMode");let Z=await this.collect();return this[YZ]?Z.join(""):Buffer.concat(Z,Z.dataLength)}async promise(){return new Promise((Z,J)=>{this.on(w8,()=>J(new Error("stream destroyed"))),this.on("error",(X)=>J(X)),this.on("end",()=>Z())})}[Symbol.asyncIterator](){this[E7]=!1;let Z=!1,J=async()=>{return this.pause(),Z=!0,{value:void 0,done:!0}};return{next:()=>{if(Z)return J();let $=this.read();if($!==null)return Promise.resolve({done:!1,value:$});if(this[cJ])return J();let Y,Q,W=(H)=>{this.off("data",K),this.off("end",G),this.off(w8,V),J(),Q(H)},K=(H)=>{this.off("error",W),this.off("end",G),this.off(w8,V),this.pause(),Y({value:H,done:!!this[cJ]})},G=()=>{this.off("error",W),this.off("data",K),this.off(w8,V),J(),Y({done:!0,value:void 0})},V=()=>W(new Error("stream destroyed"));return new Promise((H,q)=>{Q=q,Y=H,this.once(w8,V),this.once("error",W),this.once("end",G),this.once("data",K)})},throw:J,return:J,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[E7]=!1;let Z=!1,J=()=>{return this.pause(),this.off(LR,J),this.off(w8,J),this.off("end",J),Z=!0,{done:!0,value:void 0}},X=()=>{if(Z)return J();let $=this.read();return $===null?J():{done:!1,value:$}};return this.once("end",J),this.once(LR,J),this.once(w8,J),{next:X,throw:J,return:J,[Symbol.iterator](){return this}}}destroy(Z){if(this[w8]){if(Z)this.emit("error",Z);else this.emit(w8);return this}this[w8]=!0,this[E7]=!0,this[u8].length=0,this[c8]=0;let J=this;if(typeof J.close==="function"&&!this[BF])J.close();if(Z)this.emit("error",Z);else this.emit(w8);return this}static get isStream(){return fG5}}var tG5=rG5.native,NG={lstatSync:iG5,readdir:nG5,readdirSync:sG5,readlinkSync:aG5,realpathSync:tG5,promises:{lstat:eG5,readdir:ZV5,readlink:JV5,realpath:XV5}},wu=(Z)=>!Z||Z===NG||Z===oG5?NG:{...NG,...Z,promises:{...NG.promises,...Z.promises||{}}},Ou=/^\\\\\?\\([a-z]:)\\?$/i,$V5=(Z)=>Z.replace(/\//g,"\\").replace(Ou,"$1\\"),YV5=/[\\\/]/,V9=0,Nu=1,ju=2,pZ=4,Mu=6,Ru=8,a$=10,Du=12,G9=15,OG=~G9,RR=16,Fu=32,jG=64,QZ=128,NF=256,MF=512,Uu=jG|QZ|MF,QV5=1023,DR=(Z)=>Z.isFile()?Ru:Z.isDirectory()?pZ:Z.isSymbolicLink()?a$:Z.isCharacterDevice()?ju:Z.isBlockDevice()?Mu:Z.isSocket()?Du:Z.isFIFO()?Nu:V9,Bu=new Map,MG=(Z)=>{let J=Bu.get(Z);if(J)return J;let X=Z.normalize("NFKD");return Bu.set(Z,X),X},Lu=new Map,jF=(Z)=>{let J=Lu.get(Z);if(J)return J;let X=MG(Z.toLowerCase());return Lu.set(Z,X),X};class CR extends FG{constructor(){super({max:256})}}class Pu extends FG{constructor(Z=16384){super({maxSize:Z,sizeCalculation:(J)=>J.length+1})}}var Cu=Symbol("PathScurry setAsCwd");class _6{name;root;roots;parent;nocase;isCWD=!1;#Z;#X;get dev(){return this.#X}#J;get mode(){return this.#J}#$;get nlink(){return this.#$}#Y;get uid(){return this.#Y}#Q;get gid(){return this.#Q}#W;get rdev(){return this.#W}#K;get blksize(){return this.#K}#G;get ino(){return this.#G}#H;get size(){return this.#H}#z;get blocks(){return this.#z}#V;get atimeMs(){return this.#V}#U;get mtimeMs(){return this.#U}#L;get ctimeMs(){return this.#L}#B;get birthtimeMs(){return this.#B}#O;get atime(){return this.#O}#k;get mtime(){return this.#k}#N;get ctime(){return this.#N}#E;get birthtime(){return this.#E}#R;#M;#j;#C;#w;#v;#q;#A;#D;#S;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(Z,J=V9,X,$,Y,Q,W){if(this.name=Z,this.#R=Y?jF(Z):MG(Z),this.#q=J&QV5,this.nocase=Y,this.roots=$,this.root=X||this,this.#A=Q,this.#j=W.fullpath,this.#w=W.relative,this.#v=W.relativePosix,this.parent=W.parent,this.parent)this.#Z=this.parent.#Z;else this.#Z=wu(W.fs)}depth(){if(this.#M!==void 0)return this.#M;if(!this.parent)return this.#M=0;return this.#M=this.parent.depth()+1}childrenCache(){return this.#A}resolve(Z){if(!Z)return this;let J=this.getRootString(Z),$=Z.substring(J.length).split(this.splitSep);return J?this.getRoot(J).#P($):this.#P($)}#P(Z){let J=this;for(let X of Z)J=J.child(X);return J}children(){let Z=this.#A.get(this);if(Z)return Z;let J=Object.assign([],{provisional:0});return this.#A.set(this,J),this.#q&=~RR,J}child(Z,J){if(Z===""||Z===".")return this;if(Z==="..")return this.parent||this;let X=this.children(),$=this.nocase?jF(Z):MG(Z);for(let K of X)if(K.#R===$)return K;let Y=this.parent?this.sep:"",Q=this.#j?this.#j+Y+Z:void 0,W=this.newChild(Z,V9,{...J,parent:this,fullpath:Q});if(!this.canReaddir())W.#q|=QZ;return X.push(W),W}relative(){if(this.isCWD)return"";if(this.#w!==void 0)return this.#w;let Z=this.name,J=this.parent;if(!J)return this.#w=this.name;let X=J.relative();return X+(!X||!J.parent?"":this.sep)+Z}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#v!==void 0)return this.#v;let Z=this.name,J=this.parent;if(!J)return this.#v=this.fullpathPosix();let X=J.relativePosix();return X+(!X||!J.parent?"":"/")+Z}fullpath(){if(this.#j!==void 0)return this.#j;let Z=this.name,J=this.parent;if(!J)return this.#j=this.name;let $=J.fullpath()+(!J.parent?"":this.sep)+Z;return this.#j=$}fullpathPosix(){if(this.#C!==void 0)return this.#C;if(this.sep==="/")return this.#C=this.fullpath();if(!this.parent){let $=this.fullpath().replace(/\\/g,"/");if(/^[a-z]:\//i.test($))return this.#C=`//?/${$}`;else return this.#C=$}let Z=this.parent,J=Z.fullpathPosix(),X=J+(!J||!Z.parent?"":"/")+this.name;return this.#C=X}isUnknown(){return(this.#q&G9)===V9}isType(Z){return this[`is${Z}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#q&G9)===Ru}isDirectory(){return(this.#q&G9)===pZ}isCharacterDevice(){return(this.#q&G9)===ju}isBlockDevice(){return(this.#q&G9)===Mu}isFIFO(){return(this.#q&G9)===Nu}isSocket(){return(this.#q&G9)===Du}isSymbolicLink(){return(this.#q&a$)===a$}lstatCached(){return this.#q&Fu?this:void 0}readlinkCached(){return this.#D}realpathCached(){return this.#S}readdirCached(){let Z=this.children();return Z.slice(0,Z.provisional)}canReadlink(){if(this.#D)return!0;if(!this.parent)return!1;let Z=this.#q&G9;return!(Z!==V9&&Z!==a$||this.#q&NF||this.#q&QZ)}calledReaddir(){return!!(this.#q&RR)}isENOENT(){return!!(this.#q&QZ)}isNamed(Z){return!this.nocase?this.#R===MG(Z):this.#R===jF(Z)}async readlink(){let Z=this.#D;if(Z)return Z;if(!this.canReadlink())return;if(!this.parent)return;try{let J=await this.#Z.promises.readlink(this.fullpath()),X=(await this.parent.realpath())?.resolve(J);if(X)return this.#D=X}catch(J){this.#b(J.code);return}}readlinkSync(){let Z=this.#D;if(Z)return Z;if(!this.canReadlink())return;if(!this.parent)return;try{let J=this.#Z.readlinkSync(this.fullpath()),X=this.parent.realpathSync()?.resolve(J);if(X)return this.#D=X}catch(J){this.#b(J.code);return}}#m(Z){this.#q|=RR;for(let J=Z.provisional;J<Z.length;J++){let X=Z[J];if(X)X.#x()}}#x(){if(this.#q&QZ)return;this.#q=(this.#q|QZ)&OG,this.#h()}#h(){let Z=this.children();Z.provisional=0;for(let J of Z)J.#x()}#d(){this.#q|=MF,this.#T()}#T(){if(this.#q&jG)return;let Z=this.#q;if((Z&G9)===pZ)Z&=OG;this.#q=Z|jG,this.#h()}#I(Z=""){if(Z==="ENOTDIR"||Z==="EPERM")this.#T();else if(Z==="ENOENT")this.#x();else this.children().provisional=0}#u(Z=""){if(Z==="ENOTDIR")this.parent.#T();else if(Z==="ENOENT")this.#x()}#b(Z=""){let J=this.#q;if(J|=NF,Z==="ENOENT")J|=QZ;if(Z==="EINVAL"||Z==="UNKNOWN")J&=OG;if(this.#q=J,Z==="ENOTDIR"&&this.parent)this.parent.#T()}#f(Z,J){return this.#c(Z,J)||this.#F(Z,J)}#F(Z,J){let X=DR(Z),$=this.newChild(Z.name,X,{parent:this}),Y=$.#q&G9;if(Y!==pZ&&Y!==a$&&Y!==V9)$.#q|=jG;return J.unshift($),J.provisional++,$}#c(Z,J){for(let X=J.provisional;X<J.length;X++){let $=J[X];if((this.nocase?jF(Z.name):MG(Z.name))!==$.#R)continue;return this.#y(Z,$,X,J)}}#y(Z,J,X,$){let Y=J.name;if(J.#q=J.#q&OG|DR(Z),Y!==Z.name)J.name=Z.name;if(X!==$.provisional){if(X===$.length-1)$.pop();else $.splice(X,1);$.unshift(J)}return $.provisional++,J}async lstat(){if((this.#q&QZ)===0)try{return this.#_(await this.#Z.promises.lstat(this.fullpath())),this}catch(Z){this.#u(Z.code)}}lstatSync(){if((this.#q&QZ)===0)try{return this.#_(this.#Z.lstatSync(this.fullpath())),this}catch(Z){this.#u(Z.code)}}#_(Z){let{atime:J,atimeMs:X,birthtime:$,birthtimeMs:Y,blksize:Q,blocks:W,ctime:K,ctimeMs:G,dev:V,gid:H,ino:q,mode:z,mtime:F,mtimeMs:U,nlink:L,rdev:B,size:w,uid:O}=Z;this.#O=J,this.#V=X,this.#E=$,this.#B=Y,this.#K=Q,this.#z=W,this.#N=K,this.#L=G,this.#X=V,this.#Q=H,this.#G=q,this.#J=z,this.#k=F,this.#U=U,this.#$=L,this.#W=B,this.#H=w,this.#Y=O;let M=DR(Z);if(this.#q=this.#q&OG|M|Fu,M!==V9&&M!==pZ&&M!==a$)this.#q|=jG}#g=[];#p=!1;#i(Z){this.#p=!1;let J=this.#g.slice();this.#g.length=0,J.forEach((X)=>X(null,Z))}readdirCB(Z,J=!1){if(!this.canReaddir()){if(J)Z(null,[]);else queueMicrotask(()=>Z(null,[]));return}let X=this.children();if(this.calledReaddir()){let Y=X.slice(0,X.provisional);if(J)Z(null,Y);else queueMicrotask(()=>Z(null,Y));return}if(this.#g.push(Z),this.#p)return;this.#p=!0;let $=this.fullpath();this.#Z.readdir($,{withFileTypes:!0},(Y,Q)=>{if(Y)this.#I(Y.code),X.provisional=0;else{for(let W of Q)this.#f(W,X);this.#m(X)}this.#i(X.slice(0,X.provisional));return})}#l;async readdir(){if(!this.canReaddir())return[];let Z=this.children();if(this.calledReaddir())return Z.slice(0,Z.provisional);let J=this.fullpath();if(this.#l)await this.#l;else{let X=()=>{};this.#l=new Promise(($)=>X=$);try{for(let $ of await this.#Z.promises.readdir(J,{withFileTypes:!0}))this.#f($,Z);this.#m(Z)}catch($){this.#I($.code),Z.provisional=0}this.#l=void 0,X()}return Z.slice(0,Z.provisional)}readdirSync(){if(!this.canReaddir())return[];let Z=this.children();if(this.calledReaddir())return Z.slice(0,Z.provisional);let J=this.fullpath();try{for(let X of this.#Z.readdirSync(J,{withFileTypes:!0}))this.#f(X,Z);this.#m(Z)}catch(X){this.#I(X.code),Z.provisional=0}return Z.slice(0,Z.provisional)}canReaddir(){if(this.#q&Uu)return!1;let Z=G9&this.#q;if(!(Z===V9||Z===pZ||Z===a$))return!1;return!0}shouldWalk(Z,J){return(this.#q&pZ)===pZ&&!(this.#q&Uu)&&!Z.has(this)&&(!J||J(this))}async realpath(){if(this.#S)return this.#S;if((MF|NF|QZ)&this.#q)return;try{let Z=await this.#Z.promises.realpath(this.fullpath());return this.#S=this.resolve(Z)}catch(Z){this.#d()}}realpathSync(){if(this.#S)return this.#S;if((MF|NF|QZ)&this.#q)return;try{let Z=this.#Z.realpathSync(this.fullpath());return this.#S=this.resolve(Z)}catch(Z){this.#d()}}[Cu](Z){if(Z===this)return;Z.isCWD=!1,this.isCWD=!0;let J=new Set([]),X=[],$=this;while($&&$.parent)J.add($),$.#w=X.join(this.sep),$.#v=X.join("/"),$=$.parent,X.push("..");$=Z;while($&&$.parent&&!J.has($))$.#w=void 0,$.#v=void 0,$=$.parent}}class RF extends _6{sep="\\";splitSep=YV5;constructor(Z,J=V9,X,$,Y,Q,W){super(Z,J,X,$,Y,Q,W)}newChild(Z,J=V9,X={}){return new RF(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}getRootString(Z){return PR.parse(Z).root}getRoot(Z){if(Z=$V5(Z.toUpperCase()),Z===this.root.name)return this.root;for(let[J,X]of Object.entries(this.roots))if(this.sameRoot(Z,J))return this.roots[Z]=X;return this.roots[Z]=new RG(Z,this).root}sameRoot(Z,J=this.root.name){return Z=Z.toUpperCase().replace(/\//g,"\\").replace(Ou,"$1\\"),Z===J}}class DF extends _6{splitSep="/";sep="/";constructor(Z,J=V9,X,$,Y,Q,W){super(Z,J,X,$,Y,Q,W)}getRootString(Z){return Z.startsWith("/")?"/":""}getRoot(Z){return this.root}newChild(Z,J=V9,X={}){return new DF(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}}class TR{root;rootPath;roots;cwd;#Z;#X;#J;nocase;#$;constructor(Z=process.cwd(),J,X,{nocase:$,childrenCacheSize:Y=16384,fs:Q=NG}={}){if(this.#$=wu(Q),Z instanceof URL||Z.startsWith("file://"))Z=pG5(Z);let W=J.resolve(Z);this.roots=Object.create(null),this.rootPath=this.parseRootPath(W),this.#Z=new CR,this.#X=new CR,this.#J=new Pu(Y);let K=W.substring(this.rootPath.length).split(X);if(K.length===1&&!K[0])K.pop();if($===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=$,this.root=this.newRoot(this.#$),this.roots[this.rootPath]=this.root;let G=this.root,V=K.length-1,H=J.sep,q=this.rootPath,z=!1;for(let F of K){let U=V--;G=G.child(F,{relative:new Array(U).fill("..").join(H),relativePosix:new Array(U).fill("..").join("/"),fullpath:q+=(z?"":H)+F}),z=!0}this.cwd=G}depth(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.depth()}childrenCache(){return this.#J}resolve(...Z){let J="";for(let Y=Z.length-1;Y>=0;Y--){let Q=Z[Y];if(!Q||Q===".")continue;if(J=J?`${Q}/${J}`:Q,this.isAbsolute(Q))break}let X=this.#Z.get(J);if(X!==void 0)return X;let $=this.cwd.resolve(J).fullpath();return this.#Z.set(J,$),$}resolvePosix(...Z){let J="";for(let Y=Z.length-1;Y>=0;Y--){let Q=Z[Y];if(!Q||Q===".")continue;if(J=J?`${Q}/${J}`:Q,this.isAbsolute(Q))break}let X=this.#X.get(J);if(X!==void 0)return X;let $=this.cwd.resolve(J).fullpathPosix();return this.#X.set(J,$),$}relative(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.relative()}relativePosix(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.relativePosix()}basename(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.name}dirname(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return(Z.parent||Z).fullpath()}async readdir(Z=this.cwd,J={withFileTypes:!0}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X}=J;if(!Z.canReaddir())return[];else{let $=await Z.readdir();return X?$:$.map((Y)=>Y.name)}}readdirSync(Z=this.cwd,J={withFileTypes:!0}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0}=J;if(!Z.canReaddir())return[];else if(X)return Z.readdirSync();else return Z.readdirSync().map(($)=>$.name)}async lstat(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.lstat()}lstatSync(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.lstatSync()}async readlink(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z.withFileTypes,Z=this.cwd;let X=await Z.readlink();return J?X:X?.fullpath()}readlinkSync(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z.withFileTypes,Z=this.cwd;let X=Z.readlinkSync();return J?X:X?.fullpath()}async realpath(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z.withFileTypes,Z=this.cwd;let X=await Z.realpath();return J?X:X?.fullpath()}realpathSync(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z.withFileTypes,Z=this.cwd;let X=Z.realpathSync();return J?X:X?.fullpath()}async walk(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,W=[];if(!Y||Y(Z))W.push(X?Z:Z.fullpath());let K=new Set,G=(H,q)=>{K.add(H),H.readdirCB((z,F)=>{if(z)return q(z);let U=F.length;if(!U)return q();let L=()=>{if(--U===0)q()};for(let B of F){if(!Y||Y(B))W.push(X?B:B.fullpath());if($&&B.isSymbolicLink())B.realpath().then((w)=>w?.isUnknown()?w.lstat():w).then((w)=>w?.shouldWalk(K,Q)?G(w,L):L());else if(B.shouldWalk(K,Q))G(B,L);else L()}},!0)},V=Z;return new Promise((H,q)=>{G(V,(z)=>{if(z)return q(z);H(W)})})}walkSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,W=[];if(!Y||Y(Z))W.push(X?Z:Z.fullpath());let K=new Set([Z]);for(let G of K){let V=G.readdirSync();for(let H of V){if(!Y||Y(H))W.push(X?H:H.fullpath());let q=H;if(H.isSymbolicLink()){if(!($&&(q=H.realpathSync())))continue;if(q.isUnknown())q.lstatSync()}if(q.shouldWalk(K,Q))K.add(q)}}return W}[Symbol.asyncIterator](){return this.iterate()}iterate(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;return this.stream(Z,J)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J;if(!Y||Y(Z))yield X?Z:Z.fullpath();let W=new Set([Z]);for(let K of W){let G=K.readdirSync();for(let V of G){if(!Y||Y(V))yield X?V:V.fullpath();let H=V;if(V.isSymbolicLink()){if(!($&&(H=V.realpathSync())))continue;if(H.isUnknown())H.lstatSync()}if(H.shouldWalk(W,Q))W.add(H)}}}stream(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,W=new s$({objectMode:!0});if(!Y||Y(Z))W.write(X?Z:Z.fullpath());let K=new Set,G=[Z],V=0,H=()=>{let q=!1;while(!q){let z=G.shift();if(!z){if(V===0)W.end();return}V++,K.add(z);let F=(L,B,w=!1)=>{if(L)return W.emit("error",L);if($&&!w){let O=[];for(let M of B)if(M.isSymbolicLink())O.push(M.realpath().then((N)=>N?.isUnknown()?N.lstat():N));if(O.length){Promise.all(O).then(()=>F(null,B,!0));return}}for(let O of B)if(O&&(!Y||Y(O))){if(!W.write(X?O:O.fullpath()))q=!0}V--;for(let O of B){let M=O.realpathCached()||O;if(M.shouldWalk(K,Q))G.push(M)}if(q&&!W.flowing)W.once("drain",H);else if(!U)H()},U=!0;z.readdirCB(F,!0),U=!1}};return H(),W}streamSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,W=new s$({objectMode:!0}),K=new Set;if(!Y||Y(Z))W.write(X?Z:Z.fullpath());let G=[Z],V=0,H=()=>{let q=!1;while(!q){let z=G.shift();if(!z){if(V===0)W.end();return}V++,K.add(z);let F=z.readdirSync();for(let U of F)if(!Y||Y(U)){if(!W.write(X?U:U.fullpath()))q=!0}V--;for(let U of F){let L=U;if(U.isSymbolicLink()){if(!($&&(L=U.realpathSync())))continue;if(L.isUnknown())L.lstatSync()}if(L.shouldWalk(K,Q))G.push(L)}}if(q&&!W.flowing)W.once("drain",H)};return H(),W}chdir(Z=this.cwd){let J=this.cwd;this.cwd=typeof Z==="string"?this.cwd.resolve(Z):Z,this.cwd[Cu](J)}}class RG extends TR{sep="\\";constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,PR,"\\",{...J,nocase:X});this.nocase=X;for(let $=this.cwd;$;$=$.parent)$.nocase=this.nocase}parseRootPath(Z){return PR.parse(Z).root.toUpperCase()}newRoot(Z){return new RF(this.rootPath,pZ,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")||Z.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(Z)}}class DG extends TR{sep="/";constructor(Z=process.cwd(),J={}){let{nocase:X=!1}=J;super(Z,lG5,"/",{...J,nocase:X});this.nocase=X}parseRootPath(Z){return"/"}newRoot(Z){return new DF(this.rootPath,pZ,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")}}class PF extends DG{constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,{...J,nocase:X})}}var g46=process.platform==="win32"?RF:DF,Tu=process.platform==="win32"?RG:process.platform==="darwin"?PF:DG;var WV5=(Z)=>Z.length>=1,KV5=(Z)=>Z.length>=1;class DW{#Z;#X;#J;length;#$;#Y;#Q;#W;#K;#G;#H=!0;constructor(Z,J,X,$){if(!WV5(Z))throw new TypeError("empty pattern list");if(!KV5(J))throw new TypeError("empty glob list");if(J.length!==Z.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=Z.length,X<0||X>=this.length)throw new TypeError("index out of range");if(this.#Z=Z,this.#X=J,this.#J=X,this.#$=$,this.#J===0){if(this.isUNC()){let[Y,Q,W,K,...G]=this.#Z,[V,H,q,z,...F]=this.#X;if(G[0]==="")G.shift(),F.shift();let U=[Y,Q,W,K,""].join("/"),L=[V,H,q,z,""].join("/");this.#Z=[U,...G],this.#X=[L,...F],this.length=this.#Z.length}else if(this.isDrive()||this.isAbsolute()){let[Y,...Q]=this.#Z,[W,...K]=this.#X;if(Q[0]==="")Q.shift(),K.shift();let G=Y+"/",V=W+"/";this.#Z=[G,...Q],this.#X=[V,...K],this.length=this.#Z.length}}}pattern(){return this.#Z[this.#J]}isString(){return typeof this.#Z[this.#J]==="string"}isGlobstar(){return this.#Z[this.#J]===J6}isRegExp(){return this.#Z[this.#J]instanceof RegExp}globString(){return this.#Q=this.#Q||(this.#J===0?this.isAbsolute()?this.#X[0]+this.#X.slice(1).join("/"):this.#X.join("/"):this.#X.slice(this.#J).join("/"))}hasMore(){return this.length>this.#J+1}rest(){if(this.#Y!==void 0)return this.#Y;if(!this.hasMore())return this.#Y=null;return this.#Y=new DW(this.#Z,this.#X,this.#J+1,this.#$),this.#Y.#G=this.#G,this.#Y.#K=this.#K,this.#Y.#W=this.#W,this.#Y}isUNC(){let Z=this.#Z;return this.#K!==void 0?this.#K:this.#K=this.#$==="win32"&&this.#J===0&&Z[0]===""&&Z[1]===""&&typeof Z[2]==="string"&&!!Z[2]&&typeof Z[3]==="string"&&!!Z[3]}isDrive(){let Z=this.#Z;return this.#W!==void 0?this.#W:this.#W=this.#$==="win32"&&this.#J===0&&this.length>1&&typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0])}isAbsolute(){let Z=this.#Z;return this.#G!==void 0?this.#G:this.#G=Z[0]===""&&Z.length>1||this.isDrive()||this.isUNC()}root(){let Z=this.#Z[0];return typeof Z==="string"&&this.isAbsolute()&&this.#J===0?Z:""}checkFollowGlobstar(){return!(this.#J===0||!this.isGlobstar()||!this.#H)}markFollowGlobstar(){if(this.#J===0||!this.isGlobstar()||!this.#H)return!1;return this.#H=!1,!0}}var GV5=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class PG{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(Z,{nobrace:J,nocase:X,noext:$,noglobstar:Y,platform:Q=GV5}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=Q,this.mmopts={dot:!0,nobrace:J,nocase:X,noext:$,noglobstar:Y,optimizationLevel:2,platform:Q,nocomment:!0,nonegate:!0};for(let W of Z)this.add(W)}add(Z){let J=new K9(Z,this.mmopts);for(let X=0;X<J.set.length;X++){let $=J.set[X],Y=J.globParts[X];if(!$||!Y)throw new Error("invalid pattern object");while($[0]==="."&&Y[0]===".")$.shift(),Y.shift();let Q=new DW($,Y,0,this.platform),W=new K9(Q.globString(),this.mmopts),K=Y[Y.length-1]==="**",G=Q.isAbsolute();if(G)this.absolute.push(W);else this.relative.push(W);if(K)if(G)this.absoluteChildren.push(W);else this.relativeChildren.push(W)}}ignored(Z){let J=Z.fullpath(),X=`${J}/`,$=Z.relative()||".",Y=`${$}/`;for(let Q of this.relative)if(Q.match($)||Q.match(Y))return!0;for(let Q of this.absolute)if(Q.match(J)||Q.match(X))return!0;return!1}childrenIgnored(Z){let J=Z.fullpath()+"/",X=(Z.relative()||".")+"/";for(let $ of this.relativeChildren)if($.match(X))return!0;for(let $ of this.absoluteChildren)if($.match(J))return!0;return!1}}class kR{store;constructor(Z=new Map){this.store=Z}copy(){return new kR(new Map(this.store))}hasWalked(Z,J){return this.store.get(Z.fullpath())?.has(J.globString())}storeWalked(Z,J){let X=Z.fullpath(),$=this.store.get(X);if($)$.add(J.globString());else this.store.set(X,new Set([J.globString()]))}}class ku{store=new Map;add(Z,J,X){let $=(J?2:0)|(X?1:0),Y=this.store.get(Z);this.store.set(Z,Y===void 0?$:$&Y)}entries(){return[...this.store.entries()].map(([Z,J])=>[Z,!!(J&2),!!(J&1)])}}class Eu{store=new Map;add(Z,J){if(!Z.canReaddir())return;let X=this.store.get(Z);if(X){if(!X.find(($)=>$.globString()===J.globString()))X.push(J)}else this.store.set(Z,[J])}get(Z){let J=this.store.get(Z);if(!J)throw new Error("attempting to walk unknown path");return J}entries(){return this.keys().map((Z)=>[Z,this.store.get(Z)])}keys(){return[...this.store.keys()].filter((Z)=>Z.canReaddir())}}class CG{hasWalkedCache;matches=new ku;subwalks=new Eu;patterns;follow;dot;opts;constructor(Z,J){this.opts=Z,this.follow=!!Z.follow,this.dot=!!Z.dot,this.hasWalkedCache=J?J.copy():new kR}processPatterns(Z,J){this.patterns=J;let X=J.map(($)=>[Z,$]);for(let[$,Y]of X){this.hasWalkedCache.storeWalked($,Y);let Q=Y.root(),W=Y.isAbsolute()&&this.opts.absolute!==!1;if(Q){$=$.resolve(Q==="/"&&this.opts.root!==void 0?this.opts.root:Q);let H=Y.rest();if(!H){this.matches.add($,!0,!1);continue}else Y=H}if($.isENOENT())continue;let K,G,V=!1;while(typeof(K=Y.pattern())==="string"&&(G=Y.rest()))$=$.resolve(K),Y=G,V=!0;if(K=Y.pattern(),G=Y.rest(),V){if(this.hasWalkedCache.hasWalked($,Y))continue;this.hasWalkedCache.storeWalked($,Y)}if(typeof K==="string"){let H=K===".."||K===""||K===".";this.matches.add($.resolve(K),W,H);continue}else if(K===J6){if(!$.isSymbolicLink()||this.follow||Y.checkFollowGlobstar())this.subwalks.add($,Y);let H=G?.pattern(),q=G?.rest();if(!G||(H===""||H===".")&&!q)this.matches.add($,W,H===""||H===".");else if(H===".."){let z=$.parent||$;if(!q)this.matches.add(z,W,!0);else if(!this.hasWalkedCache.hasWalked(z,q))this.subwalks.add(z,q)}}else if(K instanceof RegExp)this.subwalks.add($,Y)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new CG(this.opts,this.hasWalkedCache)}filterEntries(Z,J){let X=this.subwalks.get(Z),$=this.child();for(let Y of J)for(let Q of X){let W=Q.isAbsolute(),K=Q.pattern(),G=Q.rest();if(K===J6)$.testGlobstar(Y,Q,G,W);else if(K instanceof RegExp)$.testRegExp(Y,K,G,W);else $.testString(Y,K,G,W)}return $}testGlobstar(Z,J,X,$){if(this.dot||!Z.name.startsWith(".")){if(!J.hasMore())this.matches.add(Z,$,!1);if(Z.canReaddir()){if(this.follow||!Z.isSymbolicLink())this.subwalks.add(Z,J);else if(Z.isSymbolicLink()){if(X&&J.checkFollowGlobstar())this.subwalks.add(Z,X);else if(J.markFollowGlobstar())this.subwalks.add(Z,J)}}}if(X){let Y=X.pattern();if(typeof Y==="string"&&Y!==".."&&Y!==""&&Y!==".")this.testString(Z,Y,X.rest(),$);else if(Y===".."){let Q=Z.parent||Z;this.subwalks.add(Q,X)}else if(Y instanceof RegExp)this.testRegExp(Z,Y,X.rest(),$)}}testRegExp(Z,J,X,$){if(!J.test(Z.name))return;if(!X)this.matches.add(Z,$,!1);else this.subwalks.add(Z,X)}testString(Z,J,X,$){if(!Z.isNamed(J))return;if(!X)this.matches.add(Z,$,!1);else this.subwalks.add(Z,X)}}var VV5=(Z,J)=>typeof Z==="string"?new PG([Z],J):Array.isArray(Z)?new PG(Z,J):Z;class ER{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#Z=[];#X;#J;signal;maxDepth;includeChildMatches;constructor(Z,J,X){if(this.patterns=Z,this.path=J,this.opts=X,this.#J=!X.posix&&X.platform==="win32"?"\\":"/",this.includeChildMatches=X.includeChildMatches!==!1,X.ignore||!this.includeChildMatches){if(this.#X=VV5(X.ignore??[],X),!this.includeChildMatches&&typeof this.#X.add!=="function")throw new Error("cannot ignore child matches, ignore lacks add() method.")}if(this.maxDepth=X.maxDepth||1/0,X.signal)this.signal=X.signal,this.signal.addEventListener("abort",()=>{this.#Z.length=0})}#$(Z){return this.seen.has(Z)||!!this.#X?.ignored?.(Z)}#Y(Z){return!!this.#X?.childrenIgnored?.(Z)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let Z=void 0;while(!this.paused&&(Z=this.#Z.shift()))Z()}onResume(Z){if(this.signal?.aborted)return;if(!this.paused)Z();else this.#Z.push(Z)}async matchCheck(Z,J){if(J&&this.opts.nodir)return;let X;if(this.opts.realpath){if(X=Z.realpathCached()||await Z.realpath(),!X)return;Z=X}let Y=Z.isUnknown()||this.opts.stat?await Z.lstat():Z;if(this.opts.follow&&this.opts.nodir&&Y?.isSymbolicLink()){let Q=await Y.realpath();if(Q&&(Q.isUnknown()||this.opts.stat))await Q.lstat()}return this.matchCheckTest(Y,J)}matchCheckTest(Z,J){return Z&&(this.maxDepth===1/0||Z.depth()<=this.maxDepth)&&(!J||Z.canReaddir())&&(!this.opts.nodir||!Z.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!Z.isSymbolicLink()||!Z.realpathCached()?.isDirectory())&&!this.#$(Z)?Z:void 0}matchCheckSync(Z,J){if(J&&this.opts.nodir)return;let X;if(this.opts.realpath){if(X=Z.realpathCached()||Z.realpathSync(),!X)return;Z=X}let Y=Z.isUnknown()||this.opts.stat?Z.lstatSync():Z;if(this.opts.follow&&this.opts.nodir&&Y?.isSymbolicLink()){let Q=Y.realpathSync();if(Q&&(Q?.isUnknown()||this.opts.stat))Q.lstatSync()}return this.matchCheckTest(Y,J)}matchFinish(Z,J){if(this.#$(Z))return;if(!this.includeChildMatches&&this.#X?.add){let Y=`${Z.relativePosix()}/**`;this.#X.add(Y)}let X=this.opts.absolute===void 0?J:this.opts.absolute;this.seen.add(Z);let $=this.opts.mark&&Z.isDirectory()?this.#J:"";if(this.opts.withFileTypes)this.matchEmit(Z);else if(X){let Y=this.opts.posix?Z.fullpathPosix():Z.fullpath();this.matchEmit(Y+$)}else{let Y=this.opts.posix?Z.relativePosix():Z.relative(),Q=this.opts.dotRelative&&!Y.startsWith(".."+this.#J)?"."+this.#J:"";this.matchEmit(!Y?"."+$:Q+Y+$)}}async match(Z,J,X){let $=await this.matchCheck(Z,X);if($)this.matchFinish($,J)}matchSync(Z,J,X){let $=this.matchCheckSync(Z,X);if($)this.matchFinish($,J)}walkCB(Z,J,X){if(this.signal?.aborted)X();this.walkCB2(Z,J,new CG(this.opts),X)}walkCB2(Z,J,X,$){if(this.#Y(Z))return $();if(this.signal?.aborted)$();if(this.paused){this.onResume(()=>this.walkCB2(Z,J,X,$));return}X.processPatterns(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[W,K,G]of X.matches.entries()){if(this.#$(W))continue;Y++,this.match(W,K,G).then(()=>Q())}for(let W of X.subwalkTargets()){if(this.maxDepth!==1/0&&W.depth()>=this.maxDepth)continue;Y++;let K=W.readdirCached();if(W.calledReaddir())this.walkCB3(W,K,X,Q);else W.readdirCB((G,V)=>this.walkCB3(W,V,X,Q),!0)}Q()}walkCB3(Z,J,X,$){X=X.filterEntries(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[W,K,G]of X.matches.entries()){if(this.#$(W))continue;Y++,this.match(W,K,G).then(()=>Q())}for(let[W,K]of X.subwalks.entries())Y++,this.walkCB2(W,K,X.child(),Q);Q()}walkCBSync(Z,J,X){if(this.signal?.aborted)X();this.walkCB2Sync(Z,J,new CG(this.opts),X)}walkCB2Sync(Z,J,X,$){if(this.#Y(Z))return $();if(this.signal?.aborted)$();if(this.paused){this.onResume(()=>this.walkCB2Sync(Z,J,X,$));return}X.processPatterns(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[W,K,G]of X.matches.entries()){if(this.#$(W))continue;this.matchSync(W,K,G)}for(let W of X.subwalkTargets()){if(this.maxDepth!==1/0&&W.depth()>=this.maxDepth)continue;Y++;let K=W.readdirSync();this.walkCB3Sync(W,K,X,Q)}Q()}walkCB3Sync(Z,J,X,$){X=X.filterEntries(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[W,K,G]of X.matches.entries()){if(this.#$(W))continue;this.matchSync(W,K,G)}for(let[W,K]of X.subwalks.entries())Y++,this.walkCB2Sync(W,K,X.child(),Q);Q()}}class CF extends ER{matches=new Set;constructor(Z,J,X){super(Z,J,X)}matchEmit(Z){this.matches.add(Z)}async walk(){if(this.signal?.aborted)throw this.signal.reason;if(this.path.isUnknown())await this.path.lstat();return await new Promise((Z,J)=>{this.walkCB(this.path,this.patterns,()=>{if(this.signal?.aborted)J(this.signal.reason);else Z(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;if(this.path.isUnknown())this.path.lstatSync();return this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}}class TF extends ER{results;constructor(Z,J,X){super(Z,J,X);this.results=new s$({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(Z){if(this.results.write(Z),!this.results.flowing)this.pause()}stream(){let Z=this.path;if(Z.isUnknown())Z.lstat().then(()=>{this.walkCB(Z,this.patterns,()=>this.results.end())});else this.walkCB(Z,this.patterns,()=>this.results.end());return this.results}streamSync(){if(this.path.isUnknown())this.path.lstatSync();return this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}}var qV5=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class iZ{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(Z,J){if(!J)throw new TypeError("glob options required");if(this.withFileTypes=!!J.withFileTypes,this.signal=J.signal,this.follow=!!J.follow,this.dot=!!J.dot,this.dotRelative=!!J.dotRelative,this.nodir=!!J.nodir,this.mark=!!J.mark,!J.cwd)this.cwd="";else if(J.cwd instanceof URL||J.cwd.startsWith("file://"))J.cwd=HV5(J.cwd);if(this.cwd=J.cwd||"",this.root=J.root,this.magicalBraces=!!J.magicalBraces,this.nobrace=!!J.nobrace,this.noext=!!J.noext,this.realpath=!!J.realpath,this.absolute=J.absolute,this.includeChildMatches=J.includeChildMatches!==!1,this.noglobstar=!!J.noglobstar,this.matchBase=!!J.matchBase,this.maxDepth=typeof J.maxDepth==="number"?J.maxDepth:1/0,this.stat=!!J.stat,this.ignore=J.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof Z==="string")Z=[Z];if(this.windowsPathsNoEscape=!!J.windowsPathsNoEscape||J.allowWindowsEscape===!1,this.windowsPathsNoEscape)Z=Z.map((K)=>K.replace(/\\/g,"/"));if(this.matchBase){if(J.noglobstar)throw new TypeError("base matching requires globstar");Z=Z.map((K)=>K.includes("/")?K:`./**/${K}`)}if(this.pattern=Z,this.platform=J.platform||qV5,this.opts={...J,platform:this.platform},J.scurry){if(this.scurry=J.scurry,J.nocase!==void 0&&J.nocase!==J.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let K=J.platform==="win32"?RG:J.platform==="darwin"?PF:J.platform?DG:Tu;this.scurry=new K(this.cwd,{nocase:J.nocase,fs:J.fs})}this.nocase=this.scurry.nocase;let X=this.platform==="darwin"||this.platform==="win32",$={...J,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:X,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},Y=this.pattern.map((K)=>new K9(K,$)),[Q,W]=Y.reduce((K,G)=>{return K[0].push(...G.set),K[1].push(...G.globParts),K},[[],[]]);this.patterns=Q.map((K,G)=>{let V=W[G];if(!V)throw new Error("invalid pattern object");return new DW(K,V,0,this.platform)})}async walk(){return[...await new CF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new CF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new TF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new TF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}}var IR=(Z,J={})=>{if(!Array.isArray(Z))Z=[Z];for(let X of Z)if(new K9(X,J).hasMagic())return!0;return!1};function EF(Z,J={}){return new iZ(Z,J).streamSync()}function vu(Z,J={}){return new iZ(Z,J).stream()}function Su(Z,J={}){return new iZ(Z,J).walkSync()}async function Iu(Z,J={}){return new iZ(Z,J).walk()}function IF(Z,J={}){return new iZ(Z,J).iterateSync()}function _u(Z,J={}){return new iZ(Z,J).iterate()}var zV5=EF,FV5=Object.assign(vu,{sync:EF}),UV5=IF,BV5=Object.assign(_u,{sync:IF}),LV5=Object.assign(Su,{stream:EF,iterate:IF}),kF=Object.assign(Iu,{glob:Iu,globSync:Su,sync:LV5,globStream:vu,stream:FV5,globStreamSync:EF,streamSync:zV5,globIterate:_u,iterate:BV5,globIterateSync:IF,iterateSync:UV5,Glob:iZ,hasMagic:IR,escape:OW,unescape:$Z});kF.glob=kF;class vR{constructor(){this._listeners={}}addEventListener(Z,J){let X=this._listeners;if(X[Z]===void 0)X[Z]=[];if(X[Z].indexOf(J)===-1)X[Z].push(J);return this}removeEventListener(Z,J){let $=this._listeners[Z];if($!==void 0){let Y=$.indexOf(J);if(Y!==-1)$.splice(Y,1)}return this}dispatchEvent(Z){let X=this._listeners[Z.type];if(X!==void 0){let $=X.slice(0);for(let Y=0,Q=$.length;Y<Q;Y++)$[Y].call(this,Z)}return this}dispose(){for(let Z in this._listeners)delete this._listeners[Z]}}class Y7{constructor(Z,J,X,$={}){if(this._name=void 0,this._parent=void 0,this._child=void 0,this._attributes=void 0,this._disposed=!1,this._name=Z,this._parent=J,this._child=X,this._attributes=$,!J.isOnGraph(X))throw new Error("Cannot connect disconnected graphs.")}getName(){return this._name}getParent(){return this._parent}getChild(){return this._child}setChild(Z){return this._child=Z,this}getAttributes(){return this._attributes}dispose(){if(this._disposed)return;this._parent._destroyRef(this),this._disposed=!0}isDisposed(){return this._disposed}}class PW extends vR{constructor(...Z){super(...Z);this._emptySet=new Set,this._edges=new Set,this._parentEdges=new Map,this._childEdges=new Map}listEdges(){return Array.from(this._edges)}listParentEdges(Z){return Array.from(this._childEdges.get(Z)||this._emptySet)}listParents(Z){let J=new Set;for(let X of this.listParentEdges(Z))J.add(X.getParent());return Array.from(J)}listChildEdges(Z){return Array.from(this._parentEdges.get(Z)||this._emptySet)}listChildren(Z){let J=new Set;for(let X of this.listChildEdges(Z))J.add(X.getChild());return Array.from(J)}disconnectParents(Z,J){for(let X of this.listParentEdges(Z))if(!J||J(X.getParent()))X.dispose();return this}_createEdge(Z,J,X,$){let Y=new Y7(Z,J,X,$);this._edges.add(Y);let Q=Y.getParent();if(!this._parentEdges.has(Q))this._parentEdges.set(Q,new Set);this._parentEdges.get(Q).add(Y);let W=Y.getChild();if(!this._childEdges.has(W))this._childEdges.set(W,new Set);return this._childEdges.get(W).add(Y),Y}_destroyEdge(Z){return this._edges.delete(Z),this._parentEdges.get(Z.getParent()).delete(Z),this._childEdges.get(Z.getChild()).delete(Z),this}}function TG(){return TG=Object.assign||function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)if(Object.prototype.hasOwnProperty.call(X,$))Z[$]=X[$]}return Z},TG.apply(this,arguments)}class z6{constructor(Z){if(this.list=[],Z)for(let J of Z)this.list.push(J)}add(Z){this.list.push(Z)}remove(Z){let J=this.list.indexOf(Z);if(J>=0)this.list.splice(J,1)}removeChild(Z){let J=[];for(let X of this.list)if(X.getChild()===Z)J.push(X);for(let X of J)this.remove(X);return J}listRefsByChild(Z){let J=[];for(let X of this.list)if(X.getChild()===Z)J.push(X);return J}values(){return this.list}}class I0{constructor(Z){if(this.set=new Set,this.map=new Map,Z)for(let J of Z)this.add(J)}add(Z){let J=Z.getChild();this.removeChild(J),this.set.add(Z),this.map.set(J,Z)}remove(Z){this.set.delete(Z),this.map.delete(Z.getChild())}removeChild(Z){let J=this.map.get(Z)||null;if(J)this.remove(J);return J}getRefByChild(Z){return this.map.get(Z)||null}values(){return Array.from(this.set)}}class a5{constructor(Z){if(this.map={},Z)Object.assign(this.map,Z)}set(Z,J){this.map[Z]=J}delete(Z){delete this.map[Z]}get(Z){return this.map[Z]||null}keys(){return Object.keys(this.map)}values(){return Object.values(this.map)}}var y0=Symbol("attributes"),WZ=Symbol("immutableKeys");class CW extends vR{constructor(Z){super();this._disposed=!1,this.graph=void 0,this[y0]=void 0,this[WZ]=void 0,this.graph=Z,this[WZ]=new Set,this[y0]=this._createAttributes()}getDefaults(){return{}}_createAttributes(){let Z=this.getDefaults(),J={};for(let X in Z){let $=Z[X];if($ instanceof CW){let Y=this.graph._createEdge(X,this,$);this[WZ].add(X),J[X]=Y}else J[X]=$}return J}isOnGraph(Z){return this.graph===Z.graph}isDisposed(){return this._disposed}dispose(){if(this._disposed)return;this.graph.listChildEdges(this).forEach((Z)=>Z.dispose()),this.graph.disconnectParents(this),this._disposed=!0,this.dispatchEvent({type:"dispose"})}detach(){return this.graph.disconnectParents(this),this}swap(Z,J){for(let X in this[y0]){let $=this[y0][X];if($ instanceof Y7){let Y=$;if(Y.getChild()===Z)this.setRef(X,J,Y.getAttributes())}else if($ instanceof z6)for(let Y of $.listRefsByChild(Z)){let Q=Y.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}else if($ instanceof I0){let Y=$.getRefByChild(Z);if(Y){let Q=Y.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}}else if($ instanceof a5)for(let Y of $.keys()){let Q=$.get(Y);if(Q.getChild()===Z)this.setRefMap(X,Y,J,Q.getAttributes())}}return this}get(Z){return this[y0][Z]}set(Z,J){return this[y0][Z]=J,this.dispatchEvent({type:"change",attribute:Z})}getRef(Z){let J=this[y0][Z];return J?J.getChild():null}setRef(Z,J,X){if(this[WZ].has(Z))throw new Error(`Cannot overwrite immutable attribute, "${Z}".`);let $=this[y0][Z];if($)$.dispose();if(!J)return this;let Y=this.graph._createEdge(Z,this,J,X);return this[y0][Z]=Y,this.dispatchEvent({type:"change",attribute:Z})}listRefs(Z){return this.assertRefList(Z).values().map((X)=>X.getChild())}addRef(Z,J,X){let $=this.graph._createEdge(Z,this,J,X);return this.assertRefList(Z).add($),this.dispatchEvent({type:"change",attribute:Z})}removeRef(Z,J){let X=this.assertRefList(Z);if(X instanceof z6)for(let $ of X.listRefsByChild(J))$.dispose();else{let $=X.getRefByChild(J);if($)$.dispose()}return this}assertRefList(Z){let J=this[y0][Z];if(J instanceof z6||J instanceof I0)return J;throw new Error(`Expected RefList or RefSet for attribute "${Z}"`)}listRefMapKeys(Z){return this.assertRefMap(Z).keys()}listRefMapValues(Z){return this.assertRefMap(Z).values().map((J)=>J.getChild())}getRefMap(Z,J){let $=this.assertRefMap(Z).get(J);return $?$.getChild():null}setRefMap(Z,J,X,$){let Y=this.assertRefMap(Z),Q=Y.get(J);if(Q)Q.dispose();if(!X)return this;$=Object.assign($||{},{key:J});let W=this.graph._createEdge(Z,this,X,TG({},$,{key:J}));return Y.set(J,W),this.dispatchEvent({type:"change",attribute:Z,key:J})}assertRefMap(Z){let J=this[y0][Z];if(J instanceof a5)return J;throw new Error(`Expected RefMap for attribute "${Z}"`)}dispatchEvent(Z){return super.dispatchEvent(TG({},Z,{target:this})),this.graph.dispatchEvent(TG({},Z,{target:this,type:`node:${Z.type}`})),this}_destroyRef(Z){let J=Z.getName();if(this[y0][J]===Z){if(this[y0][J]=null,this[WZ].has(J))Z.getChild().dispose()}else if(this[y0][J]instanceof z6)this[y0][J].remove(Z);else if(this[y0][J]instanceof I0)this[y0][J].remove(Z);else if(this[y0][J]instanceof a5){let X=this[y0][J];for(let $ of X.keys())if(X.get($)===Z)X.delete($)}else return;this.graph._destroyEdge(Z),this.dispatchEvent({type:"change",attribute:J})}}var gu="v4.1.1",fF="@glb.bin",n;(function(Z){Z.ACCESSOR="Accessor",Z.ANIMATION="Animation",Z.ANIMATION_CHANNEL="AnimationChannel",Z.ANIMATION_SAMPLER="AnimationSampler",Z.BUFFER="Buffer",Z.CAMERA="Camera",Z.MATERIAL="Material",Z.MESH="Mesh",Z.PRIMITIVE="Primitive",Z.PRIMITIVE_TARGET="PrimitiveTarget",Z.NODE="Node",Z.ROOT="Root",Z.SCENE="Scene",Z.SKIN="Skin",Z.TEXTURE="Texture",Z.TEXTURE_INFO="TextureInfo"})(n||(n={}));var hF;(function(Z){Z.INTERLEAVED="interleaved",Z.SEPARATE="separate"})(hF||(hF={}));var I7;(function(Z){Z.ARRAY_BUFFER="ARRAY_BUFFER",Z.ELEMENT_ARRAY_BUFFER="ELEMENT_ARRAY_BUFFER",Z.INVERSE_BIND_MATRICES="INVERSE_BIND_MATRICES",Z.OTHER="OTHER",Z.SPARSE="SPARSE"})(I7||(I7={}));var bF;(function(Z){Z[Z.R=4096]="R",Z[Z.G=256]="G",Z[Z.B=16]="B",Z[Z.A=1]="A"})(bF||(bF={}));var pJ;(function(Z){Z.GLTF="GLTF",Z.GLB="GLB"})(pJ||(pJ={}));var $X={"5120":Int8Array,"5121":Uint8Array,"5122":Int16Array,"5123":Uint16Array,"5125":Uint32Array,"5126":Float32Array},_R=typeof Float32Array!=="undefined"?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var Z=0,J=arguments.length;while(J--)Z+=arguments[J]*arguments[J];return Math.sqrt(Z)};function wV5(){var Z=new _R(3);if(_R!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function SR(Z){var J=Z[0],X=Z[1],$=Z[2];return Math.hypot(J,X,$)}function OV5(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=X[3]*$+X[7]*Y+X[11]*Q+X[15];return W=W||1,Z[0]=(X[0]*$+X[4]*Y+X[8]*Q+X[12])/W,Z[1]=(X[1]*$+X[5]*Y+X[9]*Q+X[13])/W,Z[2]=(X[2]*$+X[6]*Y+X[10]*Q+X[14])/W,Z}(function(){var Z=wV5();return function(J,X,$,Y,Q,W){var K,G;if(!X)X=3;if(!$)$=0;if(Y)G=Math.min(Y*X+$,J.length);else G=J.length;for(K=$;K<G;K+=X)Z[0]=J[K],Z[1]=J[K+1],Z[2]=J[K+2],Q(Z,Z,W),J[K]=Z[0],J[K+1]=Z[1],J[K+2]=Z[2];return J}})();function hR(Z){let J=mu(),X=Z.propertyType===n.NODE?[Z]:Z.listChildren();for(let $ of X)$.traverse((Y)=>{let Q=Y.getMesh();if(!Q)return;let W=NV5(Q,Y.getWorldMatrix());if(W.min.every(isFinite)&&W.max.every(isFinite))AR(W.min,J),AR(W.max,J)});return J}function NV5(Z,J){let X=mu();for(let $ of Z.listPrimitives()){let Y=$.getAttribute("POSITION"),Q=$.getIndices();if(!Y)continue;let W=[0,0,0],K=[0,0,0];for(let G=0,V=Q?Q.getCount():Y.getCount();G<V;G++){let H=Q?Q.getScalar(G):G;W=Y.getElement(H,W),K=OV5(K,W,J),AR(K,X)}}return X}function AR(Z,J){for(let X=0;X<3;X++)J.min[X]=Math.min(Z[X],J.min[X]),J.max[X]=Math.max(Z[X],J.max[X])}function mu(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}class r0{static createBufferFromDataURI(Z){if(typeof Buffer==="undefined"){let J=atob(Z.split(",")[1]),X=new Uint8Array(J.length);for(let $=0;$<J.length;$++)X[$]=J.charCodeAt($);return X}else{let J=Z.split(",")[1],X=Z.indexOf("base64")>=0;return Buffer.from(J,X?"base64":"utf8")}}static encodeText(Z){return new TextEncoder().encode(Z)}static decodeText(Z){return new TextDecoder().decode(Z)}static concat(Z){let J=0;for(let Y of Z)J+=Y.byteLength;let X=new Uint8Array(J),$=0;for(let Y of Z)X.set(Y,$),$+=Y.byteLength;return X}static pad(Z,J=0){let X=this.padNumber(Z.byteLength);if(X===Z.byteLength)return Z;let $=new Uint8Array(X);if($.set(Z),J!==0)for(let Y=Z.byteLength;Y<X;Y++)$[Y]=J;return $}static padNumber(Z){return Math.ceil(Z/4)*4}static equals(Z,J){if(Z===J)return!0;if(Z.byteLength!==J.byteLength)return!1;let X=Z.byteLength;while(X--)if(Z[X]!==J[X])return!1;return!0}static toView(Z,J=0,X=1/0){return new Uint8Array(Z.buffer,Z.byteOffset+J,Math.min(Z.byteLength,X))}static assertView(Z){if(Z&&!ArrayBuffer.isView(Z))throw new Error(`Method requires Uint8Array parameter; received "${typeof Z}".`);return Z}}class bR{static hexToFactor(Z,J){Z=Math.floor(Z);let X=J;return X[0]=(Z>>16&255)/255,X[1]=(Z>>8&255)/255,X[2]=(Z&255)/255,this.convertSRGBToLinear(J,J)}static factorToHex(Z){let J=[...Z],[X,$,Y]=this.convertLinearToSRGB(Z,J);return X*255<<16^$*255<<8^Y*255<<0}static convertSRGBToLinear(Z,J){let X=Z,$=J;for(let Y=0;Y<3;Y++)$[Y]=X[Y]<0.04045?X[Y]*0.0773993808:Math.pow(X[Y]*0.9478672986+0.0521327014,2.4);return J}static convertLinearToSRGB(Z,J){let X=Z,$=J;for(let Y=0;Y<3;Y++)$[Y]=X[Y]<0.0031308?X[Y]*12.92:1.055*Math.pow(X[Y],0.41666)-0.055;return J}}class du{match(Z){return Z.length>=3&&Z[0]===255&&Z[1]===216&&Z[2]===255}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset+4),X,$;while(J.byteLength){if(X=J.getUint16(0,!1),jV5(J,X),$=J.getUint8(X+1),$===192||$===193||$===194)return[J.getUint16(X+7,!1),J.getUint16(X+5,!1)];J=new DataView(Z.buffer,J.byteOffset+X+2)}throw new TypeError("Invalid JPG, no size found")}getChannels(Z){return 3}}class mF{match(Z){return Z.length>=8&&Z[0]===137&&Z[1]===80&&Z[2]===78&&Z[3]===71&&Z[4]===13&&Z[5]===10&&Z[6]===26&&Z[7]===10}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset);if(r0.decodeText(Z.slice(12,16))===mF.PNG_FRIED_CHUNK_NAME)return[J.getUint32(32,!1),J.getUint32(36,!1)];return[J.getUint32(16,!1),J.getUint32(20,!1)]}getChannels(Z){return 4}}mF.PNG_FRIED_CHUNK_NAME="CgBI";class iJ{static registerFormat(Z,J){this.impls[Z]=J}static getMimeType(Z){for(let J in this.impls)if(this.impls[J].match(Z))return J;return null}static getSize(Z,J){if(!this.impls[J])return null;return this.impls[J].getSize(Z)}static getChannels(Z,J){if(!this.impls[J])return null;return this.impls[J].getChannels(Z)}static getVRAMByteLength(Z,J){if(!this.impls[J])return null;if(this.impls[J].getVRAMByteLength)return this.impls[J].getVRAMByteLength(Z);let X=0,$=4,Y=this.getSize(Z,J);if(!Y)return null;while(Y[0]>1||Y[1]>1)X+=Y[0]*Y[1]*$,Y[0]=Math.max(Math.floor(Y[0]/2),1),Y[1]=Math.max(Math.floor(Y[1]/2),1);return X+=1*$,X}static mimeTypeToExtension(Z){if(Z==="image/jpeg")return"jpg";return Z.split("/").pop()}static extensionToMimeType(Z){if(Z==="jpg")return"image/jpeg";if(!Z)return"";return`image/${Z}`}}iJ.impls={"image/jpeg":new du,"image/png":new mF};function jV5(Z,J){if(J>Z.byteLength)throw new TypeError("Corrupt JPG, exceeded buffer limits");if(Z.getUint8(J)!==255)throw new TypeError("Invalid JPG, marker table corrupted");return Z}class nJ{static basename(Z){let J=Z.split(/[\\/]/).pop();return J.substring(0,J.lastIndexOf("."))}static extension(Z){if(Z.startsWith("data:image/")){let J=Z.match(/data:(image\/\w+)/)[1];return iJ.mimeTypeToExtension(J)}else if(Z.startsWith("data:model/gltf+json"))return"gltf";else if(Z.startsWith("data:model/gltf-binary"))return"glb";else if(Z.startsWith("data:application/"))return"bin";return Z.split(/[\\/]/).pop().split(/[.]/).pop()}}function Au(Z){return Object.prototype.toString.call(Z)==="[object Object]"}function r$(Z){if(Au(Z)===!1)return!1;let J=Z.constructor;if(J===void 0)return!0;let X=J.prototype;if(Au(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}var xR,kG;(function(Z){Z[Z.SILENT=4]="SILENT",Z[Z.ERROR=3]="ERROR",Z[Z.WARN=2]="WARN",Z[Z.INFO=1]="INFO",Z[Z.DEBUG=0]="DEBUG"})(kG||(kG={}));class W7{constructor(Z){this.verbosity=void 0,this.verbosity=Z}debug(Z){if(this.verbosity<=W7.Verbosity.DEBUG)console.debug(Z)}info(Z){if(this.verbosity<=W7.Verbosity.INFO)console.info(Z)}warn(Z){if(this.verbosity<=W7.Verbosity.WARN)console.warn(Z)}error(Z){if(this.verbosity<=W7.Verbosity.ERROR)console.error(Z)}}xR=W7;W7.Verbosity=kG;W7.DEFAULT_INSTANCE=new xR(xR.Verbosity.INFO);function MV5(Z){var J=Z[0],X=Z[1],$=Z[2],Y=Z[3],Q=Z[4],W=Z[5],K=Z[6],G=Z[7],V=Z[8],H=Z[9],q=Z[10],z=Z[11],F=Z[12],U=Z[13],L=Z[14],B=Z[15],w=J*W-X*Q,O=J*K-$*Q,M=J*G-Y*Q,N=X*K-$*W,P=X*G-Y*W,D=$*G-Y*K,C=V*U-H*F,T=V*L-q*F,k=V*B-z*F,A=H*L-q*U,v=H*B-z*U,x=q*B-z*L;return w*x-O*v+M*A+N*k-P*T+D*C}function RV5(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=J[3],K=J[4],G=J[5],V=J[6],H=J[7],q=J[8],z=J[9],F=J[10],U=J[11],L=J[12],B=J[13],w=J[14],O=J[15],M=X[0],N=X[1],P=X[2],D=X[3];return Z[0]=M*$+N*K+P*q+D*L,Z[1]=M*Y+N*G+P*z+D*B,Z[2]=M*Q+N*V+P*F+D*w,Z[3]=M*W+N*H+P*U+D*O,M=X[4],N=X[5],P=X[6],D=X[7],Z[4]=M*$+N*K+P*q+D*L,Z[5]=M*Y+N*G+P*z+D*B,Z[6]=M*Q+N*V+P*F+D*w,Z[7]=M*W+N*H+P*U+D*O,M=X[8],N=X[9],P=X[10],D=X[11],Z[8]=M*$+N*K+P*q+D*L,Z[9]=M*Y+N*G+P*z+D*B,Z[10]=M*Q+N*V+P*F+D*w,Z[11]=M*W+N*H+P*U+D*O,M=X[12],N=X[13],P=X[14],D=X[15],Z[12]=M*$+N*K+P*q+D*L,Z[13]=M*Y+N*G+P*z+D*B,Z[14]=M*Q+N*V+P*F+D*w,Z[15]=M*W+N*H+P*U+D*O,Z}function DV5(Z,J){var X=J[0],$=J[1],Y=J[2],Q=J[4],W=J[5],K=J[6],G=J[8],V=J[9],H=J[10];return Z[0]=Math.hypot(X,$,Y),Z[1]=Math.hypot(Q,W,K),Z[2]=Math.hypot(G,V,H),Z}function PV5(Z,J){var X=new _R(3);DV5(X,J);var $=1/X[0],Y=1/X[1],Q=1/X[2],W=J[0]*$,K=J[1]*Y,G=J[2]*Q,V=J[4]*$,H=J[5]*Y,q=J[6]*Q,z=J[8]*$,F=J[9]*Y,U=J[10]*Q,L=W+H+U,B=0;if(L>0)B=Math.sqrt(L+1)*2,Z[3]=0.25*B,Z[0]=(q-F)/B,Z[1]=(z-G)/B,Z[2]=(K-V)/B;else if(W>H&&W>U)B=Math.sqrt(1+W-H-U)*2,Z[3]=(q-F)/B,Z[0]=0.25*B,Z[1]=(K+V)/B,Z[2]=(z+G)/B;else if(H>U)B=Math.sqrt(1+H-W-U)*2,Z[3]=(z-G)/B,Z[0]=(K+V)/B,Z[1]=0.25*B,Z[2]=(q+F)/B;else B=Math.sqrt(1+U-W-H)*2,Z[3]=(K-V)/B,Z[0]=(z+G)/B,Z[1]=(q+F)/B,Z[2]=0.25*B;return Z}class i0{static identity(Z){return Z}static eq(Z,J,X=0.00001){if(Z.length!==J.length)return!1;for(let $=0;$<Z.length;$++)if(Math.abs(Z[$]-J[$])>X)return!1;return!0}static clamp(Z,J,X){if(Z<J)return J;if(Z>X)return X;return Z}static decodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Z/65535;case 5121:return Z/255;case 5122:return Math.max(Z/32767,-1);case 5120:return Math.max(Z/127,-1);default:throw new Error("Invalid component type.")}}static encodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Math.round(i0.clamp(Z,0,1)*65535);case 5121:return Math.round(i0.clamp(Z,0,1)*255);case 5122:return Math.round(i0.clamp(Z,-1,1)*32767);case 5120:return Math.round(i0.clamp(Z,-1,1)*127);default:throw new Error("Invalid component type.")}}static decompose(Z,J,X,$){let Y=SR([Z[0],Z[1],Z[2]]),Q=SR([Z[4],Z[5],Z[6]]),W=SR([Z[8],Z[9],Z[10]]);if(MV5(Z)<0)Y=-Y;J[0]=Z[12],J[1]=Z[13],J[2]=Z[14];let G=Z.slice(),V=1/Y,H=1/Q,q=1/W;G[0]*=V,G[1]*=V,G[2]*=V,G[4]*=H,G[5]*=H,G[6]*=H,G[8]*=q,G[9]*=q,G[10]*=q,PV5(X,G),$[0]=Y,$[1]=Q,$[2]=W}static compose(Z,J,X,$){let Y=$,Q=J[0],W=J[1],K=J[2],G=J[3],V=Q+Q,H=W+W,q=K+K,z=Q*V,F=Q*H,U=Q*q,L=W*H,B=W*q,w=K*q,O=G*V,M=G*H,N=G*q,P=X[0],D=X[1],C=X[2];return Y[0]=(1-(L+w))*P,Y[1]=(F+N)*P,Y[2]=(U-M)*P,Y[3]=0,Y[4]=(F-N)*D,Y[5]=(1-(z+w))*D,Y[6]=(B+O)*D,Y[7]=0,Y[8]=(U+M)*C,Y[9]=(B-O)*C,Y[10]=(1-(z+L))*C,Y[11]=0,Y[12]=Z[0],Y[13]=Z[1],Y[14]=Z[2],Y[15]=1,Y}}function CV5(Z,J){if(!!Z!==!!J)return!1;let X=Z.getChild(),$=J.getChild();return X===$||X.equals($)}function TV5(Z,J){if(!!Z!==!!J)return!1;let X=Z.values(),$=J.values();if(X.length!==$.length)return!1;for(let Y=0;Y<X.length;Y++){let Q=X[Y],W=$[Y];if(Q.getChild()===W.getChild())continue;if(!Q.getChild().equals(W.getChild()))return!1}return!0}function kV5(Z,J){if(!!Z!==!!J)return!1;let X=Z.keys(),$=J.keys();if(X.length!==$.length)return!1;for(let Y of X){let Q=Z.get(Y),W=J.get(Y);if(!!Q!==!!W)return!1;let K=Q.getChild(),G=W.getChild();if(K===G)continue;if(!K.equals(G))return!1}return!0}function uu(Z,J){if(Z===J)return!0;if(!!Z!==!!J||!Z||!J)return!1;if(Z.length!==J.length)return!1;for(let X=0;X<Z.length;X++)if(Z[X]!==J[X])return!1;return!0}function cu(Z,J){if(Z===J)return!0;if(!!Z!==!!J)return!1;if(!r$(Z)||!r$(J))return Z===J;let X=Z,$=J,Y=0,Q=0,W;for(W in X)Y++;for(W in $)Q++;if(Y!==Q)return!1;for(W in X){let K=X[W],G=$[W];if(yF(K)&&yF(G)){if(!uu(K,G))return!1}else if(r$(K)&&r$(G)){if(!cu(K,G))return!1}else if(K!==G)return!1}return!0}function yF(Z){return Array.isArray(Z)||ArrayBuffer.isView(Z)}var xu="23456789abdegjkmnpqrvwxyzABDEGJKMNPQRVWXYZ",EV5=999,IV5=6,fu=new Set,vV5=function Z(){let J="";for(let X=0;X<IV5;X++)J+=xu.charAt(Math.floor(Math.random()*xu.length));return J},lu=function Z(){for(let J=0;J<EV5;J++){let X=vV5();if(!fu.has(X))return fu.add(X),X}return""},hu="https://null.example";class H9{static dirname(Z){let J=Z.lastIndexOf("/");if(J===-1)return"./";return Z.substring(0,J+1)}static basename(Z){return nJ.basename(new URL(Z,hu).pathname)}static extension(Z){return nJ.extension(new URL(Z,hu).pathname)}static resolve(Z,J){if(!this.isRelativePath(J))return J;let X=Z.split("/"),$=J.split("/");X.pop();for(let Y=0;Y<$.length;Y++){if($[Y]===".")continue;if($[Y]==="..")X.pop();else X.push($[Y])}return X.join("/")}static isAbsoluteURL(Z){return this.PROTOCOL_REGEXP.test(Z)}static isRelativePath(Z){return!/^(?:[a-zA-Z]+:)?\//.test(Z)}}H9.DEFAULT_INIT={};H9.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;var XX=(Z)=>Z,SV5=new Set;class dF extends CW{constructor(Z,J=""){super(Z);this[y0].name=J,this.init(),this.dispatchEvent({type:"create"})}getGraph(){return this.graph}getDefaults(){return Object.assign(super.getDefaults(),{name:"",extras:{}})}set(Z,J){if(Array.isArray(J))J=J.slice();return super.set(Z,J)}getName(){return this.get("name")}setName(Z){return this.set("name",Z)}getExtras(){return this.get("extras")}setExtras(Z){return this.set("extras",Z)}clone(){return new this.constructor(this.graph).copy(this,XX)}copy(Z,J=XX){for(let X in this[y0]){let $=this[y0][X];if($ instanceof Y7){if(!this[WZ].has(X))$.dispose()}else if($ instanceof z6||$ instanceof I0)for(let Y of $.values())Y.dispose();else if($ instanceof a5)for(let Y of $.values())Y.dispose()}for(let X in Z[y0]){let $=this[y0][X],Y=Z[y0][X];if(Y instanceof Y7)if(this[WZ].has(X))$.getChild().copy(J(Y.getChild()),J);else this.setRef(X,J(Y.getChild()),Y.getAttributes());else if(Y instanceof I0||Y instanceof z6)for(let Q of Y.values())this.addRef(X,J(Q.getChild()),Q.getAttributes());else if(Y instanceof a5)for(let Q of Y.keys()){let W=Y.get(Q);this.setRefMap(X,Q,J(W.getChild()),W.getAttributes())}else if(r$(Y))this[y0][X]=JSON.parse(JSON.stringify(Y));else if(Array.isArray(Y)||Y instanceof ArrayBuffer||ArrayBuffer.isView(Y))this[y0][X]=Y.slice();else this[y0][X]=Y}return this}equals(Z,J=SV5){if(this===Z)return!0;if(this.propertyType!==Z.propertyType)return!1;for(let X in this[y0]){if(J.has(X))continue;let $=this[y0][X],Y=Z[y0][X];if($ instanceof Y7||Y instanceof Y7){if(!CV5($,Y))return!1}else if($ instanceof I0||Y instanceof I0||$ instanceof z6||Y instanceof z6){if(!TV5($,Y))return!1}else if($ instanceof a5||Y instanceof a5){if(!kV5($,Y))return!1}else if(r$($)||r$(Y)){if(!cu($,Y))return!1}else if(yF($)||yF(Y)){if(!uu($,Y))return!1}else if($!==Y)return!1}return!0}detach(){return this.graph.disconnectParents(this,(Z)=>Z.propertyType!=="Root"),this}listParents(){return this.graph.listParents(this)}}class U6 extends dF{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new a5})}getExtension(Z){return this.getRefMap("extensions",Z)}setExtension(Z,J){if(J)J._validateParent(this);return this.setRefMap("extensions",Z,J)}listExtensions(){return this.listRefMapValues("extensions")}}class f0 extends U6{init(){this.propertyType=n.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:f0.Type.SCALAR,componentType:f0.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(Z){switch(Z){case f0.Type.SCALAR:return 1;case f0.Type.VEC2:return 2;case f0.Type.VEC3:return 3;case f0.Type.VEC4:return 4;case f0.Type.MAT2:return 4;case f0.Type.MAT3:return 9;case f0.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+Z)}}static getComponentSize(Z){switch(Z){case f0.ComponentType.BYTE:return 1;case f0.ComponentType.UNSIGNED_BYTE:return 1;case f0.ComponentType.SHORT:return 2;case f0.ComponentType.UNSIGNED_SHORT:return 2;case f0.ComponentType.UNSIGNED_INT:return 4;case f0.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+Z)}}getMinNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),$=this.getComponentType();if(this.getMin(Z),J)for(let Y=0;Y<X;Y++)Z[Y]=i0.decodeNormalizedInt(Z[Y],$);return Z}getMin(Z){let J=this.getArray(),X=this.getCount(),$=this.getElementSize();for(let Y=0;Y<$;Y++)Z[Y]=1/0;for(let Y=0;Y<X*$;Y+=$)for(let Q=0;Q<$;Q++){let W=J[Y+Q];if(Number.isFinite(W))Z[Q]=Math.min(Z[Q],W)}return Z}getMaxNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),$=this.getComponentType();if(this.getMax(Z),J)for(let Y=0;Y<X;Y++)Z[Y]=i0.decodeNormalizedInt(Z[Y],$);return Z}getMax(Z){let J=this.get("array"),X=this.getCount(),$=this.getElementSize();for(let Y=0;Y<$;Y++)Z[Y]=-1/0;for(let Y=0;Y<X*$;Y+=$)for(let Q=0;Q<$;Q++){let W=J[Y+Q];if(Number.isFinite(W))Z[Q]=Math.max(Z[Q],W)}return Z}getCount(){let Z=this.get("array");return Z?Z.length/this.getElementSize():0}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getElementSize(){return f0.getElementSize(this.get("type"))}getComponentSize(){return this.get("array").BYTES_PER_ELEMENT}getComponentType(){return this.get("componentType")}getNormalized(){return this.get("normalized")}setNormalized(Z){return this.set("normalized",Z)}getScalar(Z){let J=this.getElementSize(),X=this.getComponentType(),$=this.getArray();if(this.getNormalized())return i0.decodeNormalizedInt($[Z*J],X);return $[Z*J]}setScalar(Z,J){let X=this.getElementSize(),$=this.getComponentType(),Y=this.getArray();if(this.getNormalized())Y[Z*X]=i0.encodeNormalizedInt(J,$);else Y[Z*X]=J;return this}getElement(Z,J){let X=this.getNormalized(),$=this.getElementSize(),Y=this.getComponentType(),Q=this.getArray();for(let W=0;W<$;W++)if(X)J[W]=i0.decodeNormalizedInt(Q[Z*$+W],Y);else J[W]=Q[Z*$+W];return J}setElement(Z,J){let X=this.getNormalized(),$=this.getElementSize(),Y=this.getComponentType(),Q=this.getArray();for(let W=0;W<$;W++)if(X)Q[Z*$+W]=i0.encodeNormalizedInt(J[W],Y);else Q[Z*$+W]=J[W];return this}getSparse(){return this.get("sparse")}setSparse(Z){return this.set("sparse",Z)}getBuffer(){return this.getRef("buffer")}setBuffer(Z){return this.setRef("buffer",Z)}getArray(){return this.get("array")}setArray(Z){return this.set("componentType",Z?_V5(Z):f0.ComponentType.FLOAT),this.set("array",Z),this}getByteLength(){let Z=this.get("array");return Z?Z.byteLength:0}}f0.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};f0.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};function _V5(Z){switch(Z.constructor){case Float32Array:return f0.ComponentType.FLOAT;case Uint32Array:return f0.ComponentType.UNSIGNED_INT;case Uint16Array:return f0.ComponentType.UNSIGNED_SHORT;case Uint8Array:return f0.ComponentType.UNSIGNED_BYTE;case Int16Array:return f0.ComponentType.SHORT;case Int8Array:return f0.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}class yR extends U6{init(){this.propertyType=n.ANIMATION}getDefaults(){return Object.assign(super.getDefaults(),{channels:new I0,samplers:new I0})}addChannel(Z){return this.addRef("channels",Z)}removeChannel(Z){return this.removeRef("channels",Z)}listChannels(){return this.listRefs("channels")}addSampler(Z){return this.addRef("samplers",Z)}removeSampler(Z){return this.removeRef("samplers",Z)}listSamplers(){return this.listRefs("samplers")}}class o$ extends U6{init(){this.propertyType=n.ANIMATION_CHANNEL}getDefaults(){return Object.assign(super.getDefaults(),{targetPath:null,targetNode:null,sampler:null})}getTargetPath(){return this.get("targetPath")}setTargetPath(Z){return this.set("targetPath",Z)}getTargetNode(){return this.getRef("targetNode")}setTargetNode(Z){return this.setRef("targetNode",Z)}getSampler(){return this.getRef("sampler")}setSampler(Z){return this.setRef("sampler",Z)}}o$.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class TW extends U6{init(){this.propertyType=n.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:TW.Interpolation.LINEAR,input:null,output:null})}getInterpolation(){return this.get("interpolation")}setInterpolation(Z){return this.set("interpolation",Z)}getInput(){return this.getRef("input")}setInput(Z){return this.setRef("input",Z,{usage:I7.OTHER})}getOutput(){return this.getRef("output")}setOutput(Z){return this.setRef("output",Z,{usage:I7.OTHER})}}TW.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class gR extends U6{init(){this.propertyType=n.BUFFER}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(Z){return this.set("uri",Z)}}class t$ extends U6{init(){this.propertyType=n.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:t$.Type.PERSPECTIVE,znear:0.1,zfar:100,aspectRatio:null,yfov:Math.PI*2*50/360,xmag:1,ymag:1})}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getZNear(){return this.get("znear")}setZNear(Z){return this.set("znear",Z)}getZFar(){return this.get("zfar")}setZFar(Z){return this.set("zfar",Z)}getAspectRatio(){return this.get("aspectRatio")}setAspectRatio(Z){return this.set("aspectRatio",Z)}getYFov(){return this.get("yfov")}setYFov(Z){return this.set("yfov",Z)}getXMag(){return this.get("xmag")}setXMag(Z){return this.set("xmag",Z)}getYMag(){return this.get("ymag")}setYMag(Z){return this.set("ymag",Z)}}t$.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class kW extends dF{_validateParent(Z){if(!this.parentTypes.includes(Z.propertyType))throw new Error(`Parent "${Z.propertyType}" invalid for child "${this.propertyType}".`)}}kW.EXTENSION_NAME=void 0;class Q7 extends U6{init(){this.propertyType=n.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:Q7.WrapMode.REPEAT,wrapT:Q7.WrapMode.REPEAT})}getTexCoord(){return this.get("texCoord")}setTexCoord(Z){return this.set("texCoord",Z)}getMagFilter(){return this.get("magFilter")}setMagFilter(Z){return this.set("magFilter",Z)}getMinFilter(){return this.get("minFilter")}setMinFilter(Z){return this.set("minFilter",Z)}getWrapS(){return this.get("wrapS")}setWrapS(Z){return this.set("wrapS",Z)}getWrapT(){return this.get("wrapT")}setWrapT(Z){return this.set("wrapT",Z)}}Q7.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};Q7.MagFilter={NEAREST:9728,LINEAR:9729};Q7.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};var{R:vF,G:SF,B:_F,A:AV5}=bF;class nZ extends U6{init(){this.propertyType=n.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:nZ.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new Q7(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new Q7(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new Q7(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new Q7(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new Q7(this.graph,"metallicRoughnessTextureInfo")})}getDoubleSided(){return this.get("doubleSided")}setDoubleSided(Z){return this.set("doubleSided",Z)}getAlpha(){return this.get("baseColorFactor")[3]}setAlpha(Z){let J=this.get("baseColorFactor").slice();return J[3]=Z,this.set("baseColorFactor",J)}getAlphaMode(){return this.get("alphaMode")}setAlphaMode(Z){return this.set("alphaMode",Z)}getAlphaCutoff(){return this.get("alphaCutoff")}setAlphaCutoff(Z){return this.set("alphaCutoff",Z)}getBaseColorFactor(){return this.get("baseColorFactor")}setBaseColorFactor(Z){return this.set("baseColorFactor",Z)}getBaseColorTexture(){return this.getRef("baseColorTexture")}getBaseColorTextureInfo(){return this.getRef("baseColorTexture")?this.getRef("baseColorTextureInfo"):null}setBaseColorTexture(Z){return this.setRef("baseColorTexture",Z,{channels:vF|SF|_F|AV5,isColor:!0})}getEmissiveFactor(){return this.get("emissiveFactor")}setEmissiveFactor(Z){return this.set("emissiveFactor",Z)}getEmissiveTexture(){return this.getRef("emissiveTexture")}getEmissiveTextureInfo(){return this.getRef("emissiveTexture")?this.getRef("emissiveTextureInfo"):null}setEmissiveTexture(Z){return this.setRef("emissiveTexture",Z,{channels:vF|SF|_F,isColor:!0})}getNormalScale(){return this.get("normalScale")}setNormalScale(Z){return this.set("normalScale",Z)}getNormalTexture(){return this.getRef("normalTexture")}getNormalTextureInfo(){return this.getRef("normalTexture")?this.getRef("normalTextureInfo"):null}setNormalTexture(Z){return this.setRef("normalTexture",Z,{channels:vF|SF|_F})}getOcclusionStrength(){return this.get("occlusionStrength")}setOcclusionStrength(Z){return this.set("occlusionStrength",Z)}getOcclusionTexture(){return this.getRef("occlusionTexture")}getOcclusionTextureInfo(){return this.getRef("occlusionTexture")?this.getRef("occlusionTextureInfo"):null}setOcclusionTexture(Z){return this.setRef("occlusionTexture",Z,{channels:vF})}getRoughnessFactor(){return this.get("roughnessFactor")}setRoughnessFactor(Z){return this.set("roughnessFactor",Z)}getMetallicFactor(){return this.get("metallicFactor")}setMetallicFactor(Z){return this.set("metallicFactor",Z)}getMetallicRoughnessTexture(){return this.getRef("metallicRoughnessTexture")}getMetallicRoughnessTextureInfo(){return this.getRef("metallicRoughnessTexture")?this.getRef("metallicRoughnessTextureInfo"):null}setMetallicRoughnessTexture(Z){return this.setRef("metallicRoughnessTexture",Z,{channels:SF|_F})}}nZ.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class IG extends U6{init(){this.propertyType=n.MESH}getDefaults(){return Object.assign(super.getDefaults(),{weights:[],primitives:new I0})}addPrimitive(Z){return this.addRef("primitives",Z)}removePrimitive(Z){return this.removeRef("primitives",Z)}listPrimitives(){return this.listRefs("primitives")}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}}class uF extends U6{init(){this.propertyType=n.NODE}getDefaults(){return Object.assign(super.getDefaults(),{translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1],weights:[],camera:null,mesh:null,skin:null,children:new I0})}copy(Z,J=XX){if(J===XX)throw new Error("Node cannot be copied.");return super.copy(Z,J)}getTranslation(){return this.get("translation")}getRotation(){return this.get("rotation")}getScale(){return this.get("scale")}setTranslation(Z){return this.set("translation",Z)}setRotation(Z){return this.set("rotation",Z)}setScale(Z){return this.set("scale",Z)}getMatrix(){return i0.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(Z){let J=this.get("translation").slice(),X=this.get("rotation").slice(),$=this.get("scale").slice();return i0.decompose(Z,J,X,$),this.set("translation",J).set("rotation",X).set("scale",$)}getWorldTranslation(){let Z=[0,0,0];return i0.decompose(this.getWorldMatrix(),Z,[0,0,0,1],[1,1,1]),Z}getWorldRotation(){let Z=[0,0,0,1];return i0.decompose(this.getWorldMatrix(),[0,0,0],Z,[1,1,1]),Z}getWorldScale(){let Z=[1,1,1];return i0.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],Z),Z}getWorldMatrix(){let Z=[];for(let $=this;$!=null;$=$.getParentNode())Z.push($);let J,X=Z.pop().getMatrix();while(J=Z.pop())RV5(X,X,J.getMatrix());return X}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);for(let X of Z.listParents())if(X.propertyType===n.SCENE)X.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}getParentNode(){for(let Z of this.listParents())if(Z.propertyType===n.NODE)return Z;return null}getMesh(){return this.getRef("mesh")}setMesh(Z){return this.setRef("mesh",Z)}getCamera(){return this.getRef("camera")}setCamera(Z){return this.setRef("camera",Z)}getSkin(){return this.getRef("skin")}setSkin(Z){return this.setRef("skin",Z)}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}traverse(Z){Z(this);for(let J of this.listChildren())J.traverse(Z);return this}}class O8 extends U6{init(){this.propertyType=n.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:O8.Mode.TRIANGLES,material:null,indices:null,attributes:new a5,targets:new I0})}getIndices(){return this.getRef("indices")}setIndices(Z){return this.setRef("indices",Z,{usage:I7.ELEMENT_ARRAY_BUFFER})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:I7.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}getMaterial(){return this.getRef("material")}setMaterial(Z){return this.setRef("material",Z)}getMode(){return this.get("mode")}setMode(Z){return this.set("mode",Z)}listTargets(){return this.listRefs("targets")}addTarget(Z){return this.addRef("targets",Z)}removeTarget(Z){return this.removeRef("targets",Z)}}O8.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class mR extends dF{init(){this.propertyType=n.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new a5})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:I7.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function A6(){return A6=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)({}).hasOwnProperty.call(X,$)&&(Z[$]=X[$])}return Z},A6.apply(null,arguments)}class EW extends U6{init(){this.propertyType=n.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:new I0})}copy(Z,J=XX){if(J===XX)throw new Error("Scene cannot be copied.");return super.copy(Z,J)}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}traverse(Z){for(let J of this.listChildren())J.traverse(Z);return this}}class dR extends U6{init(){this.propertyType=n.SKIN}getDefaults(){return Object.assign(super.getDefaults(),{skeleton:null,inverseBindMatrices:null,joints:new I0})}getSkeleton(){return this.getRef("skeleton")}setSkeleton(Z){return this.setRef("skeleton",Z)}getInverseBindMatrices(){return this.getRef("inverseBindMatrices")}setInverseBindMatrices(Z){return this.setRef("inverseBindMatrices",Z,{usage:I7.INVERSE_BIND_MATRICES})}addJoint(Z){return this.addRef("joints",Z)}removeJoint(Z){return this.removeRef("joints",Z)}listJoints(){return this.listRefs("joints")}}class e$ extends U6{init(){this.propertyType=n.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||iJ.extensionToMimeType(nJ.extension(this.get("uri")))}setMimeType(Z){return this.set("mimeType",Z)}getURI(){return this.get("uri")}setURI(Z){this.set("uri",Z);let J=iJ.extensionToMimeType(nJ.extension(Z));if(J)this.set("mimeType",J);return this}getImage(){return this.get("image")}setImage(Z){return this.set("image",r0.assertView(Z))}getSize(){let Z=this.get("image");if(!Z)return null;return iJ.getSize(Z,this.getMimeType())}}class ZY extends U6{init(){this.propertyType=n.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${gu}`,version:"2.0"},defaultScene:null,accessors:new I0,animations:new I0,buffers:new I0,cameras:new I0,materials:new I0,meshes:new I0,nodes:new I0,scenes:new I0,skins:new I0,textures:new I0})}constructor(Z){super(Z);this._extensions=new Set,Z.addEventListener("node:create",(J)=>{this._addChildOfRoot(J.target)})}clone(){throw new Error("Root cannot be cloned.")}copy(Z,J=XX){if(J===XX)throw new Error("Root cannot be copied.");this.set("asset",A6({},Z.get("asset"))),this.setName(Z.getName()),this.setExtras(A6({},Z.getExtras())),this.setDefaultScene(Z.getDefaultScene()?J(Z.getDefaultScene()):null);for(let X of Z.listRefMapKeys("extensions")){let $=Z.getExtension(X);this.setExtension(X,J($))}return this}_addChildOfRoot(Z){if(Z instanceof EW)this.addRef("scenes",Z);else if(Z instanceof uF)this.addRef("nodes",Z);else if(Z instanceof t$)this.addRef("cameras",Z);else if(Z instanceof dR)this.addRef("skins",Z);else if(Z instanceof IG)this.addRef("meshes",Z);else if(Z instanceof nZ)this.addRef("materials",Z);else if(Z instanceof e$)this.addRef("textures",Z);else if(Z instanceof yR)this.addRef("animations",Z);else if(Z instanceof f0)this.addRef("accessors",Z);else if(Z instanceof gR)this.addRef("buffers",Z);return this}getAsset(){return this.get("asset")}listExtensionsUsed(){return Array.from(this._extensions)}listExtensionsRequired(){return this.listExtensionsUsed().filter((Z)=>Z.isRequired())}_enableExtension(Z){return this._extensions.add(Z),this}_disableExtension(Z){return this._extensions.delete(Z),this}listScenes(){return this.listRefs("scenes")}setDefaultScene(Z){return this.setRef("defaultScene",Z)}getDefaultScene(){return this.getRef("defaultScene")}listNodes(){return this.listRefs("nodes")}listCameras(){return this.listRefs("cameras")}listSkins(){return this.listRefs("skins")}listMeshes(){return this.listRefs("meshes")}listMaterials(){return this.listRefs("materials")}listTextures(){return this.listRefs("textures")}listAnimations(){return this.listRefs("animations")}listAccessors(){return this.listRefs("accessors")}listBuffers(){return this.listRefs("buffers")}}class F6{static fromGraph(Z){return F6._GRAPH_DOCUMENTS.get(Z)||null}constructor(){this._graph=new PW,this._root=new ZY(this._graph),this._logger=W7.DEFAULT_INSTANCE,F6._GRAPH_DOCUMENTS.set(this._graph,this)}getRoot(){return this._root}getGraph(){return this._graph}getLogger(){return this._logger}setLogger(Z){return this._logger=Z,this}clone(){throw new Error("Use 'cloneDocument(source)' from '@gltf-transform/functions'.")}merge(Z){throw new Error("Use 'mergeDocuments(target, source)' from '@gltf-transform/functions'.")}async transform(...Z){let J=Z.map((X)=>X.name);for(let X of Z)await X(this,{stack:J});return this}createExtension(Z){let J=Z.EXTENSION_NAME;return this.getRoot().listExtensionsUsed().find(($)=>$.extensionName===J)||new Z(this)}createScene(Z=""){return new EW(this._graph,Z)}createNode(Z=""){return new uF(this._graph,Z)}createCamera(Z=""){return new t$(this._graph,Z)}createSkin(Z=""){return new dR(this._graph,Z)}createMesh(Z=""){return new IG(this._graph,Z)}createPrimitive(){return new O8(this._graph)}createPrimitiveTarget(Z=""){return new mR(this._graph,Z)}createMaterial(Z=""){return new nZ(this._graph,Z)}createTexture(Z=""){return new e$(this._graph,Z)}createAnimation(Z=""){return new yR(this._graph,Z)}createAnimationChannel(Z=""){return new o$(this._graph,Z)}createAnimationSampler(Z=""){return new TW(this._graph,Z)}createAccessor(Z="",J=null){if(!J)J=this.getRoot().listBuffers()[0];return new f0(this._graph,Z).setBuffer(J)}createBuffer(Z=""){return new gR(this._graph,Z)}}F6._GRAPH_DOCUMENTS=new WeakMap;class pu{constructor(Z){this.extensionName="",this.prereadTypes=[],this.prewriteTypes=[],this.readDependencies=[],this.writeDependencies=[],this.document=void 0,this.required=!1,this.properties=new Set,this._listener=void 0,this.document=Z,Z.getRoot()._enableExtension(this),this._listener=(X)=>{let $=X,Y=$.target;if(Y instanceof kW&&Y.extensionName===this.extensionName){if($.type==="node:create")this._addExtensionProperty(Y);if($.type==="node:dispose")this._removeExtensionProperty(Y)}};let J=Z.getGraph();J.addEventListener("node:create",this._listener),J.addEventListener("node:dispose",this._listener)}dispose(){this.document.getRoot()._disableExtension(this);let Z=this.document.getGraph();Z.removeEventListener("node:create",this._listener),Z.removeEventListener("node:dispose",this._listener);for(let J of this.properties)J.dispose()}static register(){}isRequired(){return this.required}setRequired(Z){return this.required=Z,this}listProperties(){return Array.from(this.properties)}_addExtensionProperty(Z){return this.properties.add(Z),this}_removeExtensionProperty(Z){return this.properties.delete(Z),this}install(Z,J){return this}preread(Z,J){return this}prewrite(Z,J){return this}}pu.EXTENSION_NAME=void 0;class iu{constructor(Z){this.jsonDoc=void 0,this.buffers=[],this.bufferViews=[],this.bufferViewBuffers=[],this.accessors=[],this.textures=[],this.textureInfos=new Map,this.materials=[],this.meshes=[],this.cameras=[],this.nodes=[],this.skins=[],this.animations=[],this.scenes=[],this.jsonDoc=Z}setTextureInfo(Z,J){if(this.textureInfos.set(Z,J),J.texCoord!==void 0)Z.setTexCoord(J.texCoord);if(J.extras!==void 0)Z.setExtras(J.extras);let X=this.jsonDoc.json.textures[J.index];if(X.sampler===void 0)return;let $=this.jsonDoc.json.samplers[X.sampler];if($.magFilter!==void 0)Z.setMagFilter($.magFilter);if($.minFilter!==void 0)Z.setMinFilter($.minFilter);if($.wrapS!==void 0)Z.setWrapS($.wrapS);if($.wrapT!==void 0)Z.setWrapT($.wrapT)}}var bu={logger:W7.DEFAULT_INSTANCE,extensions:[],dependencies:{}},xV5=new Set([n.BUFFER,n.TEXTURE,n.MATERIAL,n.MESH,n.PRIMITIVE,n.NODE,n.SCENE]);class nu{static read(Z,J=bu){let X=A6({},bu,J),{json:$}=Z,Y=new F6().setLogger(X.logger);this.validate(Z,X);let Q=new iu(Z),W=$.asset,K=Y.getRoot().getAsset();if(W.copyright)K.copyright=W.copyright;if(W.extras)K.extras=W.extras;if($.extras!==void 0)Y.getRoot().setExtras(A6({},$.extras));let G=$.extensionsUsed||[],V=$.extensionsRequired||[];X.extensions.sort((D,C)=>D.EXTENSION_NAME>C.EXTENSION_NAME?1:-1);for(let D of X.extensions)if(G.includes(D.EXTENSION_NAME)){let C=Y.createExtension(D).setRequired(V.includes(D.EXTENSION_NAME)),T=C.prereadTypes.filter((k)=>!xV5.has(k));if(T.length)X.logger.warn(`Preread hooks for some types (${T.join()}), requested by extension ${C.extensionName}, are unsupported. Please file an issue or a PR.`);for(let k of C.readDependencies)C.install(k,X.dependencies[k])}let H=$.buffers||[];Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.BUFFER)).forEach((D)=>D.preread(Q,n.BUFFER)),Q.buffers=H.map((D)=>{let C=Y.createBuffer(D.name);if(D.extras)C.setExtras(D.extras);if(D.uri&&D.uri.indexOf("__")!==0)C.setURI(D.uri);return C});let q=$.bufferViews||[];Q.bufferViewBuffers=q.map((D,C)=>{if(!Q.bufferViews[C]){let T=Z.json.buffers[D.buffer],k=T.uri?Z.resources[T.uri]:Z.resources[fF],A=D.byteOffset||0;Q.bufferViews[C]=r0.toView(k,A,D.byteLength)}return Q.buffers[D.buffer]});let z=$.accessors||[];Q.accessors=z.map((D)=>{let C=Q.bufferViewBuffers[D.bufferView],T=Y.createAccessor(D.name,C).setType(D.type);if(D.extras)T.setExtras(D.extras);if(D.normalized!==void 0)T.setNormalized(D.normalized);if(D.bufferView===void 0)return T;return T.setArray(xF(D,Q)),T});let F=$.images||[],U=$.textures||[];Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.TEXTURE)).forEach((D)=>D.preread(Q,n.TEXTURE)),Q.textures=F.map((D)=>{let C=Y.createTexture(D.name);if(D.extras)C.setExtras(D.extras);if(D.bufferView!==void 0){let T=$.bufferViews[D.bufferView],k=Z.json.buffers[T.buffer],A=k.uri?Z.resources[k.uri]:Z.resources[fF],v=T.byteOffset||0,x=T.byteLength,I=A.slice(v,v+x);C.setImage(I)}else if(D.uri!==void 0){if(C.setImage(Z.resources[D.uri]),D.uri.indexOf("__")!==0)C.setURI(D.uri)}if(D.mimeType!==void 0)C.setMimeType(D.mimeType);else if(D.uri){let T=nJ.extension(D.uri);C.setMimeType(iJ.extensionToMimeType(T))}return C}),Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.MATERIAL)).forEach((D)=>D.preread(Q,n.MATERIAL));let L=$.materials||[];Q.materials=L.map((D)=>{let C=Y.createMaterial(D.name);if(D.extras)C.setExtras(D.extras);if(D.alphaMode!==void 0)C.setAlphaMode(D.alphaMode);if(D.alphaCutoff!==void 0)C.setAlphaCutoff(D.alphaCutoff);if(D.doubleSided!==void 0)C.setDoubleSided(D.doubleSided);let T=D.pbrMetallicRoughness||{};if(T.baseColorFactor!==void 0)C.setBaseColorFactor(T.baseColorFactor);if(D.emissiveFactor!==void 0)C.setEmissiveFactor(D.emissiveFactor);if(T.metallicFactor!==void 0)C.setMetallicFactor(T.metallicFactor);if(T.roughnessFactor!==void 0)C.setRoughnessFactor(T.roughnessFactor);if(T.baseColorTexture!==void 0){let k=T.baseColorTexture,A=Q.textures[U[k.index].source];C.setBaseColorTexture(A),Q.setTextureInfo(C.getBaseColorTextureInfo(),k)}if(D.emissiveTexture!==void 0){let k=D.emissiveTexture,A=Q.textures[U[k.index].source];C.setEmissiveTexture(A),Q.setTextureInfo(C.getEmissiveTextureInfo(),k)}if(D.normalTexture!==void 0){let k=D.normalTexture,A=Q.textures[U[k.index].source];if(C.setNormalTexture(A),Q.setTextureInfo(C.getNormalTextureInfo(),k),D.normalTexture.scale!==void 0)C.setNormalScale(D.normalTexture.scale)}if(D.occlusionTexture!==void 0){let k=D.occlusionTexture,A=Q.textures[U[k.index].source];if(C.setOcclusionTexture(A),Q.setTextureInfo(C.getOcclusionTextureInfo(),k),D.occlusionTexture.strength!==void 0)C.setOcclusionStrength(D.occlusionTexture.strength)}if(T.metallicRoughnessTexture!==void 0){let k=T.metallicRoughnessTexture,A=Q.textures[U[k.index].source];C.setMetallicRoughnessTexture(A),Q.setTextureInfo(C.getMetallicRoughnessTextureInfo(),k)}return C}),Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.MESH)).forEach((D)=>D.preread(Q,n.MESH));let B=$.meshes||[];Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.PRIMITIVE)).forEach((D)=>D.preread(Q,n.PRIMITIVE)),Q.meshes=B.map((D)=>{let C=Y.createMesh(D.name);if(D.extras)C.setExtras(D.extras);if(D.weights!==void 0)C.setWeights(D.weights);return(D.primitives||[]).forEach((k)=>{let A=Y.createPrimitive();if(k.extras)A.setExtras(k.extras);if(k.material!==void 0)A.setMaterial(Q.materials[k.material]);if(k.mode!==void 0)A.setMode(k.mode);for(let[I,S]of Object.entries(k.attributes||{}))A.setAttribute(I,Q.accessors[S]);if(k.indices!==void 0)A.setIndices(Q.accessors[k.indices]);let v=D.extras&&D.extras.targetNames||[];(k.targets||[]).forEach((I,S)=>{let g=v[S]||S.toString(),m=Y.createPrimitiveTarget(g);for(let[i,r]of Object.entries(I))m.setAttribute(i,Q.accessors[r]);A.addTarget(m)}),C.addPrimitive(A)}),C});let w=$.cameras||[];Q.cameras=w.map((D)=>{let C=Y.createCamera(D.name).setType(D.type);if(D.extras)C.setExtras(D.extras);if(D.type===t$.Type.PERSPECTIVE){let T=D.perspective;if(C.setYFov(T.yfov),C.setZNear(T.znear),T.zfar!==void 0)C.setZFar(T.zfar);if(T.aspectRatio!==void 0)C.setAspectRatio(T.aspectRatio)}else{let T=D.orthographic;C.setZNear(T.znear).setZFar(T.zfar).setXMag(T.xmag).setYMag(T.ymag)}return C});let O=$.nodes||[];Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.NODE)).forEach((D)=>D.preread(Q,n.NODE)),Q.nodes=O.map((D)=>{let C=Y.createNode(D.name);if(D.extras)C.setExtras(D.extras);if(D.translation!==void 0)C.setTranslation(D.translation);if(D.rotation!==void 0)C.setRotation(D.rotation);if(D.scale!==void 0)C.setScale(D.scale);if(D.matrix!==void 0){let T=[0,0,0],k=[0,0,0,1],A=[1,1,1];i0.decompose(D.matrix,T,k,A),C.setTranslation(T),C.setRotation(k),C.setScale(A)}if(D.weights!==void 0)C.setWeights(D.weights);return C});let M=$.skins||[];Q.skins=M.map((D)=>{let C=Y.createSkin(D.name);if(D.extras)C.setExtras(D.extras);if(D.inverseBindMatrices!==void 0)C.setInverseBindMatrices(Q.accessors[D.inverseBindMatrices]);if(D.skeleton!==void 0)C.setSkeleton(Q.nodes[D.skeleton]);for(let T of D.joints)C.addJoint(Q.nodes[T]);return C}),O.map((D,C)=>{let T=Q.nodes[C];if((D.children||[]).forEach((A)=>T.addChild(Q.nodes[A])),D.mesh!==void 0)T.setMesh(Q.meshes[D.mesh]);if(D.camera!==void 0)T.setCamera(Q.cameras[D.camera]);if(D.skin!==void 0)T.setSkin(Q.skins[D.skin])});let N=$.animations||[];Q.animations=N.map((D)=>{let C=Y.createAnimation(D.name);if(D.extras)C.setExtras(D.extras);let k=(D.samplers||[]).map((v)=>{let x=Y.createAnimationSampler().setInput(Q.accessors[v.input]).setOutput(Q.accessors[v.output]).setInterpolation(v.interpolation||TW.Interpolation.LINEAR);if(v.extras)x.setExtras(v.extras);return C.addSampler(x),x});return(D.channels||[]).forEach((v)=>{let x=Y.createAnimationChannel().setSampler(k[v.sampler]).setTargetPath(v.target.path);if(v.target.node!==void 0)x.setTargetNode(Q.nodes[v.target.node]);if(v.extras)x.setExtras(v.extras);C.addChannel(x)}),C});let P=$.scenes||[];if(Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.SCENE)).forEach((D)=>D.preread(Q,n.SCENE)),Q.scenes=P.map((D)=>{let C=Y.createScene(D.name);if(D.extras)C.setExtras(D.extras);return(D.nodes||[]).map((k)=>Q.nodes[k]).forEach((k)=>C.addChild(k)),C}),$.scene!==void 0)Y.getRoot().setDefaultScene(Q.scenes[$.scene]);return Y.getRoot().listExtensionsUsed().forEach((D)=>D.read(Q)),z.forEach((D,C)=>{let T=Q.accessors[C],k=!!D.sparse,A=!D.bufferView&&!T.getArray();if(k||A)T.setSparse(!0).setArray(hV5(D,Q))}),Y}static validate(Z,J){let X=Z.json;if(X.asset.version!=="2.0")throw new Error(`Unsupported glTF version, "${X.asset.version}".`);if(X.extensionsRequired){for(let $ of X.extensionsRequired)if(!J.extensions.find((Y)=>Y.EXTENSION_NAME===$))throw new Error(`Missing required extension, "${$}".`)}if(X.extensionsUsed){for(let $ of X.extensionsUsed)if(!J.extensions.find((Y)=>Y.EXTENSION_NAME===$))J.logger.warn(`Missing optional extension, "${$}".`)}}}function fV5(Z,J){let X=J.jsonDoc,$=J.bufferViews[Z.bufferView],Y=X.json.bufferViews[Z.bufferView],Q=$X[Z.componentType],W=f0.getElementSize(Z.type),K=Q.BYTES_PER_ELEMENT,G=Z.byteOffset||0,V=new Q(Z.count*W),H=new DataView($.buffer,$.byteOffset,$.byteLength),q=Y.byteStride;for(let z=0;z<Z.count;z++)for(let F=0;F<W;F++){let U=G+z*q+F*K,L;switch(Z.componentType){case f0.ComponentType.FLOAT:L=H.getFloat32(U,!0);break;case f0.ComponentType.UNSIGNED_INT:L=H.getUint32(U,!0);break;case f0.ComponentType.UNSIGNED_SHORT:L=H.getUint16(U,!0);break;case f0.ComponentType.UNSIGNED_BYTE:L=H.getUint8(U);break;case f0.ComponentType.SHORT:L=H.getInt16(U,!0);break;case f0.ComponentType.BYTE:L=H.getInt8(U);break;default:throw new Error(`Unexpected componentType "${Z.componentType}".`)}V[z*W+F]=L}return V}function xF(Z,J){let X=J.jsonDoc,$=J.bufferViews[Z.bufferView],Y=X.json.bufferViews[Z.bufferView],Q=$X[Z.componentType],W=f0.getElementSize(Z.type),K=Q.BYTES_PER_ELEMENT,G=W*K;if(Y.byteStride!==void 0&&Y.byteStride!==G)return fV5(Z,J);let V=$.byteOffset+(Z.byteOffset||0),H=Z.count*W*K;return new Q($.buffer.slice(V,V+H))}function hV5(Z,J){let X=$X[Z.componentType],$=f0.getElementSize(Z.type),Y;if(Z.bufferView!==void 0)Y=xF(Z,J);else Y=new X(Z.count*$);let Q=Z.sparse;if(!Q)return Y;let W=Q.count,K=A6({},Z,Q.indices,{count:W,type:"SCALAR"}),G=A6({},Z,Q.values,{count:W}),V=xF(K,J),H=xF(G,J);for(let q=0;q<K.count;q++)for(let z=0;z<$;z++)Y[V[q]*$+z]=H[q*$+z];return Y}var EG;(function(Z){Z[Z.ARRAY_BUFFER=34962]="ARRAY_BUFFER",Z[Z.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"})(EG||(EG={}));class JX{constructor(Z,J,X){this._doc=void 0,this.jsonDoc=void 0,this.options=void 0,this.accessorIndexMap=new Map,this.animationIndexMap=new Map,this.bufferIndexMap=new Map,this.cameraIndexMap=new Map,this.skinIndexMap=new Map,this.materialIndexMap=new Map,this.meshIndexMap=new Map,this.nodeIndexMap=new Map,this.imageIndexMap=new Map,this.textureDefIndexMap=new Map,this.textureInfoDefMap=new Map,this.samplerDefIndexMap=new Map,this.sceneIndexMap=new Map,this.imageBufferViews=[],this.otherBufferViews=new Map,this.otherBufferViewsIndexMap=new Map,this.extensionData={},this.bufferURIGenerator=void 0,this.imageURIGenerator=void 0,this.logger=void 0,this._accessorUsageMap=new Map,this.accessorUsageGroupedByParent=new Set(["ARRAY_BUFFER"]),this.accessorParents=new Map,this._doc=Z,this.jsonDoc=J,this.options=X;let $=Z.getRoot(),Y=$.listBuffers().length,Q=$.listTextures().length;this.bufferURIGenerator=new fR(Y>1,()=>X.basename||"buffer"),this.imageURIGenerator=new fR(Q>1,(W)=>bV5(Z,W)||X.basename||"texture"),this.logger=Z.getLogger()}createTextureInfoDef(Z,J){let X={magFilter:J.getMagFilter()||void 0,minFilter:J.getMinFilter()||void 0,wrapS:J.getWrapS(),wrapT:J.getWrapT()},$=JSON.stringify(X);if(!this.samplerDefIndexMap.has($))this.samplerDefIndexMap.set($,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(X);let Y={source:this.imageIndexMap.get(Z),sampler:this.samplerDefIndexMap.get($)},Q=JSON.stringify(Y);if(!this.textureDefIndexMap.has(Q))this.textureDefIndexMap.set(Q,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push(Y);let W={index:this.textureDefIndexMap.get(Q)};if(J.getTexCoord()!==0)W.texCoord=J.getTexCoord();if(Object.keys(J.getExtras()).length>0)W.extras=J.getExtras();return this.textureInfoDefMap.set(J,W),W}createPropertyDef(Z){let J={};if(Z.getName())J.name=Z.getName();if(Object.keys(Z.getExtras()).length>0)J.extras=Z.getExtras();return J}createAccessorDef(Z){let J=this.createPropertyDef(Z);if(J.type=Z.getType(),J.componentType=Z.getComponentType(),J.count=Z.getCount(),this._doc.getGraph().listParentEdges(Z).some(($)=>$.getName()==="attributes"&&$.getAttributes().key==="POSITION"||$.getName()==="input"))J.max=Z.getMax([]).map(Math.fround),J.min=Z.getMin([]).map(Math.fround);if(Z.getNormalized())J.normalized=Z.getNormalized();return J}createImageData(Z,J,X){if(this.options.format===pJ.GLB)this.imageBufferViews.push(J),Z.bufferView=this.jsonDoc.json.bufferViews.length,this.jsonDoc.json.bufferViews.push({buffer:0,byteOffset:-1,byteLength:J.byteLength});else{let $=iJ.mimeTypeToExtension(X.getMimeType());Z.uri=this.imageURIGenerator.createURI(X,$),this.assignResourceURI(Z.uri,J,!1)}}assignResourceURI(Z,J,X){let $=this.jsonDoc.resources;if(!(Z in $)){$[Z]=J;return}if(J===$[Z]){this.logger.warn(`Duplicate resource URI, "${Z}".`);return}let Y=`Resource URI "${Z}" already assigned to different data.`;if(!X){this.logger.warn(Y);return}throw new Error(Y)}getAccessorUsage(Z){let J=this._accessorUsageMap.get(Z);if(J)return J;if(Z.getSparse())return I7.SPARSE;for(let X of this._doc.getGraph().listParentEdges(Z)){let{usage:$}=X.getAttributes();if($)return $;if(X.getParent().propertyType!==n.ROOT)this.logger.warn(`Missing attribute ".usage" on edge, "${X.getName()}".`)}return I7.OTHER}addAccessorToUsageGroup(Z,J){let X=this._accessorUsageMap.get(Z);if(X&&X!==J)throw new Error(`Accessor with usage "${X}" cannot be reused as "${J}".`);return this._accessorUsageMap.set(Z,J),this}}JX.BufferViewTarget=EG;JX.BufferViewUsage=I7;JX.USAGE_TO_TARGET={[I7.ARRAY_BUFFER]:EG.ARRAY_BUFFER,[I7.ELEMENT_ARRAY_BUFFER]:EG.ELEMENT_ARRAY_BUFFER};class fR{constructor(Z,J){this.multiple=void 0,this.basename=void 0,this.counter={},this.multiple=Z,this.basename=J}createURI(Z,J){if(Z.getURI())return Z.getURI();else if(!this.multiple)return`${this.basename(Z)}.${J}`;else{let X=this.basename(Z);return this.counter[X]=this.counter[X]||1,`${X}_${this.counter[X]++}.${J}`}}}function bV5(Z,J){let X=Z.getGraph().listParentEdges(J).find(($)=>$.getParent()!==Z.getRoot());return X?X.getName().replace(/texture$/i,""):""}var{BufferViewUsage:AF}=JX,{UNSIGNED_INT:yV5,UNSIGNED_SHORT:gV5,UNSIGNED_BYTE:mV5}=f0.ComponentType,dV5=new Set([n.ACCESSOR,n.BUFFER,n.MATERIAL,n.MESH]);class su{static write(Z,J){let X=Z.getGraph(),$=Z.getRoot(),Y={asset:A6({generator:`glTF-Transform ${gu}`},$.getAsset()),extras:A6({},$.getExtras())},Q={json:Y,resources:{}},W=new JX(Z,Q,J),K=J.logger||W7.DEFAULT_INSTANCE,G=new Set(J.extensions.map((B)=>B.EXTENSION_NAME)),V=Z.getRoot().listExtensionsUsed().filter((B)=>G.has(B.extensionName)).sort((B,w)=>B.extensionName>w.extensionName?1:-1),H=Z.getRoot().listExtensionsRequired().filter((B)=>G.has(B.extensionName)).sort((B,w)=>B.extensionName>w.extensionName?1:-1);if(V.length<Z.getRoot().listExtensionsUsed().length)K.warn("Some extensions were not registered for I/O, and will not be written.");for(let B of V){let w=B.prewriteTypes.filter((O)=>!dV5.has(O));if(w.length)K.warn(`Prewrite hooks for some types (${w.join()}), requested by extension ${B.extensionName}, are unsupported. Please file an issue or a PR.`);for(let O of B.writeDependencies)B.install(O,J.dependencies[O])}function q(B,w,O,M){let N=[],P=0;for(let T of B){let k=W.createAccessorDef(T);k.bufferView=Y.bufferViews.length;let A=T.getArray(),v=r0.pad(r0.toView(A));k.byteOffset=P,P+=v.byteLength,N.push(v),W.accessorIndexMap.set(T,Y.accessors.length),Y.accessors.push(k)}let D=r0.concat(N),C={buffer:w,byteOffset:O,byteLength:D.byteLength};if(M)C.target=M;return Y.bufferViews.push(C),{buffers:N,byteLength:P}}function z(B,w,O){let M=B[0].getCount(),N=0;for(let k of B){let A=W.createAccessorDef(k);A.bufferView=Y.bufferViews.length,A.byteOffset=N;let v=k.getElementSize(),x=k.getComponentSize();N+=r0.padNumber(v*x),W.accessorIndexMap.set(k,Y.accessors.length),Y.accessors.push(A)}let P=M*N,D=new ArrayBuffer(P),C=new DataView(D);for(let k=0;k<M;k++){let A=0;for(let v of B){let x=v.getElementSize(),I=v.getComponentSize(),S=v.getComponentType(),g=v.getArray();for(let m=0;m<x;m++){let i=k*N+A+m*I,r=g[k*x+m];switch(S){case f0.ComponentType.FLOAT:C.setFloat32(i,r,!0);break;case f0.ComponentType.BYTE:C.setInt8(i,r);break;case f0.ComponentType.SHORT:C.setInt16(i,r,!0);break;case f0.ComponentType.UNSIGNED_BYTE:C.setUint8(i,r);break;case f0.ComponentType.UNSIGNED_SHORT:C.setUint16(i,r,!0);break;case f0.ComponentType.UNSIGNED_INT:C.setUint32(i,r,!0);break;default:throw new Error("Unexpected component type: "+S)}}A+=r0.padNumber(x*I)}}let T={buffer:w,byteOffset:O,byteLength:P,byteStride:N,target:JX.BufferViewTarget.ARRAY_BUFFER};return Y.bufferViews.push(T),{byteLength:P,buffers:[new Uint8Array(D)]}}function F(B,w,O){let M=[],N=0,P=new Map,D=-1/0,C=!1;for(let S of B){let g=W.createAccessorDef(S);Y.accessors.push(g),W.accessorIndexMap.set(S,Y.accessors.length-1);let m=[],i=[],r=[],Q0=new Array(S.getElementSize()).fill(0);for(let o0=0,T8=S.getCount();o0<T8;o0++){if(S.getElement(o0,r),i0.eq(r,Q0,0))continue;D=Math.max(o0,D),m.push(o0);for(let n5=0;n5<r.length;n5++)i.push(r[n5])}let F0=m.length,_0={accessorDef:g,count:F0};if(P.set(S,_0),F0===0)continue;if(F0>S.getCount()/2)C=!0;let A0=$X[S.getComponentType()];_0.indices=m,_0.values=new A0(i)}if(!Number.isFinite(D))return{buffers:M,byteLength:N};if(C)K.warn("Some sparse accessors have >50% non-zero elements, which may increase file size.");let T=D<255?Uint8Array:D<65535?Uint16Array:Uint32Array,k=D<255?mV5:D<65535?gV5:yV5,A={buffer:w,byteOffset:O+N,byteLength:0};for(let S of B){let g=P.get(S);if(g.count===0)continue;g.indicesByteOffset=A.byteLength;let m=r0.pad(r0.toView(new T(g.indices)));M.push(m),N+=m.byteLength,A.byteLength+=m.byteLength}Y.bufferViews.push(A);let v=Y.bufferViews.length-1,x={buffer:w,byteOffset:O+N,byteLength:0};for(let S of B){let g=P.get(S);if(g.count===0)continue;g.valuesByteOffset=x.byteLength;let m=r0.pad(r0.toView(g.values));M.push(m),N+=m.byteLength,x.byteLength+=m.byteLength}Y.bufferViews.push(x);let I=Y.bufferViews.length-1;for(let S of B){let g=P.get(S);if(g.count===0)continue;g.accessorDef.sparse={count:g.count,indices:{bufferView:v,byteOffset:g.indicesByteOffset,componentType:k},values:{bufferView:I,byteOffset:g.valuesByteOffset}}}return{buffers:M,byteLength:N}}if(Y.accessors=[],Y.bufferViews=[],Y.samplers=[],Y.textures=[],Y.images=$.listTextures().map((B,w)=>{let O=W.createPropertyDef(B);if(B.getMimeType())O.mimeType=B.getMimeType();let M=B.getImage();if(M)W.createImageData(O,M,B);return W.imageIndexMap.set(B,w),O}),V.filter((B)=>B.prewriteTypes.includes(n.ACCESSOR)).forEach((B)=>B.prewrite(W,n.ACCESSOR)),$.listAccessors().forEach((B)=>{let{accessorUsageGroupedByParent:w,accessorParents:O}=W;if(W.accessorIndexMap.has(B))return;let M=W.getAccessorUsage(B);if(W.addAccessorToUsageGroup(B,M),w.has(M)){let N=X.listParents(B).find((P)=>P.propertyType!==n.ROOT);O.set(B,N)}}),V.filter((B)=>B.prewriteTypes.includes(n.BUFFER)).forEach((B)=>B.prewrite(W,n.BUFFER)),($.listAccessors().length>0||W.otherBufferViews.size>0||$.listTextures().length>0&&J.format===pJ.GLB)&&$.listBuffers().length===0)throw new Error("Buffer required for Document resources, but none was found.");if(Y.buffers=[],$.listBuffers().forEach((B,w)=>{let O=W.createPropertyDef(B),M=W.accessorUsageGroupedByParent,N=B.listParents().filter((x)=>x instanceof f0),P=new Set(N.map((x)=>W.accessorParents.get(x))),D=new Map(Array.from(P).map((x,I)=>[x,I])),C={};for(let x of N){var T;if(W.accessorIndexMap.has(x))continue;let I=W.getAccessorUsage(x),S=I;if(M.has(I)){let g=W.accessorParents.get(x);S+=`:${D.get(g)}`}C[T=S]||(C[T]={usage:I,accessors:[]}),C[S].accessors.push(x)}let k=[],A=Y.buffers.length,v=0;for(let{usage:x,accessors:I}of Object.values(C))if(x===AF.ARRAY_BUFFER&&J.vertexLayout===hF.INTERLEAVED){let S=z(I,A,v);v+=S.byteLength;for(let g of S.buffers)k.push(g)}else if(x===AF.ARRAY_BUFFER)for(let S of I){let g=z([S],A,v);v+=g.byteLength;for(let m of g.buffers)k.push(m)}else if(x===AF.SPARSE){let S=F(I,A,v);v+=S.byteLength;for(let g of S.buffers)k.push(g)}else if(x===AF.ELEMENT_ARRAY_BUFFER){let S=JX.BufferViewTarget.ELEMENT_ARRAY_BUFFER,g=q(I,A,v,S);v+=g.byteLength;for(let m of g.buffers)k.push(m)}else{let S=q(I,A,v);v+=S.byteLength;for(let g of S.buffers)k.push(g)}if(W.imageBufferViews.length&&w===0){for(let x=0;x<W.imageBufferViews.length;x++)if(Y.bufferViews[Y.images[x].bufferView].byteOffset=v,v+=W.imageBufferViews[x].byteLength,k.push(W.imageBufferViews[x]),v%8){let I=8-v%8;v+=I,k.push(new Uint8Array(I))}}if(W.otherBufferViews.has(B))for(let x of W.otherBufferViews.get(B))Y.bufferViews.push({buffer:A,byteOffset:v,byteLength:x.byteLength}),W.otherBufferViewsIndexMap.set(x,Y.bufferViews.length-1),v+=x.byteLength,k.push(x);if(v){let x;if(J.format===pJ.GLB)x=fF;else x=W.bufferURIGenerator.createURI(B,"bin"),O.uri=x;O.byteLength=v,W.assignResourceURI(x,r0.concat(k),!0)}Y.buffers.push(O),W.bufferIndexMap.set(B,w)}),$.listAccessors().find((B)=>!B.getBuffer()))K.warn("Skipped writing one or more Accessors: no Buffer assigned.");V.filter((B)=>B.prewriteTypes.includes(n.MATERIAL)).forEach((B)=>B.prewrite(W,n.MATERIAL)),Y.materials=$.listMaterials().map((B,w)=>{let O=W.createPropertyDef(B);if(B.getAlphaMode()!==nZ.AlphaMode.OPAQUE)O.alphaMode=B.getAlphaMode();if(B.getAlphaMode()===nZ.AlphaMode.MASK)O.alphaCutoff=B.getAlphaCutoff();if(B.getDoubleSided())O.doubleSided=!0;if(O.pbrMetallicRoughness={},!i0.eq(B.getBaseColorFactor(),[1,1,1,1]))O.pbrMetallicRoughness.baseColorFactor=B.getBaseColorFactor();if(!i0.eq(B.getEmissiveFactor(),[0,0,0]))O.emissiveFactor=B.getEmissiveFactor();if(B.getRoughnessFactor()!==1)O.pbrMetallicRoughness.roughnessFactor=B.getRoughnessFactor();if(B.getMetallicFactor()!==1)O.pbrMetallicRoughness.metallicFactor=B.getMetallicFactor();if(B.getBaseColorTexture()){let M=B.getBaseColorTexture(),N=B.getBaseColorTextureInfo();O.pbrMetallicRoughness.baseColorTexture=W.createTextureInfoDef(M,N)}if(B.getEmissiveTexture()){let M=B.getEmissiveTexture(),N=B.getEmissiveTextureInfo();O.emissiveTexture=W.createTextureInfoDef(M,N)}if(B.getNormalTexture()){let M=B.getNormalTexture(),N=B.getNormalTextureInfo(),P=W.createTextureInfoDef(M,N);if(B.getNormalScale()!==1)P.scale=B.getNormalScale();O.normalTexture=P}if(B.getOcclusionTexture()){let M=B.getOcclusionTexture(),N=B.getOcclusionTextureInfo(),P=W.createTextureInfoDef(M,N);if(B.getOcclusionStrength()!==1)P.strength=B.getOcclusionStrength();O.occlusionTexture=P}if(B.getMetallicRoughnessTexture()){let M=B.getMetallicRoughnessTexture(),N=B.getMetallicRoughnessTextureInfo();O.pbrMetallicRoughness.metallicRoughnessTexture=W.createTextureInfoDef(M,N)}return W.materialIndexMap.set(B,w),O}),V.filter((B)=>B.prewriteTypes.includes(n.MESH)).forEach((B)=>B.prewrite(W,n.MESH)),Y.meshes=$.listMeshes().map((B,w)=>{let O=W.createPropertyDef(B),M=null;if(O.primitives=B.listPrimitives().map((N)=>{let P={attributes:{}};P.mode=N.getMode();let D=N.getMaterial();if(D)P.material=W.materialIndexMap.get(D);if(Object.keys(N.getExtras()).length)P.extras=N.getExtras();let C=N.getIndices();if(C)P.indices=W.accessorIndexMap.get(C);for(let T of N.listSemantics())P.attributes[T]=W.accessorIndexMap.get(N.getAttribute(T));for(let T of N.listTargets()){let k={};for(let A of T.listSemantics())k[A]=W.accessorIndexMap.get(T.getAttribute(A));P.targets=P.targets||[],P.targets.push(k)}if(N.listTargets().length&&!M)M=N.listTargets().map((T)=>T.getName());return P}),B.getWeights().length)O.weights=B.getWeights();if(M)O.extras=O.extras||{},O.extras.targetNames=M;return W.meshIndexMap.set(B,w),O}),Y.cameras=$.listCameras().map((B,w)=>{let O=W.createPropertyDef(B);if(O.type=B.getType(),O.type===t$.Type.PERSPECTIVE){O.perspective={znear:B.getZNear(),zfar:B.getZFar(),yfov:B.getYFov()};let M=B.getAspectRatio();if(M!==null)O.perspective.aspectRatio=M}else O.orthographic={znear:B.getZNear(),zfar:B.getZFar(),xmag:B.getXMag(),ymag:B.getYMag()};return W.cameraIndexMap.set(B,w),O}),Y.nodes=$.listNodes().map((B,w)=>{let O=W.createPropertyDef(B);if(!i0.eq(B.getTranslation(),[0,0,0]))O.translation=B.getTranslation();if(!i0.eq(B.getRotation(),[0,0,0,1]))O.rotation=B.getRotation();if(!i0.eq(B.getScale(),[1,1,1]))O.scale=B.getScale();if(B.getWeights().length)O.weights=B.getWeights();return W.nodeIndexMap.set(B,w),O}),Y.skins=$.listSkins().map((B,w)=>{let O=W.createPropertyDef(B),M=B.getInverseBindMatrices();if(M)O.inverseBindMatrices=W.accessorIndexMap.get(M);let N=B.getSkeleton();if(N)O.skeleton=W.nodeIndexMap.get(N);return O.joints=B.listJoints().map((P)=>W.nodeIndexMap.get(P)),W.skinIndexMap.set(B,w),O}),$.listNodes().forEach((B,w)=>{let O=Y.nodes[w],M=B.getMesh();if(M)O.mesh=W.meshIndexMap.get(M);let N=B.getCamera();if(N)O.camera=W.cameraIndexMap.get(N);let P=B.getSkin();if(P)O.skin=W.skinIndexMap.get(P);if(B.listChildren().length>0)O.children=B.listChildren().map((D)=>W.nodeIndexMap.get(D))}),Y.animations=$.listAnimations().map((B,w)=>{let O=W.createPropertyDef(B),M=new Map;return O.samplers=B.listSamplers().map((N,P)=>{let D=W.createPropertyDef(N);return D.input=W.accessorIndexMap.get(N.getInput()),D.output=W.accessorIndexMap.get(N.getOutput()),D.interpolation=N.getInterpolation(),M.set(N,P),D}),O.channels=B.listChannels().map((N)=>{let P=W.createPropertyDef(N);return P.sampler=M.get(N.getSampler()),P.target={node:W.nodeIndexMap.get(N.getTargetNode()),path:N.getTargetPath()},P}),W.animationIndexMap.set(B,w),O}),Y.scenes=$.listScenes().map((B,w)=>{let O=W.createPropertyDef(B);return O.nodes=B.listChildren().map((M)=>W.nodeIndexMap.get(M)),W.sceneIndexMap.set(B,w),O});let L=$.getDefaultScene();if(L)Y.scene=$.listScenes().indexOf(L);return Y.extensionsUsed=V.map((B)=>B.extensionName),Y.extensionsRequired=H.map((B)=>B.extensionName),V.forEach((B)=>B.write(W)),uV5(Y),Q}}function uV5(Z){let J=[];for(let X in Z){let $=Z[X];if(Array.isArray($)&&$.length===0)J.push(X);else if($===null||$==="")J.push(X);else if($&&typeof $==="object"&&Object.keys($).length===0)J.push(X)}for(let X of J)delete Z[X]}var gF;(function(Z){Z[Z.JSON=1313821514]="JSON",Z[Z.BIN=5130562]="BIN"})(gF||(gF={}));class au{constructor(){this._logger=W7.DEFAULT_INSTANCE,this._extensions=new Set,this._dependencies={},this._vertexLayout=hF.INTERLEAVED,this.lastReadBytes=0,this.lastWriteBytes=0}setLogger(Z){return this._logger=Z,this}registerExtensions(Z){for(let J of Z)this._extensions.add(J),J.register();return this}registerDependencies(Z){return Object.assign(this._dependencies,Z),this}setVertexLayout(Z){return this._vertexLayout=Z,this}async read(Z){return await this.readJSON(await this.readAsJSON(Z))}async readAsJSON(Z){let J=await this.readURI(Z,"view");this.lastReadBytes=J.byteLength;let X=yu(J)?this._binaryToJSON(J):{json:JSON.parse(r0.decodeText(J)),resources:{}};return await this._readResourcesExternal(X,this.dirname(Z)),this._readResourcesInternal(X),X}async readJSON(Z){return Z=this._copyJSON(Z),this._readResourcesInternal(Z),nu.read(Z,{extensions:Array.from(this._extensions),dependencies:this._dependencies,logger:this._logger})}async binaryToJSON(Z){let J=this._binaryToJSON(r0.assertView(Z));this._readResourcesInternal(J);let X=J.json;if(X.buffers&&X.buffers.some(($)=>cV5(J,$)))throw new Error("Cannot resolve external buffers with binaryToJSON().");else if(X.images&&X.images.some(($)=>lV5(J,$)))throw new Error("Cannot resolve external images with binaryToJSON().");return J}async readBinary(Z){return this.readJSON(await this.binaryToJSON(r0.assertView(Z)))}async writeJSON(Z,J={}){if(J.format===pJ.GLB&&Z.getRoot().listBuffers().length>1)throw new Error("GLB must have 0–1 buffers.");return su.write(Z,{format:J.format||pJ.GLTF,basename:J.basename||"",logger:this._logger,vertexLayout:this._vertexLayout,dependencies:A6({},this._dependencies),extensions:Array.from(this._extensions)})}async writeBinary(Z){let{json:J,resources:X}=await this.writeJSON(Z,{format:pJ.GLB}),$=new Uint32Array([1179937895,2,12]),Y=JSON.stringify(J),Q=r0.pad(r0.encodeText(Y),32),W=r0.toView(new Uint32Array([Q.byteLength,1313821514])),K=r0.concat([W,Q]);$[$.length-1]+=K.byteLength;let G=Object.values(X)[0];if(!G||!G.byteLength)return r0.concat([r0.toView($),K]);let V=r0.pad(G,0),H=r0.toView(new Uint32Array([V.byteLength,5130562])),q=r0.concat([H,V]);return $[$.length-1]+=q.byteLength,r0.concat([r0.toView($),K,q])}async _readResourcesExternal(Z,J){var X=this;let $=Z.json.images||[],Y=Z.json.buffers||[],Q=[...$,...Y].map(async function(W){let K=W.uri;if(!K||K.match(/data:/))return Promise.resolve();Z.resources[K]=await X.readURI(X.resolve(J,K),"view"),X.lastReadBytes+=Z.resources[K].byteLength});await Promise.all(Q)}_readResourcesInternal(Z){function J(Y){if(!Y.uri)return;if(Y.uri in Z.resources){r0.assertView(Z.resources[Y.uri]);return}if(Y.uri.match(/data:/)){let Q=`__${lu()}.${nJ.extension(Y.uri)}`;Z.resources[Q]=r0.createBufferFromDataURI(Y.uri),Y.uri=Q}}(Z.json.images||[]).forEach((Y)=>{if(Y.bufferView===void 0&&Y.uri===void 0)throw new Error("Missing resource URI or buffer view.");J(Y)}),(Z.json.buffers||[]).forEach(J)}_copyJSON(Z){let{images:J,buffers:X}=Z.json;if(Z={json:A6({},Z.json),resources:A6({},Z.resources)},J)Z.json.images=J.map(($)=>A6({},$));if(X)Z.json.buffers=X.map(($)=>A6({},$));return Z}_binaryToJSON(Z){if(!yu(Z))throw new Error("Invalid glTF 2.0 binary.");let J=new Uint32Array(Z.buffer,Z.byteOffset+12,2);if(J[1]!==gF.JSON)throw new Error("Missing required GLB JSON chunk.");let X=20,$=J[0],Y=r0.decodeText(r0.toView(Z,X,$)),Q=JSON.parse(Y),W=X+$;if(Z.byteLength<=W)return{json:Q,resources:{}};let K=new Uint32Array(Z.buffer,Z.byteOffset+W,2);if(K[1]!==gF.BIN)return{json:Q,resources:{}};let G=K[0],V=r0.toView(Z,W+8,G);return{json:Q,resources:{[fF]:V}}}}function cV5(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)}function lV5(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)&&J.bufferView===void 0}function yu(Z){if(Z.byteLength<3*Uint32Array.BYTES_PER_ELEMENT)return!1;let J=new Uint32Array(Z.buffer,Z.byteOffset,3);return J[0]===1179937895&&J[1]===2}class uR extends au{constructor(Z=null,J=H9.DEFAULT_INIT){super();this._fetch=void 0,this._fetchConfig=void 0,this._init=void 0,this._fetchEnabled=!1,this._fetch=Z,this._fetchConfig=J,this._init=this.init()}async init(){if(this._init)return this._init;return Promise.all([import("fs"),import("path")]).then(([Z,J])=>{this._fs=Z.promises,this._path=J})}setAllowNetwork(Z){if(Z&&!this._fetch)throw new Error("NodeIO requires a Fetch API implementation for HTTP requests.");return this._fetchEnabled=Z,this}async readURI(Z,J){if(await this.init(),H9.isAbsoluteURL(Z)){if(!this._fetchEnabled||!this._fetch)throw new Error("Network request blocked. Allow HTTP requests explicitly, if needed.");let X=await this._fetch(Z,this._fetchConfig);switch(J){case"view":return new Uint8Array(await X.arrayBuffer());case"text":return X.text()}}else switch(J){case"view":return this._fs.readFile(Z);case"text":return this._fs.readFile(Z,"utf8")}}resolve(Z,J){if(H9.isAbsoluteURL(Z)||H9.isAbsoluteURL(J))return H9.resolve(Z,J);return this._path.resolve(Z,decodeURIComponent(J))}dirname(Z){if(H9.isAbsoluteURL(Z))return H9.dirname(Z);return this._path.dirname(Z)}async write(Z,J){await this.init(),await(!!Z.match(/\.glb$/)?this._writeGLB(Z,J):this._writeGLTF(Z,J))}async _writeGLTF(Z,J){var X=this;this.lastWriteBytes=0;let{json:$,resources:Y}=await this.writeJSON(J,{format:pJ.GLTF,basename:nJ.basename(Z)}),{_fs:Q,_path:W}=this,K=W.dirname(Z),G=JSON.stringify($,null,2);await Q.writeFile(Z,G),this.lastWriteBytes+=G.length;for(let V of pV5(Object.keys(Y),10))await Promise.all(V.map(async function(H){if(H9.isAbsoluteURL(H)){if(H9.extension(H)==="bin")throw new Error(`Cannot write buffer to path "${H}".`);return}let q=W.join(K,decodeURIComponent(H));await Q.mkdir(W.dirname(q),{recursive:!0}),await Q.writeFile(q,Y[H]),X.lastWriteBytes+=Y[H].byteLength}))}async _writeGLB(Z,J){let X=await this.writeBinary(J);await this._fs.writeFile(Z,X),this.lastWriteBytes=X.byteLength}}function pV5(Z,J){let X=[];for(let $=0,Y=Z.length;$<Y;$+=J){let Q=[];for(let W=0;W<J&&$+W<Y;W++)Q.push(Z[$+W]);X.push(Q)}return X}var pp=e(cR(),1),ip=e(Ep(),1),hF5=e(lp(),1);async function bF5(Z,J){if(!(Z instanceof Uint8Array))throw new Error("[ndarray-pixels] Input must be Uint8Array or Buffer.");let{data:X,info:$}=await ip.default(Z).ensureAlpha().raw().toBuffer({resolveWithObject:!0});return pp.default(new Uint8Array(X),[$.width,$.height,4],[4,4*$.width|0,1],0)}async function np(Z,J){return bF5(Z)}var yF5="v4.1.3",MD="@glb.bin",s;(function(Z){Z.ACCESSOR="Accessor",Z.ANIMATION="Animation",Z.ANIMATION_CHANNEL="AnimationChannel",Z.ANIMATION_SAMPLER="AnimationSampler",Z.BUFFER="Buffer",Z.CAMERA="Camera",Z.MATERIAL="Material",Z.MESH="Mesh",Z.PRIMITIVE="Primitive",Z.PRIMITIVE_TARGET="PrimitiveTarget",Z.NODE="Node",Z.ROOT="Root",Z.SCENE="Scene",Z.SKIN="Skin",Z.TEXTURE="Texture",Z.TEXTURE_INFO="TextureInfo"})(s||(s={}));var sp;(function(Z){Z.INTERLEAVED="interleaved",Z.SEPARATE="separate"})(sp||(sp={}));var _7;(function(Z){Z.ARRAY_BUFFER="ARRAY_BUFFER",Z.ELEMENT_ARRAY_BUFFER="ELEMENT_ARRAY_BUFFER",Z.INVERSE_BIND_MATRICES="INVERSE_BIND_MATRICES",Z.OTHER="OTHER",Z.SPARSE="SPARSE"})(_7||(_7={}));var A7;(function(Z){Z[Z.R=4096]="R",Z[Z.G=256]="G",Z[Z.B=16]="B",Z[Z.A=1]="A"})(A7||(A7={}));var BD;(function(Z){Z.GLTF="GLTF",Z.GLB="GLB"})(BD||(BD={}));var LD=typeof Float32Array!=="undefined"?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var Z=0,J=arguments.length;while(J--)Z+=arguments[J]*arguments[J];return Math.sqrt(Z)};function gF5(){var Z=new LD(3);if(LD!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function UD(Z){var J=Z[0],X=Z[1],$=Z[2];return Math.hypot(J,X,$)}function mF5(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=X[3]*$+X[7]*Y+X[11]*Q+X[15];return W=W||1,Z[0]=(X[0]*$+X[4]*Y+X[8]*Q+X[12])/W,Z[1]=(X[1]*$+X[5]*Y+X[9]*Q+X[13])/W,Z[2]=(X[2]*$+X[6]*Y+X[10]*Q+X[14])/W,Z}(function(){var Z=gF5();return function(J,X,$,Y,Q,W){var K,G;if(!X)X=3;if(!$)$=0;if(Y)G=Math.min(Y*X+$,J.length);else G=J.length;for(K=$;K<G;K+=X)Z[0]=J[K],Z[1]=J[K+1],Z[2]=J[K+2],Q(Z,Z,W),J[K]=Z[0],J[K+1]=Z[1],J[K+2]=Z[2];return J}})();function tp(Z){let J=ep(),X=Z.propertyType===s.NODE?[Z]:Z.listChildren();for(let $ of X)$.traverse((Y)=>{let Q=Y.getMesh();if(!Q)return;let W=dF5(Q,Y.getWorldMatrix());if(W.min.every(isFinite)&&W.max.every(isFinite))wD(W.min,J),wD(W.max,J)});return J}function dF5(Z,J){let X=ep();for(let $ of Z.listPrimitives()){let Y=$.getAttribute("POSITION"),Q=$.getIndices();if(!Y)continue;let W=[0,0,0],K=[0,0,0];for(let G=0,V=Q?Q.getCount():Y.getCount();G<V;G++){let H=Q?Q.getScalar(G):G;W=Y.getElement(H,W),K=mF5(K,W,J),wD(K,X)}}return X}function wD(Z,J){for(let X=0;X<3;X++)J.min[X]=Math.min(Z[X],J.min[X]),J.max[X]=Math.max(Z[X],J.max[X])}function ep(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}class B6{static createBufferFromDataURI(Z){if(typeof Buffer==="undefined"){let J=atob(Z.split(",")[1]),X=new Uint8Array(J.length);for(let $=0;$<J.length;$++)X[$]=J.charCodeAt($);return X}else{let J=Z.split(",")[1],X=Z.indexOf("base64")>=0;return Buffer.from(J,X?"base64":"utf8")}}static encodeText(Z){return new TextEncoder().encode(Z)}static decodeText(Z){return new TextDecoder().decode(Z)}static concat(Z){let J=0;for(let Y of Z)J+=Y.byteLength;let X=new Uint8Array(J),$=0;for(let Y of Z)X.set(Y,$),$+=Y.byteLength;return X}static pad(Z,J=0){let X=this.padNumber(Z.byteLength);if(X===Z.byteLength)return Z;let $=new Uint8Array(X);if($.set(Z),J!==0)for(let Y=Z.byteLength;Y<X;Y++)$[Y]=J;return $}static padNumber(Z){return Math.ceil(Z/4)*4}static equals(Z,J){if(Z===J)return!0;if(Z.byteLength!==J.byteLength)return!1;let X=Z.byteLength;while(X--)if(Z[X]!==J[X])return!1;return!0}static toView(Z,J=0,X=1/0){return new Uint8Array(Z.buffer,Z.byteOffset+J,Math.min(Z.byteLength,X))}static assertView(Z){if(Z&&!ArrayBuffer.isView(Z))throw new Error(`Method requires Uint8Array parameter; received "${typeof Z}".`);return Z}}class Zi{match(Z){return Z.length>=3&&Z[0]===255&&Z[1]===216&&Z[2]===255}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset+4),X,$;while(J.byteLength){if(X=J.getUint16(0,!1),uF5(J,X),$=J.getUint8(X+1),$===192||$===193||$===194)return[J.getUint16(X+7,!1),J.getUint16(X+5,!1)];J=new DataView(Z.buffer,J.byteOffset+X+2)}throw new TypeError("Invalid JPG, no size found")}getChannels(Z){return 3}}class wU{match(Z){return Z.length>=8&&Z[0]===137&&Z[1]===80&&Z[2]===78&&Z[3]===71&&Z[4]===13&&Z[5]===10&&Z[6]===26&&Z[7]===10}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset);if(B6.decodeText(Z.slice(12,16))===wU.PNG_FRIED_CHUNK_NAME)return[J.getUint32(32,!1),J.getUint32(36,!1)];return[J.getUint32(16,!1),J.getUint32(20,!1)]}getChannels(Z){return 4}}wU.PNG_FRIED_CHUNK_NAME="CgBI";class GZ{static registerFormat(Z,J){this.impls[Z]=J}static getMimeType(Z){for(let J in this.impls)if(this.impls[J].match(Z))return J;return null}static getSize(Z,J){if(!this.impls[J])return null;return this.impls[J].getSize(Z)}static getChannels(Z,J){if(!this.impls[J])return null;return this.impls[J].getChannels(Z)}static getVRAMByteLength(Z,J){if(!this.impls[J])return null;if(this.impls[J].getVRAMByteLength)return this.impls[J].getVRAMByteLength(Z);let X=0,$=4,Y=this.getSize(Z,J);if(!Y)return null;while(Y[0]>1||Y[1]>1)X+=Y[0]*Y[1]*$,Y[0]=Math.max(Math.floor(Y[0]/2),1),Y[1]=Math.max(Math.floor(Y[1]/2),1);return X+=1*$,X}static mimeTypeToExtension(Z){if(Z==="image/jpeg")return"jpg";return Z.split("/").pop()}static extensionToMimeType(Z){if(Z==="jpg")return"image/jpeg";if(!Z)return"";return`image/${Z}`}}GZ.impls={"image/jpeg":new Zi,"image/png":new wU};function uF5(Z,J){if(J>Z.byteLength)throw new TypeError("Corrupt JPG, exceeded buffer limits");if(Z.getUint8(J)!==255)throw new TypeError("Invalid JPG, marker table corrupted");return Z}class gG{static basename(Z){let J=Z.split(/[\\/]/).pop();return J.substring(0,J.lastIndexOf("."))}static extension(Z){if(Z.startsWith("data:image/")){let J=Z.match(/data:(image\/\w+)/)[1];return GZ.mimeTypeToExtension(J)}else if(Z.startsWith("data:model/gltf+json"))return"gltf";else if(Z.startsWith("data:model/gltf-binary"))return"glb";else if(Z.startsWith("data:application/"))return"bin";return Z.split(/[\\/]/).pop().split(/[.]/).pop()}}function ap(Z){return Object.prototype.toString.call(Z)==="[object Object]"}function YY(Z){if(ap(Z)===!1)return!1;let J=Z.constructor;if(J===void 0)return!0;let X=J.prototype;if(ap(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}var OD,ND;(function(Z){Z[Z.SILENT=4]="SILENT",Z[Z.ERROR=3]="ERROR",Z[Z.WARN=2]="WARN",Z[Z.INFO=1]="INFO",Z[Z.DEBUG=0]="DEBUG"})(ND||(ND={}));class eZ{constructor(Z){this.verbosity=void 0,this.verbosity=Z}debug(Z){if(this.verbosity<=eZ.Verbosity.DEBUG)console.debug(Z)}info(Z){if(this.verbosity<=eZ.Verbosity.INFO)console.info(Z)}warn(Z){if(this.verbosity<=eZ.Verbosity.WARN)console.warn(Z)}error(Z){if(this.verbosity<=eZ.Verbosity.ERROR)console.error(Z)}}OD=eZ;eZ.Verbosity=ND;eZ.DEFAULT_INSTANCE=new OD(OD.Verbosity.INFO);function cF5(Z){var J=Z[0],X=Z[1],$=Z[2],Y=Z[3],Q=Z[4],W=Z[5],K=Z[6],G=Z[7],V=Z[8],H=Z[9],q=Z[10],z=Z[11],F=Z[12],U=Z[13],L=Z[14],B=Z[15],w=J*W-X*Q,O=J*K-$*Q,M=J*G-Y*Q,N=X*K-$*W,P=X*G-Y*W,D=$*G-Y*K,C=V*U-H*F,T=V*L-q*F,k=V*B-z*F,A=H*L-q*U,v=H*B-z*U,x=q*B-z*L;return w*x-O*v+M*A+N*k-P*T+D*C}function lF5(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=J[3],K=J[4],G=J[5],V=J[6],H=J[7],q=J[8],z=J[9],F=J[10],U=J[11],L=J[12],B=J[13],w=J[14],O=J[15],M=X[0],N=X[1],P=X[2],D=X[3];return Z[0]=M*$+N*K+P*q+D*L,Z[1]=M*Y+N*G+P*z+D*B,Z[2]=M*Q+N*V+P*F+D*w,Z[3]=M*W+N*H+P*U+D*O,M=X[4],N=X[5],P=X[6],D=X[7],Z[4]=M*$+N*K+P*q+D*L,Z[5]=M*Y+N*G+P*z+D*B,Z[6]=M*Q+N*V+P*F+D*w,Z[7]=M*W+N*H+P*U+D*O,M=X[8],N=X[9],P=X[10],D=X[11],Z[8]=M*$+N*K+P*q+D*L,Z[9]=M*Y+N*G+P*z+D*B,Z[10]=M*Q+N*V+P*F+D*w,Z[11]=M*W+N*H+P*U+D*O,M=X[12],N=X[13],P=X[14],D=X[15],Z[12]=M*$+N*K+P*q+D*L,Z[13]=M*Y+N*G+P*z+D*B,Z[14]=M*Q+N*V+P*F+D*w,Z[15]=M*W+N*H+P*U+D*O,Z}function pF5(Z,J){var X=J[0],$=J[1],Y=J[2],Q=J[4],W=J[5],K=J[6],G=J[8],V=J[9],H=J[10];return Z[0]=Math.hypot(X,$,Y),Z[1]=Math.hypot(Q,W,K),Z[2]=Math.hypot(G,V,H),Z}function iF5(Z,J){var X=new LD(3);pF5(X,J);var $=1/X[0],Y=1/X[1],Q=1/X[2],W=J[0]*$,K=J[1]*Y,G=J[2]*Q,V=J[4]*$,H=J[5]*Y,q=J[6]*Q,z=J[8]*$,F=J[9]*Y,U=J[10]*Q,L=W+H+U,B=0;if(L>0)B=Math.sqrt(L+1)*2,Z[3]=0.25*B,Z[0]=(q-F)/B,Z[1]=(z-G)/B,Z[2]=(K-V)/B;else if(W>H&&W>U)B=Math.sqrt(1+W-H-U)*2,Z[3]=(q-F)/B,Z[0]=0.25*B,Z[1]=(K+V)/B,Z[2]=(z+G)/B;else if(H>U)B=Math.sqrt(1+H-W-U)*2,Z[3]=(z-G)/B,Z[0]=(K+V)/B,Z[1]=0.25*B,Z[2]=(q+F)/B;else B=Math.sqrt(1+U-W-H)*2,Z[3]=(K-V)/B,Z[0]=(z+G)/B,Z[1]=(q+F)/B,Z[2]=0.25*B;return Z}class $8{static identity(Z){return Z}static eq(Z,J,X=0.00001){if(Z.length!==J.length)return!1;for(let $=0;$<Z.length;$++)if(Math.abs(Z[$]-J[$])>X)return!1;return!0}static clamp(Z,J,X){if(Z<J)return J;if(Z>X)return X;return Z}static decodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Z/65535;case 5121:return Z/255;case 5122:return Math.max(Z/32767,-1);case 5120:return Math.max(Z/127,-1);default:throw new Error("Invalid component type.")}}static encodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Math.round($8.clamp(Z,0,1)*65535);case 5121:return Math.round($8.clamp(Z,0,1)*255);case 5122:return Math.round($8.clamp(Z,-1,1)*32767);case 5120:return Math.round($8.clamp(Z,-1,1)*127);default:throw new Error("Invalid component type.")}}static decompose(Z,J,X,$){let Y=UD([Z[0],Z[1],Z[2]]),Q=UD([Z[4],Z[5],Z[6]]),W=UD([Z[8],Z[9],Z[10]]);if(cF5(Z)<0)Y=-Y;J[0]=Z[12],J[1]=Z[13],J[2]=Z[14];let G=Z.slice(),V=1/Y,H=1/Q,q=1/W;G[0]*=V,G[1]*=V,G[2]*=V,G[4]*=H,G[5]*=H,G[6]*=H,G[8]*=q,G[9]*=q,G[10]*=q,iF5(X,G),$[0]=Y,$[1]=Q,$[2]=W}static compose(Z,J,X,$){let Y=$,Q=J[0],W=J[1],K=J[2],G=J[3],V=Q+Q,H=W+W,q=K+K,z=Q*V,F=Q*H,U=Q*q,L=W*H,B=W*q,w=K*q,O=G*V,M=G*H,N=G*q,P=X[0],D=X[1],C=X[2];return Y[0]=(1-(L+w))*P,Y[1]=(F+N)*P,Y[2]=(U-M)*P,Y[3]=0,Y[4]=(F-N)*D,Y[5]=(1-(z+w))*D,Y[6]=(B+O)*D,Y[7]=0,Y[8]=(U+M)*C,Y[9]=(B-O)*C,Y[10]=(1-(z+L))*C,Y[11]=0,Y[12]=Z[0],Y[13]=Z[1],Y[14]=Z[2],Y[15]=1,Y}}function nF5(Z,J){if(!!Z!==!!J)return!1;let X=Z.getChild(),$=J.getChild();return X===$||X.equals($)}function sF5(Z,J){if(!!Z!==!!J)return!1;let X=Z.values(),$=J.values();if(X.length!==$.length)return!1;for(let Y=0;Y<X.length;Y++){let Q=X[Y],W=$[Y];if(Q.getChild()===W.getChild())continue;if(!Q.getChild().equals(W.getChild()))return!1}return!0}function aF5(Z,J){if(!!Z!==!!J)return!1;let X=Z.keys(),$=J.keys();if(X.length!==$.length)return!1;for(let Y of X){let Q=Z.get(Y),W=J.get(Y);if(!!Q!==!!W)return!1;let K=Q.getChild(),G=W.getChild();if(K===G)continue;if(!K.equals(G))return!1}return!0}function Ji(Z,J){if(Z===J)return!0;if(!!Z!==!!J||!Z||!J)return!1;if(Z.length!==J.length)return!1;for(let X=0;X<Z.length;X++)if(Z[X]!==J[X])return!1;return!0}function Xi(Z,J){if(Z===J)return!0;if(!!Z!==!!J)return!1;if(!YY(Z)||!YY(J))return Z===J;let X=Z,$=J,Y=0,Q=0,W;for(W in X)Y++;for(W in $)Q++;if(Y!==Q)return!1;for(W in X){let K=X[W],G=$[W];if(UU(K)&&UU(G)){if(!Ji(K,G))return!1}else if(YY(K)&&YY(G)){if(!Xi(K,G))return!1}else if(K!==G)return!1}return!0}function UU(Z){return Array.isArray(Z)||ArrayBuffer.isView(Z)}var rp="https://null.example";class RD{static dirname(Z){let J=Z.lastIndexOf("/");if(J===-1)return"./";return Z.substring(0,J+1)}static basename(Z){return gG.basename(new URL(Z,rp).pathname)}static extension(Z){return gG.extension(new URL(Z,rp).pathname)}static resolve(Z,J){if(!this.isRelativePath(J))return J;let X=Z.split("/"),$=J.split("/");X.pop();for(let Y=0;Y<$.length;Y++){if($[Y]===".")continue;if($[Y]==="..")X.pop();else X.push($[Y])}return X.join("/")}static isAbsoluteURL(Z){return this.PROTOCOL_REGEXP.test(Z)}static isRelativePath(Z){return!/^(?:[a-zA-Z]+:)?\//.test(Z)}}RD.DEFAULT_INIT={};RD.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;var VX=(Z)=>Z,rF5=new Set;class OU extends CW{constructor(Z,J=""){super(Z);this[y0].name=J,this.init(),this.dispatchEvent({type:"create"})}getGraph(){return this.graph}getDefaults(){return Object.assign(super.getDefaults(),{name:"",extras:{}})}set(Z,J){if(Array.isArray(J))J=J.slice();return super.set(Z,J)}getName(){return this.get("name")}setName(Z){return this.set("name",Z)}getExtras(){return this.get("extras")}setExtras(Z){return this.set("extras",Z)}clone(){return new this.constructor(this.graph).copy(this,VX)}copy(Z,J=VX){for(let X in this[y0]){let $=this[y0][X];if($ instanceof Y7){if(!this[WZ].has(X))$.dispose()}else if($ instanceof z6||$ instanceof I0)for(let Y of $.values())Y.dispose();else if($ instanceof a5)for(let Y of $.values())Y.dispose()}for(let X in Z[y0]){let $=this[y0][X],Y=Z[y0][X];if(Y instanceof Y7)if(this[WZ].has(X))$.getChild().copy(J(Y.getChild()),J);else this.setRef(X,J(Y.getChild()),Y.getAttributes());else if(Y instanceof I0||Y instanceof z6)for(let Q of Y.values())this.addRef(X,J(Q.getChild()),Q.getAttributes());else if(Y instanceof a5)for(let Q of Y.keys()){let W=Y.get(Q);this.setRefMap(X,Q,J(W.getChild()),W.getAttributes())}else if(YY(Y))this[y0][X]=JSON.parse(JSON.stringify(Y));else if(Array.isArray(Y)||Y instanceof ArrayBuffer||ArrayBuffer.isView(Y))this[y0][X]=Y.slice();else this[y0][X]=Y}return this}equals(Z,J=rF5){if(this===Z)return!0;if(this.propertyType!==Z.propertyType)return!1;for(let X in this[y0]){if(J.has(X))continue;let $=this[y0][X],Y=Z[y0][X];if($ instanceof Y7||Y instanceof Y7){if(!nF5($,Y))return!1}else if($ instanceof I0||Y instanceof I0||$ instanceof z6||Y instanceof z6){if(!sF5($,Y))return!1}else if($ instanceof a5||Y instanceof a5){if(!aF5($,Y))return!1}else if(YY($)||YY(Y)){if(!Xi($,Y))return!1}else if(UU($)||UU(Y)){if(!Ji($,Y))return!1}else if($!==Y)return!1}return!0}detach(){return this.graph.disconnectParents(this,(Z)=>Z.propertyType!=="Root"),this}listParents(){return this.graph.listParents(this)}}class L6 extends OU{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new a5})}getExtension(Z){return this.getRefMap("extensions",Z)}setExtension(Z,J){if(J)J._validateParent(this);return this.setRefMap("extensions",Z,J)}listExtensions(){return this.listRefMapValues("extensions")}}class k0 extends L6{init(){this.propertyType=s.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:k0.Type.SCALAR,componentType:k0.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(Z){switch(Z){case k0.Type.SCALAR:return 1;case k0.Type.VEC2:return 2;case k0.Type.VEC3:return 3;case k0.Type.VEC4:return 4;case k0.Type.MAT2:return 4;case k0.Type.MAT3:return 9;case k0.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+Z)}}static getComponentSize(Z){switch(Z){case k0.ComponentType.BYTE:return 1;case k0.ComponentType.UNSIGNED_BYTE:return 1;case k0.ComponentType.SHORT:return 2;case k0.ComponentType.UNSIGNED_SHORT:return 2;case k0.ComponentType.UNSIGNED_INT:return 4;case k0.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+Z)}}getMinNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),$=this.getComponentType();if(this.getMin(Z),J)for(let Y=0;Y<X;Y++)Z[Y]=$8.decodeNormalizedInt(Z[Y],$);return Z}getMin(Z){let J=this.getArray(),X=this.getCount(),$=this.getElementSize();for(let Y=0;Y<$;Y++)Z[Y]=1/0;for(let Y=0;Y<X*$;Y+=$)for(let Q=0;Q<$;Q++){let W=J[Y+Q];if(Number.isFinite(W))Z[Q]=Math.min(Z[Q],W)}return Z}getMaxNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),$=this.getComponentType();if(this.getMax(Z),J)for(let Y=0;Y<X;Y++)Z[Y]=$8.decodeNormalizedInt(Z[Y],$);return Z}getMax(Z){let J=this.get("array"),X=this.getCount(),$=this.getElementSize();for(let Y=0;Y<$;Y++)Z[Y]=-1/0;for(let Y=0;Y<X*$;Y+=$)for(let Q=0;Q<$;Q++){let W=J[Y+Q];if(Number.isFinite(W))Z[Q]=Math.max(Z[Q],W)}return Z}getCount(){let Z=this.get("array");return Z?Z.length/this.getElementSize():0}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getElementSize(){return k0.getElementSize(this.get("type"))}getComponentSize(){return this.get("array").BYTES_PER_ELEMENT}getComponentType(){return this.get("componentType")}getNormalized(){return this.get("normalized")}setNormalized(Z){return this.set("normalized",Z)}getScalar(Z){let J=this.getElementSize(),X=this.getComponentType(),$=this.getArray();if(this.getNormalized())return $8.decodeNormalizedInt($[Z*J],X);return $[Z*J]}setScalar(Z,J){let X=this.getElementSize(),$=this.getComponentType(),Y=this.getArray();if(this.getNormalized())Y[Z*X]=$8.encodeNormalizedInt(J,$);else Y[Z*X]=J;return this}getElement(Z,J){let X=this.getNormalized(),$=this.getElementSize(),Y=this.getComponentType(),Q=this.getArray();for(let W=0;W<$;W++)if(X)J[W]=$8.decodeNormalizedInt(Q[Z*$+W],Y);else J[W]=Q[Z*$+W];return J}setElement(Z,J){let X=this.getNormalized(),$=this.getElementSize(),Y=this.getComponentType(),Q=this.getArray();for(let W=0;W<$;W++)if(X)Q[Z*$+W]=$8.encodeNormalizedInt(J[W],Y);else Q[Z*$+W]=J[W];return this}getSparse(){return this.get("sparse")}setSparse(Z){return this.set("sparse",Z)}getBuffer(){return this.getRef("buffer")}setBuffer(Z){return this.setRef("buffer",Z)}getArray(){return this.get("array")}setArray(Z){return this.set("componentType",Z?oF5(Z):k0.ComponentType.FLOAT),this.set("array",Z),this}getByteLength(){let Z=this.get("array");return Z?Z.byteLength:0}}k0.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};k0.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};function oF5(Z){switch(Z.constructor){case Float32Array:return k0.ComponentType.FLOAT;case Uint32Array:return k0.ComponentType.UNSIGNED_INT;case Uint16Array:return k0.ComponentType.UNSIGNED_SHORT;case Uint8Array:return k0.ComponentType.UNSIGNED_BYTE;case Int16Array:return k0.ComponentType.SHORT;case Int8Array:return k0.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}class DD extends L6{init(){this.propertyType=s.ANIMATION}getDefaults(){return Object.assign(super.getDefaults(),{channels:new I0,samplers:new I0})}addChannel(Z){return this.addRef("channels",Z)}removeChannel(Z){return this.removeRef("channels",Z)}listChannels(){return this.listRefs("channels")}addSampler(Z){return this.addRef("samplers",Z)}removeSampler(Z){return this.removeRef("samplers",Z)}listSamplers(){return this.listRefs("samplers")}}class dG extends L6{init(){this.propertyType=s.ANIMATION_CHANNEL}getDefaults(){return Object.assign(super.getDefaults(),{targetPath:null,targetNode:null,sampler:null})}getTargetPath(){return this.get("targetPath")}setTargetPath(Z){return this.set("targetPath",Z)}getTargetNode(){return this.getRef("targetNode")}setTargetNode(Z){return this.setRef("targetNode",Z)}getSampler(){return this.getRef("sampler")}setSampler(Z){return this.setRef("sampler",Z)}}dG.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class yW extends L6{init(){this.propertyType=s.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:yW.Interpolation.LINEAR,input:null,output:null})}getInterpolation(){return this.get("interpolation")}setInterpolation(Z){return this.set("interpolation",Z)}getInput(){return this.getRef("input")}setInput(Z){return this.setRef("input",Z,{usage:_7.OTHER})}getOutput(){return this.getRef("output")}setOutput(Z){return this.setRef("output",Z,{usage:_7.OTHER})}}yW.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class PD extends L6{init(){this.propertyType=s.BUFFER}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(Z){return this.set("uri",Z)}}class uG extends L6{init(){this.propertyType=s.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:uG.Type.PERSPECTIVE,znear:0.1,zfar:100,aspectRatio:null,yfov:Math.PI*2*50/360,xmag:1,ymag:1})}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getZNear(){return this.get("znear")}setZNear(Z){return this.set("znear",Z)}getZFar(){return this.get("zfar")}setZFar(Z){return this.set("zfar",Z)}getAspectRatio(){return this.get("aspectRatio")}setAspectRatio(Z){return this.set("aspectRatio",Z)}getYFov(){return this.get("yfov")}setYFov(Z){return this.set("yfov",Z)}getXMag(){return this.get("xmag")}setXMag(Z){return this.set("xmag",Z)}getYMag(){return this.get("ymag")}setYMag(Z){return this.set("ymag",Z)}}uG.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class c5 extends OU{_validateParent(Z){if(!this.parentTypes.includes(Z.propertyType))throw new Error(`Parent "${Z.propertyType}" invalid for child "${this.propertyType}".`)}}c5.EXTENSION_NAME=void 0;class R5 extends L6{init(){this.propertyType=s.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:R5.WrapMode.REPEAT,wrapT:R5.WrapMode.REPEAT})}getTexCoord(){return this.get("texCoord")}setTexCoord(Z){return this.set("texCoord",Z)}getMagFilter(){return this.get("magFilter")}setMagFilter(Z){return this.set("magFilter",Z)}getMinFilter(){return this.get("minFilter")}setMinFilter(Z){return this.set("minFilter",Z)}getWrapS(){return this.get("wrapS")}setWrapS(Z){return this.set("wrapS",Z)}getWrapT(){return this.get("wrapT")}setWrapT(Z){return this.set("wrapT",Z)}}R5.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};R5.MagFilter={NEAREST:9728,LINEAR:9729};R5.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};var{R:qU,G:zU,B:FU,A:tF5}=A7;class cG extends L6{init(){this.propertyType=s.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:cG.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new R5(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new R5(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new R5(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new R5(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new R5(this.graph,"metallicRoughnessTextureInfo")})}getDoubleSided(){return this.get("doubleSided")}setDoubleSided(Z){return this.set("doubleSided",Z)}getAlpha(){return this.get("baseColorFactor")[3]}setAlpha(Z){let J=this.get("baseColorFactor").slice();return J[3]=Z,this.set("baseColorFactor",J)}getAlphaMode(){return this.get("alphaMode")}setAlphaMode(Z){return this.set("alphaMode",Z)}getAlphaCutoff(){return this.get("alphaCutoff")}setAlphaCutoff(Z){return this.set("alphaCutoff",Z)}getBaseColorFactor(){return this.get("baseColorFactor")}setBaseColorFactor(Z){return this.set("baseColorFactor",Z)}getBaseColorTexture(){return this.getRef("baseColorTexture")}getBaseColorTextureInfo(){return this.getRef("baseColorTexture")?this.getRef("baseColorTextureInfo"):null}setBaseColorTexture(Z){return this.setRef("baseColorTexture",Z,{channels:qU|zU|FU|tF5,isColor:!0})}getEmissiveFactor(){return this.get("emissiveFactor")}setEmissiveFactor(Z){return this.set("emissiveFactor",Z)}getEmissiveTexture(){return this.getRef("emissiveTexture")}getEmissiveTextureInfo(){return this.getRef("emissiveTexture")?this.getRef("emissiveTextureInfo"):null}setEmissiveTexture(Z){return this.setRef("emissiveTexture",Z,{channels:qU|zU|FU,isColor:!0})}getNormalScale(){return this.get("normalScale")}setNormalScale(Z){return this.set("normalScale",Z)}getNormalTexture(){return this.getRef("normalTexture")}getNormalTextureInfo(){return this.getRef("normalTexture")?this.getRef("normalTextureInfo"):null}setNormalTexture(Z){return this.setRef("normalTexture",Z,{channels:qU|zU|FU})}getOcclusionStrength(){return this.get("occlusionStrength")}setOcclusionStrength(Z){return this.set("occlusionStrength",Z)}getOcclusionTexture(){return this.getRef("occlusionTexture")}getOcclusionTextureInfo(){return this.getRef("occlusionTexture")?this.getRef("occlusionTextureInfo"):null}setOcclusionTexture(Z){return this.setRef("occlusionTexture",Z,{channels:qU})}getRoughnessFactor(){return this.get("roughnessFactor")}setRoughnessFactor(Z){return this.set("roughnessFactor",Z)}getMetallicFactor(){return this.get("metallicFactor")}setMetallicFactor(Z){return this.set("metallicFactor",Z)}getMetallicRoughnessTexture(){return this.getRef("metallicRoughnessTexture")}getMetallicRoughnessTextureInfo(){return this.getRef("metallicRoughnessTexture")?this.getRef("metallicRoughnessTextureInfo"):null}setMetallicRoughnessTexture(Z){return this.setRef("metallicRoughnessTexture",Z,{channels:zU|FU})}}cG.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class CD extends L6{init(){this.propertyType=s.MESH}getDefaults(){return Object.assign(super.getDefaults(),{weights:[],primitives:new I0})}addPrimitive(Z){return this.addRef("primitives",Z)}removePrimitive(Z){return this.removeRef("primitives",Z)}listPrimitives(){return this.listRefs("primitives")}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}}class TD extends L6{init(){this.propertyType=s.NODE}getDefaults(){return Object.assign(super.getDefaults(),{translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1],weights:[],camera:null,mesh:null,skin:null,children:new I0})}copy(Z,J=VX){if(J===VX)throw new Error("Node cannot be copied.");return super.copy(Z,J)}getTranslation(){return this.get("translation")}getRotation(){return this.get("rotation")}getScale(){return this.get("scale")}setTranslation(Z){return this.set("translation",Z)}setRotation(Z){return this.set("rotation",Z)}setScale(Z){return this.set("scale",Z)}getMatrix(){return $8.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(Z){let J=this.get("translation").slice(),X=this.get("rotation").slice(),$=this.get("scale").slice();return $8.decompose(Z,J,X,$),this.set("translation",J).set("rotation",X).set("scale",$)}getWorldTranslation(){let Z=[0,0,0];return $8.decompose(this.getWorldMatrix(),Z,[0,0,0,1],[1,1,1]),Z}getWorldRotation(){let Z=[0,0,0,1];return $8.decompose(this.getWorldMatrix(),[0,0,0],Z,[1,1,1]),Z}getWorldScale(){let Z=[1,1,1];return $8.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],Z),Z}getWorldMatrix(){let Z=[];for(let $=this;$!=null;$=$.getParentNode())Z.push($);let J,X=Z.pop().getMatrix();while(J=Z.pop())lF5(X,X,J.getMatrix());return X}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);for(let X of Z.listParents())if(X.propertyType===s.SCENE)X.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}getParentNode(){for(let Z of this.listParents())if(Z.propertyType===s.NODE)return Z;return null}getMesh(){return this.getRef("mesh")}setMesh(Z){return this.setRef("mesh",Z)}getCamera(){return this.getRef("camera")}setCamera(Z){return this.setRef("camera",Z)}getSkin(){return this.getRef("skin")}setSkin(Z){return this.setRef("skin",Z)}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}traverse(Z){Z(this);for(let J of this.listChildren())J.traverse(Z);return this}}class HX extends L6{init(){this.propertyType=s.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:HX.Mode.TRIANGLES,material:null,indices:null,attributes:new a5,targets:new I0})}getIndices(){return this.getRef("indices")}setIndices(Z){return this.setRef("indices",Z,{usage:_7.ELEMENT_ARRAY_BUFFER})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:_7.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}getMaterial(){return this.getRef("material")}setMaterial(Z){return this.setRef("material",Z)}getMode(){return this.get("mode")}setMode(Z){return this.set("mode",Z)}listTargets(){return this.listRefs("targets")}addTarget(Z){return this.addRef("targets",Z)}removeTarget(Z){return this.removeRef("targets",Z)}}HX.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class $i extends OU{init(){this.propertyType=s.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new a5})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:_7.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function BU(){return BU=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)({}).hasOwnProperty.call(X,$)&&(Z[$]=X[$])}return Z},BU.apply(null,arguments)}class kD extends L6{init(){this.propertyType=s.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:new I0})}copy(Z,J=VX){if(J===VX)throw new Error("Scene cannot be copied.");return super.copy(Z,J)}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}traverse(Z){for(let J of this.listChildren())J.traverse(Z);return this}}class ED extends L6{init(){this.propertyType=s.SKIN}getDefaults(){return Object.assign(super.getDefaults(),{skeleton:null,inverseBindMatrices:null,joints:new I0})}getSkeleton(){return this.getRef("skeleton")}setSkeleton(Z){return this.setRef("skeleton",Z)}getInverseBindMatrices(){return this.getRef("inverseBindMatrices")}setInverseBindMatrices(Z){return this.setRef("inverseBindMatrices",Z,{usage:_7.INVERSE_BIND_MATRICES})}addJoint(Z){return this.addRef("joints",Z)}removeJoint(Z){return this.removeRef("joints",Z)}listJoints(){return this.listRefs("joints")}}class ID extends L6{init(){this.propertyType=s.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||GZ.extensionToMimeType(gG.extension(this.get("uri")))}setMimeType(Z){return this.set("mimeType",Z)}getURI(){return this.get("uri")}setURI(Z){this.set("uri",Z);let J=GZ.extensionToMimeType(gG.extension(Z));if(J)this.set("mimeType",J);return this}getImage(){return this.get("image")}setImage(Z){return this.set("image",B6.assertView(Z))}getSize(){let Z=this.get("image");if(!Z)return null;return GZ.getSize(Z,this.getMimeType())}}class NU extends L6{init(){this.propertyType=s.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${yF5}`,version:"2.0"},defaultScene:null,accessors:new I0,animations:new I0,buffers:new I0,cameras:new I0,materials:new I0,meshes:new I0,nodes:new I0,scenes:new I0,skins:new I0,textures:new I0})}constructor(Z){super(Z);this._extensions=new Set,Z.addEventListener("node:create",(J)=>{this._addChildOfRoot(J.target)})}clone(){throw new Error("Root cannot be cloned.")}copy(Z,J=VX){if(J===VX)throw new Error("Root cannot be copied.");this.set("asset",BU({},Z.get("asset"))),this.setName(Z.getName()),this.setExtras(BU({},Z.getExtras())),this.setDefaultScene(Z.getDefaultScene()?J(Z.getDefaultScene()):null);for(let X of Z.listRefMapKeys("extensions")){let $=Z.getExtension(X);this.setExtension(X,J($))}return this}_addChildOfRoot(Z){if(Z instanceof kD)this.addRef("scenes",Z);else if(Z instanceof TD)this.addRef("nodes",Z);else if(Z instanceof uG)this.addRef("cameras",Z);else if(Z instanceof ED)this.addRef("skins",Z);else if(Z instanceof CD)this.addRef("meshes",Z);else if(Z instanceof cG)this.addRef("materials",Z);else if(Z instanceof ID)this.addRef("textures",Z);else if(Z instanceof DD)this.addRef("animations",Z);else if(Z instanceof k0)this.addRef("accessors",Z);else if(Z instanceof PD)this.addRef("buffers",Z);return this}getAsset(){return this.get("asset")}listExtensionsUsed(){return Array.from(this._extensions)}listExtensionsRequired(){return this.listExtensionsUsed().filter((Z)=>Z.isRequired())}_enableExtension(Z){return this._extensions.add(Z),this}_disableExtension(Z){return this._extensions.delete(Z),this}listScenes(){return this.listRefs("scenes")}setDefaultScene(Z){return this.setRef("defaultScene",Z)}getDefaultScene(){return this.getRef("defaultScene")}listNodes(){return this.listRefs("nodes")}listCameras(){return this.listRefs("cameras")}listSkins(){return this.listRefs("skins")}listMeshes(){return this.listRefs("meshes")}listMaterials(){return this.listRefs("materials")}listTextures(){return this.listRefs("textures")}listAnimations(){return this.listRefs("animations")}listAccessors(){return this.listRefs("accessors")}listBuffers(){return this.listRefs("buffers")}}class LU{static fromGraph(Z){return LU._GRAPH_DOCUMENTS.get(Z)||null}constructor(){this._graph=new PW,this._root=new NU(this._graph),this._logger=eZ.DEFAULT_INSTANCE,LU._GRAPH_DOCUMENTS.set(this._graph,this)}getRoot(){return this._root}getGraph(){return this._graph}getLogger(){return this._logger}setLogger(Z){return this._logger=Z,this}clone(){throw new Error("Use 'cloneDocument(source)' from '@gltf-transform/functions'.")}merge(Z){throw new Error("Use 'mergeDocuments(target, source)' from '@gltf-transform/functions'.")}async transform(...Z){let J=Z.map((X)=>X.name);for(let X of Z)await X(this,{stack:J});return this}createExtension(Z){let J=Z.EXTENSION_NAME;return this.getRoot().listExtensionsUsed().find(($)=>$.extensionName===J)||new Z(this)}createScene(Z=""){return new kD(this._graph,Z)}createNode(Z=""){return new TD(this._graph,Z)}createCamera(Z=""){return new uG(this._graph,Z)}createSkin(Z=""){return new ED(this._graph,Z)}createMesh(Z=""){return new CD(this._graph,Z)}createPrimitive(){return new HX(this._graph)}createPrimitiveTarget(Z=""){return new $i(this._graph,Z)}createMaterial(Z=""){return new cG(this._graph,Z)}createTexture(Z=""){return new ID(this._graph,Z)}createAnimation(Z=""){return new DD(this._graph,Z)}createAnimationChannel(Z=""){return new dG(this._graph,Z)}createAnimationSampler(Z=""){return new yW(this._graph,Z)}createAccessor(Z="",J=null){if(!J)J=this.getRoot().listBuffers()[0];return new k0(this._graph,Z).setBuffer(J)}createBuffer(Z=""){return new PD(this._graph,Z)}}LU._GRAPH_DOCUMENTS=new WeakMap;class P5{constructor(Z){this.extensionName="",this.prereadTypes=[],this.prewriteTypes=[],this.readDependencies=[],this.writeDependencies=[],this.document=void 0,this.required=!1,this.properties=new Set,this._listener=void 0,this.document=Z,Z.getRoot()._enableExtension(this),this._listener=(X)=>{let $=X,Y=$.target;if(Y instanceof c5&&Y.extensionName===this.extensionName){if($.type==="node:create")this._addExtensionProperty(Y);if($.type==="node:dispose")this._removeExtensionProperty(Y)}};let J=Z.getGraph();J.addEventListener("node:create",this._listener),J.addEventListener("node:dispose",this._listener)}dispose(){this.document.getRoot()._disableExtension(this);let Z=this.document.getGraph();Z.removeEventListener("node:create",this._listener),Z.removeEventListener("node:dispose",this._listener);for(let J of this.properties)J.dispose()}static register(){}isRequired(){return this.required}setRequired(Z){return this.required=Z,this}listProperties(){return Array.from(this.properties)}_addExtensionProperty(Z){return this.properties.add(Z),this}_removeExtensionProperty(Z){return this.properties.delete(Z),this}install(Z,J){return this}preread(Z,J){return this}prewrite(Z,J){return this}}P5.EXTENSION_NAME=void 0;var jV6={logger:eZ.DEFAULT_INSTANCE,extensions:[],dependencies:{}},MV6=new Set([s.BUFFER,s.TEXTURE,s.MATERIAL,s.MESH,s.PRIMITIVE,s.NODE,s.SCENE]);var mG;(function(Z){Z[Z.ARRAY_BUFFER=34962]="ARRAY_BUFFER",Z[Z.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"})(mG||(mG={}));class qX{constructor(Z,J,X){this._doc=void 0,this.jsonDoc=void 0,this.options=void 0,this.accessorIndexMap=new Map,this.animationIndexMap=new Map,this.bufferIndexMap=new Map,this.cameraIndexMap=new Map,this.skinIndexMap=new Map,this.materialIndexMap=new Map,this.meshIndexMap=new Map,this.nodeIndexMap=new Map,this.imageIndexMap=new Map,this.textureDefIndexMap=new Map,this.textureInfoDefMap=new Map,this.samplerDefIndexMap=new Map,this.sceneIndexMap=new Map,this.imageBufferViews=[],this.otherBufferViews=new Map,this.otherBufferViewsIndexMap=new Map,this.extensionData={},this.bufferURIGenerator=void 0,this.imageURIGenerator=void 0,this.logger=void 0,this._accessorUsageMap=new Map,this.accessorUsageGroupedByParent=new Set(["ARRAY_BUFFER"]),this.accessorParents=new Map,this._doc=Z,this.jsonDoc=J,this.options=X;let $=Z.getRoot(),Y=$.listBuffers().length,Q=$.listTextures().length;this.bufferURIGenerator=new jD(Y>1,()=>X.basename||"buffer"),this.imageURIGenerator=new jD(Q>1,(W)=>eF5(Z,W)||X.basename||"texture"),this.logger=Z.getLogger()}createTextureInfoDef(Z,J){let X={magFilter:J.getMagFilter()||void 0,minFilter:J.getMinFilter()||void 0,wrapS:J.getWrapS(),wrapT:J.getWrapT()},$=JSON.stringify(X);if(!this.samplerDefIndexMap.has($))this.samplerDefIndexMap.set($,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(X);let Y={source:this.imageIndexMap.get(Z),sampler:this.samplerDefIndexMap.get($)},Q=JSON.stringify(Y);if(!this.textureDefIndexMap.has(Q))this.textureDefIndexMap.set(Q,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push(Y);let W={index:this.textureDefIndexMap.get(Q)};if(J.getTexCoord()!==0)W.texCoord=J.getTexCoord();if(Object.keys(J.getExtras()).length>0)W.extras=J.getExtras();return this.textureInfoDefMap.set(J,W),W}createPropertyDef(Z){let J={};if(Z.getName())J.name=Z.getName();if(Object.keys(Z.getExtras()).length>0)J.extras=Z.getExtras();return J}createAccessorDef(Z){let J=this.createPropertyDef(Z);if(J.type=Z.getType(),J.componentType=Z.getComponentType(),J.count=Z.getCount(),this._doc.getGraph().listParentEdges(Z).some(($)=>$.getName()==="attributes"&&$.getAttributes().key==="POSITION"||$.getName()==="input"))J.max=Z.getMax([]).map(Math.fround),J.min=Z.getMin([]).map(Math.fround);if(Z.getNormalized())J.normalized=Z.getNormalized();return J}createImageData(Z,J,X){if(this.options.format===BD.GLB)this.imageBufferViews.push(J),Z.bufferView=this.jsonDoc.json.bufferViews.length,this.jsonDoc.json.bufferViews.push({buffer:0,byteOffset:-1,byteLength:J.byteLength});else{let $=GZ.mimeTypeToExtension(X.getMimeType());Z.uri=this.imageURIGenerator.createURI(X,$),this.assignResourceURI(Z.uri,J,!1)}}assignResourceURI(Z,J,X){let $=this.jsonDoc.resources;if(!(Z in $)){$[Z]=J;return}if(J===$[Z]){this.logger.warn(`Duplicate resource URI, "${Z}".`);return}let Y=`Resource URI "${Z}" already assigned to different data.`;if(!X){this.logger.warn(Y);return}throw new Error(Y)}getAccessorUsage(Z){let J=this._accessorUsageMap.get(Z);if(J)return J;if(Z.getSparse())return _7.SPARSE;for(let X of this._doc.getGraph().listParentEdges(Z)){let{usage:$}=X.getAttributes();if($)return $;if(X.getParent().propertyType!==s.ROOT)this.logger.warn(`Missing attribute ".usage" on edge, "${X.getName()}".`)}return _7.OTHER}addAccessorToUsageGroup(Z,J){let X=this._accessorUsageMap.get(Z);if(X&&X!==J)throw new Error(`Accessor with usage "${X}" cannot be reused as "${J}".`);return this._accessorUsageMap.set(Z,J),this}}qX.BufferViewTarget=mG;qX.BufferViewUsage=_7;qX.USAGE_TO_TARGET={[_7.ARRAY_BUFFER]:mG.ARRAY_BUFFER,[_7.ELEMENT_ARRAY_BUFFER]:mG.ELEMENT_ARRAY_BUFFER};class jD{constructor(Z,J){this.multiple=void 0,this.basename=void 0,this.counter={},this.multiple=Z,this.basename=J}createURI(Z,J){if(Z.getURI())return Z.getURI();else if(!this.multiple)return`${this.basename(Z)}.${J}`;else{let X=this.basename(Z);return this.counter[X]=this.counter[X]||1,`${X}_${this.counter[X]++}.${J}`}}}function eF5(Z,J){let X=Z.getGraph().listParentEdges(J).find(($)=>$.getParent()!==Z.getRoot());return X?X.getName().replace(/texture$/i,""):""}var{UNSIGNED_INT:RV6,UNSIGNED_SHORT:DV6,UNSIGNED_BYTE:PV6}=k0.ComponentType,CV6=new Set([s.ACCESSOR,s.BUFFER,s.MATERIAL,s.MESH]);var op;(function(Z){Z[Z.JSON=1313821514]="JSON",Z[Z.BIN=5130562]="BIN"})(op||(op={}));var Qi=163,Wi=166;function ZU5(){return{vkFormat:0,typeSize:1,pixelWidth:0,pixelHeight:0,pixelDepth:0,layerCount:0,faceCount:1,supercompressionScheme:0,levels:[],dataFormatDescriptor:[{vendorId:0,descriptorType:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],keyValue:{},globalData:null}}class gW{constructor(Z,J,X,$){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(Z.buffer,Z.byteOffset+J,X),this._littleEndian=$,this._offset=0}_nextUint8(){let Z=this._dataView.getUint8(this._offset);return this._offset+=1,Z}_nextUint16(){let Z=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,Z}_nextUint32(){let Z=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,Z}_nextUint64(){let Z=this._dataView.getUint32(this._offset,this._littleEndian),J=this._dataView.getUint32(this._offset+4,this._littleEndian),X=Z+4294967296*J;return this._offset+=8,X}_nextInt32(){let Z=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,Z}_nextUint8Array(Z){let J=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,Z);return this._offset+=Z,J}_skip(Z){return this._offset+=Z,this}_scan(Z,J=0){let X=this._offset,$=0;while(this._dataView.getUint8(this._offset)!==J&&$<Z)$++,this._offset++;if($<Z)this._offset++;return new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+X,$)}}var EV6=new Uint8Array([0]),b6=[171,75,84,88,32,50,48,187,13,10,26,10];function Yi(Z){return new TextDecoder().decode(Z)}function jU(Z){let J=new Uint8Array(Z.buffer,Z.byteOffset,b6.length);if(J[0]!==b6[0]||J[1]!==b6[1]||J[2]!==b6[2]||J[3]!==b6[3]||J[4]!==b6[4]||J[5]!==b6[5]||J[6]!==b6[6]||J[7]!==b6[7]||J[8]!==b6[8]||J[9]!==b6[9]||J[10]!==b6[10]||J[11]!==b6[11])throw new Error("Missing KTX 2.0 identifier.");let X=ZU5(),$=17*Uint32Array.BYTES_PER_ELEMENT,Y=new gW(Z,b6.length,$,!0);X.vkFormat=Y._nextUint32(),X.typeSize=Y._nextUint32(),X.pixelWidth=Y._nextUint32(),X.pixelHeight=Y._nextUint32(),X.pixelDepth=Y._nextUint32(),X.layerCount=Y._nextUint32(),X.faceCount=Y._nextUint32();let Q=Y._nextUint32();X.supercompressionScheme=Y._nextUint32();let W=Y._nextUint32(),K=Y._nextUint32(),G=Y._nextUint32(),V=Y._nextUint32(),H=Y._nextUint64(),q=Y._nextUint64(),z=Q*3*8,F=new gW(Z,b6.length+$,z,!0);for(let t8=0;t8<Q;t8++)X.levels.push({levelData:new Uint8Array(Z.buffer,Z.byteOffset+F._nextUint64(),F._nextUint64()),uncompressedByteLength:F._nextUint64()});let U=new gW(Z,W,K,!0);U._skip(4);let L=U._nextUint16(),B=U._nextUint16(),w=U._nextUint16(),O=U._nextUint16(),M=U._nextUint8(),N=U._nextUint8(),P=U._nextUint8(),D=U._nextUint8(),C=[U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8()],T=[U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8()],A={vendorId:L,descriptorType:B,versionNumber:w,colorModel:M,colorPrimaries:N,transferFunction:P,flags:D,texelBlockDimension:C,bytesPlane:T,samples:[]},v=6,x=4,I=(O/4-v)/x;for(let t8=0;t8<I;t8++){let _J={bitOffset:U._nextUint16(),bitLength:U._nextUint8(),channelType:U._nextUint8(),samplePosition:[U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8()],sampleLower:Number.NEGATIVE_INFINITY,sampleUpper:Number.POSITIVE_INFINITY};if(_J.channelType&64)_J.sampleLower=U._nextInt32(),_J.sampleUpper=U._nextInt32();else _J.sampleLower=U._nextUint32(),_J.sampleUpper=U._nextUint32();A.samples[t8]=_J}X.dataFormatDescriptor.length=0,X.dataFormatDescriptor.push(A);let S=new gW(Z,G,V,!0);while(S._offset<V){let t8=S._nextUint32(),_J=S._scan(t8),Oz=Yi(_J);if(X.keyValue[Oz]=S._nextUint8Array(t8-_J.byteLength-1),Oz.match(/^ktx/i)){let _f=Yi(X.keyValue[Oz]);X.keyValue[Oz]=_f.substring(0,_f.lastIndexOf("\x00"))}let X15=t8%4?4-t8%4:0;S._skip(X15)}if(q<=0)return X;let g=new gW(Z,H,q,!0),m=g._nextUint16(),i=g._nextUint16(),r=g._nextUint32(),Q0=g._nextUint32(),F0=g._nextUint32(),_0=g._nextUint32(),A0=[];for(let t8=0;t8<Q;t8++)A0.push({imageFlags:g._nextUint32(),rgbSliceByteOffset:g._nextUint32(),rgbSliceByteLength:g._nextUint32(),alphaSliceByteOffset:g._nextUint32(),alphaSliceByteLength:g._nextUint32()});let o0=H+g._offset,T8=o0+r,n5=T8+Q0,hZ=n5+F0,a9=new Uint8Array(Z.buffer,Z.byteOffset+o0,r),oQ=new Uint8Array(Z.buffer,Z.byteOffset+T8,Q0),tQ=new Uint8Array(Z.buffer,Z.byteOffset+n5,F0),x$=new Uint8Array(Z.buffer,Z.byteOffset+hZ,_0);return X.globalData={endpointCount:m,selectorCount:i,imageDescs:A0,endpointsData:a9,selectorsData:oQ,tablesData:tQ,extendedData:x$},X}var xD="EXT_mesh_gpu_instancing",SD="EXT_meshopt_compression",JU5="EXT_texture_webp",XU5="EXT_texture_avif",ji="KHR_draco_mesh_compression",fD="KHR_lights_punctual",hD="KHR_materials_anisotropy",bD="KHR_materials_clearcoat",yD="KHR_materials_diffuse_transmission",gD="KHR_materials_dispersion",mD="KHR_materials_emissive_strength",dD="KHR_materials_ior",uD="KHR_materials_iridescence",cD="KHR_materials_pbrSpecularGlossiness",lD="KHR_materials_sheen",pD="KHR_materials_specular",iD="KHR_materials_transmission",nD="KHR_materials_unlit",sD="KHR_materials_volume",NY="KHR_materials_variants",$U5="KHR_mesh_quantization",YU5="KHR_texture_basisu",aD="KHR_texture_transform",MU="KHR_xmp_json_ld",_D="INSTANCE_ATTRIBUTE";class rD extends c5{init(){this.extensionName=xD,this.propertyType="InstancedMesh",this.parentTypes=[s.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new a5})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:_D})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}rD.EXTENSION_NAME=xD;var QY=xD;class PU extends P5{constructor(...Z){super(...Z);this.extensionName=QY,this.provideTypes=[s.NODE],this.prewriteTypes=[s.ACCESSOR]}createInstancedMesh(){return new rD(this.document.getGraph())}read(Z){return(Z.jsonDoc.json.nodes||[]).forEach(($,Y)=>{if(!$.extensions||!$.extensions[QY])return;let Q=$.extensions[QY],W=this.createInstancedMesh();for(let K in Q.attributes)W.setAttribute(K,Z.accessors[Q.attributes[K]]);Z.nodes[Y].setExtension(QY,W)}),this}prewrite(Z){Z.accessorUsageGroupedByParent.add(_D);for(let J of this.properties)for(let X of J.listAttributes())Z.addAccessorToUsageGroup(X,_D);return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listNodes().forEach((X)=>{let $=X.getExtension(QY);if($){let Y=Z.nodeIndexMap.get(X),Q=J.json.nodes[Y],W={attributes:{}};$.listSemantics().forEach((K)=>{let G=$.getAttribute(K);W.attributes[K]=Z.accessorIndexMap.get(G)}),Q.extensions=Q.extensions||{},Q.extensions[QY]=W}}),this}}PU.EXTENSION_NAME=QY;function oJ(){return oJ=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)({}).hasOwnProperty.call(X,$)&&(Z[$]=X[$])}return Z},oJ.apply(null,arguments)}var nG;(function(Z){Z.QUANTIZE="quantize",Z.FILTER="filter"})(nG||(nG={}));var dW;(function(Z){Z.ATTRIBUTES="ATTRIBUTES",Z.TRIANGLES="TRIANGLES",Z.INDICES="INDICES"})(dW||(dW={}));var Y8;(function(Z){Z.NONE="NONE",Z.OCTAHEDRAL="OCTAHEDRAL",Z.QUATERNION="QUATERNION",Z.EXPONENTIAL="EXPONENTIAL"})(Y8||(Y8={}));var{BYTE:QU5,SHORT:Ki,FLOAT:WU5}=k0.ComponentType,{encodeNormalizedInt:Gi,decodeNormalizedInt:AD}=$8;function KU5(Z,J,X,$){let{filter:Y,bits:Q}=$,W={array:Z.getArray(),byteStride:Z.getElementSize()*Z.getComponentSize(),componentType:Z.getComponentType(),normalized:Z.getNormalized()};if(X!==dW.ATTRIBUTES)return W;if(Y!==Y8.NONE){let K=Z.getNormalized()?GU5(Z):new Float32Array(W.array);switch(Y){case Y8.EXPONENTIAL:W.byteStride=Z.getElementSize()*4,W.componentType=WU5,W.normalized=!1,W.array=J.encodeFilterExp(K,Z.getCount(),W.byteStride,Q);break;case Y8.OCTAHEDRAL:W.byteStride=Q>8?8:4,W.componentType=Q>8?Ki:QU5,W.normalized=!0,K=Z.getElementSize()===3?HU5(K):K,W.array=J.encodeFilterOct(K,Z.getCount(),W.byteStride,Q);break;case Y8.QUATERNION:W.byteStride=8,W.componentType=Ki,W.normalized=!0,W.array=J.encodeFilterQuat(K,Z.getCount(),W.byteStride,Q);break;default:throw new Error("Invalid filter.")}if(W.min=Z.getMin([]),W.max=Z.getMax([]),Z.getNormalized())W.min=W.min.map((G)=>AD(G,Z.getComponentType())),W.max=W.max.map((G)=>AD(G,Z.getComponentType()));if(W.normalized)W.min=W.min.map((G)=>Gi(G,W.componentType)),W.max=W.max.map((G)=>Gi(G,W.componentType))}else if(W.byteStride%4)W.array=VU5(W.array,Z.getElementSize()),W.byteStride=W.array.byteLength/Z.getCount();return W}function GU5(Z){let J=Z.getComponentType(),X=Z.getArray(),$=new Float32Array(X.length);for(let Y=0;Y<X.length;Y++)$[Y]=AD(X[Y],J);return $}function VU5(Z,J){let $=B6.padNumber(Z.BYTES_PER_ELEMENT*J)/Z.BYTES_PER_ELEMENT,Y=Z.length/J,Q=new Z.constructor(Y*$);for(let W=0;W*J<Z.length;W++)for(let K=0;K<J;K++)Q[W*$+K]=Z[W*J+K];return Q}function HU5(Z){let J=new Float32Array(Z.length*4/3);for(let X=0,$=Z.length/3;X<$;X++)J[X*4]=Z[X*3],J[X*4+1]=Z[X*3+1],J[X*4+2]=Z[X*3+2];return J}function qU5(Z,J){if(J===qX.BufferViewUsage.ELEMENT_ARRAY_BUFFER)return Z.listParents().some(($)=>{return $ instanceof HX&&$.getMode()===HX.Mode.TRIANGLES})?dW.TRIANGLES:dW.INDICES;return dW.ATTRIBUTES}function zU5(Z,J){let X=J.getGraph().listParentEdges(Z).filter(($)=>!($.getParent()instanceof NU));for(let $ of X){let Y=$.getName(),Q=$.getAttributes().key||"",W=$.getParent().propertyType===s.PRIMITIVE_TARGET;if(Y==="indices")return{filter:Y8.NONE};if(Y==="attributes"){if(Q==="POSITION")return{filter:Y8.NONE};if(Q==="TEXCOORD_0")return{filter:Y8.NONE};if(Q.startsWith("JOINTS_"))return{filter:Y8.NONE};if(Q.startsWith("WEIGHTS_"))return{filter:Y8.NONE};if(Q==="NORMAL"||Q==="TANGENT")return W?{filter:Y8.NONE}:{filter:Y8.OCTAHEDRAL,bits:8}}if(Y==="output"){let K=Mi(Z);if(K==="rotation")return{filter:Y8.QUATERNION,bits:16};if(K==="translation")return{filter:Y8.EXPONENTIAL,bits:12};if(K==="scale")return{filter:Y8.EXPONENTIAL,bits:12};return{filter:Y8.NONE}}if(Y==="input")return{filter:Y8.NONE};if(Y==="inverseBindMatrices")return{filter:Y8.NONE}}return{filter:Y8.NONE}}function Mi(Z){for(let J of Z.listParents()){if(!(J instanceof yW))continue;for(let X of J.listParents()){if(!(X instanceof dG))continue;return X.getTargetPath()}}return null}function FU5(Z){if(!Z.extensions||!Z.extensions[SD])return!1;return!!Z.extensions[SD].fallback}var y6=SD,Vi={method:nG.QUANTIZE};class aG extends P5{constructor(...Z){super(...Z);this.extensionName=y6,this.prereadTypes=[s.BUFFER,s.PRIMITIVE],this.prewriteTypes=[s.BUFFER,s.ACCESSOR],this.readDependencies=["meshopt.decoder"],this.writeDependencies=["meshopt.encoder"],this._decoder=null,this._decoderFallbackBufferMap=new Map,this._encoder=null,this._encoderOptions=Vi,this._encoderFallbackBuffer=null,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={}}install(Z,J){if(Z==="meshopt.decoder")this._decoder=J;if(Z==="meshopt.encoder")this._encoder=J;return this}setEncoderOptions(Z){return this._encoderOptions=oJ({},Vi,Z),this}preread(Z,J){if(!this._decoder){if(!this.isRequired())return this;throw new Error(`[${y6}] Please install extension dependency, "meshopt.decoder".`)}if(!this._decoder.supported){if(!this.isRequired())return this;throw new Error(`[${y6}]: Missing WASM support.`)}if(J===s.BUFFER)this._prereadBuffers(Z);else if(J===s.PRIMITIVE)this._prereadPrimitives(Z);return this}_prereadBuffers(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach(($,Y)=>{if(!$.extensions||!$.extensions[y6])return;let Q=$.extensions[y6],W=Q.byteOffset||0,K=Q.byteLength||0,G=Q.count,V=Q.byteStride,H=new Uint8Array(G*V),q=J.json.buffers[Q.buffer],z=q.uri?J.resources[q.uri]:J.resources[MD],F=B6.toView(z,W,K);this._decoder.decodeGltfBuffer(H,G,V,F,Q.mode,Q.filter),Z.bufferViews[Y]=H})}_prereadPrimitives(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach(($)=>{if(!$.extensions||!$.extensions[y6])return;let Y=$.extensions[y6],Q=Z.buffers[Y.buffer],W=Z.buffers[$.buffer],K=J.json.buffers[$.buffer];if(FU5(K))this._decoderFallbackBufferMap.set(W,Q)})}read(Z){if(!this.isRequired())return this;for(let[J,X]of this._decoderFallbackBufferMap){for(let $ of J.listParents())if($ instanceof k0)$.swap(J,X);J.dispose()}return this}prewrite(Z,J){if(J===s.ACCESSOR)this._prewriteAccessors(Z);else if(J===s.BUFFER)this._prewriteBuffers(Z);return this}_prewriteAccessors(Z){let J=Z.jsonDoc.json,X=this._encoder,$=this._encoderOptions,Y=this.document.getGraph(),Q=this.document.createBuffer(),W=this.document.getRoot().listBuffers().indexOf(Q),K=1,G=new Map,V=(H)=>{for(let q of Y.listParents(H)){if(q.propertyType===s.ROOT)continue;let z=G.get(H);if(z===void 0)G.set(H,z=K++);return z}return-1};this._encoderFallbackBuffer=Q,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={};for(let H of this.document.getRoot().listAccessors()){if(Mi(H)==="weights")continue;if(H.getSparse())continue;let q=Z.getAccessorUsage(H),z=Z.accessorUsageGroupedByParent.has(q)?V(H):null,F=qU5(H,q),U=$.method===nG.FILTER?zU5(H,this.document):{filter:Y8.NONE},L=KU5(H,X,F,U),{array:B,byteStride:w}=L,O=H.getBuffer();if(!O)throw new Error(`${y6}: Missing buffer for accessor.`);let M=this.document.getRoot().listBuffers().indexOf(O),N=[q,z,F,U.filter,w,M].join(":"),P=this._encoderBufferViews[N],D=this._encoderBufferViewData[N],C=this._encoderBufferViewAccessors[N];if(!P||!D)C=this._encoderBufferViewAccessors[N]=[],D=this._encoderBufferViewData[N]=[],P=this._encoderBufferViews[N]={buffer:W,target:qX.USAGE_TO_TARGET[q],byteOffset:0,byteLength:0,byteStride:q===qX.BufferViewUsage.ARRAY_BUFFER?w:void 0,extensions:{[y6]:{buffer:M,byteOffset:0,byteLength:0,mode:F,filter:U.filter!==Y8.NONE?U.filter:void 0,byteStride:w,count:0}}};let T=Z.createAccessorDef(H);if(T.componentType=L.componentType,T.normalized=L.normalized,T.byteOffset=P.byteLength,T.min&&L.min)T.min=L.min;if(T.max&&L.max)T.max=L.max;Z.accessorIndexMap.set(H,J.accessors.length),J.accessors.push(T),C.push(T),D.push(new Uint8Array(B.buffer,B.byteOffset,B.byteLength)),P.byteLength+=B.byteLength,P.extensions.EXT_meshopt_compression.count+=H.getCount()}}_prewriteBuffers(Z){let J=this._encoder;for(let X in this._encoderBufferViews){let $=this._encoderBufferViews[X],Y=this._encoderBufferViewData[X],Q=this.document.getRoot().listBuffers()[$.extensions[y6].buffer],W=Z.otherBufferViews.get(Q)||[],{count:K,byteStride:G,mode:V}=$.extensions[y6],H=B6.concat(Y),q=J.encodeGltfBuffer(H,K,G,V),z=B6.pad(q);$.extensions[y6].byteLength=q.byteLength,Y.length=0,Y.push(z),W.push(z),Z.otherBufferViews.set(Q,W)}}write(Z){let J=0;for(let Q in this._encoderBufferViews){let W=this._encoderBufferViews[Q],K=this._encoderBufferViewData[Q][0],G=Z.otherBufferViewsIndexMap.get(K),V=this._encoderBufferViewAccessors[Q];for(let F of V)F.bufferView=G;let H=Z.jsonDoc.json.bufferViews[G],q=H.byteOffset||0;Object.assign(H,W),H.byteOffset=J;let z=H.extensions[y6];z.byteOffset=q,J+=B6.padNumber(W.byteLength)}let X=this._encoderFallbackBuffer,$=Z.bufferIndexMap.get(X),Y=Z.jsonDoc.json.buffers[$];return Y.byteLength=J,Y.extensions={[y6]:{fallback:!0}},X.dispose(),this}}aG.EXTENSION_NAME=y6;aG.EncoderMethod=nG;var lG=XU5;class Ri{match(Z){return Z.length>=12&&B6.decodeText(Z.slice(4,12))==="ftypavif"}getSize(Z){if(!this.match(Z))return null;let J=new DataView(Z.buffer,Z.byteOffset,Z.byteLength),X=Hi(J,0);if(!X)return null;let $=X.end;while(X=Hi(J,$))if(X.type==="meta")$=X.start+4;else if(X.type==="iprp"||X.type==="ipco")$=X.start;else if(X.type==="ispe")return[J.getUint32(X.start+4),J.getUint32(X.start+8)];else if(X.type==="mdat")break;else $=X.end;return null}getChannels(Z){return 4}}class CU extends P5{constructor(...Z){super(...Z);this.extensionName=lG,this.prereadTypes=[s.TEXTURE]}static register(){GZ.registerFormat("image/avif",new Ri)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[lG])X.source=X.extensions[lG].source}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/avif"){let $=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===$)Q.extensions=Q.extensions||{},Q.extensions[lG]={source:Q.source},delete Q.source})}}),this}}CU.EXTENSION_NAME=lG;function Hi(Z,J){if(Z.byteLength<4+J)return null;let X=Z.getUint32(J);if(Z.byteLength<X+J||X<8)return null;return{type:B6.decodeText(new Uint8Array(Z.buffer,Z.byteOffset+J+4,4)),start:J+8,end:J+X}}var pG=JU5;class Di{match(Z){return Z.length>=12&&Z[8]===87&&Z[9]===69&&Z[10]===66&&Z[11]===80}getSize(Z){let J=B6.decodeText(Z.slice(0,4)),X=B6.decodeText(Z.slice(8,12));if(J!=="RIFF"||X!=="WEBP")return null;let $=new DataView(Z.buffer,Z.byteOffset),Y=12;while(Y<$.byteLength){let Q=B6.decodeText(new Uint8Array([$.getUint8(Y),$.getUint8(Y+1),$.getUint8(Y+2),$.getUint8(Y+3)])),W=$.getUint32(Y+4,!0);if(Q==="VP8 "){let K=$.getInt16(Y+14,!0)&16383,G=$.getInt16(Y+16,!0)&16383;return[K,G]}else if(Q==="VP8L"){let K=$.getUint8(Y+9),G=$.getUint8(Y+10),V=$.getUint8(Y+11),H=$.getUint8(Y+12),q=1+((G&63)<<8|K),z=1+((H&15)<<10|V<<2|(G&192)>>6);return[q,z]}Y+=8+W+W%2}return null}getChannels(Z){return 4}}class TU extends P5{constructor(...Z){super(...Z);this.extensionName=pG,this.prereadTypes=[s.TEXTURE]}static register(){GZ.registerFormat("image/webp",new Di)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[pG])X.source=X.extensions[pG].source}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/webp"){let $=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===$)Q.extensions=Q.extensions||{},Q.extensions[pG]={source:Q.source},delete Q.source})}}),this}}TU.EXTENSION_NAME=pG;var qi=ji,f8,Pi,Ci;function UU5(Z,J){let X=new f8.DecoderBuffer;try{if(X.Init(J,J.length),Z.GetEncodedGeometryType(X)!==f8.TRIANGULAR_MESH)throw new Error(`[${qi}] Unknown geometry type.`);let Y=new f8.Mesh;if(!Z.DecodeBufferToMesh(X,Y).ok()||Y.ptr===0)throw new Error(`[${qi}] Decoding failure.`);return Y}finally{f8.destroy(X)}}function BU5(Z,J){let $=J.num_faces()*3,Y,Q;if(J.num_points()<=65534){let W=$*Uint16Array.BYTES_PER_ELEMENT;Y=f8._malloc(W),Z.GetTrianglesUInt16Array(J,W,Y),Q=new Uint16Array(f8.HEAPU16.buffer,Y,$).slice()}else{let W=$*Uint32Array.BYTES_PER_ELEMENT;Y=f8._malloc(W),Z.GetTrianglesUInt32Array(J,W,Y),Q=new Uint32Array(f8.HEAPU32.buffer,Y,$).slice()}return f8._free(Y),Q}function LU5(Z,J,X,$){let Y=Ci[$.componentType],Q=Pi[$.componentType],W=X.num_components(),G=J.num_points()*W,V=G*Q.BYTES_PER_ELEMENT,H=f8._malloc(V);Z.GetAttributeDataArrayForAllPoints(J,X,Y,V,H);let q=new Q(f8.HEAPF32.buffer,H,G).slice();return f8._free(H),q}function wU5(Z){f8=Z,Pi={[k0.ComponentType.FLOAT]:Float32Array,[k0.ComponentType.UNSIGNED_INT]:Uint32Array,[k0.ComponentType.UNSIGNED_SHORT]:Uint16Array,[k0.ComponentType.UNSIGNED_BYTE]:Uint8Array,[k0.ComponentType.SHORT]:Int16Array,[k0.ComponentType.BYTE]:Int8Array},Ci={[k0.ComponentType.FLOAT]:f8.DT_FLOAT32,[k0.ComponentType.UNSIGNED_INT]:f8.DT_UINT32,[k0.ComponentType.UNSIGNED_SHORT]:f8.DT_UINT16,[k0.ComponentType.UNSIGNED_BYTE]:f8.DT_UINT8,[k0.ComponentType.SHORT]:f8.DT_INT16,[k0.ComponentType.BYTE]:f8.DT_INT8}}var z9,sG;(function(Z){Z[Z.EDGEBREAKER=1]="EDGEBREAKER",Z[Z.SEQUENTIAL=0]="SEQUENTIAL"})(sG||(sG={}));var F9;(function(Z){Z.POSITION="POSITION",Z.NORMAL="NORMAL",Z.COLOR="COLOR",Z.TEX_COORD="TEX_COORD",Z.GENERIC="GENERIC"})(F9||(F9={}));var Ti={[F9.POSITION]:14,[F9.NORMAL]:10,[F9.COLOR]:8,[F9.TEX_COORD]:12,[F9.GENERIC]:12},zi={decodeSpeed:5,encodeSpeed:5,method:sG.EDGEBREAKER,quantizationBits:Ti,quantizationVolume:"mesh"};function OU5(Z){z9=Z}function NU5(Z,J=zi){let X=oJ({},zi,J);X.quantizationBits=oJ({},Ti,J.quantizationBits);let $=new z9.MeshBuilder,Y=new z9.Mesh,Q=new z9.ExpertEncoder(Y),W={},K=new z9.DracoInt8Array,G=Z.listTargets().length>0,V=!1;for(let L of Z.listSemantics()){let B=Z.getAttribute(L);if(B.getSparse()){V=!0;continue}let w=jU5(L),O=MU5($,B.getComponentType(),Y,z9[w],B.getCount(),B.getElementSize(),B.getArray());if(O===-1)throw new Error(`Error compressing "${L}" attribute.`);if(W[L]=O,X.quantizationVolume==="mesh"||L!=="POSITION")Q.SetAttributeQuantization(O,X.quantizationBits[w]);else if(typeof X.quantizationVolume==="object"){let{quantizationVolume:M}=X,N=Math.max(M.max[0]-M.min[0],M.max[1]-M.min[1],M.max[2]-M.min[2]);Q.SetAttributeExplicitQuantization(O,X.quantizationBits[w],B.getElementSize(),M.min,N)}else throw new Error("Invalid quantization volume state.")}let H=Z.getIndices();if(!H)throw new RU("Primitive must have indices.");if($.AddFacesToMesh(Y,H.getCount()/3,H.getArray()),Q.SetSpeedOptions(X.encodeSpeed,X.decodeSpeed),Q.SetTrackEncodedProperties(!0),X.method===sG.SEQUENTIAL||G||V)Q.SetEncodingMethod(z9.MESH_SEQUENTIAL_ENCODING);else Q.SetEncodingMethod(z9.MESH_EDGEBREAKER_ENCODING);let q=Q.EncodeToDracoBuffer(!(G||V),K);if(q<=0)throw new RU("Error applying Draco compression.");let z=new Uint8Array(q);for(let L=0;L<q;++L)z[L]=K.GetValue(L);let F=Q.GetNumberOfEncodedPoints(),U=Q.GetNumberOfEncodedFaces()*3;return z9.destroy(K),z9.destroy(Y),z9.destroy($),z9.destroy(Q),{numVertices:F,numIndices:U,data:z,attributeIDs:W}}function jU5(Z){if(Z==="POSITION")return F9.POSITION;else if(Z==="NORMAL")return F9.NORMAL;else if(Z.startsWith("COLOR_"))return F9.COLOR;else if(Z.startsWith("TEXCOORD_"))return F9.TEX_COORD;return F9.GENERIC}function MU5(Z,J,X,$,Y,Q,W){switch(J){case k0.ComponentType.UNSIGNED_BYTE:return Z.AddUInt8Attribute(X,$,Y,Q,W);case k0.ComponentType.BYTE:return Z.AddInt8Attribute(X,$,Y,Q,W);case k0.ComponentType.UNSIGNED_SHORT:return Z.AddUInt16Attribute(X,$,Y,Q,W);case k0.ComponentType.SHORT:return Z.AddInt16Attribute(X,$,Y,Q,W);case k0.ComponentType.UNSIGNED_INT:return Z.AddUInt32Attribute(X,$,Y,Q,W);case k0.ComponentType.FLOAT:return Z.AddFloatAttribute(X,$,Y,Q,W);default:throw new Error(`Unexpected component type, "${J}".`)}}class RU extends Error{}var j8=ji;class rG extends P5{constructor(...Z){super(...Z);this.extensionName=j8,this.prereadTypes=[s.PRIMITIVE],this.prewriteTypes=[s.ACCESSOR],this.readDependencies=["draco3d.decoder"],this.writeDependencies=["draco3d.encoder"],this._decoderModule=null,this._encoderModule=null,this._encoderOptions={}}install(Z,J){if(Z==="draco3d.decoder")this._decoderModule=J,wU5(this._decoderModule);if(Z==="draco3d.encoder")this._encoderModule=J,OU5(this._encoderModule);return this}setEncoderOptions(Z){return this._encoderOptions=Z,this}preread(Z){if(!this._decoderModule)throw new Error(`[${j8}] Please install extension dependency, "draco3d.decoder".`);let J=this.document.getLogger(),X=Z.jsonDoc,$=new Map;try{let Y=X.json.meshes||[];for(let Q of Y)for(let W of Q.primitives){if(!W.extensions||!W.extensions[j8])continue;let K=W.extensions[j8],[G,V]=$.get(K.bufferView)||[];if(!V||!G){let H=X.json.bufferViews[K.bufferView],q=X.json.buffers[H.buffer],z=q.uri?X.resources[q.uri]:X.resources[MD],F=H.byteOffset||0,U=H.byteLength,L=B6.toView(z,F,U);G=new this._decoderModule.Decoder,V=UU5(G,L),$.set(K.bufferView,[G,V]),J.debug(`[${j8}] Decompressed ${L.byteLength} bytes.`)}for(let H in K.attributes){let q=Z.jsonDoc.json.accessors[W.attributes[H]],z=G.GetAttributeByUniqueId(V,K.attributes[H]),F=LU5(G,V,z,q);Z.accessors[W.attributes[H]].setArray(F)}if(W.indices!==void 0)Z.accessors[W.indices].setArray(BU5(G,V))}}finally{for(let[Y,Q]of Array.from($.values()))this._decoderModule.destroy(Y),this._decoderModule.destroy(Q)}return this}read(Z){return this}prewrite(Z,J){if(!this._encoderModule)throw new Error(`[${j8}] Please install extension dependency, "draco3d.encoder".`);let X=this.document.getLogger();X.debug(`[${j8}] Compression options: ${JSON.stringify(this._encoderOptions)}`);let $=RU5(this.document),Y=new Map,Q="mesh";if(this._encoderOptions.quantizationVolume==="scene")if(this.document.getRoot().listScenes().length!==1)X.warn(`[${j8}]: quantizationVolume=scene requires exactly 1 scene.`);else Q=tp(this.document.getRoot().listScenes().pop());for(let W of Array.from($.keys())){let K=$.get(W);if(!K)throw new Error("Unexpected primitive.");if(Y.has(K)){Y.set(K,Y.get(K));continue}let G=W.getIndices(),V=Z.jsonDoc.json.accessors,H;try{H=NU5(W,oJ({},this._encoderOptions,{quantizationVolume:Q}))}catch(F){if(F instanceof RU){X.warn(`[${j8}]: ${F.message} Skipping primitive compression.`);continue}throw F}Y.set(K,H);let q=Z.createAccessorDef(G);if(q.count=H.numIndices,Z.accessorIndexMap.set(G,V.length),V.push(q),H.numVertices>65534&&k0.getComponentSize(q.componentType)<=2)q.componentType=k0.ComponentType.UNSIGNED_INT;else if(H.numVertices>254&&k0.getComponentSize(q.componentType)<=1)q.componentType=k0.ComponentType.UNSIGNED_SHORT;for(let F of W.listSemantics()){let U=W.getAttribute(F);if(H.attributeIDs[F]===void 0)continue;let L=Z.createAccessorDef(U);L.count=H.numVertices,Z.accessorIndexMap.set(U,V.length),V.push(L)}let z=W.getAttribute("POSITION").getBuffer()||this.document.getRoot().listBuffers()[0];if(!Z.otherBufferViews.has(z))Z.otherBufferViews.set(z,[]);Z.otherBufferViews.get(z).push(H.data)}return X.debug(`[${j8}] Compressed ${$.size} primitives.`),Z.extensionData[j8]={primitiveHashMap:$,primitiveEncodingMap:Y},this}write(Z){let J=Z.extensionData[j8];for(let X of this.document.getRoot().listMeshes()){let $=Z.jsonDoc.json.meshes[Z.meshIndexMap.get(X)];for(let Y=0;Y<X.listPrimitives().length;Y++){let Q=X.listPrimitives()[Y],W=$.primitives[Y],K=J.primitiveHashMap.get(Q);if(!K)continue;let G=J.primitiveEncodingMap.get(K);if(!G)continue;W.extensions=W.extensions||{},W.extensions[j8]={bufferView:Z.otherBufferViewsIndexMap.get(G.data),attributes:G.attributeIDs}}}if(!J.primitiveHashMap.size){let X=Z.jsonDoc.json;X.extensionsUsed=(X.extensionsUsed||[]).filter(($)=>$!==j8),X.extensionsRequired=(X.extensionsRequired||[]).filter(($)=>$!==j8)}return this}}rG.EXTENSION_NAME=j8;rG.EncoderMethod=sG;function RU5(Z){let J=Z.getLogger(),X=new Set,$=new Set,Y=0,Q=0;for(let q of Z.getRoot().listMeshes())for(let z of q.listPrimitives())if(!z.getIndices())$.add(z),Y++;else if(z.getMode()!==HX.Mode.TRIANGLES)$.add(z),Q++;else X.add(z);if(Y>0)J.warn(`[${j8}] Skipping Draco compression of ${Y} non-indexed primitives.`);if(Q>0)J.warn(`[${j8}] Skipping Draco compression of ${Q} non-TRIANGLES primitives.`);let W=Z.getRoot().listAccessors(),K=new Map;for(let q=0;q<W.length;q++)K.set(W[q],q);let G=new Map,V=new Set,H=new Map;for(let q of Array.from(X)){let z=Fi(q,K);if(V.has(z)){H.set(q,z);continue}if(G.has(q.getIndices())){let F=q.getIndices(),U=F.clone();K.set(U,Z.getRoot().listAccessors().length-1),q.swap(F,U)}for(let F of q.listAttributes())if(G.has(F)){let U=F.clone();K.set(U,Z.getRoot().listAccessors().length-1),q.swap(F,U)}z=Fi(q,K),V.add(z),H.set(q,z),G.set(q.getIndices(),z);for(let F of q.listAttributes())G.set(F,z)}for(let q of Array.from(G.keys())){let z=new Set(q.listParents().map((F)=>F.propertyType));if(z.size!==2||!z.has(s.PRIMITIVE)||!z.has(s.ROOT))throw new Error(`[${j8}] Compressed accessors must only be used as indices or vertex attributes.`)}for(let q of Array.from(X)){let z=H.get(q),F=q.getIndices();if(G.get(F)!==z||q.listAttributes().some((U)=>G.get(U)!==z))throw new Error(`[${j8}] Draco primitives must share all, or no, accessors.`)}for(let q of Array.from($)){let z=q.getIndices();if(G.has(z)||q.listAttributes().some((F)=>G.has(F)))throw new Error(`[${j8}] Accessor cannot be shared by compressed and uncompressed primitives.`)}return H}function Fi(Z,J){let X=[],$=Z.getIndices();X.push(J.get($));for(let Y of Z.listAttributes())X.push(J.get(Y));return X.sort().join("|")}class uW extends c5{init(){this.extensionName=fD,this.propertyType="Light",this.parentTypes=[s.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{color:[1,1,1],intensity:1,type:uW.Type.POINT,range:null,innerConeAngle:0,outerConeAngle:Math.PI/4})}getColor(){return this.get("color")}setColor(Z){return this.set("color",Z)}getIntensity(){return this.get("intensity")}setIntensity(Z){return this.set("intensity",Z)}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getRange(){return this.get("range")}setRange(Z){return this.set("range",Z)}getInnerConeAngle(){return this.get("innerConeAngle")}setInnerConeAngle(Z){return this.set("innerConeAngle",Z)}getOuterConeAngle(){return this.get("outerConeAngle")}setOuterConeAngle(Z){return this.set("outerConeAngle",Z)}}uW.EXTENSION_NAME=fD;uW.Type={POINT:"point",SPOT:"spot",DIRECTIONAL:"directional"};var ZJ=fD;class oD extends P5{constructor(...Z){super(...Z);this.extensionName=ZJ}createLight(Z=""){return new uW(this.document.getGraph(),Z)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[ZJ])return this;let Y=(J.json.extensions[ZJ].lights||[]).map((Q)=>{var W,K;let G=this.createLight().setName(Q.name||"").setType(Q.type);if(Q.color!==void 0)G.setColor(Q.color);if(Q.intensity!==void 0)G.setIntensity(Q.intensity);if(Q.range!==void 0)G.setRange(Q.range);if(((W=Q.spot)==null?void 0:W.innerConeAngle)!==void 0)G.setInnerConeAngle(Q.spot.innerConeAngle);if(((K=Q.spot)==null?void 0:K.outerConeAngle)!==void 0)G.setOuterConeAngle(Q.spot.outerConeAngle);return G});return J.json.nodes.forEach((Q,W)=>{if(!Q.extensions||!Q.extensions[ZJ])return;let K=Q.extensions[ZJ];Z.nodes[W].setExtension(ZJ,Y[K.light])}),this}write(Z){let J=Z.jsonDoc;if(this.properties.size===0)return this;let X=[],$=new Map;for(let Y of this.properties){let Q=Y,W={type:Q.getType()};if(!$8.eq(Q.getColor(),[1,1,1]))W.color=Q.getColor();if(Q.getIntensity()!==1)W.intensity=Q.getIntensity();if(Q.getRange()!=null)W.range=Q.getRange();if(Q.getName())W.name=Q.getName();if(Q.getType()===uW.Type.SPOT)W.spot={innerConeAngle:Q.getInnerConeAngle(),outerConeAngle:Q.getOuterConeAngle()};X.push(W),$.set(Q,X.length-1)}return this.document.getRoot().listNodes().forEach((Y)=>{let Q=Y.getExtension(ZJ);if(Q){let W=Z.nodeIndexMap.get(Y),K=J.json.nodes[W];K.extensions=K.extensions||{},K.extensions[ZJ]={light:$.get(Q)}}}),J.json.extensions=J.json.extensions||{},J.json.extensions[ZJ]={lights:X},this}}oD.EXTENSION_NAME=ZJ;var{R:DU5,G:PU5,B:CU5}=A7;class tD extends c5{init(){this.extensionName=hD,this.propertyType="Anisotropy",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{anisotropyStrength:0,anisotropyRotation:0,anisotropyTexture:null,anisotropyTextureInfo:new R5(this.graph,"anisotropyTextureInfo")})}getAnisotropyStrength(){return this.get("anisotropyStrength")}setAnisotropyStrength(Z){return this.set("anisotropyStrength",Z)}getAnisotropyRotation(){return this.get("anisotropyRotation")}setAnisotropyRotation(Z){return this.set("anisotropyRotation",Z)}getAnisotropyTexture(){return this.getRef("anisotropyTexture")}getAnisotropyTextureInfo(){return this.getRef("anisotropyTexture")?this.getRef("anisotropyTextureInfo"):null}setAnisotropyTexture(Z){return this.setRef("anisotropyTexture",Z,{channels:DU5|PU5|CU5})}}tD.EXTENSION_NAME=hD;var WY=hD;class eD extends P5{constructor(...Z){super(...Z);this.extensionName=WY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createAnisotropy(){return new tD(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[WY]){let W=this.createAnisotropy();Z.materials[Q].setExtension(WY,W);let K=Y.extensions[WY];if(K.anisotropyStrength!==void 0)W.setAnisotropyStrength(K.anisotropyStrength);if(K.anisotropyRotation!==void 0)W.setAnisotropyRotation(K.anisotropyRotation);if(K.anisotropyTexture!==void 0){let G=K.anisotropyTexture,V=Z.textures[$[G.index].source];W.setAnisotropyTexture(V),Z.setTextureInfo(W.getAnisotropyTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(WY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[WY]={};if($.getAnisotropyStrength()>0)W.anisotropyStrength=$.getAnisotropyStrength();if($.getAnisotropyRotation()!==0)W.anisotropyRotation=$.getAnisotropyRotation();if($.getAnisotropyTexture()){let K=$.getAnisotropyTexture(),G=$.getAnisotropyTextureInfo();W.anisotropyTexture=Z.createTextureInfoDef(K,G)}}}),this}}eD.EXTENSION_NAME=WY;var{R:Ui,G:Bi,B:TU5}=A7;class ZP extends c5{init(){this.extensionName=bD,this.propertyType="Clearcoat",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{clearcoatFactor:0,clearcoatTexture:null,clearcoatTextureInfo:new R5(this.graph,"clearcoatTextureInfo"),clearcoatRoughnessFactor:0,clearcoatRoughnessTexture:null,clearcoatRoughnessTextureInfo:new R5(this.graph,"clearcoatRoughnessTextureInfo"),clearcoatNormalScale:1,clearcoatNormalTexture:null,clearcoatNormalTextureInfo:new R5(this.graph,"clearcoatNormalTextureInfo")})}getClearcoatFactor(){return this.get("clearcoatFactor")}setClearcoatFactor(Z){return this.set("clearcoatFactor",Z)}getClearcoatTexture(){return this.getRef("clearcoatTexture")}getClearcoatTextureInfo(){return this.getRef("clearcoatTexture")?this.getRef("clearcoatTextureInfo"):null}setClearcoatTexture(Z){return this.setRef("clearcoatTexture",Z,{channels:Ui})}getClearcoatRoughnessFactor(){return this.get("clearcoatRoughnessFactor")}setClearcoatRoughnessFactor(Z){return this.set("clearcoatRoughnessFactor",Z)}getClearcoatRoughnessTexture(){return this.getRef("clearcoatRoughnessTexture")}getClearcoatRoughnessTextureInfo(){return this.getRef("clearcoatRoughnessTexture")?this.getRef("clearcoatRoughnessTextureInfo"):null}setClearcoatRoughnessTexture(Z){return this.setRef("clearcoatRoughnessTexture",Z,{channels:Bi})}getClearcoatNormalScale(){return this.get("clearcoatNormalScale")}setClearcoatNormalScale(Z){return this.set("clearcoatNormalScale",Z)}getClearcoatNormalTexture(){return this.getRef("clearcoatNormalTexture")}getClearcoatNormalTextureInfo(){return this.getRef("clearcoatNormalTexture")?this.getRef("clearcoatNormalTextureInfo"):null}setClearcoatNormalTexture(Z){return this.setRef("clearcoatNormalTexture",Z,{channels:Ui|Bi|TU5})}}ZP.EXTENSION_NAME=bD;var KY=bD;class JP extends P5{constructor(...Z){super(...Z);this.extensionName=KY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createClearcoat(){return new ZP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[KY]){let W=this.createClearcoat();Z.materials[Q].setExtension(KY,W);let K=Y.extensions[KY];if(K.clearcoatFactor!==void 0)W.setClearcoatFactor(K.clearcoatFactor);if(K.clearcoatRoughnessFactor!==void 0)W.setClearcoatRoughnessFactor(K.clearcoatRoughnessFactor);if(K.clearcoatTexture!==void 0){let G=K.clearcoatTexture,V=Z.textures[$[G.index].source];W.setClearcoatTexture(V),Z.setTextureInfo(W.getClearcoatTextureInfo(),G)}if(K.clearcoatRoughnessTexture!==void 0){let G=K.clearcoatRoughnessTexture,V=Z.textures[$[G.index].source];W.setClearcoatRoughnessTexture(V),Z.setTextureInfo(W.getClearcoatRoughnessTextureInfo(),G)}if(K.clearcoatNormalTexture!==void 0){let G=K.clearcoatNormalTexture,V=Z.textures[$[G.index].source];if(W.setClearcoatNormalTexture(V),Z.setTextureInfo(W.getClearcoatNormalTextureInfo(),G),G.scale!==void 0)W.setClearcoatNormalScale(G.scale)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(KY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[KY]={clearcoatFactor:$.getClearcoatFactor(),clearcoatRoughnessFactor:$.getClearcoatRoughnessFactor()};if($.getClearcoatTexture()){let K=$.getClearcoatTexture(),G=$.getClearcoatTextureInfo();W.clearcoatTexture=Z.createTextureInfoDef(K,G)}if($.getClearcoatRoughnessTexture()){let K=$.getClearcoatRoughnessTexture(),G=$.getClearcoatRoughnessTextureInfo();W.clearcoatRoughnessTexture=Z.createTextureInfoDef(K,G)}if($.getClearcoatNormalTexture()){let K=$.getClearcoatNormalTexture(),G=$.getClearcoatNormalTextureInfo();if(W.clearcoatNormalTexture=Z.createTextureInfoDef(K,G),$.getClearcoatNormalScale()!==1)W.clearcoatNormalTexture.scale=$.getClearcoatNormalScale()}}}),this}}JP.EXTENSION_NAME=KY;var{R:kU5,G:EU5,B:IU5,A:vU5}=A7;class XP extends c5{init(){this.extensionName=yD,this.propertyType="DiffuseTransmission",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseTransmissionFactor:0,diffuseTransmissionTexture:null,diffuseTransmissionTextureInfo:new R5(this.graph,"diffuseTransmissionTextureInfo"),diffuseTransmissionColorFactor:[1,1,1],diffuseTransmissionColorTexture:null,diffuseTransmissionColorTextureInfo:new R5(this.graph,"diffuseTransmissionColorTextureInfo")})}getDiffuseTransmissionFactor(){return this.get("diffuseTransmissionFactor")}setDiffuseTransmissionFactor(Z){return this.set("diffuseTransmissionFactor",Z)}getDiffuseTransmissionTexture(){return this.getRef("diffuseTransmissionTexture")}getDiffuseTransmissionTextureInfo(){return this.getRef("diffuseTransmissionTexture")?this.getRef("diffuseTransmissionTextureInfo"):null}setDiffuseTransmissionTexture(Z){return this.setRef("diffuseTransmissionTexture",Z,{channels:vU5})}getDiffuseTransmissionColorFactor(){return this.get("diffuseTransmissionColorFactor")}setDiffuseTransmissionColorFactor(Z){return this.set("diffuseTransmissionColorFactor",Z)}getDiffuseTransmissionColorTexture(){return this.getRef("diffuseTransmissionColorTexture")}getDiffuseTransmissionColorTextureInfo(){return this.getRef("diffuseTransmissionColorTexture")?this.getRef("diffuseTransmissionColorTextureInfo"):null}setDiffuseTransmissionColorTexture(Z){return this.setRef("diffuseTransmissionColorTexture",Z,{channels:kU5|EU5|IU5})}}XP.EXTENSION_NAME=yD;var GY=yD;class $P extends P5{constructor(...Z){super(...Z);this.extensionName=GY}createDiffuseTransmission(){return new XP(this.document.getGraph())}read(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[GY]){let W=this.createDiffuseTransmission();Z.materials[Q].setExtension(GY,W);let K=Y.extensions[GY];if(K.diffuseTransmissionFactor!==void 0)W.setDiffuseTransmissionFactor(K.diffuseTransmissionFactor);if(K.diffuseTransmissionColorFactor!==void 0)W.setDiffuseTransmissionColorFactor(K.diffuseTransmissionColorFactor);if(K.diffuseTransmissionTexture!==void 0){let G=K.diffuseTransmissionTexture,V=Z.textures[$[G.index].source];W.setDiffuseTransmissionTexture(V),Z.setTextureInfo(W.getDiffuseTransmissionTextureInfo(),G)}if(K.diffuseTransmissionColorTexture!==void 0){let G=K.diffuseTransmissionColorTexture,V=Z.textures[$[G.index].source];W.setDiffuseTransmissionColorTexture(V),Z.setTextureInfo(W.getDiffuseTransmissionColorTextureInfo(),G)}}}),this}write(Z){let J=Z.jsonDoc;for(let X of this.document.getRoot().listMaterials()){let $=X.getExtension(GY);if(!$)continue;let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[GY]={diffuseTransmissionFactor:$.getDiffuseTransmissionFactor(),diffuseTransmissionColorFactor:$.getDiffuseTransmissionColorFactor()};if($.getDiffuseTransmissionTexture()){let K=$.getDiffuseTransmissionTexture(),G=$.getDiffuseTransmissionTextureInfo();W.diffuseTransmissionTexture=Z.createTextureInfoDef(K,G)}if($.getDiffuseTransmissionColorTexture()){let K=$.getDiffuseTransmissionColorTexture(),G=$.getDiffuseTransmissionColorTextureInfo();W.diffuseTransmissionColorTexture=Z.createTextureInfoDef(K,G)}}return this}}$P.EXTENSION_NAME=GY;class YP extends c5{init(){this.extensionName=gD,this.propertyType="Dispersion",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{dispersion:0})}getDispersion(){return this.get("dispersion")}setDispersion(Z){return this.set("dispersion",Z)}}YP.EXTENSION_NAME=gD;var VY=gD;class QP extends P5{constructor(...Z){super(...Z);this.extensionName=VY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createDispersion(){return new YP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach(($,Y)=>{if($.extensions&&$.extensions[VY]){let Q=this.createDispersion();Z.materials[Y].setExtension(VY,Q);let W=$.extensions[VY];if(W.dispersion!==void 0)Q.setDispersion(W.dispersion)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(VY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{},Q.extensions[VY]={dispersion:$.getDispersion()}}}),this}}QP.EXTENSION_NAME=VY;class WP extends c5{init(){this.extensionName=mD,this.propertyType="EmissiveStrength",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{emissiveStrength:1})}getEmissiveStrength(){return this.get("emissiveStrength")}setEmissiveStrength(Z){return this.set("emissiveStrength",Z)}}WP.EXTENSION_NAME=mD;var HY=mD;class KP extends P5{constructor(...Z){super(...Z);this.extensionName=HY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createEmissiveStrength(){return new WP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach(($,Y)=>{if($.extensions&&$.extensions[HY]){let Q=this.createEmissiveStrength();Z.materials[Y].setExtension(HY,Q);let W=$.extensions[HY];if(W.emissiveStrength!==void 0)Q.setEmissiveStrength(W.emissiveStrength)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(HY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{},Q.extensions[HY]={emissiveStrength:$.getEmissiveStrength()}}}),this}}KP.EXTENSION_NAME=HY;class GP extends c5{init(){this.extensionName=dD,this.propertyType="IOR",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{ior:1.5})}getIOR(){return this.get("ior")}setIOR(Z){return this.set("ior",Z)}}GP.EXTENSION_NAME=dD;var qY=dD;class kU extends P5{constructor(...Z){super(...Z);this.extensionName=qY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createIOR(){return new GP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach(($,Y)=>{if($.extensions&&$.extensions[qY]){let Q=this.createIOR();Z.materials[Y].setExtension(qY,Q);let W=$.extensions[qY];if(W.ior!==void 0)Q.setIOR(W.ior)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(qY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{},Q.extensions[qY]={ior:$.getIOR()}}}),this}}kU.EXTENSION_NAME=qY;var{R:SU5,G:_U5}=A7;class VP extends c5{init(){this.extensionName=uD,this.propertyType="Iridescence",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{iridescenceFactor:0,iridescenceTexture:null,iridescenceTextureInfo:new R5(this.graph,"iridescenceTextureInfo"),iridescenceIOR:1.3,iridescenceThicknessMinimum:100,iridescenceThicknessMaximum:400,iridescenceThicknessTexture:null,iridescenceThicknessTextureInfo:new R5(this.graph,"iridescenceThicknessTextureInfo")})}getIridescenceFactor(){return this.get("iridescenceFactor")}setIridescenceFactor(Z){return this.set("iridescenceFactor",Z)}getIridescenceTexture(){return this.getRef("iridescenceTexture")}getIridescenceTextureInfo(){return this.getRef("iridescenceTexture")?this.getRef("iridescenceTextureInfo"):null}setIridescenceTexture(Z){return this.setRef("iridescenceTexture",Z,{channels:SU5})}getIridescenceIOR(){return this.get("iridescenceIOR")}setIridescenceIOR(Z){return this.set("iridescenceIOR",Z)}getIridescenceThicknessMinimum(){return this.get("iridescenceThicknessMinimum")}setIridescenceThicknessMinimum(Z){return this.set("iridescenceThicknessMinimum",Z)}getIridescenceThicknessMaximum(){return this.get("iridescenceThicknessMaximum")}setIridescenceThicknessMaximum(Z){return this.set("iridescenceThicknessMaximum",Z)}getIridescenceThicknessTexture(){return this.getRef("iridescenceThicknessTexture")}getIridescenceThicknessTextureInfo(){return this.getRef("iridescenceThicknessTexture")?this.getRef("iridescenceThicknessTextureInfo"):null}setIridescenceThicknessTexture(Z){return this.setRef("iridescenceThicknessTexture",Z,{channels:_U5})}}VP.EXTENSION_NAME=uD;var zY=uD;class HP extends P5{constructor(...Z){super(...Z);this.extensionName=zY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createIridescence(){return new VP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[zY]){let W=this.createIridescence();Z.materials[Q].setExtension(zY,W);let K=Y.extensions[zY];if(K.iridescenceFactor!==void 0)W.setIridescenceFactor(K.iridescenceFactor);if(K.iridescenceIor!==void 0)W.setIridescenceIOR(K.iridescenceIor);if(K.iridescenceThicknessMinimum!==void 0)W.setIridescenceThicknessMinimum(K.iridescenceThicknessMinimum);if(K.iridescenceThicknessMaximum!==void 0)W.setIridescenceThicknessMaximum(K.iridescenceThicknessMaximum);if(K.iridescenceTexture!==void 0){let G=K.iridescenceTexture,V=Z.textures[$[G.index].source];W.setIridescenceTexture(V),Z.setTextureInfo(W.getIridescenceTextureInfo(),G)}if(K.iridescenceThicknessTexture!==void 0){let G=K.iridescenceThicknessTexture,V=Z.textures[$[G.index].source];W.setIridescenceThicknessTexture(V),Z.setTextureInfo(W.getIridescenceThicknessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(zY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[zY]={};if($.getIridescenceFactor()>0)W.iridescenceFactor=$.getIridescenceFactor();if($.getIridescenceIOR()!==1.3)W.iridescenceIor=$.getIridescenceIOR();if($.getIridescenceThicknessMinimum()!==100)W.iridescenceThicknessMinimum=$.getIridescenceThicknessMinimum();if($.getIridescenceThicknessMaximum()!==400)W.iridescenceThicknessMaximum=$.getIridescenceThicknessMaximum();if($.getIridescenceTexture()){let K=$.getIridescenceTexture(),G=$.getIridescenceTextureInfo();W.iridescenceTexture=Z.createTextureInfoDef(K,G)}if($.getIridescenceThicknessTexture()){let K=$.getIridescenceThicknessTexture(),G=$.getIridescenceThicknessTextureInfo();W.iridescenceThicknessTexture=Z.createTextureInfoDef(K,G)}}}),this}}HP.EXTENSION_NAME=zY;var{R:Li,G:wi,B:Oi,A:Ni}=A7;class qP extends c5{init(){this.extensionName=cD,this.propertyType="PBRSpecularGlossiness",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseFactor:[1,1,1,1],diffuseTexture:null,diffuseTextureInfo:new R5(this.graph,"diffuseTextureInfo"),specularFactor:[1,1,1],glossinessFactor:1,specularGlossinessTexture:null,specularGlossinessTextureInfo:new R5(this.graph,"specularGlossinessTextureInfo")})}getDiffuseFactor(){return this.get("diffuseFactor")}setDiffuseFactor(Z){return this.set("diffuseFactor",Z)}getDiffuseTexture(){return this.getRef("diffuseTexture")}getDiffuseTextureInfo(){return this.getRef("diffuseTexture")?this.getRef("diffuseTextureInfo"):null}setDiffuseTexture(Z){return this.setRef("diffuseTexture",Z,{channels:Li|wi|Oi|Ni,isColor:!0})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(Z){return this.set("specularFactor",Z)}getGlossinessFactor(){return this.get("glossinessFactor")}setGlossinessFactor(Z){return this.set("glossinessFactor",Z)}getSpecularGlossinessTexture(){return this.getRef("specularGlossinessTexture")}getSpecularGlossinessTextureInfo(){return this.getRef("specularGlossinessTexture")?this.getRef("specularGlossinessTextureInfo"):null}setSpecularGlossinessTexture(Z){return this.setRef("specularGlossinessTexture",Z,{channels:Li|wi|Oi|Ni})}}qP.EXTENSION_NAME=cD;var FY=cD;class EU extends P5{constructor(...Z){super(...Z);this.extensionName=FY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createPBRSpecularGlossiness(){return new qP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[FY]){let W=this.createPBRSpecularGlossiness();Z.materials[Q].setExtension(FY,W);let K=Y.extensions[FY];if(K.diffuseFactor!==void 0)W.setDiffuseFactor(K.diffuseFactor);if(K.specularFactor!==void 0)W.setSpecularFactor(K.specularFactor);if(K.glossinessFactor!==void 0)W.setGlossinessFactor(K.glossinessFactor);if(K.diffuseTexture!==void 0){let G=K.diffuseTexture,V=Z.textures[$[G.index].source];W.setDiffuseTexture(V),Z.setTextureInfo(W.getDiffuseTextureInfo(),G)}if(K.specularGlossinessTexture!==void 0){let G=K.specularGlossinessTexture,V=Z.textures[$[G.index].source];W.setSpecularGlossinessTexture(V),Z.setTextureInfo(W.getSpecularGlossinessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(FY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[FY]={diffuseFactor:$.getDiffuseFactor(),specularFactor:$.getSpecularFactor(),glossinessFactor:$.getGlossinessFactor()};if($.getDiffuseTexture()){let K=$.getDiffuseTexture(),G=$.getDiffuseTextureInfo();W.diffuseTexture=Z.createTextureInfoDef(K,G)}if($.getSpecularGlossinessTexture()){let K=$.getSpecularGlossinessTexture(),G=$.getSpecularGlossinessTextureInfo();W.specularGlossinessTexture=Z.createTextureInfoDef(K,G)}}}),this}}EU.EXTENSION_NAME=FY;var{R:AU5,G:xU5,B:fU5,A:hU5}=A7;class zP extends c5{init(){this.extensionName=lD,this.propertyType="Sheen",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{sheenColorFactor:[0,0,0],sheenColorTexture:null,sheenColorTextureInfo:new R5(this.graph,"sheenColorTextureInfo"),sheenRoughnessFactor:0,sheenRoughnessTexture:null,sheenRoughnessTextureInfo:new R5(this.graph,"sheenRoughnessTextureInfo")})}getSheenColorFactor(){return this.get("sheenColorFactor")}setSheenColorFactor(Z){return this.set("sheenColorFactor",Z)}getSheenColorTexture(){return this.getRef("sheenColorTexture")}getSheenColorTextureInfo(){return this.getRef("sheenColorTexture")?this.getRef("sheenColorTextureInfo"):null}setSheenColorTexture(Z){return this.setRef("sheenColorTexture",Z,{channels:AU5|xU5|fU5,isColor:!0})}getSheenRoughnessFactor(){return this.get("sheenRoughnessFactor")}setSheenRoughnessFactor(Z){return this.set("sheenRoughnessFactor",Z)}getSheenRoughnessTexture(){return this.getRef("sheenRoughnessTexture")}getSheenRoughnessTextureInfo(){return this.getRef("sheenRoughnessTexture")?this.getRef("sheenRoughnessTextureInfo"):null}setSheenRoughnessTexture(Z){return this.setRef("sheenRoughnessTexture",Z,{channels:hU5})}}zP.EXTENSION_NAME=lD;var UY=lD;class FP extends P5{constructor(...Z){super(...Z);this.extensionName=UY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createSheen(){return new zP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[UY]){let W=this.createSheen();Z.materials[Q].setExtension(UY,W);let K=Y.extensions[UY];if(K.sheenColorFactor!==void 0)W.setSheenColorFactor(K.sheenColorFactor);if(K.sheenRoughnessFactor!==void 0)W.setSheenRoughnessFactor(K.sheenRoughnessFactor);if(K.sheenColorTexture!==void 0){let G=K.sheenColorTexture,V=Z.textures[$[G.index].source];W.setSheenColorTexture(V),Z.setTextureInfo(W.getSheenColorTextureInfo(),G)}if(K.sheenRoughnessTexture!==void 0){let G=K.sheenRoughnessTexture,V=Z.textures[$[G.index].source];W.setSheenRoughnessTexture(V),Z.setTextureInfo(W.getSheenRoughnessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(UY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[UY]={sheenColorFactor:$.getSheenColorFactor(),sheenRoughnessFactor:$.getSheenRoughnessFactor()};if($.getSheenColorTexture()){let K=$.getSheenColorTexture(),G=$.getSheenColorTextureInfo();W.sheenColorTexture=Z.createTextureInfoDef(K,G)}if($.getSheenRoughnessTexture()){let K=$.getSheenRoughnessTexture(),G=$.getSheenRoughnessTextureInfo();W.sheenRoughnessTexture=Z.createTextureInfoDef(K,G)}}}),this}}FP.EXTENSION_NAME=UY;var{R:bU5,G:yU5,B:gU5,A:mU5}=A7;class UP extends c5{init(){this.extensionName=pD,this.propertyType="Specular",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{specularFactor:1,specularTexture:null,specularTextureInfo:new R5(this.graph,"specularTextureInfo"),specularColorFactor:[1,1,1],specularColorTexture:null,specularColorTextureInfo:new R5(this.graph,"specularColorTextureInfo")})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(Z){return this.set("specularFactor",Z)}getSpecularColorFactor(){return this.get("specularColorFactor")}setSpecularColorFactor(Z){return this.set("specularColorFactor",Z)}getSpecularTexture(){return this.getRef("specularTexture")}getSpecularTextureInfo(){return this.getRef("specularTexture")?this.getRef("specularTextureInfo"):null}setSpecularTexture(Z){return this.setRef("specularTexture",Z,{channels:mU5})}getSpecularColorTexture(){return this.getRef("specularColorTexture")}getSpecularColorTextureInfo(){return this.getRef("specularColorTexture")?this.getRef("specularColorTextureInfo"):null}setSpecularColorTexture(Z){return this.setRef("specularColorTexture",Z,{channels:bU5|yU5|gU5,isColor:!0})}}UP.EXTENSION_NAME=pD;var BY=pD;class IU extends P5{constructor(...Z){super(...Z);this.extensionName=BY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createSpecular(){return new UP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[BY]){let W=this.createSpecular();Z.materials[Q].setExtension(BY,W);let K=Y.extensions[BY];if(K.specularFactor!==void 0)W.setSpecularFactor(K.specularFactor);if(K.specularColorFactor!==void 0)W.setSpecularColorFactor(K.specularColorFactor);if(K.specularTexture!==void 0){let G=K.specularTexture,V=Z.textures[$[G.index].source];W.setSpecularTexture(V),Z.setTextureInfo(W.getSpecularTextureInfo(),G)}if(K.specularColorTexture!==void 0){let G=K.specularColorTexture,V=Z.textures[$[G.index].source];W.setSpecularColorTexture(V),Z.setTextureInfo(W.getSpecularColorTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(BY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[BY]={};if($.getSpecularFactor()!==1)W.specularFactor=$.getSpecularFactor();if(!$8.eq($.getSpecularColorFactor(),[1,1,1]))W.specularColorFactor=$.getSpecularColorFactor();if($.getSpecularTexture()){let K=$.getSpecularTexture(),G=$.getSpecularTextureInfo();W.specularTexture=Z.createTextureInfoDef(K,G)}if($.getSpecularColorTexture()){let K=$.getSpecularColorTexture(),G=$.getSpecularColorTextureInfo();W.specularColorTexture=Z.createTextureInfoDef(K,G)}}}),this}}IU.EXTENSION_NAME=BY;var{R:dU5}=A7;class BP extends c5{init(){this.extensionName=iD,this.propertyType="Transmission",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{transmissionFactor:0,transmissionTexture:null,transmissionTextureInfo:new R5(this.graph,"transmissionTextureInfo")})}getTransmissionFactor(){return this.get("transmissionFactor")}setTransmissionFactor(Z){return this.set("transmissionFactor",Z)}getTransmissionTexture(){return this.getRef("transmissionTexture")}getTransmissionTextureInfo(){return this.getRef("transmissionTexture")?this.getRef("transmissionTextureInfo"):null}setTransmissionTexture(Z){return this.setRef("transmissionTexture",Z,{channels:dU5})}}BP.EXTENSION_NAME=iD;var LY=iD;class LP extends P5{constructor(...Z){super(...Z);this.extensionName=LY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createTransmission(){return new BP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[LY]){let W=this.createTransmission();Z.materials[Q].setExtension(LY,W);let K=Y.extensions[LY];if(K.transmissionFactor!==void 0)W.setTransmissionFactor(K.transmissionFactor);if(K.transmissionTexture!==void 0){let G=K.transmissionTexture,V=Z.textures[$[G.index].source];W.setTransmissionTexture(V),Z.setTextureInfo(W.getTransmissionTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(LY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[LY]={transmissionFactor:$.getTransmissionFactor()};if($.getTransmissionTexture()){let K=$.getTransmissionTexture(),G=$.getTransmissionTextureInfo();W.transmissionTexture=Z.createTextureInfoDef(K,G)}}}),this}}LP.EXTENSION_NAME=LY;class wP extends c5{init(){this.extensionName=nD,this.propertyType="Unlit",this.parentTypes=[s.MATERIAL]}}wP.EXTENSION_NAME=nD;var mW=nD;class vU extends P5{constructor(...Z){super(...Z);this.extensionName=mW,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createUnlit(){return new wP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((X,$)=>{if(X.extensions&&X.extensions[mW])Z.materials[$].setExtension(mW,this.createUnlit())}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{if(X.getExtension(mW)){let $=Z.materialIndexMap.get(X),Y=J.json.materials[$];Y.extensions=Y.extensions||{},Y.extensions[mW]={}}}),this}}vU.EXTENSION_NAME=mW;class OP extends c5{init(){this.extensionName=NY,this.propertyType="Mapping",this.parentTypes=["MappingList"]}getDefaults(){return Object.assign(super.getDefaults(),{material:null,variants:new I0})}getMaterial(){return this.getRef("material")}setMaterial(Z){return this.setRef("material",Z)}addVariant(Z){return this.addRef("variants",Z)}removeVariant(Z){return this.removeRef("variants",Z)}listVariants(){return this.listRefs("variants")}}OP.EXTENSION_NAME=NY;class NP extends c5{init(){this.extensionName=NY,this.propertyType="MappingList",this.parentTypes=[s.PRIMITIVE]}getDefaults(){return Object.assign(super.getDefaults(),{mappings:new I0})}addMapping(Z){return this.addRef("mappings",Z)}removeMapping(Z){return this.removeRef("mappings",Z)}listMappings(){return this.listRefs("mappings")}}NP.EXTENSION_NAME=NY;class DU extends c5{init(){this.extensionName=NY,this.propertyType="Variant",this.parentTypes=["MappingList"]}}DU.EXTENSION_NAME=NY;var JJ=NY;class jP extends P5{constructor(...Z){super(...Z);this.extensionName=JJ}createMappingList(){return new NP(this.document.getGraph())}createVariant(Z=""){return new DU(this.document.getGraph(),Z)}createMapping(){return new OP(this.document.getGraph())}listVariants(){return Array.from(this.properties).filter((Z)=>Z instanceof DU)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[JJ])return this;let Y=(J.json.extensions[JJ].variants||[]).map((W)=>this.createVariant().setName(W.name||""));return(J.json.meshes||[]).forEach((W,K)=>{let G=Z.meshes[K];(W.primitives||[]).forEach((H,q)=>{if(!H.extensions||!H.extensions[JJ])return;let z=this.createMappingList(),F=H.extensions[JJ];for(let U of F.mappings){let L=this.createMapping();if(U.material!==void 0)L.setMaterial(Z.materials[U.material]);for(let B of U.variants||[])L.addVariant(Y[B]);z.addMapping(L)}G.listPrimitives()[q].setExtension(JJ,z)})}),this}write(Z){let J=Z.jsonDoc,X=this.listVariants();if(!X.length)return this;let $=[],Y=new Map;for(let Q of X)Y.set(Q,$.length),$.push(Z.createPropertyDef(Q));for(let Q of this.document.getRoot().listMeshes()){let W=Z.meshIndexMap.get(Q);Q.listPrimitives().forEach((K,G)=>{let V=K.getExtension(JJ);if(!V)return;let H=Z.jsonDoc.json.meshes[W].primitives[G],q=V.listMappings().map((z)=>{let F=Z.createPropertyDef(z),U=z.getMaterial();if(U)F.material=Z.materialIndexMap.get(U);return F.variants=z.listVariants().map((L)=>Y.get(L)),F});H.extensions=H.extensions||{},H.extensions[JJ]={mappings:q}})}return J.json.extensions=J.json.extensions||{},J.json.extensions[JJ]={variants:$},this}}jP.EXTENSION_NAME=JJ;var{G:uU5}=A7;class MP extends c5{init(){this.extensionName=sD,this.propertyType="Volume",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{thicknessFactor:0,thicknessTexture:null,thicknessTextureInfo:new R5(this.graph,"thicknessTexture"),attenuationDistance:1/0,attenuationColor:[1,1,1]})}getThicknessFactor(){return this.get("thicknessFactor")}setThicknessFactor(Z){return this.set("thicknessFactor",Z)}getThicknessTexture(){return this.getRef("thicknessTexture")}getThicknessTextureInfo(){return this.getRef("thicknessTexture")?this.getRef("thicknessTextureInfo"):null}setThicknessTexture(Z){return this.setRef("thicknessTexture",Z,{channels:uU5})}getAttenuationDistance(){return this.get("attenuationDistance")}setAttenuationDistance(Z){return this.set("attenuationDistance",Z)}getAttenuationColor(){return this.get("attenuationColor")}setAttenuationColor(Z){return this.set("attenuationColor",Z)}}MP.EXTENSION_NAME=sD;var wY=sD;class RP extends P5{constructor(...Z){super(...Z);this.extensionName=wY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createVolume(){return new MP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[wY]){let W=this.createVolume();Z.materials[Q].setExtension(wY,W);let K=Y.extensions[wY];if(K.thicknessFactor!==void 0)W.setThicknessFactor(K.thicknessFactor);if(K.attenuationDistance!==void 0)W.setAttenuationDistance(K.attenuationDistance);if(K.attenuationColor!==void 0)W.setAttenuationColor(K.attenuationColor);if(K.thicknessTexture!==void 0){let G=K.thicknessTexture,V=Z.textures[$[G.index].source];W.setThicknessTexture(V),Z.setTextureInfo(W.getThicknessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(wY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[wY]={};if($.getThicknessFactor()>0)W.thicknessFactor=$.getThicknessFactor();if(Number.isFinite($.getAttenuationDistance()))W.attenuationDistance=$.getAttenuationDistance();if(!$8.eq($.getAttenuationColor(),[1,1,1]))W.attenuationColor=$.getAttenuationColor();if($.getThicknessTexture()){let K=$.getThicknessTexture(),G=$.getThicknessTextureInfo();W.thicknessTexture=Z.createTextureInfoDef(K,G)}}}),this}}RP.EXTENSION_NAME=wY;var ki=$U5;class oG extends P5{constructor(...Z){super(...Z);this.extensionName=ki}read(Z){return this}write(Z){return this}}oG.EXTENSION_NAME=ki;var iG=YU5;class Ei{match(Z){return Z[0]===171&&Z[1]===75&&Z[2]===84&&Z[3]===88&&Z[4]===32&&Z[5]===50&&Z[6]===48&&Z[7]===187&&Z[8]===13&&Z[9]===10&&Z[10]===26&&Z[11]===10}getSize(Z){let J=jU(Z);return[J.pixelWidth,J.pixelHeight]}getChannels(Z){let X=jU(Z).dataFormatDescriptor[0];if(X.colorModel===Qi)return X.samples.length===2&&(X.samples[1].channelType&15)===15?4:3;else if(X.colorModel===Wi)return(X.samples[0].channelType&15)===3?4:3;throw new Error(`Unexpected KTX2 colorModel, "${X.colorModel}".`)}getVRAMByteLength(Z){let J=jU(Z),X=this.getChannels(Z)>3,$=0;for(let Y=0;Y<J.levels.length;Y++){let Q=J.levels[Y];if(Q.uncompressedByteLength)$+=Q.uncompressedByteLength;else{let W=Math.max(1,Math.floor(J.pixelWidth/Math.pow(2,Y))),K=Math.max(1,Math.floor(J.pixelHeight/Math.pow(2,Y))),G=X?16:8;$+=W/4*(K/4)*G}}return $}}class DP extends P5{constructor(...Z){super(...Z);this.extensionName=iG,this.prereadTypes=[s.TEXTURE]}static register(){GZ.registerFormat("image/ktx2",new Ei)}preread(Z){return Z.jsonDoc.json.textures.forEach((J)=>{if(J.extensions&&J.extensions[iG]){let X=J.extensions[iG];J.source=X.source}}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/ktx2"){let $=Z.imageIndexMap.get(X);J.json.textures.forEach((Y)=>{if(Y.source===$)Y.extensions=Y.extensions||{},Y.extensions[iG]={source:Y.source},delete Y.source})}}),this}}DP.EXTENSION_NAME=iG;class PP extends c5{init(){this.extensionName=aD,this.propertyType="Transform",this.parentTypes=[s.TEXTURE_INFO]}getDefaults(){return Object.assign(super.getDefaults(),{offset:[0,0],rotation:0,scale:[1,1],texCoord:null})}getOffset(){return this.get("offset")}setOffset(Z){return this.set("offset",Z)}getRotation(){return this.get("rotation")}setRotation(Z){return this.set("rotation",Z)}getScale(){return this.get("scale")}setScale(Z){return this.set("scale",Z)}getTexCoord(){return this.get("texCoord")}setTexCoord(Z){return this.set("texCoord",Z)}}PP.EXTENSION_NAME=aD;var OY=aD;class CP extends P5{constructor(...Z){super(...Z);this.extensionName=OY}createTransform(){return new PP(this.document.getGraph())}read(Z){for(let[J,X]of Array.from(Z.textureInfos.entries())){if(!X.extensions||!X.extensions[OY])continue;let $=this.createTransform(),Y=X.extensions[OY];if(Y.offset!==void 0)$.setOffset(Y.offset);if(Y.rotation!==void 0)$.setRotation(Y.rotation);if(Y.scale!==void 0)$.setScale(Y.scale);if(Y.texCoord!==void 0)$.setTexCoord(Y.texCoord);J.setExtension(OY,$)}return this}write(Z){let J=Array.from(Z.textureInfoDefMap.entries());for(let[X,$]of J){let Y=X.getExtension(OY);if(!Y)continue;$.extensions=$.extensions||{};let Q={},W=$8.eq;if(!W(Y.getOffset(),[0,0]))Q.offset=Y.getOffset();if(Y.getRotation()!==0)Q.rotation=Y.getRotation();if(!W(Y.getScale(),[1,1]))Q.scale=Y.getScale();if(Y.getTexCoord()!=null)Q.texCoord=Y.getTexCoord();$.extensions[OY]=Q}return this}}CP.EXTENSION_NAME=OY;var cU5=[s.ROOT,s.SCENE,s.NODE,s.MESH,s.MATERIAL,s.TEXTURE,s.ANIMATION];class TP extends c5{init(){this.extensionName=MU,this.propertyType="Packet",this.parentTypes=cU5}getDefaults(){return Object.assign(super.getDefaults(),{context:{},properties:{}})}getContext(){return this.get("context")}setContext(Z){return this.set("context",oJ({},Z))}listProperties(){return Object.keys(this.get("properties"))}getProperty(Z){let J=this.get("properties");return Z in J?J[Z]:null}setProperty(Z,J){this._assertContext(Z);let X=oJ({},this.get("properties"));if(J)X[Z]=J;else delete X[Z];return this.set("properties",X)}toJSONLD(){let Z=vD(this.get("context")),J=vD(this.get("properties"));return oJ({"@context":Z},J)}fromJSONLD(Z){Z=vD(Z);let J=Z["@context"];if(J)this.set("context",J);return delete Z["@context"],this.set("properties",Z)}_assertContext(Z){if(!(Z.split(":")[0]in this.get("context")))throw new Error(`${MU}: Missing context for term, "${Z}".`)}}TP.EXTENSION_NAME=MU;function vD(Z){return JSON.parse(JSON.stringify(Z))}var rJ=MU;class kP extends P5{constructor(...Z){super(...Z);this.extensionName=rJ}createPacket(){return new TP(this.document.getGraph())}listPackets(){return Array.from(this.properties)}read(Z){var J;let X=(J=Z.jsonDoc.json.extensions)==null?void 0:J[rJ];if(!X||!X.packets)return this;let $=Z.jsonDoc.json,Y=this.document.getRoot(),Q=X.packets.map((G)=>this.createPacket().fromJSONLD(G)),W=[[$.asset],$.scenes,$.nodes,$.meshes,$.materials,$.images,$.animations],K=[[Y],Y.listScenes(),Y.listNodes(),Y.listMeshes(),Y.listMaterials(),Y.listTextures(),Y.listAnimations()];for(let G=0;G<W.length;G++){let V=W[G]||[];for(let H=0;H<V.length;H++){let q=V[H];if(q.extensions&&q.extensions[rJ]){let z=q.extensions[rJ];K[G][H].setExtension(rJ,Q[z.packet])}}}return this}write(Z){let{json:J}=Z.jsonDoc,X=[];for(let $ of this.properties){X.push($.toJSONLD());for(let Y of $.listParents()){let Q;switch(Y.propertyType){case s.ROOT:Q=J.asset;break;case s.SCENE:Q=J.scenes[Z.sceneIndexMap.get(Y)];break;case s.NODE:Q=J.nodes[Z.nodeIndexMap.get(Y)];break;case s.MESH:Q=J.meshes[Z.meshIndexMap.get(Y)];break;case s.MATERIAL:Q=J.materials[Z.materialIndexMap.get(Y)];break;case s.TEXTURE:Q=J.images[Z.imageIndexMap.get(Y)];break;case s.ANIMATION:Q=J.animations[Z.animationIndexMap.get(Y)];break;default:Q=null,this.document.getLogger().warn(`[${rJ}]: Unsupported parent property, "${Y.propertyType}"`);break}if(!Q)continue;Q.extensions=Q.extensions||{},Q.extensions[rJ]={packet:X.length-1}}}if(X.length>0)J.extensions=J.extensions||{},J.extensions[rJ]={packets:X};return this}}kP.EXTENSION_NAME=rJ;var lU5=[rG,oD,eD,JP,$P,QP,KP,kU,HP,EU,IU,FP,LP,vU,jP,RP,oG,DP,CP,kP],_V6=[PU,aG,CU,TU,...lU5];var pU5=e(cR(),1);function pW(){return pW=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)({}).hasOwnProperty.call(X,$)&&(Z[$]=X[$])}return Z},pW.apply(null,arguments)}var{POINTS:Ii,LINES:SU,LINE_STRIP:iU5,LINE_LOOP:nU5,TRIANGLES:_U,TRIANGLE_STRIP:sU5,TRIANGLE_FAN:aU5}=O8.Mode;function BX(Z,J){return Object.defineProperty(J,"name",{value:Z}),J}function XJ(Z,J){let X=pW({},Z);for(let $ in J)if(J[$]!==void 0)X[$]=J[$];return X}function ai(Z){let J=Z.getIndices(),X=Z.getAttribute("POSITION");switch(Z.getMode()){case O8.Mode.POINTS:return J?J.getCount():X.getCount();case O8.Mode.LINES:return J?J.getCount()/2:X.getCount()/2;case O8.Mode.LINE_LOOP:return J?J.getCount():X.getCount();case O8.Mode.LINE_STRIP:return J?J.getCount()-1:X.getCount()-1;case O8.Mode.TRIANGLES:return J?J.getCount()/3:X.getCount()/3;case O8.Mode.TRIANGLE_STRIP:case O8.Mode.TRIANGLE_FAN:return J?J.getCount()-2:X.getCount()-2;default:throw new Error("Unexpected mode: "+Z.getMode())}}var rU5=new Intl.NumberFormat(void 0,{maximumFractionDigits:0});function SP(Z){return rU5.format(Z)}function oU5(Z,J,X=2){let $=Z>J?"–":"+",Y="%";return $+(Math.abs(Z-J)/Z*100).toFixed(X)+"%"}function bU(Z,J){return`${SP(Z)} → ${SP(J)} (${oU5(Z,J)})`}function yP(Z){let J=[];for(let X of Z.listAttributes())J.push(X);for(let X of Z.listTargets())for(let $ of X.listAttributes())J.push($);return Array.from(new Set(J))}function tU5(Z,J,X){Z.swap(J,X);for(let $ of Z.listTargets())$.swap(J,X)}function eU5(Z,J){if(Z==null&&J==null)return!0;if(Z==null||J==null)return!1;if(Z.length!==J.length)return!1;for(let X=0;X<Z.length;X++)if(Z[X]!==J[X])return!1;return!0}function tJ(Z,J){return Z.createAccessor(J.getName()).setArray(J.getArray()).setType(J.getType()).setBuffer(J.getBuffer()).setNormalized(J.getNormalized()).setSparse(J.getSparse())}function ZB5(Z,J=Z){let X=gP(Z,J);for(let $=0;$<X.length;$++)X[$]=$;return X}function gP(Z,J=Z){return J<=65534?new Uint16Array(Z):new Uint32Array(Z)}function JB5(Z){return Z.listParents().some((J)=>J.propertyType!==n.ROOT)}function ri(Z){for(let J in Z)return!1;return!0}function oi(Z){let J=F6.fromGraph(Z.getGraph()),X=Z.getMaterial(),$=J.getRoot().listMaterials().indexOf(X),Y=$B5[Z.getMode()],Q=!!Z.getIndices(),W=Z.listSemantics().sort().map((G)=>{let V=Z.getAttribute(G),H=V.getElementSize(),q=V.getComponentType();return`${G}:${H}:${q}`}).join("+"),K=Z.listTargets().map((G)=>{return G.listSemantics().sort().map((V)=>{let H=Z.getAttribute(V),q=H.getElementSize(),z=H.getComponentType();return`${V}:${q}:${z}`}).join("+")}).join("~");return`${$}|${Y}|${Q}|${W}|${K}`}function XB5(Z){return Math.pow(2,Math.ceil(Math.log(Z)/Math.LN2))}var $B5={[Ii]:Ii,[SU]:SU,[iU5]:SU,[nU5]:SU,[_U]:_U,[sU5]:_U,[aU5]:_U},cW="center",vi={pivot:"center"};function ti(Z=vi){let J=XJ(vi,Z);return BX(cW,(X)=>{let $=X.getLogger(),Y=X.getRoot(),Q=Y.listAnimations().length>0||Y.listSkins().length>0;X.getRoot().listScenes().forEach((W,K)=>{$.debug(`${cW}: Scene ${K+1} / ${Y.listScenes().length}.`);let G;if(typeof J.pivot==="string"){let H=hR(W);if(G=[(H.max[0]-H.min[0])/2+H.min[0],(H.max[1]-H.min[1])/2+H.min[1],(H.max[2]-H.min[2])/2+H.min[2]],J.pivot==="above")G[1]=H.max[1];if(J.pivot==="below")G[1]=H.min[1]}else G=J.pivot;$.debug(`${cW}: Pivot "${G.join(", ")}".`);let V=[-1*G[0],-1*G[1],-1*G[2]];if(Q){$.debug(`${cW}: Model contains animation or skin. Adding a wrapper node.`);let H=X.createNode("Pivot").setTranslation(V);W.listChildren().forEach((q)=>H.addChild(q)),W.addChild(H)}else $.debug(`${cW}: Skipping wrapper, offsetting all root nodes.`),W.listChildren().forEach((H)=>{let q=H.getTranslation();H.setTranslation([q[0]+V[0],q[1]+V[1],q[2]+V[2]])})}),$.debug(`${cW}: Complete.`)})}function YB5(Z){let J=new Set,X=Z,$;while($=X.getParentNode()){if(J.has($))throw new Error("Circular dependency in scene graph.");J.add($),X=$}return X.listParents().filter((Y)=>Y instanceof EW)}function QB5(Z){let J=YB5(Z),X=Z.getParentNode();if(!X)return Z;Z.setMatrix(Z.getWorldMatrix()),X.removeChild(Z);for(let $ of J)$.addChild(Z);return Z}var iW=typeof Float32Array!=="undefined"?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var Z=0,J=arguments.length;while(J--)Z+=arguments[J]*arguments[J];return Math.sqrt(Z)};function WB5(Z,J){var X=J[0],$=J[1],Y=J[2],Q=J[3],W=J[4],K=J[5],G=J[6],V=J[7],H=J[8],q=J[9],z=J[10],F=J[11],U=J[12],L=J[13],B=J[14],w=J[15],O=X*K-$*W,M=X*G-Y*W,N=X*V-Q*W,P=$*G-Y*K,D=$*V-Q*K,C=Y*V-Q*G,T=H*L-q*U,k=H*B-z*U,A=H*w-F*U,v=q*B-z*L,x=q*w-F*L,I=z*w-F*B,S=O*I-M*x+N*v+P*A-D*k+C*T;if(!S)return null;return S=1/S,Z[0]=(K*I-G*x+V*v)*S,Z[1]=(Y*x-$*I-Q*v)*S,Z[2]=(L*C-B*D+w*P)*S,Z[3]=(z*D-q*C-F*P)*S,Z[4]=(G*A-W*I-V*k)*S,Z[5]=(X*I-Y*A+Q*k)*S,Z[6]=(B*N-U*C-w*M)*S,Z[7]=(H*C-z*N+F*M)*S,Z[8]=(W*x-K*A+V*T)*S,Z[9]=($*A-X*x-Q*T)*S,Z[10]=(U*D-L*N+w*O)*S,Z[11]=(q*N-H*D-F*O)*S,Z[12]=(K*k-W*v-G*T)*S,Z[13]=(X*v-$*k+Y*T)*S,Z[14]=(L*M-U*P-B*O)*S,Z[15]=(H*P-q*M+z*O)*S,Z}function KB5(Z){var J=Z[0],X=Z[1],$=Z[2],Y=Z[3],Q=Z[4],W=Z[5],K=Z[6],G=Z[7],V=Z[8],H=Z[9],q=Z[10],z=Z[11],F=Z[12],U=Z[13],L=Z[14],B=Z[15],w=J*W-X*Q,O=J*K-$*Q,M=J*G-Y*Q,N=X*K-$*W,P=X*G-Y*W,D=$*G-Y*K,C=V*U-H*F,T=V*L-q*F,k=V*B-z*F,A=H*L-q*U,v=H*B-z*U,x=q*B-z*L;return w*x-O*v+M*A+N*k-P*T+D*C}function ei(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=J[3],K=J[4],G=J[5],V=J[6],H=J[7],q=J[8],z=J[9],F=J[10],U=J[11],L=J[12],B=J[13],w=J[14],O=J[15],M=X[0],N=X[1],P=X[2],D=X[3];return Z[0]=M*$+N*K+P*q+D*L,Z[1]=M*Y+N*G+P*z+D*B,Z[2]=M*Q+N*V+P*F+D*w,Z[3]=M*W+N*H+P*U+D*O,M=X[4],N=X[5],P=X[6],D=X[7],Z[4]=M*$+N*K+P*q+D*L,Z[5]=M*Y+N*G+P*z+D*B,Z[6]=M*Q+N*V+P*F+D*w,Z[7]=M*W+N*H+P*U+D*O,M=X[8],N=X[9],P=X[10],D=X[11],Z[8]=M*$+N*K+P*q+D*L,Z[9]=M*Y+N*G+P*z+D*B,Z[10]=M*Q+N*V+P*F+D*w,Z[11]=M*W+N*H+P*U+D*O,M=X[12],N=X[13],P=X[14],D=X[15],Z[12]=M*$+N*K+P*q+D*L,Z[13]=M*Y+N*G+P*z+D*B,Z[14]=M*Q+N*V+P*F+D*w,Z[15]=M*W+N*H+P*U+D*O,Z}function GB5(){var Z=new iW(9);if(iW!=Float32Array)Z[1]=0,Z[2]=0,Z[3]=0,Z[5]=0,Z[6]=0,Z[7]=0;return Z[0]=1,Z[4]=1,Z[8]=1,Z}function VB5(Z,J){return Z[0]=J[0],Z[1]=J[1],Z[2]=J[2],Z[3]=J[4],Z[4]=J[5],Z[5]=J[6],Z[6]=J[8],Z[7]=J[9],Z[8]=J[10],Z}function HB5(Z,J){if(Z===J){var X=J[1],$=J[2],Y=J[5];Z[1]=J[3],Z[2]=J[6],Z[3]=X,Z[5]=J[7],Z[6]=$,Z[7]=Y}else Z[0]=J[0],Z[1]=J[3],Z[2]=J[6],Z[3]=J[1],Z[4]=J[4],Z[5]=J[7],Z[6]=J[2],Z[7]=J[5],Z[8]=J[8];return Z}function qB5(Z,J){var X=J[0],$=J[1],Y=J[2],Q=J[3],W=J[4],K=J[5],G=J[6],V=J[7],H=J[8],q=H*W-K*V,z=-H*Q+K*G,F=V*Q-W*G,U=X*q+$*z+Y*F;if(!U)return null;return U=1/U,Z[0]=q*U,Z[1]=(-H*$+Y*V)*U,Z[2]=(K*$-Y*W)*U,Z[3]=z*U,Z[4]=(H*X-Y*G)*U,Z[5]=(-K*X+Y*Q)*U,Z[6]=F*U,Z[7]=(-V*X+$*G)*U,Z[8]=(W*X-$*Q)*U,Z}function yU(){var Z=new iW(3);if(iW!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function zB5(Z,J,X){return Z[0]=J[0]*X[0],Z[1]=J[1]*X[1],Z[2]=J[2]*X[2],Z}function Zn(Z,J){var X=J[0],$=J[1],Y=J[2],Q=X*X+$*$+Y*Y;if(Q>0)Q=1/Math.sqrt(Q);return Z[0]=J[0]*Q,Z[1]=J[1]*Q,Z[2]=J[2]*Q,Z}function FB5(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=X[3]*$+X[7]*Y+X[11]*Q+X[15];return W=W||1,Z[0]=(X[0]*$+X[4]*Y+X[8]*Q+X[12])/W,Z[1]=(X[1]*$+X[5]*Y+X[9]*Q+X[13])/W,Z[2]=(X[2]*$+X[6]*Y+X[10]*Q+X[14])/W,Z}function UB5(Z,J,X){var $=J[0],Y=J[1],Q=J[2];return Z[0]=$*X[0]+Y*X[3]+Q*X[6],Z[1]=$*X[1]+Y*X[4]+Q*X[7],Z[2]=$*X[2]+Y*X[5]+Q*X[8],Z}var BB5=zB5;(function(){var Z=yU();return function(J,X,$,Y,Q,W){var K,G;if(!X)X=3;if(!$)$=0;if(Y)G=Math.min(Y*X+$,J.length);else G=J.length;for(K=$;K<G;K+=X)Z[0]=J[K],Z[1]=J[K+1],Z[2]=J[K+2],Q(Z,Z,W),J[K]=Z[0],J[K+1]=Z[1],J[K+2]=Z[2];return J}})();var FX="dedup",EP={keepUniqueNames:!1,propertyTypes:[n.ACCESSOR,n.MESH,n.TEXTURE,n.MATERIAL,n.SKIN]};function Jn(Z=EP){let J=XJ(EP,Z),X=new Set(J.propertyTypes);for(let $ of J.propertyTypes)if(!EP.propertyTypes.includes($))throw new Error(`${FX}: Unsupported deduplication on type "${$}".`);return BX(FX,($)=>{let Y=$.getLogger();if(X.has(n.ACCESSOR))LB5($);if(X.has(n.TEXTURE))OB5($,J);if(X.has(n.MATERIAL))NB5($,J);if(X.has(n.MESH))wB5($,J);if(X.has(n.SKIN))jB5($,J);Y.debug(`${FX}: Complete.`)})}function LB5(Z){let J=Z.getLogger(),X=new Map,$=new Map,Y=new Map,Q=new Map,W=Z.getRoot().listMeshes();W.forEach((q)=>{q.listPrimitives().forEach((z)=>{z.listAttributes().forEach((F)=>K(F,$)),K(z.getIndices(),X)})});for(let q of Z.getRoot().listAnimations())for(let z of q.listSamplers())K(z.getInput(),Y),K(z.getOutput(),Q);function K(q,z){if(!q)return;let F=[q.getCount(),q.getType(),q.getComponentType(),q.getNormalized(),q.getSparse()].join(":"),U=z.get(F);if(!U)z.set(F,U=new Set);U.add(q)}function G(q,z){for(let F=0;F<q.length;F++){let U=q[F],L=r0.toView(U.getArray());if(z.has(U))continue;for(let B=F+1;B<q.length;B++){let w=q[B];if(z.has(w))continue;if(r0.equals(L,r0.toView(w.getArray())))z.set(w,U)}}}let V=0,H=new Map;for(let q of[$,X,Y,Q])for(let z of q.values())V+=z.size,G(Array.from(z),H);J.debug(`${FX}: Merged ${H.size} of ${V} accessors.`),W.forEach((q)=>{q.listPrimitives().forEach((z)=>{z.listAttributes().forEach((U)=>{if(H.has(U))z.swap(U,H.get(U))});let F=z.getIndices();if(F&&H.has(F))z.swap(F,H.get(F))})});for(let q of Z.getRoot().listAnimations())for(let z of q.listSamplers()){let F=z.getInput(),U=z.getOutput();if(F&&H.has(F))z.swap(F,H.get(F));if(U&&H.has(U))z.swap(U,H.get(U))}Array.from(H.keys()).forEach((q)=>q.dispose())}function wB5(Z,J){let X=Z.getLogger(),$=Z.getRoot(),Y=new Map;$.listAccessors().forEach((K,G)=>Y.set(K,G)),$.listMaterials().forEach((K,G)=>Y.set(K,G));let Q=$.listMeshes().length,W=new Map;for(let K of $.listMeshes()){let G=[];for(let H of K.listPrimitives())G.push(Xn(H,Y));let V="";if(J.keepUniqueNames)V+=K.getName()+";";if(V+=G.join(";"),W.has(V)){let H=W.get(V);K.listParents().forEach((q)=>{if(q.propertyType!==n.ROOT)q.swap(K,H)}),K.dispose()}else W.set(V,K)}X.debug(`${FX}: Merged ${Q-W.size} of ${Q} meshes.`)}function OB5(Z,J){let X=Z.getLogger(),$=Z.getRoot(),Y=$.listTextures(),Q=new Map;for(let W=0;W<Y.length;W++){let K=Y[W],G=K.getImage();if(Q.has(K))continue;for(let V=W+1;V<Y.length;V++){let H=Y[V],q=H.getImage();if(Q.has(H))continue;if(K.getMimeType()!==H.getMimeType())continue;if(J.keepUniqueNames&&K.getName()!==H.getName())continue;let z=K.getSize(),F=H.getSize();if(!z||!F)continue;if(z[0]!==F[0])continue;if(z[1]!==F[1])continue;if(!G||!q)continue;if(r0.equals(G,q))Q.set(H,K)}}X.debug(`${FX}: Merged ${Q.size} of ${$.listTextures().length} textures.`),Array.from(Q.entries()).forEach(([W,K])=>{W.listParents().forEach((G)=>{if(!(G instanceof ZY))G.swap(W,K)}),W.dispose()})}function NB5(Z,J){let X=Z.getLogger(),Y=Z.getRoot().listMaterials(),Q=new Map,W=new Map,K=new Set;if(!J.keepUniqueNames)K.add("name");for(let G=0;G<Y.length;G++){let V=Y[G];if(Q.has(V))continue;if(Si(V,W))continue;for(let H=G+1;H<Y.length;H++){let q=Y[H];if(Q.has(q))continue;if(Si(q,W))continue;if(V.equals(q,K))Q.set(q,V)}}X.debug(`${FX}: Merged ${Q.size} of ${Y.length} materials.`),Array.from(Q.entries()).forEach(([G,V])=>{G.listParents().forEach((H)=>{if(!(H instanceof ZY))H.swap(G,V)}),G.dispose()})}function jB5(Z,J){let X=Z.getLogger(),Y=Z.getRoot().listSkins(),Q=new Map,W=new Set(["joints"]);if(!J.keepUniqueNames)W.add("name");for(let K=0;K<Y.length;K++){let G=Y[K];if(Q.has(G))continue;for(let V=K+1;V<Y.length;V++){let H=Y[V];if(Q.has(H))continue;if(G.equals(H,W)&&eU5(G.listJoints(),H.listJoints()))Q.set(H,G)}}X.debug(`${FX}: Merged ${Q.size} of ${Y.length} skins.`),Array.from(Q.entries()).forEach(([K,G])=>{K.listParents().forEach((V)=>{if(!(V instanceof ZY))V.swap(K,G)}),K.dispose()})}function Xn(Z,J){let X=[];for(let $ of Z.listSemantics()){let Y=Z.getAttribute($);X.push($+":"+J.get(Y))}if(Z instanceof O8){let $=Z.getIndices();if($)X.push("indices:"+J.get($));let Y=Z.getMaterial();if(Y)X.push("material:"+J.get(Y));X.push("mode:"+Z.getMode());for(let Q of Z.listTargets())X.push("target:"+Xn(Q,J))}return X.join(",")}function Si(Z,J){if(J.has(Z))return J.get(Z);let X=Z.getGraph(),$=new Set,Y=X.listParentEdges(Z);while(Y.length>0){let Q=Y.pop();if(Q.getAttributes().modifyChild===!0)return J.set(Z,!0),!0;let W=Q.getChild();if($.has(W))continue;for(let K of X.listChildEdges(W))Y.push(K)}return J.set(Z,!1),!1}function $n(){var Z=new iW(4);if(iW!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0,Z[3]=0;return Z}function MB5(Z,J,X){return Z[0]=J[0]+X[0],Z[1]=J[1]+X[1],Z[2]=J[2]+X[2],Z[3]=J[3]+X[3],Z}function RB5(Z,J,X){return Z[0]=J[0]-X[0],Z[1]=J[1]-X[1],Z[2]=J[2]-X[2],Z[3]=J[3]-X[3],Z}function DB5(Z,J,X){return Z[0]=J[0]*X[0],Z[1]=J[1]*X[1],Z[2]=J[2]*X[2],Z[3]=J[3]*X[3],Z}function PB5(Z,J,X){return Z[0]=J[0]*X,Z[1]=J[1]*X,Z[2]=J[2]*X,Z[3]=J[3]*X,Z}function CB5(Z){var J=Z[0],X=Z[1],$=Z[2],Y=Z[3];return Math.hypot(J,X,$,Y)}var Yn=RB5,TB5=DB5,Qn=CB5;(function(){var Z=$n();return function(J,X,$,Y,Q,W){var K,G;if(!X)X=4;if(!$)$=0;if(Y)G=Math.min(Y*X+$,J.length);else G=J.length;for(K=$;K<G;K+=X)Z[0]=J[K],Z[1]=J[K+1],Z[2]=J[K+2],Z[3]=J[K+3],Q(Z,Z,W),J[K]=Z[0],J[K+1]=Z[1],J[K+2]=Z[2],J[K+3]=Z[3];return J}})();var kB5=/color|emissive|diffuse/i;function EB5(Z){return Z.getGraph().listParentEdges(Z).some((Y)=>{return Y.getAttributes().isColor||kB5.test(Y.getName())})?"srgb":null}function IB5(Z){let J=Z.getGraph(),X=new Set,$=new Set;function Y(Q){let W=new Set;for(let K of J.listChildEdges(Q))if(K.getChild()instanceof e$)W.add(K.getName()+"Info");for(let K of J.listChildEdges(Q)){let G=K.getChild();if(X.has(G))continue;if(X.add(G),G instanceof Q7&&W.has(K.getName()))$.add(G);else if(G instanceof kW)Y(G)}}return Y(Z),Array.from($)}function vB5(Z){let X=F6.fromGraph(Z.getGraph()).getRoot(),$=Z.getGraph().listParentEdges(Z).filter((Y)=>Y.getParent()!==X).map((Y)=>Y.getName());return Array.from(new Set($))}var lW="prune",_P=0.011764705882352941,_i={propertyTypes:[n.NODE,n.SKIN,n.MESH,n.CAMERA,n.PRIMITIVE,n.PRIMITIVE_TARGET,n.ANIMATION,n.MATERIAL,n.TEXTURE,n.ACCESSOR,n.BUFFER],keepLeaves:!1,keepAttributes:!1,keepIndices:!1,keepSolidTextures:!1,keepExtras:!1};function gU(Z=_i){let J=XJ(_i,Z),X=new Set(J.propertyTypes),$=J.keepExtras;return BX(lW,async(Y)=>{let Q=Y.getLogger(),W=Y.getRoot(),K=Y.getGraph(),G=new Wn,V=(H)=>G.dispose(H.target);if(K.addEventListener("node:dispose",V),X.has(n.MESH))for(let H of W.listMeshes()){if(H.listPrimitives().length>0)continue;H.dispose()}if(X.has(n.NODE)){if(!J.keepLeaves)for(let H of W.listScenes())Kn(K,H,$);for(let H of W.listNodes())U9(H,$)}if(X.has(n.SKIN))for(let H of W.listSkins())U9(H,$);if(X.has(n.MESH))for(let H of W.listMeshes())U9(H,$);if(X.has(n.CAMERA))for(let H of W.listCameras())U9(H,$);if(X.has(n.PRIMITIVE))Ai(K,n.PRIMITIVE,$);if(X.has(n.PRIMITIVE_TARGET))Ai(K,n.PRIMITIVE_TARGET,$);if(!J.keepAttributes&&X.has(n.ACCESSOR)){let H=new Map;for(let q of W.listMeshes())for(let z of q.listPrimitives()){let F=z.getMaterial();if(!F)continue;let U=Gn(Y,z,F),L=_B5(z,U);xi(z,L),z.listTargets().forEach((B)=>xi(B,L)),H.has(F)?H.get(F).add(z):H.set(F,new Set([z]))}for(let[q,z]of H)AB5(q,Array.from(z))}if(!J.keepIndices&&X.has(n.ACCESSOR))for(let H of W.listMeshes())for(let q of H.listPrimitives())SB5(q);if(X.has(n.ANIMATION))for(let H of W.listAnimations()){for(let q of H.listChannels())if(!q.getTargetNode())q.dispose();if(!H.listChannels().length){let q=H.listSamplers();U9(H,$),q.forEach((z)=>U9(z,$))}else H.listSamplers().forEach((q)=>U9(q,$))}if(X.has(n.MATERIAL))W.listMaterials().forEach((H)=>U9(H,$));if(X.has(n.TEXTURE)){if(W.listTextures().forEach((H)=>U9(H,$)),!J.keepSolidTextures)await xB5(Y)}if(X.has(n.ACCESSOR))W.listAccessors().forEach((H)=>U9(H,$));if(X.has(n.BUFFER))W.listBuffers().forEach((H)=>U9(H,$));if(K.removeEventListener("node:dispose",V),!G.empty()){let H=G.entries().map(([q,z])=>`${q} (${z})`).join(", ");Q.info(`${lW}: Removed types... ${H}`)}else Q.debug(`${lW}: No unused properties found.`);Q.debug(`${lW}: Complete.`)})}class Wn{constructor(){this.disposed={}}empty(){for(let Z in this.disposed)return!1;return!0}entries(){return Object.entries(this.disposed)}dispose(Z){this.disposed[Z.propertyType]=this.disposed[Z.propertyType]||0,this.disposed[Z.propertyType]++}}function U9(Z,J){let X=Z.listParents().filter((Y)=>!(Y instanceof ZY||Y instanceof o$)),$=J&&!ri(Z.getExtras());if(!X.length&&!$)Z.dispose()}function Ai(Z,J,X){for(let $ of Z.listEdges()){let Y=$.getParent();if(Y.propertyType===J)U9(Y,X)}}function Kn(Z,J,X){if(J.listChildren().forEach((W)=>Kn(Z,W,X)),J instanceof EW)return;let $=Z.listParentEdges(J).some((W)=>{let K=W.getParent().propertyType;return K!==n.ROOT&&K!==n.SCENE&&K!==n.NODE}),Y=Z.listChildren(J).length===0,Q=X&&!ri(J.getExtras());if(Y&&!$&&!Q)J.dispose()}function xi(Z,J){for(let X of J)Z.setAttribute(X,null)}function SB5(Z){let J=Z.getIndices(),X=J&&J.getArray(),$=Z.listAttributes()[0];if(!X||!$)return;if(J.getCount()!==$.getCount())return;for(let Y=0,Q=X.length;Y<Q;Y++)if(Y!==X[Y])return;Z.setIndices(null)}function _B5(Z,J){let X=[];for(let $ of Z.listSemantics())if($==="NORMAL"&&!J.has($))X.push($);else if($==="TANGENT"&&!J.has($))X.push($);else if($.startsWith("TEXCOORD_")&&!J.has($))X.push($);else if($.startsWith("COLOR_")&&$!=="COLOR_0")X.push($);return X}function Gn(Z,J,X,$=new Set){let Q=Z.getGraph().listChildEdges(X),W=new Set;for(let V of Q)if(V.getChild()instanceof e$)W.add(V.getName());for(let V of Q){let H=V.getName(),q=V.getChild();if(q instanceof Q7){if(W.has(H.replace(/Info$/,"")))$.add(`TEXCOORD_${q.getTexCoord()}`)}if(q instanceof e$&&H.match(/normalTexture/i))$.add("TANGENT");if(q instanceof kW)Gn(Z,J,q,$)}let K=X instanceof nZ&&!X.getExtension("KHR_materials_unlit"),G=J.getMode()===O8.Mode.POINTS;if(K&&!G)$.add("NORMAL");return $}function AB5(Z,J){let X=IB5(Z),$=new Set(X.map((G)=>G.getTexCoord())),Y=Array.from($).sort(),Q=new Map(Y.map((G,V)=>[G,V])),W=new Map(Y.map((G,V)=>[`TEXCOORD_${G}`,`TEXCOORD_${V}`]));for(let G of X){let V=G.getTexCoord();G.setTexCoord(Q.get(V))}for(let G of J){let V=G.listSemantics().filter((H)=>H.startsWith("TEXCOORD_")).sort();K(G,V),G.listTargets().forEach((H)=>K(H,V))}function K(G,V){for(let H of V){let q=G.getAttribute(H);if(!q)continue;let z=W.get(H);if(z===H)continue;G.setAttribute(z,q),G.setAttribute(H,null)}}}async function xB5(Z){let J=Z.getRoot(),X=Z.getGraph(),$=Z.getLogger(),Q=J.listTextures().map(async(W)=>{var K;let G=await hB5(W);if(!G)return;if(EB5(W)==="srgb")bR.convertSRGBToLinear(G,G);let V=W.getName()||W.getURI(),H=(K=W.getSize())==null?void 0:K.join("x"),q=vB5(W);for(let z of X.listParentEdges(W)){let F=z.getParent();if(F!==J&&fB5(F,G,z.getName(),$))z.dispose()}if(W.listParents().length===1)W.dispose(),$.debug(`${lW}: Removed solid-color texture "${V}" (${H}px ${q.join(", ")})`)});await Promise.all(Q)}function fB5(Z,J,X,$){if(Z instanceof nZ)switch(X){case"baseColorTexture":return Z.setBaseColorFactor(TB5(J,J,Z.getBaseColorFactor())),!0;case"emissiveTexture":return Z.setEmissiveFactor(BB5([0,0,0],J.slice(0,3),Z.getEmissiveFactor())),!0;case"occlusionTexture":return Math.abs(J[0]-1)<=_P;case"metallicRoughnessTexture":return Z.setRoughnessFactor(J[1]*Z.getRoughnessFactor()),Z.setMetallicFactor(J[2]*Z.getMetallicFactor()),!0;case"normalTexture":return Qn(Yn($n(),J,[0.5,0.5,1,1]))<=_P}return $.warn(`${lW}: Detected single-color ${X} texture. Pruning ${X} not yet supported.`),!1}async function hB5(Z){let J=await bB5(Z);if(!J)return null;let X=[1/0,1/0,1/0,1/0],$=[-1/0,-1/0,-1/0,-1/0],Y=[0,0,0,0],[Q,W]=J.shape;for(let K=0;K<Q;K++){for(let G=0;G<W;G++)for(let V=0;V<4;V++)X[V]=Math.min(X[V],J.get(K,G,V)),$[V]=Math.max($[V],J.get(K,G,V));if(Qn(Yn(Y,$,X))/255>_P)return null}return PB5(Y,MB5(Y,$,X),0.00196078431372549)}async function bB5(Z){try{return await np(Z.getImage(),Z.getMimeType())}catch(J){return null}}var zX=4294967295;class Vn{constructor(Z){this.attributes=[],this.u8=void 0,this.u32=void 0;let J=0;for(let X of yP(Z))J+=this._initAttribute(X);this.u8=new Uint8Array(J),this.u32=new Uint32Array(this.u8.buffer)}_initAttribute(Z){let J=Z.getArray(),X=new Uint8Array(J.buffer,J.byteOffset,J.byteLength),$=Z.getElementSize()*Z.getComponentSize(),Y=r0.padNumber($);return this.attributes.push({u8:X,byteStride:$,paddedByteStride:Y}),Y}hash(Z){let J=0;for(let{u8:X,byteStride:$,paddedByteStride:Y}of this.attributes){for(let Q=0;Q<Y;Q++)if(Q<$)this.u8[J+Q]=X[Z*$+Q];else this.u8[J+Q]=0;J+=Y}return yB5(0,this.u32)}equal(Z,J){for(let{u8:X,byteStride:$}of this.attributes)for(let Y=0;Y<$;Y++)if(X[Z*$+Y]!==X[J*$+Y])return!1;return!0}}function yB5(Z,J){for(let Y=0,Q=J.length;Y<Q;Y++){let W=J[Y];W=Math.imul(W,1540483477)>>>0,W=(W^W>>24)>>>0,W=Math.imul(W,1540483477)>>>0,Z=Math.imul(Z,1540483477)>>>0,Z=(Z^W)>>>0}return Z}function gB5(Z,J,X,$,Y=zX){let Q=J-1,K=X.hash($)&Q;for(let G=0;G<=Q;G++){let V=Z[K];if(V===Y||X.equal(V,$))return K;K=K+G+1&Q}throw new Error("Hash table full.")}var X6;(function(Z){Z.RENDER="render",Z.RENDER_CACHED="render-cached",Z.UPLOAD="upload",Z.UPLOAD_NAIVE="upload-naive",Z.DISTINCT="distinct",Z.DISTINCT_POSITION="distinct-position",Z.UNUSED="unused"})(X6||(X6={}));function UX(Z,J){let X=Z.getAttribute("POSITION"),$=Z.getIndices();switch(J){case X6.RENDER:return $?$.getCount():X.getCount();case X6.RENDER_CACHED:return $?new Set($.getArray()).size:X.getCount();case X6.UPLOAD_NAIVE:case X6.UPLOAD:return X.getCount();case X6.DISTINCT:case X6.DISTINCT_POSITION:return mB5(J);case X6.UNUSED:return $?X.getCount()-new Set($.getArray()).size:0;default:return dB5(J)}}function mB5(Z){throw new Error(`Not implemented: ${Z}`)}function dB5(Z){throw new Error(`Unexpected value: ${Z}`)}function eG(Z,J,X){let $=F6.fromGraph(Z.getGraph());if(!J||!X)[J,X]=uB5(Z);let Y=Z.getIndices(),Q=Y?Y.getArray():null,W=UX(Z,X6.RENDER),K=$.createAccessor(),G=W,V=gP(G,X);for(let q=0;q<G;q++)V[q]=J[Q?Q[q]:q];Z.setIndices(K.setArray(V));let H=yP(Z);for(let q of Z.listAttributes()){let z=tJ($,q);AP(q,Y,J,z,X),Z.swap(q,z)}for(let q of Z.listTargets())for(let z of q.listAttributes()){let F=tJ($,z);AP(z,Y,J,F,X),q.swap(z,F)}if(Y&&Y.listParents().length===1)Y.dispose();for(let q of H)if(q.listParents().length===1)q.dispose();return Z}function AP(Z,J,X,$,Y){let Q=Z.getElementSize(),W=Z.getArray(),K=J?J.getArray():null,G=J?J.getCount():Z.getCount(),V=new W.constructor(Y*Q),H=new Uint8Array(Y);for(let q=0;q<G;q++){let z=K?K[q]:q,F=X[z];if(H[F])continue;for(let U=0;U<Q;U++)V[F*Q+U]=W[z*Q+U];H[F]=1}return $.setArray(V)}function uB5(Z){let J=UX(Z,X6.UPLOAD),X=Z.getIndices(),$=X?X.getArray():null;if(!X||!$)return[ZB5(J,1e6),J];let Y=new Uint32Array(J).fill(zX),Q=0;for(let W=0;W<$.length;W++){let K=$[W];if(Y[K]===zX)Y[K]=Q++}return[Y,Q]}var xP="weld",xU={overwrite:!0,cleanup:!0};function mP(Z=xU){let J=XJ(xU,Z);return BX(xP,async(X)=>{let $=X.getLogger();for(let Y of X.getRoot().listMeshes()){for(let Q of Y.listPrimitives())if(mU(Q,J),UX(Q,X6.RENDER)===0)Q.dispose();if(Y.listPrimitives().length===0)Y.dispose()}if(J.cleanup)await X.transform(gU({propertyTypes:[n.ACCESSOR,n.NODE],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}),Jn({propertyTypes:[n.ACCESSOR]}));$.debug(`${xP}: Complete.`)})}function mU(Z,J=xU){let X=Z.getGraph(),Y=F6.fromGraph(X).getLogger(),Q=pW({},xU,J);if(Z.getIndices()&&!Q.overwrite)return;if(Z.getMode()===O8.Mode.POINTS)return;let W=Z.getAttribute("POSITION").getCount(),K=Z.getIndices(),G=K==null?void 0:K.getArray(),V=K?K.getCount():W,H=new Vn(Z),q=XB5(W+W/4),z=new Uint32Array(q).fill(zX),F=new Uint32Array(W).fill(zX),U=0;for(let L=0;L<V;L++){let B=G?G[L]:L;if(F[B]!==zX)continue;let w=gB5(z,q,H,B,zX),O=z[w];if(O===zX)z[w]=B,F[B]=U++;else F[B]=F[O]}Y.debug(`${xP}: ${bU(W,U)} vertices.`),eG(Z,F,U)}var{FLOAT:cB5}=f0.ComponentType;function Hn(Z,J){let X=Z.getAttribute("POSITION");if(X)fi(J,X);let $=Z.getAttribute("NORMAL");if($)hi(J,$);let Y=Z.getAttribute("TANGENT");if(Y)bi(J,Y);for(let Q of Z.listTargets()){let W=Q.getAttribute("POSITION");if(W)fi(J,W);let K=Q.getAttribute("NORMAL");if(K)hi(J,K);let G=Q.getAttribute("TANGENT");if(G)bi(J,G)}if(KB5(J)<0)lB5(Z)}function fi(Z,J){let X=J.getComponentType(),$=J.getNormalized(),Y=J.getArray(),Q=X===cB5?Y:new Float32Array(Y.length),W=yU();for(let K=0,G=J.getCount();K<G;K++){if($)W[0]=i0.decodeNormalizedInt(Y[K*3],X),W[1]=i0.decodeNormalizedInt(Y[K*3+1],X),W[2]=i0.decodeNormalizedInt(Y[K*3+2],X);else W[0]=Y[K*3],W[1]=Y[K*3+1],W[2]=Y[K*3+2];FB5(W,W,Z),Q[K*3]=W[0],Q[K*3+1]=W[1],Q[K*3+2]=W[2]}J.setArray(Q).setNormalized(!1)}function hi(Z,J){let X=J.getArray(),$=J.getNormalized(),Y=J.getComponentType(),Q=GB5();VB5(Q,Z),qB5(Q,Q),HB5(Q,Q);let W=yU();for(let K=0,G=J.getCount();K<G;K++){if($)W[0]=i0.decodeNormalizedInt(X[K*3],Y),W[1]=i0.decodeNormalizedInt(X[K*3+1],Y),W[2]=i0.decodeNormalizedInt(X[K*3+2],Y);else W[0]=X[K*3],W[1]=X[K*3+1],W[2]=X[K*3+2];if(UB5(W,W,Q),Zn(W,W),$)X[K*3]=i0.decodeNormalizedInt(W[0],Y),X[K*3+1]=i0.decodeNormalizedInt(W[1],Y),X[K*3+2]=i0.decodeNormalizedInt(W[2],Y);else X[K*3]=W[0],X[K*3+1]=W[1],X[K*3+2]=W[2]}}function bi(Z,J){let X=J.getArray(),$=J.getNormalized(),Y=J.getComponentType(),Q=yU();for(let W=0,K=J.getCount();W<K;W++){if($)Q[0]=i0.decodeNormalizedInt(X[W*4],Y),Q[1]=i0.decodeNormalizedInt(X[W*4+1],Y),Q[2]=i0.decodeNormalizedInt(X[W*4+2],Y);else Q[0]=X[W*4],Q[1]=X[W*4+1],Q[2]=X[W*4+2];if(Q[0]=Z[0]*Q[0]+Z[4]*Q[1]+Z[8]*Q[2],Q[1]=Z[1]*Q[0]+Z[5]*Q[1]+Z[9]*Q[2],Q[2]=Z[2]*Q[0]+Z[6]*Q[1]+Z[10]*Q[2],Zn(Q,Q),$)X[W*4]=i0.decodeNormalizedInt(Q[0],Y),X[W*4+1]=i0.decodeNormalizedInt(Q[1],Y),X[W*4+2]=i0.decodeNormalizedInt(Q[2],Y);else X[W*4]=Q[0],X[W*4+1]=Q[1],X[W*4+2]=Q[2]}}function lB5(Z){if(Z.getMode()!==O8.Mode.TRIANGLES)return;if(!Z.getIndices())mU(Z);let J=Z.getIndices();for(let X=0,$=J.getCount();X<$;X+=3){let Y=J.getScalar(X),Q=J.getScalar(X+2);J.setScalar(X,Q),J.setScalar(X+2,Y)}}function pB5(Z,J){for(let X of Z.listPrimitives()){let $=iB5(X,Z);if(X!==$)Z.removePrimitive(X).addPrimitive($)}for(let X of Z.listPrimitives())eG(X),Hn(X,J)}function iB5(Z,J){if(Z.listParents().some(($)=>$ instanceof IG&&$!==J))Z=Z.clone();for(let $ of Z.listTargets())if($.listParents().some((Q)=>Q instanceof O8&&Q!==Z))Z.removeTarget($).addTarget($.clone());return Z}var yi=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function qn(Z){let J=Z.getMesh(),X=Z.getMatrix();if(J&&!i0.eq(X,yi))pB5(J,X);for(let $ of Z.listChildren()){let Y=$.getMatrix();ei(Y,Y,X),$.setMatrix(Y)}return Z.setMatrix(yi)}var{LINES:nB5,LINE_STRIP:sB5,LINE_LOOP:aB5,TRIANGLES:rB5,TRIANGLE_STRIP:oB5,TRIANGLE_FAN:tB5}=O8.Mode;function eB5(Z){let J=Z.getGraph(),X=F6.fromGraph(J);if(!Z.getIndices())mU(Z);let $=Z.getIndices(),Y=$.getArray(),Q=ai(Z),K=new $X[$.getComponentType()](Q*2),G=Z.getMode();if(G===sB5)for(let H=0;H<Q;H++)K[H*2]=Y[H],K[H*2+1]=Y[H+1];else if(G===aB5)for(let H=0;H<Q;H++)if(H<Q-1)K[H*2]=Y[H],K[H*2+1]=Y[H+1];else K[H*2]=Y[H],K[H*2+1]=Y[0];else throw new Error("Only LINE_STRIP and LINE_LOOP may be converted to LINES.");Z.setMode(nB5);let V=X.getRoot();if($.listParents().some((H)=>H!==V&&H!==Z))Z.setIndices(tJ(X,$).setArray(K));else $.setArray(K)}function zn(Z){let J=Z.getGraph(),X=F6.fromGraph(J);if(!Z.getIndices())mU(Z);let $=Z.getIndices(),Y=$.getArray(),Q=ai(Z),K=new $X[$.getComponentType()](Q*3),G=Z.getMode();if(G===oB5)for(let H=0,q=Y.length;H<q-2;H++)if(H%2)K[H*3]=Y[H+1],K[H*3+1]=Y[H],K[H*3+2]=Y[H+2];else K[H*3]=Y[H],K[H*3+1]=Y[H+1],K[H*3+2]=Y[H+2];else if(G===tB5)for(let H=0;H<Q;H++)K[H*3]=Y[0],K[H*3+1]=Y[H+1],K[H*3+2]=Y[H+2];else throw new Error("Only TRIANGLE_STRIP and TRIANGLE_FAN may be converted to TRIANGLES.");Z.setMode(rB5);let V=X.getRoot();if($.listParents().some((H)=>H!==V&&H!==Z))Z.setIndices(tJ(X,$).setArray(K));else $.setArray(K)}var gi="dequantize",fU={pattern:/^((?!JOINTS_).)*$/};function Fn(Z=fU){let J=XJ(fU,Z);return BX(gi,(X)=>{let $=X.getLogger();for(let Y of X.getRoot().listMeshes())for(let Q of Y.listPrimitives())ZL5(Q,J);X.createExtension(oG).dispose(),$.debug(`${gi}: Complete.`)})}function ZL5(Z,J=fU){let X=XJ(fU,J);for(let $ of Z.listSemantics())if(X.pattern.test($))fP(Z.getAttribute($));for(let $ of Z.listTargets())for(let Y of $.listSemantics())if(X.pattern.test(Y))fP($.getAttribute(Y))}function fP(Z){let J=Z.getArray();if(!J)return;let X=hU(J,Z.getComponentType(),Z.getNormalized());Z.setArray(X).setNormalized(!1)}function hU(Z,J,X){let $=new Float32Array(Z.length);for(let Y=0,Q=Z.length;Y<Q;Y++)if(X)$[Y]=i0.decodeNormalizedInt(Z[Y],J);else $[Y]=Z[Y];return $}var{TEXTURE_INFO:Un,ROOT:yV6}=n;function Bn(Z){let J=new F6().setLogger(Z.getLogger()),X=dP(J,Z);return JL5(J,Z,X),J.getRoot().copy(Z.getRoot(),X),J}function JL5(Z,J,X){X||(X=dP(Z,J));for(let $ of J.getRoot().listExtensionsUsed()){let Y=Z.createExtension($.constructor);if($.isRequired())Y.setRequired(!0)}return XL5(Z,J,$L5(J),X)}function XL5(Z,J,X,$){$||($=dP(Z,J));let Y=new Map;for(let Q of X)if(!Y.has(Q)&&Q.propertyType!==Un)Y.set(Q,$(Q));for(let[Q,W]of Y.entries())W.copy(Q,$);return Y}function dP(Z,J){let X=new Map([[J.getRoot(),Z.getRoot()]]);return($)=>{if($.propertyType===Un)return $;let Y=X.get($);if(!Y)Y=new $.constructor(Z.getGraph()),X.set($,Y);return Y}}function $L5(Z){let J=new Set;for(let X of Z.getGraph().listEdges())J.add(X.getChild());return Array.from(J)}var IP="flatten",mi={cleanup:!0};function Ln(Z=mi){let J=XJ(mi,Z);return BX(IP,async(X)=>{let $=X.getRoot(),Y=X.getLogger(),Q=new Set;for(let V of $.listSkins())for(let H of V.listJoints())Q.add(H);let W=new Set;for(let V of $.listAnimations())for(let H of V.listChannels()){let q=H.getTargetNode();if(q&&H.getTargetPath()!=="weights")W.add(q)}let K=new Set,G=new Set;for(let V of $.listScenes())V.traverse((H)=>{let q=H.getParentNode();if(!q)return;if(Q.has(q)||K.has(q))K.add(H);if(W.has(q)||G.has(q))G.add(H)});for(let V of $.listScenes())V.traverse((H)=>{if(W.has(H))return;if(K.has(H))return;if(G.has(H))return;QB5(H)});if(W.size)Y.debug(`${IP}: Flattening node hierarchies with TRS animation not yet supported.`);if(J.cleanup)await X.transform(gU({propertyTypes:[n.NODE],keepLeaves:!1}));Y.debug(`${IP}: Complete.`)})}function wn(Z){return hR(Z)}var YL5={skipValidation:!1},di=4294967295,{LINE_STRIP:QL5,LINE_LOOP:WL5,TRIANGLE_STRIP:KL5,TRIANGLE_FAN:GL5}=O8.Mode;function VL5(Z,J={}){let X=XJ(YL5,J),$=Z[0],Y=F6.fromGraph($.getGraph());if(!X.skipValidation&&new Set(Z.map(oi)).size>1)throw new Error("Requires >=2 Primitives, sharing the same Material and Mode, with compatible vertex attributes and indices.");for(let F of Z)switch(F.getMode()){case QL5:case WL5:eB5(F);break;case KL5:case GL5:zn(F);break}let Q=[],W=new Uint32Array(Z.length),K=0,G=0;for(let F=0;F<Z.length;F++){let U=Z[F],L=U.getIndices(),B=U.getAttribute("POSITION").getCount(),w=L?L.getArray():null,O=L?L.getCount():B,M=new Uint32Array(B).fill(di);for(let N=0;N<O;N++){let P=w?w[N]:N;if(M[P]===di)M[P]=K++,W[F]++}Q.push(M),G+=O}let V=Y.createPrimitive().setMode($.getMode()).setMaterial($.getMaterial());for(let F of $.listSemantics()){let U=$.getAttribute(F),L=$X[U.getComponentType()],B=tJ(Y,U).setArray(new L(K*U.getElementSize()));V.setAttribute(F,B)}let H=$.getIndices(),q=H?tJ(Y,H).setArray(gP(G,K)):null;V.setIndices(q);let z=0;for(let F=0;F<Q.length;F++){let U=Z[F],L=U.getIndices(),B=L?L.getCount():-1,w=Q[F];if(L&&q)qL5(L,w,q,z),z+=B;for(let O of V.listSemantics()){let M=U.getAttribute(O),N=V.getAttribute(O);HL5(M,L,w,N)}}return V}function HL5(Z,J,X,$){let Y=Z.getElementSize(),Q=J?J.getArray():null,W=Z.getCount(),K=Z.getArray(),G=$.getArray(),V=new Uint8Array(Z.getCount());for(let H=0,q=J?J.getCount():W;H<q;H++){let z=Q?Q[H]:H,F=X[z];if(V[F])continue;for(let U=0;U<Y;U++)G[F*Y+U]=K[z*Y+U];V[F]=1}}function qL5(Z,J,X,$){let Y=Z.getCount(),Q=Z.getArray(),W=X.getArray();for(let K=0;K<Y;K++){let G=Q[K],V=J[G];W[$+K]=V}}var hP="join",{ROOT:zL5,NODE:FL5,MESH:UL5,PRIMITIVE:BL5,ACCESSOR:LL5}=n,vP=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],ui={keepMeshes:!1,keepNamed:!1,cleanup:!0};function On(Z=ui){let J=XJ(ui,Z);return BX(hP,async(X)=>{let $=X.getRoot(),Y=X.getLogger();for(let Q of $.listScenes())ci(X,Q,J),Q.traverse((W)=>ci(X,W,J));if(J.cleanup)await X.transform(gU({propertyTypes:[FL5,UL5,BL5,LL5],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}));Y.debug(`${hP}: Complete.`)})}function ci(Z,J,X){let $=Z.getLogger(),Y={},Q=J.listChildren();for(let G=0;G<Q.length;G++){let V=Q[G];if(V.listParents().some((z)=>z instanceof o$))continue;let q=V.getMesh();if(!q)continue;if(V.getExtension("EXT_mesh_gpu_instancing"))continue;if(V.getSkin())continue;for(let z of q.listPrimitives()){if(z.listTargets().length>0)continue;let F=z.getMaterial();if(F&&F.getExtension("KHR_materials_volume"))continue;eG(z),OL5(z);let U=oi(z),L=q.getName()||V.getName();if(X.keepMeshes||X.keepNamed&&L)U+=`|${G}`;if(!(U in Y))Y[U]={prims:[],primMeshes:[],primNodes:[],dstNode:V,dstMesh:void 0};let B=Y[U];B.prims.push(z),B.primNodes.push(V)}}let W=Object.values(Y).filter(({prims:G})=>G.length>1),K=new Set(W.flatMap((G)=>G.primNodes));for(let G of K){let V=G.getMesh();if(V.listParents().some((q)=>{return q.propertyType!==zL5&&G!==q}))G.setMesh(V.clone())}for(let G of W){let{dstNode:V,primNodes:H}=G;G.dstMesh=V.getMesh(),G.primMeshes=H.map((q)=>q.getMesh())}for(let G of W){let{prims:V,primNodes:H,primMeshes:q,dstNode:z,dstMesh:F}=G,U=z.getMatrix();for(let w=0;w<V.length;w++){let O=H[w],M=q[w],N=V[w];if(M.removePrimitive(N),JB5(N))N=V[w]=wL5(V[w]);if(O!==z)ei(vP,WB5(vP,U),O.getMatrix()),Hn(N,vP)}let L=VL5(V),B=L.listAttributes()[0].getCount();F.addPrimitive(L),$.debug(`${hP}: Joined Primitives (${V.length}) containing ${SP(B)} vertices under Node "${z.getName()}".`)}}function wL5(Z){let J=Z.clone();for(let $ of J.listSemantics())J.setAttribute($,J.getAttribute($).clone());let X=J.getIndices();if(X)J.setIndices(X.clone());return J}function OL5(Z){for(let J of["POSITION","NORMAL","TANGENT"]){let X=Z.getAttribute(J);if(X)fP(X)}}var{TRANSLATION:gV6,ROTATION:mV6,SCALE:dV6,WEIGHTS:uV6}=o$.TargetPath;var NL5={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12,normalizeWeights:!0,cleanup:!0};var cV6=pW({level:"high"},NL5);var jL5="unweld";function ML5(Z,J=new Map){let X=Z.getIndices();if(!X)return;let $=Z.getGraph(),Y=F6.fromGraph($),Q=Y.getLogger(),W=Z.getAttribute("POSITION").getCount();for(let G of Z.listAttributes())if(Z.swap(G,li(Y,G,X,J)),G.listParents().length===1)G.dispose();for(let G of Z.listTargets())for(let V of G.listAttributes())if(G.swap(V,li(Y,V,X,J)),V.listParents().length===1)V.dispose();let K=Z.getAttribute("POSITION").getCount();if(Q.debug(`${jL5}: ${bU(W,K)} vertices.`),Z.setIndices(null),X.listParents().length===1)X.dispose()}function li(Z,J,X,$){if($.has(J)&&$.get(J).has(X))return $.get(J).get(X);let Y=J.getArray(),W=new Y.constructor(X.getCount()*J.getElementSize()),K=X.getArray(),G=J.getElementSize();for(let H=0,q=X.getCount();H<q;H++)for(let z=0;z<G;z++)W[H*G+z]=Y[K[H]*G+z];if(!$.has(J))$.set(J,new Map);let V=tJ(Z,J).setArray(W);return $.get(J).set(X,V),V}var pi;(function(Z){Z[Z.STEP=0]="STEP",Z[Z.LERP=1]="LERP",Z[Z.SLERP=2]="SLERP"})(pi||(pi={}));var RL5=0.000001;function DL5(Z,J,X,$=0.0001){let Y=J.length/Z.length,Q=new Array(Y).fill(0),W=new Array(Y).fill(0),K=new Array(Y).fill(0),G=new Array(Y).fill(0),V=Z.length-1,H=1;for(let q=1;q<V;++q){let z=Z[H-1],F=Z[q],U=Z[q+1],L=(F-z)/(U-z),B=!1;if(F!==U&&(q!==1||F!==Z[0])){if(tG(J,H-1,G),tG(J,q,W),tG(J,q+1,K),X==="slerp"){let w=TL5(Q,G,K,L),O=ni(G,W)+ni(W,K);B=!AU(W,w,$)||O+Number.EPSILON>=Math.PI}else if(X==="lerp"){let w=CL5(Q,G,K,L);B=!AU(W,w,$)}else if(X==="step")B=!AU(W,G)||!AU(W,K)}if(B){if(q!==H)Z[H]=Z[q],ii(J,H,tG(J,q,Q));H++}}if(V>0)Z[H]=Z[V],ii(J,H,tG(J,V,Q)),H++;return H}function tG(Z,J,X){for(let $=0,Y=X.length;$<Y;$++)X[$]=Z[J*Y+$];return X}function ii(Z,J,X){for(let $=0,Y=X.length;$<Y;$++)Z[J*Y+$]=X[$]}function AU(Z,J,X=0){if(Z.length!==J.length)return!1;for(let $=0;$<Z.length;$++)if(Math.abs(Z[$]-J[$])>X)return!1;return!0}function PL5(Z,J,X){return Z*(1-X)+J*X}function CL5(Z,J,X,$){for(let Y=0;Y<J.length;Y++)Z[Y]=PL5(J[Y],X[Y],$);return Z}function TL5(Z,J,X,$){let Y=J[0],Q=J[1],W=J[2],K=J[3],G=X[0],V=X[1],H=X[2],q=X[3],z,F,U,L,B;if(F=Y*G+Q*V+W*H+K*q,F<0)F=-F,G=-G,V=-V,H=-H,q=-q;if(1-F>RL5)z=Math.acos(F),U=Math.sin(z),L=Math.sin((1-$)*z)/U,B=Math.sin($*z)/U;else L=1-$,B=$;return Z[0]=L*Y+B*G,Z[1]=L*Q+B*V,Z[2]=L*W+B*H,Z[3]=L*K+B*q,Z}function ni(Z,J){let X=kL5(Z,J);return Math.acos(2*X*X-1)}function kL5(Z,J){return Z[0]*J[0]+Z[1]*J[1]+Z[2]*J[2]+Z[3]*J[3]}var lV6=new Float32Array(0),pV6={ready:Promise.resolve(),resample:DL5,tolerance:0.0001,cleanup:!0};var jY="simplify",{POINTS:Nn,LINES:EL5,LINE_STRIP:IL5,LINE_LOOP:vL5,TRIANGLES:SL5,TRIANGLE_STRIP:jn,TRIANGLE_FAN:Mn}=O8.Mode,Rn={ratio:0,error:0.0001,lockBorder:!1,cleanup:!0};function Dn(Z){let J=XJ(Rn,Z),X=J.simplifier;if(!X)throw new Error(`${jY}: simplifier dependency required — install "meshoptimizer".`);return BX(jY,async($)=>{let Y=$.getLogger();await X.ready,await $.transform(mP({overwrite:!1,cleanup:J.cleanup}));let Q=0;for(let W of $.getRoot().listMeshes()){for(let K of W.listPrimitives()){let G=K.getMode();if(G===SL5||G===jn||G===Mn){if(si(K,J),UX(K,X6.RENDER)===0)K.dispose()}else if(K.getMode()===Nn&&!!X.simplifyPoints){if(si(K,J),UX(K,X6.RENDER)===0)K.dispose()}else Q++}if(W.listPrimitives().length===0)W.dispose()}if(Q>0)Y.warn(`${jY}: Skipping simplification of ${Q} primitives: Unsupported draw mode.`);if(J.cleanup)await $.transform(gU({propertyTypes:[n.ACCESSOR,n.NODE],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}),Jn({propertyTypes:[n.ACCESSOR]}));Y.debug(`${jY}: Complete.`)})}function si(Z,J){let X=pW({},Rn,J),$=X.simplifier,Y=Z.getGraph(),Q=F6.fromGraph(Y),W=Q.getLogger();switch(Z.getMode()){case Nn:return _L5(Q,Z,X);case EL5:case IL5:case vL5:return W.warn(`${jY}: Skipping primitive simplification: Unsupported draw mode.`),Z;case jn:case Mn:zn(Z);break}let K=UX(Z,X6.UPLOAD),G=UX(Z,X6.RENDER);if(G<K/2)eG(Z);let V=Z.getAttribute("POSITION"),H=Z.getIndices(),q=V.getArray(),z=H.getArray();if(!(q instanceof Float32Array))q=hU(q,V.getComponentType(),V.getNormalized());if(!(z instanceof Uint32Array))z=new Uint32Array(z);let F=Math.floor(X.ratio*G/3)*3,U=X.lockBorder?["LockBorder"]:[],[L,B]=$.simplify(z,q,3,F,X.error,U);if(Z.setIndices(tJ(Q,H).setArray(L)),H.listParents().length===1)H.dispose();eG(Z);let w=UX(Z,X6.UPLOAD);if(w<=65534)Z.getIndices().setArray(new Uint16Array(Z.getIndices().getArray()));return W.debug(`${jY}: ${bU(K,w)} vertices, error: ${B.toFixed(4)}.`),Z}function _L5(Z,J,X){let $=X.simplifier,Y=Z.getLogger();if(J.getIndices())ML5(J);let W=J.getAttribute("POSITION"),K=J.getAttribute("COLOR_0"),G=W.getCount(),V=W.getArray(),H=K?K.getArray():void 0,q=K?K.getComponentSize():void 0;if(!(V instanceof Float32Array))V=hU(V,W.getComponentType(),W.getNormalized());if(H&&!(H instanceof Float32Array))H=hU(H,W.getComponentType(),W.getNormalized());$.useExperimentalFeatures=!0;let z=Math.floor(X.ratio*G),F=$.simplifyPoints(V,3,z,H,q);$.useExperimentalFeatures=!1;let[U,L]=$.compactMesh(F);Y.debug(`${jY}: ${bU(W.getCount(),L)} vertices.`);for(let B of yP(J)){let w=tJ(Z,B);if(AP(B,null,U,w,L),tU5(J,B,w),B.listParents().length===1)B.dispose()}return J}var bP;(function(Z){Z.LANCZOS3="lanczos3",Z.LANCZOS2="lanczos2"})(bP||(bP={}));var iV6={resizeFilter:bP.LANCZOS3,pattern:void 0,formats:void 0,slots:void 0,quality:void 0,effort:void 0,lossless:!1,nearLossless:!1,limitInputPixels:!0};var vn=e(In(),1);var nW={OPTIMIZED_DIR:".optimized",CHECKSUM_EXT:".md5",DIRECTORIES:[(()=>{try{return x7.dirname(a.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js"))}catch{return null}})(),x7.resolve(process.cwd(),"assets")].filter(Boolean),OPTIMIZER_RUNS:[{suffix:"",options:["--compress","false","--instance","false","--simplify","false"]},{suffix:"-named-nodes",options:["--compress","false","--instance","false","--simplify","false","--join","true","--join-named","false"]}]};class V7{static instance=new V7;optimize=!0;optimizeEveryStart=!1;_modelUriDocuments=new Map;_modelUriBoundingBoxes=new Map;_modelUriNodeNames=new Map;_modelUriTrimeshes=new Map;constructor(){}async preloadModels(){let Z=await this._getAbsoluteModelPaths();console.log(`ModelRegistry.preloadModels(): Preloading ${Z.length} models...`);for(let J of Z){if(this.optimize)await this._resolveOptimizedModelPath(J);await this._loadModelData(J)}console.log(`ModelRegistry.preloadModels(): Preloaded ${Z.length} models!`)}getAnimationNames(Z){let J=this._modelUriDocuments.get(Z);if(!J)u.fatalError(`ModelRegistry.getAnimationNames(): Model ${Z} not found!`);return J.getRoot().listAnimations().map(($)=>$.getName())}getBoundingBox(Z){let J=this._modelUriBoundingBoxes.get(Z);if(!J)u.fatalError(`ModelRegistry.getBoundingBox(): Model ${Z} not found!`);return J}getDepth(Z){let J=this.getBoundingBox(Z);return J.max.z-J.min.z}getHeight(Z){let J=this.getBoundingBox(Z);return J.max.y-J.min.y}getNodeNames(Z){let J=this._modelUriNodeNames.get(Z);if(!J)u.fatalError(`ModelRegistry.getNodeNames(): Model ${Z} not found!`);return J}getTrimesh(Z,J=1){let X=this._modelUriTrimeshes.get(Z);if(!X){u.error(`ModelRegistry.getTrimesh(): Model ${Z} not found!`);return}let $=X.vertices;if(J!==1){$=new Float32Array($.length);for(let Y=0;Y<$.length;Y++)$[Y]=X.vertices[Y]*J}return{vertices:$,indices:X.indices}}getWidth(Z){let J=this.getBoundingBox(Z);return J.max.x-J.min.x}modelHasNode(Z,J){let X=this._modelUriNodeNames.get(Z);if(!X)u.fatalError(`ModelRegistry.modelHasNode(): Model ${Z} not found!`);return X.includes(J)}_absoluteModelPathToModelUri(Z){let J=x7.normalize(Z);for(let X of nW.DIRECTORIES){let $=x7.normalize(X);if(J.startsWith($))return x7.relative($,J).replace(/\\/g,"/")}return x7.basename(J)}async _getAbsoluteModelPaths(){let Z=[];for(let J of nW.DIRECTORIES){let X=x7.resolve(process.cwd(),J);if(!LX.existsSync(X))continue;let $=await kF("**/*.{gltf,glb}",{cwd:X,follow:!0});for(let Y of $)Z.push(x7.join(X,Y))}return Z}async _loadModelData(Z){let J=await new uR().read(Z),X=wn(J.getRoot().listScenes()[0]),$=J.getRoot().listNodes().map((Q)=>Q.getName()),Y=this._absoluteModelPathToModelUri(Z);this._modelUriDocuments.set(Y,J),this._modelUriBoundingBoxes.set(Y,{min:{x:X.min[0],y:X.min[1],z:X.min[2]},max:{x:X.max[0],y:X.max[1],z:X.max[2]}}),this._modelUriNodeNames.set(Y,$),this._modelUriTrimeshes.set(Y,await this._buildTrimesh(Y))}async _resolveOptimizedModelPath(Z){let J=this._buildOptimizedModelPath(Z);if(!this.optimizeEveryStart&&this._isOptimizedVersionValid(Z))return J;return await this._optimizeModel(Z,J)}_isOptimizedVersionValid(Z){let J=`${this._buildOptimizedModelPath(Z)}${nW.CHECKSUM_EXT}`;if(!LX.existsSync(J))return!1;let X=this._calculateChecksum(Z),$=LX.readFileSync(J,"utf8");return X===$}_calculateChecksum(Z){if(!LX.existsSync(Z))return"";let J=LX.readFileSync(Z);return bL5.createHash("sha256").update(J.toString("base64")).digest("hex")}_buildOptimizedModelPath(Z){let J=x7.basename(Z),X=J.replace(/\.[^/.]+$/,""),$=x7.dirname(Z),Y=x7.join($,nW.OPTIMIZED_DIR,X);return x7.join(Y,J)}async _buildTrimesh(Z,J=1,X=0.001){let $=this._modelUriDocuments.get(Z);if(!$)u.fatalError(`ModelRegistry._buildTrimesh(): Model ${Z} not found!`);let Y=Bn($);Y.setLogger(new W7(kG.WARN)),await Y.transform(ti({pivot:"center"}),Ln(),On(),mP(),Dn({simplifier:vn.MeshoptSimplifier,ratio:J,error:X}),Fn());for(let V of Y.getRoot().listScenes())for(let H of V.listChildren())qn(H);let Q=Y.getRoot().listMeshes()[0];if(!Q){u.error(`ModelRegistry._buildTrimesh(): Model ${Z} has no root mesh!`);return}let W=Q.listPrimitives()[0];if(!W){u.error(`ModelRegistry._buildTrimesh(): Model ${Z} has no root primitive!`);return}let K=W.getAttribute("POSITION"),G=W.getIndices();if(!K||!G){u.error(`ModelRegistry._buildTrimesh(): Model ${Z} missing required geometry data!`);return}return{vertices:K.getArray(),indices:G.getArray()}}async _optimizeModel(Z,J){let X=x7.dirname(J);LX.rmSync(X,{recursive:!0,force:!0}),LX.mkdirSync(X,{recursive:!0}),console.log(`ModelRegistry: Optimizing model ${this._absoluteModelPathToModelUri(Z)}...`);for(let $ of nW.OPTIMIZER_RUNS){let Y=J.replace(/(\.[^/.]+)$/,`${$.suffix}$1`),{stderr:Q}=await _d("npx",["@gltf-transform/cli","optimize",Z,Y,...$.options]);if(Q)return u.warning(`ModelRegistry._optimizeModel(): Error optimizing model ${this._absoluteModelPathToModelUri(Z)}, defaulting to unoptimized model. Error: ${Q}`),Z}return LX.writeFileSync(`${J}${nW.CHECKSUM_EXT}`,this._calculateChecksum(Z)),J}}var YV;((Y)=>{Y.DYNAMIC="dynamic";Y.FIXED="fixed";Y.KINEMATIC_POSITION="kinematic_position";Y.KINEMATIC_VELOCITY="kinematic_velocity"})(YV||={});var iP=0.001,Sn="dynamic";class MY extends D0{_additionalMass=0;_colliders=new Set;_explicitSleep=!1;_enabledPositions={x:!0,y:!0,z:!0};_enabledRotations={x:!0,y:!0,z:!0};_rigidBody;_rigidBodyDesc;_rigidBodyType;_simulation;constructor(Z){super();Z.type??=Sn,this._rigidBodyDesc=this._createRigidBodyDesc(Z),this._rigidBodyType=Z.type,this._applyRigidBodyOptions(Z),this._autoAddToSimulation(Z)}get additionalMass(){if(!this._requireNotRemoved("additionalMass"))return 0;return this._additionalMass}get additionalSolverIterations(){if(!this._requireNotRemoved("additionalSolverIterations"))return 0;return this._rigidBody?this._rigidBody.additionalSolverIterations():this._rigidBodyDesc.additionalSolverIterations}get angularDamping(){if(!this._requireNotRemoved("angularDamping"))return 0;return this._rigidBody?this._rigidBody.angularDamping():this._rigidBodyDesc.angularDamping}get angularVelocity(){if(!this._requireNotRemoved("angularVelocity"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.angvel():this._rigidBodyDesc.angvel}get colliders(){return this._colliders}get dominanceGroup(){if(!this._requireNotRemoved("dominanceGroup"))return 0;return this._rigidBody?this._rigidBody.dominanceGroup():this._rigidBodyDesc.dominanceGroup}get directionFromRotation(){let{x:Z,y:J,z:X,w:$}=this.rotation;return{x:-2*(Z*X+$*J),y:-2*(J*X-$*Z),z:-(1-2*(Z*Z+J*J))}}get effectiveAngularInertia(){if(!this._requireNotRemoved("effectiveAngularInertia"))return;return this._rigidBody?this._rigidBody.effectiveAngularInertia():void 0}get effectiveInverseMass(){if(!this._requireNotRemoved("effectiveInverseMass"))return;return this._rigidBody?this._rigidBody.effectiveInvMass():void 0}get effectiveWorldInversePrincipalAngularInertiaSqrt(){if(!this._requireNotRemoved("effectiveWorldInversePrincipalAngularInertiaSqrt"))return;return this._rigidBody?this._rigidBody.effectiveWorldInvInertiaSqrt():void 0}get enabledRotations(){if(!this._requireNotRemoved("enabledRotations"))return{x:!0,y:!0,z:!0};return this._enabledRotations}get enabledPositions(){if(!this._requireNotRemoved("enabledPositions"))return{x:!0,y:!0,z:!0};return this._enabledPositions}get gravityScale(){if(!this._requireNotRemoved("gravityScale"))return 0;return this._rigidBody?this._rigidBody.gravityScale():this._rigidBodyDesc.gravityScale}get inverseMass(){if(!this._requireNotRemoved("inverseMass"))return;return this._rigidBody?this._rigidBody.invMass():void 0}get inversePrincipalAngularInertiaSqrt(){if(!this._requireNotRemoved("inversePrincipalAngularInertiaSqrt"))return;return this._rigidBody?this._rigidBody.invPrincipalInertiaSqrt():void 0}get isCcdEnabled(){if(!this._requireNotRemoved("isCcdEnabled"))return!1;return this._rigidBody?this._rigidBody.isCcdEnabled():this._rigidBodyDesc.ccdEnabled}get isDynamic(){if(!this._requireNotRemoved("isDynamic"))return!1;return this._rigidBodyType==="dynamic"}get isEnabled(){if(!this._requireNotRemoved("isEnabled"))return!1;return this._rigidBody?this._rigidBody.isEnabled():this._rigidBodyDesc.enabled}get isFixed(){if(!this._requireNotRemoved("isFixed"))return!1;return this._rigidBodyType==="fixed"}get isKinematic(){if(!this._requireNotRemoved("isKinematic"))return!1;return["kinematic_position","kinematic_velocity"].includes(this._rigidBodyType)}get isKinematicPositionBased(){if(!this._requireNotRemoved("isKinematicPositionBased"))return!1;return this._rigidBodyType==="kinematic_position"}get isKinematicVelocityBased(){if(!this._requireNotRemoved("isKinematicVelocityBased"))return!1;return this._rigidBodyType==="kinematic_velocity"}get isMoving(){if(!this._requireNotRemoved("isMoving"))return!1;return this._rigidBody?this._rigidBody.isMoving():!1}get isRemoved(){return!this._rigidBody&&!this._rigidBodyDesc}get isSimulated(){if(!this._requireNotRemoved("isSimulated"))return!1;return this._rigidBody?!0:!1}get isSleeping(){if(!this._requireNotRemoved("isSleeping"))return!1;return this._rigidBody?this._rigidBody.isSleeping():this._rigidBodyDesc.sleeping}get linearDamping(){if(!this._requireNotRemoved("linearDamping"))return 0;return this._rigidBody?this._rigidBody.linearDamping():this._rigidBodyDesc.linearDamping}get linearVelocity(){if(!this._requireNotRemoved("linearVelocity"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.linvel():this._rigidBodyDesc.linvel}get localCenterOfMass(){if(!this._requireNotRemoved("localCenterOfMass"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.localCom():this._rigidBodyDesc.centerOfMass}get mass(){if(!this._requireNotRemoved("mass"))return 0;return this._rigidBody?this._rigidBody.mass():this._rigidBodyDesc.mass}get nextKinematicRotation(){if(!this._requireNotRemoved("nextKinematicRotation"))return{x:0,y:0,z:0,w:1};return this._rigidBody?this._rigidBody.nextRotation():this._rigidBodyDesc.rotation}get nextKinematicPosition(){if(!this._requireNotRemoved("nextKinematicPosition"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.nextTranslation():this._rigidBodyDesc.translation}get numColliders(){return this._colliders.size}get principalAngularInertia(){if(!this._requireNotRemoved("principalAngularInertia"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.principalInertia():this._rigidBodyDesc.principalAngularInertia}get principalAngularInertiaLocalFrame(){if(!this._requireNotRemoved("principalAngularInertiaLocalFrame"))return;return this._rigidBody?this._rigidBody.principalInertiaLocalFrame():void 0}get position(){if(!this._requireNotRemoved("position"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.translation():this._rigidBodyDesc.translation}get rawRigidBody(){if(!this._requireNotRemoved("rawRigidBody"))return;return this._rigidBody}get rotation(){if(!this._requireNotRemoved("rotation"))return{x:0,y:0,z:0,w:1};return this._rigidBody?this._rigidBody.rotation():this._rigidBodyDesc.rotation}get softCcdPrediction(){if(!this._requireNotRemoved("softCcdPrediction"))return 0;return this._rigidBody?this._rigidBody.softCcdPrediction():this._rigidBodyDesc.softCcdPrediction}get type(){if(!this._requireNotRemoved("type"))return"dynamic";return this._rigidBodyType}get worldCenterOfMass(){if(!this._requireNotRemoved("worldCenterOfMass"))return;return this._rigidBody?this._rigidBody.worldCom():void 0}setAdditionalMass(Z){if(!this._requireDynamic("setAdditionalMass"))return;if(!this._requireNotRemoved("setAdditionalMass"))return;this._rigidBody?this._rigidBody.setAdditionalMass(Z,!this._explicitSleep):this._rigidBodyDesc.setAdditionalMass(Z)}setAdditionalMassProperties(Z){if(!this._requireDynamic("setAdditionalMassProperties"))return;if(!this._requireNotRemoved("setAdditionalMassProperties"))return;let{additionalMass:J,centerOfMass:X,principalAngularInertia:$,principalAngularInertiaLocalFrame:Y}=Z;this._rigidBody?this._rigidBody.setAdditionalMassProperties(J,X,$,Y,!this._explicitSleep):this._rigidBodyDesc.setAdditionalMassProperties(J,X,$,Y)}setAdditionalSolverIterations(Z){if(!this._requireDynamic("setAdditionalSolverIterations"))return;if(!this._requireNotRemoved("setAdditionalSolverIterations"))return;this._rigidBody?this._rigidBody.setAdditionalSolverIterations(Z):this._rigidBodyDesc.setAdditionalSolverIterations(Z)}setAngularDamping(Z){if(!this._requireDynamic("setAngularDamping"))return;if(!this._requireNotRemoved("setAngularDamping"))return;this._rigidBody?this._rigidBody.setAngularDamping(Z):this._rigidBodyDesc.setAngularDamping(Z)}setAngularVelocity(Z){if(!this._requireNotKinematicPositionBased("setAngularVelocity"))return;if(!this._requireNotRemoved("setAngularVelocity"))return;this._rigidBody?this._rigidBody.setAngvel(Z,!this._explicitSleep):this._rigidBodyDesc.setAngvel(Z)}setCcdEnabled(Z){if(!this._requireDynamic("setCcdEnabled"))return;if(!this._requireNotRemoved("setCcdEnabled"))return;this._rigidBody?this._rigidBody.enableCcd(Z):this._rigidBodyDesc.setCcdEnabled(Z)}setDominanceGroup(Z){if(!this._requireDynamic("setDominanceGroup"))return;if(!this._requireNotRemoved("setDominanceGroup"))return;this._rigidBody?this._rigidBody.setDominanceGroup(Z):this._rigidBodyDesc.setDominanceGroup(Z)}setEnabled(Z){if(!this._requireNotRemoved("setEnabled"))return;this._rigidBody?this._rigidBody.setEnabled(Z):this._rigidBodyDesc.setEnabled(Z)}setEnabledPositions(Z){if(!this._requireDynamic("setEnabledPositions"))return;if(!this._requireNotRemoved("setEnabledPositions"))return;this._rigidBody?this._rigidBody.setEnabledTranslations(Z.x,Z.y,Z.z,!this._explicitSleep):this._rigidBodyDesc.enabledTranslations(Z.x,Z.y,Z.z),this._enabledPositions=Z}setEnabledRotations(Z){if(!this._requireDynamic("setEnabledRotations"))return;if(!this._requireNotRemoved("setEnabledRotations"))return;this._rigidBody?this._rigidBody.setEnabledRotations(Z.x,Z.y,Z.z,!this._explicitSleep):this._rigidBodyDesc.enabledRotations(Z.x,Z.y,Z.z),this._enabledRotations=Z}setGravityScale(Z){if(!this._requireDynamic("setGravityScale"))return;if(!this._requireNotRemoved("setGravityScale"))return;this._rigidBody?this._rigidBody.setGravityScale(Z,!this._explicitSleep):this._rigidBodyDesc.setGravityScale(Z)}setLinearDamping(Z){if(!this._requireDynamic("setLinearDamping"))return;if(!this._requireNotRemoved("setLinearDamping"))return;this._rigidBody?this._rigidBody.setLinearDamping(Z):this._rigidBodyDesc.setLinearDamping(Z)}setLinearVelocity(Z){if(!this._requireNotKinematicPositionBased("setLinearVelocity"))return;if(!this._requireNotRemoved("setLinearVelocity"))return;this._rigidBody?this._rigidBody.setLinvel(Z,!this._explicitSleep):this._rigidBodyDesc.setLinvel(Z.x,Z.y,Z.z)}setNextKinematicRotation(Z){if(!this._requireKinematic("setNextKinematicRotation"))return;if(!this._requireNotRemoved("setNextKinematicRotation"))return;this._rigidBody?this._rigidBody.setNextKinematicRotation(Z):this._rigidBodyDesc.setRotation(Z)}setNextKinematicPosition(Z){if(!this._requireKinematic("setNextKinematicPosition"))return;if(!this._requireNotRemoved("setNextKinematicPosition"))return;this._rigidBody?this._rigidBody.setNextKinematicTranslation(Z):this._rigidBodyDesc.setTranslation(Z.x,Z.y,Z.z)}setPosition(Z){if(!this._requireNotRemoved("setPosition"))return;this._rigidBody?this._rigidBody.setTranslation(Z,!this._explicitSleep):this._rigidBodyDesc.setTranslation(Z.x,Z.y,Z.z)}setRotation(Z){if(!this._requireNotRemoved("setRotation"))return;this._rigidBody?this._rigidBody.setRotation(Z,!this._explicitSleep):this._rigidBodyDesc.setRotation(Z)}setSleeping(Z){if(!this._requireDynamic("setSleeping"))return;if(!this._requireNotRemoved("setSleeping"))return;this._rigidBody?Z?this._rigidBody.sleep():this._rigidBody.wakeUp():this._rigidBodyDesc.sleeping=Z,this._explicitSleep=Z}setSoftCcdPrediction(Z){if(!this._requireDynamic("setSoftCcdPrediction"))return;if(!this._requireNotRemoved("setSoftCcdPrediction"))return;this._rigidBody?this._rigidBody.setSoftCcdPrediction(Z):this._rigidBodyDesc.setSoftCcdPrediction(Z)}setCollisionGroupsForSolidColliders(Z){if(!this._requireNotRemoved("setCollisionGroupsForSolidColliders"))return;this._colliders.forEach((J)=>{if(J.isSensor)return;J.setCollisionGroups(Z)})}setCollisionGroupsForSensorColliders(Z){if(!this._requireNotRemoved("setCollisionGroupsForSensorColliders"))return;this._colliders.forEach((J)=>{if(!J.isSensor)return;J.setCollisionGroups(Z)})}setType(Z){if(!this._requireNotRemoved("setType"))return;let X={["dynamic"]:$5.RigidBodyType.Dynamic,["fixed"]:$5.RigidBodyType.Fixed,["kinematic_position"]:$5.RigidBodyType.KinematicPositionBased,["kinematic_velocity"]:$5.RigidBodyType.KinematicVelocityBased}[Z];if(X===void 0)return u.error(`Invalid RigidBodyType: ${Z}`);this._rigidBody?this._rigidBody.setBodyType(X,!this._explicitSleep):this._rigidBodyDesc.status=X,this._rigidBodyType=Z}addForce(Z){if(!this._requireNotRemoved("addForce"))return;if(!this._requireCreated("addForce"))return;if(!this._requireDynamic("addForce"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.addForce(Z,!this._explicitSleep)}addTorque(Z){if(!this._requireNotRemoved("addTorque"))return;if(!this._requireCreated("addTorque"))return;if(!this._requireDynamic("addTorque"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.addTorque(Z,!this._explicitSleep)}addChildColliderToSimulation(Z){if(!this._requireNotRemoved("addChildColliderToSimulation"))return;if(!this._requireCreated("addChildColliderToSimulation"))return;Z.addToSimulation(this._simulation,this)}addToSimulation(Z){if(!this._requireNotRemoved("addToSimulation"))return;if(this._rigidBody)return u.error("RigidBody.addToSimulation(): Rigid body already exists in the simulation!");this._simulation=Z,this._rigidBody=this._simulation.createRawRigidBody(this._rigidBodyDesc),this._colliders.forEach((J)=>{if(!J.isSimulated)J.addToSimulation(Z,this)})}applyImpulse(Z){if(!this._requireNotRemoved("applyImpulse"))return;if(!this._requireCreated("applyImpulse"))return;if(!this._requireDynamic("applyImpulse"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.applyImpulse(Z,!this._explicitSleep)}applyImpulseAtPoint(Z,J){if(!this._requireNotRemoved("applyImpulseAtPoint"))return;if(!this._requireCreated("applyImpulseAtPoint"))return;if(!this._requireDynamic("applyImpulseAtPoint"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.applyImpulseAtPoint(Z,J,!this._explicitSleep)}applyTorqueImpulse(Z){if(!this._requireNotRemoved("applyTorqueImpulse"))return;if(!this._requireCreated("applyTorqueImpulse"))return;if(!this._requireDynamic("applyTorqueImpulse"))return;this._rigidBody.applyTorqueImpulse(Z,!this._explicitSleep)}createAndAddChildCollider(Z){if(!this._requireNotRemoved("createAndAddChildCollider"))return null;return this._simulation?new f7({...Z,parentRigidBody:this,simulation:this._simulation}):this._createAndAddPendingChildCollider(Z)}createAndAddChildColliders(Z){let J=[];return Z.forEach((X)=>{let $=this.createAndAddChildCollider(X);if($)J.push($)}),J}getCollidersByTag(Z){let J=[];for(let X of this._colliders)if(X.tag===Z)J.push(X);return J}linkCollider(Z){if(!this._requireNotRemoved("linkCollider"))return;if(Z.parentRigidBody!==this)return u.error("RigidBody.linkCollider(): Collider cannot be linked because it is not a child of this rigid body!");this._colliders.add(Z)}lockAllRotations(){if(!this._requireNotRemoved("lockAllRotations"))return;this.setEnabledRotations({x:!1,y:!1,z:!1})}lockAllPositions(){if(!this._requireNotRemoved("lockAllPositions"))return;this.setEnabledPositions({x:!1,y:!1,z:!1})}removeFromSimulation(){if(!this._requireNotRemoved("removeFromSimulation"))return;if(!this._rigidBody)return u.error("RigidBody.removeFromSimulation(): Rigid body does not exist in the simulation!");this._colliders.forEach((Z)=>{Z.removeFromSimulation()}),this._simulation.removeRawRigidBody(this._rigidBody),this._simulation=void 0,this._rigidBody=void 0}unlinkCollider(Z){if(!this._requireNotRemoved("unlinkCollider"))return;if(!Z.isRemoved)return u.error("RigidBody.unlinkCollider(): Collider is still simulated and therefore cannot be unlinked from this rigid body!");this._colliders.delete(Z)}resetAngularVelocity(){if(!this._requireNotRemoved("resetAngularVelocity"))return;if(!this._requireCreated("resetAngularVelocity"))return;this.setAngularVelocity({x:0,y:0,z:0})}resetForces(){if(!this._requireNotRemoved("resetForces"))return;if(!this._requireCreated("resetForces"))return;this._rigidBody.resetForces(!this._explicitSleep)}resetLinearVelocity(){if(!this._requireNotRemoved("resetLinearVelocity"))return;if(!this._requireCreated("resetLinearVelocity"))return;this.setLinearVelocity({x:0,y:0,z:0})}resetTorques(){if(!this._requireNotRemoved("resetTorques"))return;if(!this._requireCreated("resetTorques"))return;this._rigidBody.resetTorques(!this._explicitSleep)}sleep(){if(!this._requireNotRemoved("sleep"))return;this.setSleeping(!0)}wakeUp(){if(!this._requireNotRemoved("wakeUp"))return;this.setSleeping(!1)}_applyRigidBodyOptions(Z){[["additionalMass",this.setAdditionalMass.bind(this)],["additionalMassProperties",this.setAdditionalMassProperties.bind(this)],["additionalSolverIterations",this.setAdditionalSolverIterations.bind(this)],["angularDamping",this.setAngularDamping.bind(this)],["angularVelocity",this.setAngularVelocity.bind(this)],["dominanceGroup",this.setDominanceGroup.bind(this)],["ccdEnabled",this.setCcdEnabled.bind(this)],["enabled",this.setEnabled.bind(this)],["enabledPositions",this.setEnabledPositions.bind(this)],["enabledRotations",this.setEnabledRotations.bind(this)],["gravityScale",this.setGravityScale.bind(this)],["linearDamping",this.setLinearDamping.bind(this)],["linearVelocity",this.setLinearVelocity.bind(this)],["position",this.setPosition.bind(this)],["rotation",this.setRotation.bind(this)],["sleeping",this.setSleeping.bind(this)],["softCcdPrediction",this.setSoftCcdPrediction.bind(this)]].forEach(([X,$])=>{if(X in Z)$(Z[X])})}_autoAddToSimulation(Z){if(Z.colliders)this._createAndAddPendingChildColliders(Z.colliders);if(Z.simulation)this.addToSimulation(Z.simulation)}_createAndAddPendingChildCollider(Z){if(!this._requireNotRemoved("createAndAddPendingChildCollider"))return null;if(!this._requireNotSimulated("createAndAddPendingChildCollider"))return null;let J=new f7(Z);return this._colliders.add(J),J}_createAndAddPendingChildColliders(Z){let J=[];return Z.forEach((X)=>{let $=this._createAndAddPendingChildCollider(X);if($)J.push($)}),J}_createRigidBodyDesc(Z){let J=Z.type??Sn;return{["dynamic"]:()=>$5.RigidBodyDesc.dynamic(),["fixed"]:()=>$5.RigidBodyDesc.fixed(),["kinematic_position"]:()=>$5.RigidBodyDesc.kinematicPositionBased(),["kinematic_velocity"]:()=>$5.RigidBodyDesc.kinematicVelocityBased()}[J]()}_requireCreated(Z){if(!this._rigidBody||!this._simulation)u.error(`RigidBody._requireCreated(): Rigid body has not been created and therefore does not support the invoked method: ${Z}()`);return!!this._rigidBody&&!!this._simulation}_requireDynamic(Z){if(!this.isDynamic)u.error(`RigidBody._requireDynamic(): Rigid body is not dynamic and therefore does not support the invoked method: ${Z}()`);return this.isDynamic}_requireKinematic(Z){if(!this.isKinematic)u.error(`RigidBody._requireKinematic(): Rigid body is not kinematic and therefore does not support the invoked method: ${Z}()`);return this.isKinematic}_requireNotKinematicPositionBased(Z){if(this.isKinematicPositionBased)u.error(`RigidBody._requireNotKinematicPositionBased(): Rigid body is kinematic position based and therefore does not support the invoked method: ${Z}()`);return!this.isKinematicPositionBased}_requireNotRemoved(Z){if(!this._rigidBody&&!this._rigidBodyDesc)u.error(`RigidBody._requireNotRemoved(): Rigid body has been removed and therefore does not support the invoked method: ${Z}()`);return!!this._rigidBody||!!this._rigidBodyDesc}_requireNotSimulated(Z){if(this.isSimulated)u.error(`RigidBody._requireNotSimulated(): Rigid body is simulated and therefore does not support the invoked method: ${Z}()`);return!this.isSimulated}_isNegligibleVector(Z){return Math.abs(Z.x)<iP&&Math.abs(Z.y)<iP&&Math.abs(Z.z)<iP}}var nP;((Y)=>{Y[Y.Average=0]="Average";Y[Y.Min=1]="Min";Y[Y.Multiply=2]="Multiply";Y[Y.Max=3]="Max"})(nP||={});var QV;((H)=>{H.NONE="none";H.BALL="ball";H.BLOCK="block";H.CAPSULE="capsule";H.CONE="cone";H.CYLINDER="cylinder";H.ROUND_CYLINDER="round-cylinder";H.TRIMESH="trimesh";H.VOXELS="voxels";H.WEDGE="wedge"})(QV||={});class f7 extends D0{_collider;_colliderDesc;_onCollision;_parentRigidBody;_relativePosition={x:0,y:0,z:0};_relativeRotation={x:0,y:0,z:0,w:1};_shape;_simulation;_tag;constructor(Z){super();this._colliderDesc=this._createColliderDesc(Z),this._shape=Z.shape,this._applyColliderOptions(Z),this._autoAddToSimulation(Z)}static optionsFromBlockHalfExtents(Z){return{shape:"block",halfExtents:Z}}static optionsFromModelUri(Z,J=1,X){let $=V7.instance.getBoundingBox(Z),Y=$.max.x-$.min.x,Q=$.max.y-$.min.y,W=$.max.z-$.min.z,K=Math.max(Y,W),G=Math.min(Y,W),V=K/G,H=K/Q,q=K*J/2,z=(O)=>Math.max(0.01,O),F=()=>({shape:"block",halfExtents:{x:z(Y*J/2),y:z(Q*J/2),z:z(W*J/2)}}),U=()=>({shape:"round-cylinder",radius:z(q),halfHeight:z(Q*J/2),borderRadius:z(q*0.1)}),L=()=>{let O=V7.instance.getTrimesh(Z,J);if(!O)return;return{shape:"trimesh",vertices:O.vertices,indices:O.indices}},B=()=>({shape:"wedge",extents:{x:Y*J,y:Q*J,z:W*J}}),w=()=>({shape:"capsule",radius:z(q),halfHeight:z(Q*J/2-q)});if(X)switch(X){case"block":return F();case"capsule":return w();case"round-cylinder":return U();case"trimesh":{let O=L();if(!O){u.error(`Collider.optionsFromModelUri(): Failed to create trimesh options for model ${Z}, falling back to generic shape!`);break}return O}case"wedge":return B();default:u.warning(`Collider.optionsFromModelUri(): Preferred shape ${X} is not yet supported with Collider.optionsFromModelUri(), defaulting to generic shape!`)}if(V>2)return F();if(H>1.5)return U();return w()}get bounciness(){if(!this._requireNotRemoved("bounciness"))return 0;return this._collider?this._collider.restitution():this._colliderDesc.restitution}get bouncinessCombineRule(){if(!this._requireNotRemoved("bouncinessCombineRule"))return 0;return this._collider?this._collider.restitutionCombineRule():this._colliderDesc.restitutionCombineRule}get collisionGroups(){if(!this._requireNotRemoved("collisionGroups"))return{belongsTo:[],collidesWith:[]};return this._collider?e9.decodeRawCollisionGroups(this._collider.collisionGroups()):e9.decodeRawCollisionGroups(this._colliderDesc.collisionGroups)}get friction(){if(!this._requireNotRemoved("friction"))return 0;return this._collider?this._collider.friction():this._colliderDesc.friction}get frictionCombineRule(){if(!this._requireNotRemoved("frictionCombineRule"))return 0;return this._collider?this._collider.frictionCombineRule():this._colliderDesc.frictionCombineRule}get isEnabled(){if(!this._requireNotRemoved("isEnabled"))return!1;return this._collider?this._collider.isEnabled():this._colliderDesc.enabled}get isRemoved(){return!this._collider&&!this._colliderDesc}get isSensor(){if(!this._requireNotRemoved("isSensor"))return!1;return this._collider?this._collider.isSensor():this._colliderDesc.isSensor}get isSimulated(){if(!this._requireNotRemoved("isSimulated"))return!1;return!!this._collider}get parentRigidBody(){if(!this._requireNotRemoved("parentRigidBody"))return;return this._parentRigidBody}get rawCollider(){if(!this._requireNotRemoved("rawCollider"))return;return this._collider}get rawShape(){if(!this._requireNotRemoved("rawShape"))return;return this._collider?this._collider.shape:this._colliderDesc.shape}get relativePosition(){if(!this._requireNotRemoved("relativePosition"))return{x:0,y:0,z:0};return this._relativePosition}get relativeRotation(){if(!this._requireNotRemoved("relativeRotation"))return{x:0,y:0,z:0,w:1};return this._relativeRotation}get shape(){if(!this._requireNotRemoved("shape"))return"none";return this._shape}get tag(){if(!this._requireNotRemoved("tag"))return;return this._tag}setBounciness(Z){if(!this._requireNotRemoved("setBounciness"))return;this._collider?this._collider.setRestitution(Z):this._colliderDesc.setRestitution(Z)}setBouncinessCombineRule(Z){if(!this._requireNotRemoved("setBouncinessCombineRule"))return;this._collider?this._collider.setRestitutionCombineRule(Z):this._colliderDesc.setRestitutionCombineRule(Z)}setCollisionGroups(Z){if(!this._requireNotRemoved("setCollisionGroups"))return;let J=e9.buildRawCollisionGroups(Z);this._collider?this._collider.setCollisionGroups(J):this._colliderDesc.setCollisionGroups(J)}setEnabled(Z){if(!this._requireNotRemoved("setEnabled"))return;this._collider?this._collider.setEnabled(Z):this._colliderDesc.setEnabled(Z)}setFriction(Z){if(!this._requireNotRemoved("setFriction"))return;this._collider?this._collider.setFriction(Z):this._colliderDesc.setFriction(Z)}setFrictionCombineRule(Z){if(!this._requireNotRemoved("setFrictionCombineRule"))return;this._collider?this._collider.setFrictionCombineRule(Z):this._colliderDesc.setFrictionCombineRule(Z)}setMass(Z){if(!this._requireNotRemoved("setMass"))return;this._collider?this._collider.setMass(Z):this._colliderDesc.setMass(Z)}setOnCollision(Z){if(!this._requireNotRemoved("setOnCollision"))return;if(this._onCollision=Z,this.isSimulated)if(this.enableCollisionEvents(!!Z),Z)this._simulation.colliderMap.setColliderCollisionCallback(this,Z);else this._simulation.colliderMap.removeColliderCollisionCallback(this)}setRelativeRotation(Z){if(!this._requireNotRemoved("setRelativeRotation"))return;this._relativeRotation=Z,this._collider?this._collider.parent()?this._collider.setRotationWrtParent(Z):this._collider.setRotation(Z):this._colliderDesc.setRotation(Z)}setRelativePosition(Z){if(!this._requireNotRemoved("setRelativePosition"))return;this._relativePosition=Z,this._collider?this._collider.parent()?this._collider.setTranslationWrtParent(Z):this._collider.setTranslation(Z):this._colliderDesc.setTranslation(Z.x,Z.y,Z.z)}setSensor(Z){if(!this._requireNotRemoved("setSensor"))return;this._collider?this._collider.setSensor(Z):this._colliderDesc.setSensor(Z)}setTag(Z){if(!this._requireNotRemoved("setTag"))return;this._tag=Z}setVoxel(Z,J){if(!this._requireNotRemoved("setVoxel"))return;if(!this._requireSimulated("setVoxel"))return;if(this.shape!=="voxels")return u.error("Collider.setVoxel(): Collider is not a voxels collider!");this._collider.setVoxel(Z.x,Z.y,Z.z,J)}addToSimulation(Z,J){if(!this._requireNotRemoved("addToSimulation"))return;if(!this._requireUnsimulated("addToSimulation"))return;if(J){if(!J.isSimulated)return u.error("Collider.addToSimulation(): Rigid body must be simulated before adding a collider to it!");if(J.type==="dynamic"&&this.shape==="trimesh")u.warning("Collider.addToSimulation(): Trimesh colliders are strongly discouraged to be used with dynamic rigid bodies, they will not contribute any mass!")}if(this._simulation=Z,this._parentRigidBody=J,this._collider=this._simulation.createRawCollider(this._colliderDesc,J?.rawRigidBody),this._colliderDesc=void 0,J)J.linkCollider(this);if(this._onCollision)this.setOnCollision(this._onCollision)}combineVoxelStates(Z){if(!this._requireNotRemoved("combineVoxelStates"))return;if(!this._requireSimulated("combineVoxelStates"))return;if(!Z.isSimulated)return u.error("Collider.combineVoxelStates(): Other collider is not simulated!");if(this.shape!=="voxels")return u.error("Collider.combineVoxelStates(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return u.error("Collider.combineVoxelStates(): Other collider is not a voxels collider!");this._collider.combineVoxelStates(Z.rawCollider,0,0,0)}enableCollisionEvents(Z){if(!this._requireNotRemoved("enableCollisionEvents"))return;let J=this._collider?this._collider.activeEvents():this._colliderDesc.activeEvents,X=Z?J|$5.ActiveEvents.COLLISION_EVENTS:J&~$5.ActiveEvents.COLLISION_EVENTS;(this._collider??this._colliderDesc).setActiveEvents(X),this._setActiveCollisionTypes()}enableContactForceEvents(Z){if(!this._requireNotRemoved("enableContactForceEvents"))return;let J=this._collider?this._collider.activeEvents():this._colliderDesc.activeEvents,X=Z?J|$5.ActiveEvents.CONTACT_FORCE_EVENTS:J&~$5.ActiveEvents.CONTACT_FORCE_EVENTS;(this._collider??this._colliderDesc).setActiveEvents(X),this._setActiveCollisionTypes()}propagateVoxelChange(Z,J){if(!this._requireNotRemoved("propagateVoxelChange"))return;if(!this._requireSimulated("propagateVoxelChange"))return;if(!Z.isSimulated)return u.error("Collider.propagateVoxelChange(): Other collider is not simulated!");if(this.shape!=="voxels")return u.error("Collider.propagateVoxelChange(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return u.error("Collider.propagateVoxelChange(): Other collider is not a voxels collider!");this._collider.propagateVoxelChange(Z.rawCollider,J.x,J.y,J.z,0,0,0)}removeFromSimulation(){if(!this._requireNotRemoved("removeFromSimulation"))return;if(!this._requireSimulated("removeFromSimulation"))return;if(this._simulation.removeRawCollider(this._collider),this._simulation=void 0,this._collider=void 0,this._parentRigidBody)this._parentRigidBody.unlinkCollider(this);this._parentRigidBody=void 0}scale(Z){if(!this._requireNotRemoved("scale"))return;switch(this.setRelativePosition({x:this.relativePosition.x*Z,y:this.relativePosition.y*Z,z:this.relativePosition.z*Z}),this._shape){case"ball":{if(this._collider)this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.radius*=Z;return}case"block":{if(this._collider){let J=this._collider.halfExtents();this._collider.setHalfExtents({x:J.x*Z,y:J.y*Z,z:J.z*Z})}else this._colliderDesc.shape.halfExtents.x*=Z,this._colliderDesc.shape.halfExtents.y*=Z,this._colliderDesc.shape.halfExtents.z*=Z;return}case"capsule":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"cone":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"cylinder":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"round-cylinder":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRoundRadius(this._collider.roundRadius()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight=this._colliderDesc.shape.halfHeight*Z,this._colliderDesc.shape.borderRadius=this._colliderDesc.shape.borderRadius*Z,this._colliderDesc.shape.radius=this._colliderDesc.shape.radius*Z;return}case"trimesh":{u.error("Collider.setScale(): Trimesh colliders cannot be scaled!");return}case"voxels":{u.error("Collider.setScale(): Voxels colliders cannot be scaled!");return}case"wedge":{u.error("Collider.setScale(): Wedge colliders cannot be scaled!");return}default:u.fatalError(`Collider.setScale(): ${this._shape} is not a valid collider shape!`)}}_applyColliderOptions(Z){[["bounciness",this.setBounciness.bind(this)],["bouncinessCombineRule",this.setBouncinessCombineRule.bind(this)],["collisionGroups",this.setCollisionGroups.bind(this)],["enabled",this.setEnabled.bind(this)],["friction",this.setFriction.bind(this)],["frictionCombineRule",this.setFrictionCombineRule.bind(this)],["isSensor",this.setSensor.bind(this)],["mass",this.setMass.bind(this)],["onCollision",this.setOnCollision.bind(this)],["relativePosition",this.setRelativePosition.bind(this)],["relativeRotation",this.setRelativeRotation.bind(this)],["tag",this.setTag.bind(this)]].forEach(([X,$])=>{if(Z[X]!==void 0)$.call(this,Z[X])})}_autoAddToSimulation(Z){if(Z.simulation)this.addToSimulation(Z.simulation,Z.parentRigidBody)}_buildWedgeConvexHullVertices(Z){let{x:J,y:X,z:$}=Z,Y=J/2,Q=$/2,W=X/2;return new Float32Array([-Y,0-W,-Q,Y,0-W,-Q,Y,0-W,Q,-Y,0-W,Q,-Y,X-W,-Q,Y,X-W,-Q])}_createColliderDesc(Z){let{shape:J,flags:X}=Z;switch(J){case"ball":{if(!Z.radius)u.fatalError("Ball collider must have a radius!");return $5.ColliderDesc.ball(Z.radius)}case"block":{if(!Z.halfExtents)u.fatalError("Block collider must have halfExtents!");return $5.ColliderDesc.cuboid(Z.halfExtents.x,Z.halfExtents.y,Z.halfExtents.z)}case"capsule":{if(!Z.halfHeight||!Z.radius)u.fatalError("Capsule collider must have halfHeight and radius!");return $5.ColliderDesc.capsule(Z.halfHeight,Z.radius)}case"cone":{if(!Z.radius||!Z.halfHeight)u.fatalError("Cone collider must have radius and halfHeight!");return $5.ColliderDesc.cone(Z.halfHeight,Z.radius)}case"cylinder":{if(!Z.radius||!Z.halfHeight)u.fatalError("Cylinder collider must have radius and halfHeight!");return $5.ColliderDesc.cylinder(Z.halfHeight,Z.radius)}case"round-cylinder":{if(!Z.radius||!Z.halfHeight||!Z.borderRadius)u.fatalError("Round cylinder collider must have radius, halfHeight, and borderRadius!");return $5.ColliderDesc.roundCylinder(Z.halfHeight,Z.radius,Z.borderRadius)}case"trimesh":{if(!Z.indices||!Z.vertices)u.fatalError("Trimesh collider must have vertices and indices!");return $5.ColliderDesc.trimesh(Z.vertices,Z.indices,X)}case"voxels":{if(!Z.coordinates||!Z.size)u.fatalError("Voxels collider must have coordinates and size!");return $5.ColliderDesc.voxels(this._coordinatesToInt32Array(Z.coordinates),Z.size)}case"wedge":{if(!Z.extents)u.fatalError("Wedge collider must have extents!");let $=this._buildWedgeConvexHullVertices(Z.extents),Y=$5.ColliderDesc.convexHull($);if(!Y)throw u.fatalError("Failed to create convex hull for wedge collider!"),new Error("Convex hull creation failed");return Y}default:u.fatalError(`Collider._createColliderDesc(): ${J} is not a valid collider shape!`)}}_requireSimulated(Z){if(!this.isSimulated)u.error(`Collider._requireSimulated(): Collider is not simulated, invoked method: ${Z}()`);return this.isSimulated}_requireUnsimulated(Z){if(this.isSimulated)u.error(`Collider._requireUnsimulated(): Collider is already simulated, invoked method: ${Z}()`);return!this.isSimulated}_requireNotRemoved(Z){if(this.isRemoved)u.error(`Collider._requireNotRemoved(): Collider is removed, invoked method: ${Z}()`);return!this.isRemoved}_setActiveCollisionTypes(){(this._collider??this._colliderDesc).setActiveCollisionTypes($5.ActiveCollisionTypes.DYNAMIC_DYNAMIC|$5.ActiveCollisionTypes.DYNAMIC_KINEMATIC|$5.ActiveCollisionTypes.DYNAMIC_FIXED|$5.ActiveCollisionTypes.KINEMATIC_KINEMATIC|$5.ActiveCollisionTypes.KINEMATIC_FIXED)}_coordinatesToInt32Array(Z){let J=new Int32Array(Z.length*3);for(let X=0;X<Z.length;X++){let $=Z[X],Y=X*3;J[Y]=Math.floor($.x),J[Y+1]=Math.floor($.y),J[Y+2]=Math.floor($.z)}return J}}var yL5={shape:"voxels"},sP;((X)=>{X.ENTITY_COLLISION="BLOCK_TYPE.ENTITY_COLLISION";X.ENTITY_CONTACT_FORCE="BLOCK_TYPE.ENTITY_CONTACT_FORCE"})(sP||={});class h7 extends D0{_id;_customColliderOptions;_halfExtents;_isLiquid;_lightLevel;_name;_textureUri;constructor(Z={id:-1,textureUri:"textures/missing.png",name:"Unknown"}){if(Z.id<0)u.fatalError("BlockType.constructor(): BlockType id not set.");super();this._id=Z.id,this._customColliderOptions=Z.customColliderOptions,this._halfExtents=Z.halfExtents??{x:0.5,y:0.5,z:0.5},this._isLiquid=Z.isLiquid??!1,this._lightLevel=Z.lightLevel??0,this._name=Z.name,this._textureUri=Z.textureUri}get id(){return this._id}get colliderOptions(){return{...this._customColliderOptions,...yL5}}get halfExtents(){return this._halfExtents}get isLiquid(){return this._isLiquid}get isMeshable(){return!this._customColliderOptions}get lightLevel(){return this._lightLevel}get name(){return this._name}get size(){return{x:this._halfExtents.x*2,y:this._halfExtents.y*2,z:this._halfExtents.z*2}}get textureUri(){return this._textureUri}createCollider(Z){let J=new f7({...this.colliderOptions,coordinates:Z,size:this.size});if(this.isLiquid)J.setSensor(!0);if(this.hasListeners("BLOCK_TYPE.ENTITY_COLLISION")||this.isLiquid)J.enableCollisionEvents(!0);if(this.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))J.enableContactForceEvents(!0);if(e9.isDefaultCollisionGroups(J.collisionGroups))J.setCollisionGroups({belongsTo:[1],collidesWith:[65535&~1]});return J}serialize(){return E0.serializeBlockType(this)}}var aP;((J)=>J.REGISTER_BLOCK_TYPE="BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE")(aP||={});class WV extends D0{_blockTypes=new Map;_world;constructor(Z){super();this._world=Z}get world(){return this._world}getAllBlockTypes(){return Array.from(this._blockTypes.values())}getBlockType(Z){let J=this._blockTypes.get(Z);if(!J)u.fatalError(`BlockTypeRegistry.getBlockType(): BlockType with id ${Z} not found.`);return J}registerGenericBlockType(Z){let X=new class extends h7{constructor($=Z){super($)}};return this.registerBlockType(X),X}registerBlockType(Z){this._blockTypes.set(Z.id,Z),this.emitWithWorld(this._world,"BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",{blockTypeRegistry:this,id:Z.id,blockType:Z})}serialize(){return E0.serializeBlockTypeRegistry(this)}}var TT={};bZ(TT,{worldSchema:()=>CT,worldPacketDefinition:()=>Tt,vectorSchema:()=>G5,vectorBooleanSchema:()=>hD5,uiSchema:()=>DT,uiPacketDefinition:()=>Pt,uiDatasSchema:()=>PT,uiDatasPacketDefinition:()=>Ct,uiDataSendPacketDefinition:()=>Vt,uiDataSchema:()=>vV,syncResponseSchema:()=>RT,syncResponsePacketDefinition:()=>Dt,syncRequestSchema:()=>rC,syncRequestPacketDefinition:()=>Gt,stateRequestSchema:()=>aC,stateRequestPacketDefinition:()=>Kt,sceneUIsSchema:()=>MT,sceneUIsPacketDefinition:()=>Rt,sceneUISchema:()=>jT,rgbColorSchema:()=>O6,registeredPackets:()=>vB,quaternionSchema:()=>GT,playersSchema:()=>NT,playersPacketDefinition:()=>Mt,playerSchema:()=>OT,physicsDebugRenderSchema:()=>wT,physicsDebugRenderPacketDefinition:()=>Nt,physicsDebugRaycastsSchema:()=>LT,physicsDebugRaycastsPacketDefinition:()=>jt,physicsDebugRaycastSchema:()=>BT,particleEmittersSchema:()=>UT,particleEmittersPacketDefinition:()=>Ot,particleEmitterSchema:()=>FT,outboundPackets:()=>IB,modelNodeOverrideSchema:()=>KT,lightsSchema:()=>zT,lightsPacketDefinition:()=>wt,lightSchema:()=>qT,isValidPacket:()=>yD5,inputSchema:()=>sC,inputPacketDefinition:()=>Wt,inboundPackets:()=>EB,hexColorSchema:()=>iC,heartbeatSchema:()=>pC,heartbeatPacketDefinition:()=>$t,entitySchema:()=>VT,entitiesSchema:()=>HT,entitiesPacketDefinition:()=>Lt,definePacket:()=>S0,debugConfigSchema:()=>nC,debugConfigPacketDefinition:()=>Qt,createPacket:()=>TD5,connectionSchema:()=>lC,connectionPacketDefinition:()=>Xt,chunksSchema:()=>WT,chunksPacketDefinition:()=>Bt,chunkSchema:()=>QT,chatMessagesSchema:()=>YT,chatMessagesPacketDefinition:()=>Ut,chatMessageSendPacketDefinition:()=>Yt,chatMessageSchema:()=>IV,cameraSchema:()=>$T,cameraPacketDefinition:()=>Ft,blocksSchema:()=>ZT,blocksPacketDefinition:()=>qt,blockTypesSchema:()=>XT,blockTypesPacketDefinition:()=>zt,blockTypeSchema:()=>JT,blockSchema:()=>eC,bidirectionalPackets:()=>kB,audiosSchema:()=>tC,audiosPacketDefinition:()=>Ht,audioSchema:()=>oC,PacketId:()=>T5});var kB={};bZ(kB,{heartbeatPacketDefinition:()=>$t,connectionPacketDefinition:()=>Xt});var uC=e(Zt(),1);class cC extends uC.default{static instance=new uC.default}var T5;((k)=>{k[k.SYNC_REQUEST=0]="SYNC_REQUEST";k[k.INPUT=1]="INPUT";k[k.STATE_REQUEST=2]="STATE_REQUEST";k[k.CHAT_MESSAGE_SEND=3]="CHAT_MESSAGE_SEND";k[k.UI_DATA_SEND=4]="UI_DATA_SEND";k[k.SYNC_RESPONSE=32]="SYNC_RESPONSE";k[k.AUDIOS=33]="AUDIOS";k[k.BLOCKS=34]="BLOCKS";k[k.BLOCK_TYPES=35]="BLOCK_TYPES";k[k.CHAT_MESSAGES=36]="CHAT_MESSAGES";k[k.CHUNKS=37]="CHUNKS";k[k.ENTITIES=38]="ENTITIES";k[k.WORLD=39]="WORLD";k[k.CAMERA=40]="CAMERA";k[k.UI=41]="UI";k[k.UI_DATAS=42]="UI_DATAS";k[k.SCENE_UIS=43]="SCENE_UIS";k[k.LIGHTS=44]="LIGHTS";k[k.PLAYERS=45]="PLAYERS";k[k.PARTICLE_EMITTERS=46]="PARTICLE_EMITTERS";k[k.CONNECTION=116]="CONNECTION";k[k.HEARTBEAT=117]="HEARTBEAT";k[k.DEBUG_CONFIG=128]="DEBUG_CONFIG";k[k.PHYSICS_DEBUG_RENDER=192]="PHYSICS_DEBUG_RENDER";k[k.PHYSICS_DEBUG_RAYCASTS=193]="PHYSICS_DEBUG_RAYCASTS"})(T5||={});function TD5(Z,J,X){if(!Z.validate(J))throw new Error(`Invalid payload for packet with id ${Z.id}. Error: ${cC.instance.errorsText(Z.validate.errors)}`);let $=[Z.id,J];if(typeof X==="number")$.push(X);return $}function S0(Z,J){return{id:Z,schema:J,validate:cC.instance.compile(J)}}var kD5={type:"object",properties:{i:{type:"string"}},required:["i"],additionalProperties:!1},Jt={type:"object",properties:{role:{type:"string",enum:["auto","client","server"],nullable:!0},fingerprints:{type:"array",items:{type:"object",properties:{algorithm:{type:"string",enum:["sha-1","sha-224","sha-256","sha-384","sha-512"]},value:{type:"string"}},required:["algorithm","value"]}}},required:["fingerprints"],additionalProperties:!1},ED5={type:"object",properties:{foundation:{type:"string"},priority:{type:"number"},ip:{type:"string"},address:{type:"string"},protocol:{type:"string",enum:["udp","tcp"]},port:{type:"number"},type:{type:"string",enum:["host"]},tcpType:{type:"string",enum:["passive"],nullable:!0}},required:["foundation","priority","ip","address","protocol","port","type"],additionalProperties:!1},ID5={type:"object",properties:{usernameFragment:{type:"string"},password:{type:"string"},iceLite:{type:"boolean",nullable:!0}},required:["usernameFragment","password"],additionalProperties:!1},vD5={type:"object",properties:{i:{type:"string"},l:{type:"string"}},required:["i","l"],additionalProperties:!1},SD5={type:"object",properties:{port:{type:"number"},OS:{type:"number"},MIS:{type:"number"},maxMessageSize:{type:"number"}},required:["port","OS","MIS","maxMessageSize"],additionalProperties:!0},_D5={type:"object",properties:{streamId:{type:"number"},ordered:{type:"boolean",nullable:!0},maxPacketLifeTime:{type:"number",nullable:!0},maxRetransmits:{type:"number",nullable:!0}},required:["streamId"],additionalProperties:!1},AD5={type:"object",properties:{i:{type:"string"},f:{type:"string",enum:["cs","sc"]},ip:ID5,ic:{type:"array",items:ED5},d:Jt,s:SD5},required:["i","f","ip","ic","d","s"],additionalProperties:!1},xD5={type:"object",properties:{i:{type:"string"},d:Jt},required:["i","d"],additionalProperties:!1},fD5={type:"object",properties:{i:{type:"string",nullable:!0},pi:{type:"string",nullable:!0},l:{type:"string"},s:_D5},required:["l","s"],additionalProperties:!1},lC={type:"object",properties:{i:{type:"string",nullable:!0},k:{type:"boolean",nullable:!0},c:{...xD5,nullable:!0},ca:{...kD5,nullable:!0},d:{type:"array",items:{...fD5},nullable:!0},pa:{...vD5,nullable:!0},t:{type:"array",items:{...AD5},nullable:!0}},additionalProperties:!1};var Xt=S0(116,lC);var pC={type:"null",nullable:!0};var $t=S0(117,pC);var EB={};bZ(EB,{uiDataSendPacketDefinition:()=>Vt,syncRequestPacketDefinition:()=>Gt,stateRequestPacketDefinition:()=>Kt,inputPacketDefinition:()=>Wt,debugConfigPacketDefinition:()=>Qt,chatMessageSendPacketDefinition:()=>Yt});var iC={type:"string",pattern:"^[0-9A-Fa-f]{6}$"};var IV={type:"object",properties:{m:{type:"string"},c:{...iC,nullable:!0},p:{type:"string",nullable:!0}},required:["m"],additionalProperties:!1};var Yt=S0(3,IV);var nC={type:"object",properties:{pdr:{type:"boolean",nullable:!0}},additionalProperties:!1};var Qt=S0(128,nC);var sC={type:"object",properties:{"1":{type:"boolean",nullable:!0},"2":{type:"boolean",nullable:!0},"3":{type:"boolean",nullable:!0},"4":{type:"boolean",nullable:!0},"5":{type:"boolean",nullable:!0},"6":{type:"boolean",nullable:!0},"7":{type:"boolean",nullable:!0},"8":{type:"boolean",nullable:!0},"9":{type:"boolean",nullable:!0},"0":{type:"boolean",nullable:!0},w:{type:"boolean",nullable:!0},a:{type:"boolean",nullable:!0},s:{type:"boolean",nullable:!0},d:{type:"boolean",nullable:!0},q:{type:"boolean",nullable:!0},e:{type:"boolean",nullable:!0},r:{type:"boolean",nullable:!0},f:{type:"boolean",nullable:!0},z:{type:"boolean",nullable:!0},x:{type:"boolean",nullable:!0},c:{type:"boolean",nullable:!0},v:{type:"boolean",nullable:!0},u:{type:"boolean",nullable:!0},i:{type:"boolean",nullable:!0},o:{type:"boolean",nullable:!0},j:{type:"boolean",nullable:!0},k:{type:"boolean",nullable:!0},l:{type:"boolean",nullable:!0},n:{type:"boolean",nullable:!0},m:{type:"boolean",nullable:!0},sp:{type:"boolean",nullable:!0},sh:{type:"boolean",nullable:!0},tb:{type:"boolean",nullable:!0},ml:{type:"boolean",nullable:!0},mr:{type:"boolean",nullable:!0},cp:{type:"number",nullable:!0},cy:{type:"number",nullable:!0},sq:{type:"number",nullable:!0}},additionalProperties:!1};var Wt=S0(1,sC);var aC={type:"object",properties:{},additionalProperties:!1};var Kt=S0(2,aC);var rC={type:"null",nullable:!0};var Gt=S0(0,rC);var vV={type:"object",properties:{},additionalProperties:!0};var Vt=S0(4,vV);var IB={};bZ(IB,{worldPacketDefinition:()=>Tt,uiPacketDefinition:()=>Pt,uiDatasPacketDefinition:()=>Ct,syncResponsePacketDefinition:()=>Dt,sceneUIsPacketDefinition:()=>Rt,playersPacketDefinition:()=>Mt,physicsDebugRenderPacketDefinition:()=>Nt,physicsDebugRaycastsPacketDefinition:()=>jt,particleEmittersPacketDefinition:()=>Ot,lightsPacketDefinition:()=>wt,entitiesPacketDefinition:()=>Lt,chunksPacketDefinition:()=>Bt,chatMessagesPacketDefinition:()=>Ut,cameraPacketDefinition:()=>Ft,blocksPacketDefinition:()=>qt,blockTypesPacketDefinition:()=>zt,audiosPacketDefinition:()=>Ht});var G5={type:"array",items:[{type:"number"},{type:"number"},{type:"number"}],minItems:3,maxItems:3};var oC={type:"object",properties:{i:{type:"number"},a:{type:"string",nullable:!0},cd:{type:"number",nullable:!0},d:{type:"number",nullable:!0},de:{type:"number",nullable:!0},di:{type:"number",minimum:0,nullable:!0},e:{type:"number",nullable:!0},l:{type:"boolean",nullable:!0},o:{type:"number",nullable:!0},p:{...G5,nullable:!0},pa:{type:"boolean",nullable:!0},pl:{type:"boolean",nullable:!0},pr:{type:"number",minimum:0,nullable:!0},r:{type:"boolean",nullable:!0},rd:{type:"number",nullable:!0},s:{type:"number",nullable:!0},v:{type:"number",minimum:0,maximum:1,nullable:!0}},required:["i"],additionalProperties:!1};var tC={type:"array",items:{...oC}};var Ht=S0(33,tC);var eC={type:"object",properties:{i:{type:"number"},c:G5},required:["i","c"],additionalProperties:!1};var ZT={type:"array",items:{...eC}};var qt=S0(34,ZT);var JT={type:"object",properties:{i:{type:"number"},l:{type:"boolean",nullable:!0},ll:{type:"number",nullable:!0},n:{type:"string",nullable:!0},t:{type:"string",nullable:!0}},required:["i"],additionalProperties:!1};var XT={type:"array",items:{...JT}};var zt=S0(35,XT);var $T={type:"object",properties:{m:{type:"number",nullable:!0},e:{type:"number",nullable:!0},et:{type:"number",nullable:!0},fo:{type:"number",nullable:!0},ffo:{type:"number",nullable:!0},fv:{type:"number",nullable:!0},h:{type:"array",items:{type:"string"},nullable:!0},o:{...G5,nullable:!0},p:{...G5,nullable:!0},pt:{...G5,nullable:!0},pl:{...G5,nullable:!0},s:{type:"array",items:{type:"string"},nullable:!0},sa:{type:"number",nullable:!0},z:{type:"number",nullable:!0}},additionalProperties:!1};var YT={type:"array",items:{...IV}};var QT={type:"object",properties:{c:G5,b:{type:"array",items:{type:"number",minimum:0,maximum:255},minItems:4096,maxItems:4096,nullable:!0},rm:{type:"boolean",nullable:!0}},required:["c"],additionalProperties:!1};var WT={type:"array",items:{...QT}};var O6={type:"array",items:[{type:"number",minimum:0,maximum:255},{type:"number",minimum:0,maximum:255},{type:"number",minimum:0,maximum:255}],minItems:3,maxItems:3};var KT={type:"object",properties:{n:{type:"string"},h:{type:"boolean",nullable:!0},o:{type:"number",minimum:0,maximum:1,nullable:!0},r:{type:"boolean",nullable:!0},s:{type:"number",nullable:!0},t:{...O6,nullable:!0}},required:["n"],additionalProperties:!1};var GT={type:"array",items:[{type:"number"},{type:"number"},{type:"number"},{type:"number"}],minItems:4,maxItems:4};var VT={type:"object",properties:{i:{type:"number"},al:{type:"array",items:{type:"string"},nullable:!0},ao:{type:"array",items:{type:"string"},nullable:!0},ap:{type:"number",nullable:!0},as:{type:"array",items:{type:"string"},nullable:!0},bh:{...G5,nullable:!0},bt:{type:"string",nullable:!0},h:{type:"array",items:{type:"string"},nullable:!0},m:{type:"string",nullable:!0},mo:{type:"array",items:{...KT},nullable:!0},mt:{type:"string",nullable:!0},n:{type:"string",nullable:!0},o:{type:"number",nullable:!0},p:{...G5,nullable:!0},pe:{type:"number",nullable:!0},pn:{type:"string",nullable:!0},r:{...GT,nullable:!0},rm:{type:"boolean",nullable:!0},s:{type:"number",nullable:!0},sn:{type:"array",items:{type:"string"},nullable:!0},t:{...O6,nullable:!0}},required:["i"],additionalProperties:!1};var HT={type:"array",items:{...VT}};var qT={type:"object",properties:{i:{type:"number"},a:{type:"number",nullable:!0},e:{type:"number",nullable:!0},c:{...O6,nullable:!0},d:{type:"number",nullable:!0},n:{type:"number",nullable:!0},o:{...G5,nullable:!0},p:{...G5,nullable:!0},pe:{type:"number",minimum:0,maximum:1,nullable:!0},rm:{type:"boolean",nullable:!0},t:{type:"number",nullable:!0},te:{type:"number",nullable:!0},tp:{...G5,nullable:!0}},required:["i"],additionalProperties:!1};var zT={type:"array",items:{...qT}};var FT={type:"object",properties:{i:{type:"number"},at:{type:"number",nullable:!0},b:{type:"number",nullable:!0},ce:{...O6,nullable:!0},cev:{...O6,nullable:!0},cs:{...O6,nullable:!0},csv:{...O6,nullable:!0},e:{type:"number",nullable:!0},en:{type:"string",nullable:!0},g:{...G5,nullable:!0},l:{type:"number",nullable:!0},lv:{type:"number",nullable:!0},mp:{type:"number",nullable:!0},o:{...G5,nullable:!0},oe:{type:"number",nullable:!0},oev:{type:"number",nullable:!0},os:{type:"number",nullable:!0},osv:{type:"number",nullable:!0},p:{...G5,nullable:!0},pa:{type:"boolean",nullable:!0},pv:{...G5,nullable:!0},r:{type:"number",nullable:!0},rv:{type:"number",nullable:!0},rm:{type:"boolean",nullable:!0},se:{type:"number",nullable:!0},sev:{type:"number",nullable:!0},ss:{type:"number",nullable:!0},ssv:{type:"number",nullable:!0},t:{type:"boolean",nullable:!0},tu:{type:"string",nullable:!0},v:{...G5,nullable:!0},vv:{...G5,nullable:!0}},required:["i"],additionalProperties:!1};var UT={type:"array",items:{...FT}};var BT={type:"object",properties:{o:{...G5},d:{...G5},l:{type:"number"},h:{type:"boolean"}},required:["o","d","l","h"],additionalProperties:!1};var LT={type:"array",items:{...BT}};var wT={type:"object",properties:{v:{type:"array",items:{type:"number"}},c:{type:"array",items:{type:"number"}}},required:["v","c"],additionalProperties:!1};var OT={type:"object",properties:{i:{type:"string"},p:{type:"string",nullable:!0},rm:{type:"boolean",nullable:!0},u:{type:"string",nullable:!0}},required:["i"],additionalProperties:!1};var NT={type:"array",items:{...OT}};var jT={type:"object",properties:{i:{type:"number"},e:{type:"number",nullable:!0},o:{...G5,nullable:!0},p:{...G5,nullable:!0},rm:{type:"boolean",nullable:!0},s:{type:"object",nullable:!0},t:{type:"string",nullable:!0},v:{type:"number",nullable:!0}},required:["i"],additionalProperties:!1};var MT={type:"array",items:{...jT}};var RT={type:"object",properties:{r:{type:"number"},s:{type:"number"},p:{type:"number"},n:{type:"number"}},required:["r","s","p","n"],additionalProperties:!1};var DT={type:"object",properties:{p:{type:"boolean",nullable:!0},u:{type:"string",nullable:!0}},additionalProperties:!1};var PT={type:"array",items:{...vV}};var hD5={type:"array",items:[{type:"boolean"},{type:"boolean"},{type:"boolean"}],minItems:3,maxItems:3};var CT={type:"object",properties:{i:{type:"number"},ac:{...O6,nullable:!0},ai:{type:"number",nullable:!0},dc:{...O6,nullable:!0},di:{type:"number",nullable:!0},dp:{...G5,nullable:!0},fc:{...O6,nullable:!0},ff:{type:"number",nullable:!0},fn:{type:"number",nullable:!0},n:{type:"string",nullable:!0},s:{type:"string",nullable:!0},si:{type:"number",nullable:!0},t:{type:"number",nullable:!0}},required:["i"],additionalProperties:!1};var Ft=S0(40,$T);var Ut=S0(36,YT);var Bt=S0(37,WT);var Lt=S0(38,HT);var wt=S0(44,zT);var Ot=S0(46,UT);var Nt=S0(192,wT);var jt=S0(193,LT);var Mt=S0(45,NT);var Rt=S0(43,MT);var Dt=S0(32,RT);var Pt=S0(41,DT);var Ct=S0(42,PT);var Tt=S0(39,CT);var vB=new Map,bD5={...kB,...EB,...IB};for(let Z of Object.values(bD5))if("id"in Z&&"schema"in Z){let J=Z;if(vB.has(J.id))throw new Error(`Packet with id ${J.id} is already registered.`);vB.set(J.id,J)}function yD5(Z){if(typeof Z!=="object"||Z===null||typeof Z[0]!=="number"||Z[0]<0||Z[1]===void 0||Z[2]!==void 0&&(typeof Z[2]!=="number"||Z[2]<0))return!1;let J=vB.get(Z[0]);return!!J&&J.validate(Z[1])}var $0=TT;var ot=e(at(),1);import EY from"fs";import rt from"path";var _V="./dev/persistence";class QJ{static instance=new QJ;gameId=process.env.HYTOPIA_GAME_ID;lobbyId=process.env.HYTOPIA_LOBBY_ID;_creativeGateway;constructor(){try{this._creativeGateway=new ot.CreativeGateway}catch{console.warn(["━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","\uD83D\uDEA8 HYTOPIA PLATFORM GATEWAY IS NOT INITIALIZED \uD83D\uDEA8","","\uD83D\uDD27 Local development is still possible, but these features will be disabled:"," • \uD83D\uDC64 Player Accounts"," • \uD83C\uDFAD Player Cosmetics"," • \uD83D\uDC1B Crash Analytics & Debug Logs","","\uD83D\uDCA1 These features will be enabled but modified:"," • \uD83D\uDCBE Player & Global Persisted Data - Data will be persisted"," locally in the ./dev/persistence directory of your project."," Player ids for data persistence will begin at 1 for the first "," player to join your local server, and increments for each"," additional player. This means that if you restart your"," server, the first player id will be 1 again. This is to ensure"," that data persistence across server restarts can be easily"," tested and debugged in local development.","","To enable the HYTOPIA Platform Gateway locally:"," 1. Set these environment variables:"," HYTOPIA_API_KEY, HYTOPIA_GAME_ID, HYTOPIA_LOBBY_ID"," 2. You can find these values at: https://create.hytopia.com","","Note: In production, these environment variables will be auto-populated ","& the HYTOPIA Platform Gateway will automatically be initialized \uD83D\uDE80","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",""].join(`
91
+ >>> no match, partial?`,Z,q,J,z),q===K)return!0}return!1}let U;if(typeof V==="string")U=H===V,this.debug("string match",V,H,U);else U=V.test(H),this.debug("pattern match",V,H,U);if(!U)return!1}if(Q===K&&W===G)return!0;else if(Q===K)return X;else if(W===G)return Q===K-1&&Z[Q]==="";else throw new Error("wtf?")}braceExpand(){return Xu(this.pattern,this.options)}parse(Z){HG(Z);let J=this.options;if(Z==="**")return J6;if(Z==="")return"";let X,$=null;if(X=Z.match(BG5))$=J.dot?wG5:LG5;else if(X=Z.match(QG5))$=(J.nocase?J.dot?VG5:GG5:J.dot?KG5:WG5)(X[1]);else if(X=Z.match(OG5))$=(J.nocase?J.dot?jG5:NG5:J.dot?MG5:RG5)(X);else if(X=Z.match(HG5))$=J.dot?zG5:qG5;else if(X=Z.match(FG5))$=UG5;let Y=Z6.fromGlob(Z,this.options).toMMPattern();if($&&typeof Y==="object")Reflect.defineProperty(Y,"test",{value:$});return Y}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Z=this.set;if(!Z.length)return this.regexp=!1,this.regexp;let J=this.options,X=J.noglobstar?CG5:J.dot?TG5:kG5,$=new Set(J.nocase?["i"]:[]),Y=Z.map((K)=>{let G=K.map((V)=>{if(V instanceof RegExp)for(let H of V.flags.split(""))$.add(H);return typeof V==="string"?_G5(V):V===J6?J6:V._src});return G.forEach((V,H)=>{let q=G[H+1],z=G[H-1];if(V!==J6||z===J6)return;if(z===void 0)if(q!==void 0&&q!==J6)G[H+1]="(?:\\/|"+X+"\\/)?"+q;else G[H]=X;else if(q===void 0)G[H-1]=z+"(?:\\/|"+X+")?";else if(q!==J6)G[H-1]=z+"(?:\\/|\\/"+X+"\\/)"+q,G[H+1]=J6}),G.filter((V)=>V!==J6).join("/")}).join("|"),[Q,W]=Z.length>1?["(?:",")"]:["",""];if(Y="^"+Q+Y+W+"$",this.negate)Y="^(?!"+Y+").+$";try{this.regexp=new RegExp(Y,[...$].join(""))}catch(K){this.regexp=!1}return this.regexp}slashSplit(Z){if(this.preserveMultipleSlashes)return Z.split("/");else if(this.isWindows&&/^\/\/[^\/]+/.test(Z))return["",...Z.split(/\/+/)];else return Z.split(/\/+/)}match(Z,J=this.partial){if(this.debug("match",Z,this.pattern),this.comment)return!1;if(this.empty)return Z==="";if(Z==="/"&&J)return!0;let X=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let $=this.slashSplit(Z);this.debug(this.pattern,"split",$);let Y=this.set;this.debug(this.pattern,"set",Y);let Q=$[$.length-1];if(!Q)for(let W=$.length-2;!Q&&W>=0;W--)Q=$[W];for(let W=0;W<Y.length;W++){let K=Y[W],G=$;if(X.matchBase&&K.length===1)G=[Q];if(this.matchOne(G,K,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return v6.defaults(Z).Minimatch}}v6.AST=Z6;v6.Minimatch=K9;v6.escape=OW;v6.unescape=$Z;import{fileURLToPath as HV5}from"node:url";var NW=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,Yu=new Set,UR=typeof process==="object"&&!!process?process:{},Qu=(Z,J,X,$)=>{typeof UR.emitWarning==="function"?UR.emitWarning(Z,J,X,$):console.error(`[${X}] ${J}: ${Z}`)},FF=globalThis.AbortController,$u=globalThis.AbortSignal;if(typeof FF==="undefined"){$u=class X{onabort;_onabort=[];reason;aborted=!1;addEventListener($,Y){this._onabort.push(Y)}},FF=class X{constructor(){J()}signal=new $u;abort($){if(this.signal.aborted)return;this.signal.reason=$,this.signal.aborted=!0;for(let Y of this.signal._onabort)Y($);this.signal.onabort?.($)}};let Z=UR.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",J=()=>{if(!Z)return;Z=!1,Qu("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",J)}}var AG5=(Z)=>!Yu.has(Z),k46=Symbol("type"),e1=(Z)=>Z&&Z===Math.floor(Z)&&Z>0&&isFinite(Z),Wu=(Z)=>!e1(Z)?null:Z<=Math.pow(2,8)?Uint8Array:Z<=Math.pow(2,16)?Uint16Array:Z<=Math.pow(2,32)?Uint32Array:Z<=Number.MAX_SAFE_INTEGER?zG:null;class zG extends Array{constructor(Z){super(Z);this.fill(0)}}class jW{heap;length;static#Z=!1;static create(Z){let J=Wu(Z);if(!J)return[];jW.#Z=!0;let X=new jW(Z,J);return jW.#Z=!1,X}constructor(Z,J){if(!jW.#Z)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new J(Z),this.length=0}push(Z){this.heap[this.length++]=Z}pop(){return this.heap[--this.length]}}class FG{#Z;#X;#J;#$;#Y;#Q;#W;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#K;#G;#H;#z;#V;#U;#L;#B;#O;#k;#N;#E;#R;#M;#j;#C;#w;#v;static unsafeExposeInternals(Z){return{starts:Z.#R,ttls:Z.#M,sizes:Z.#E,keyMap:Z.#H,keyList:Z.#z,valList:Z.#V,next:Z.#U,prev:Z.#L,get head(){return Z.#B},get tail(){return Z.#O},free:Z.#k,isBackgroundFetch:(J)=>Z.#F(J),backgroundFetch:(J,X,$,Y)=>Z.#f(J,X,$,Y),moveToTail:(J)=>Z.#y(J),indexes:(J)=>Z.#T(J),rindexes:(J)=>Z.#I(J),isStale:(J)=>Z.#P(J)}}get max(){return this.#Z}get maxSize(){return this.#X}get calculatedSize(){return this.#G}get size(){return this.#K}get fetchMethod(){return this.#Q}get memoMethod(){return this.#W}get dispose(){return this.#J}get onInsert(){return this.#$}get disposeAfter(){return this.#Y}constructor(Z){let{max:J=0,ttl:X,ttlResolution:$=1,ttlAutopurge:Y,updateAgeOnGet:Q,updateAgeOnHas:W,allowStale:K,dispose:G,onInsert:V,disposeAfter:H,noDisposeOnSet:q,noUpdateTTL:z,maxSize:F=0,maxEntrySize:U=0,sizeCalculation:L,fetchMethod:B,memoMethod:w,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:M,allowStaleOnFetchRejection:N,allowStaleOnFetchAbort:P,ignoreFetchAbort:D}=Z;if(J!==0&&!e1(J))throw new TypeError("max option must be a nonnegative integer");let C=J?Wu(J):Array;if(!C)throw new Error("invalid max value: "+J);if(this.#Z=J,this.#X=F,this.maxEntrySize=U||this.#X,this.sizeCalculation=L,this.sizeCalculation){if(!this.#X&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw new TypeError("sizeCalculation set to non-function")}if(w!==void 0&&typeof w!=="function")throw new TypeError("memoMethod must be a function if defined");if(this.#W=w,B!==void 0&&typeof B!=="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#Q=B,this.#C=!!B,this.#H=new Map,this.#z=new Array(J).fill(void 0),this.#V=new Array(J).fill(void 0),this.#U=new C(J),this.#L=new C(J),this.#B=0,this.#O=0,this.#k=jW.create(J),this.#K=0,this.#G=0,typeof G==="function")this.#J=G;if(typeof V==="function")this.#$=V;if(typeof H==="function")this.#Y=H,this.#N=[];else this.#Y=void 0,this.#N=void 0;if(this.#j=!!this.#J,this.#v=!!this.#$,this.#w=!!this.#Y,this.noDisposeOnSet=!!q,this.noUpdateTTL=!!z,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!N,this.allowStaleOnFetchAbort=!!P,this.ignoreFetchAbort=!!D,this.maxEntrySize!==0){if(this.#X!==0){if(!e1(this.#X))throw new TypeError("maxSize must be a positive integer if specified")}if(!e1(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#m()}if(this.allowStale=!!K,this.noDeleteOnStaleGet=!!M,this.updateAgeOnGet=!!Q,this.updateAgeOnHas=!!W,this.ttlResolution=e1($)||$===0?$:1,this.ttlAutopurge=!!Y,this.ttl=X||0,this.ttl){if(!e1(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#q()}if(this.#Z===0&&this.ttl===0&&this.#X===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#Z&&!this.#X){if(AG5("LRU_CACHE_UNBOUNDED"))Yu.add("LRU_CACHE_UNBOUNDED"),Qu("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",FG)}}getRemainingTTL(Z){return this.#H.has(Z)?1/0:0}#q(){let Z=new zG(this.#Z),J=new zG(this.#Z);this.#M=Z,this.#R=J,this.#S=(Y,Q,W=NW.now())=>{if(J[Y]=Q!==0?W:0,Z[Y]=Q,Q!==0&&this.ttlAutopurge){let K=setTimeout(()=>{if(this.#P(Y))this.#_(this.#z[Y],"expire")},Q+1);if(K.unref)K.unref()}},this.#A=(Y)=>{J[Y]=Z[Y]!==0?NW.now():0},this.#D=(Y,Q)=>{if(Z[Q]){let W=Z[Q],K=J[Q];if(!W||!K)return;Y.ttl=W,Y.start=K,Y.now=X||$();let G=Y.now-K;Y.remainingTTL=W-G}};let X=0,$=()=>{let Y=NW.now();if(this.ttlResolution>0){X=Y;let Q=setTimeout(()=>X=0,this.ttlResolution);if(Q.unref)Q.unref()}return Y};this.getRemainingTTL=(Y)=>{let Q=this.#H.get(Y);if(Q===void 0)return 0;let W=Z[Q],K=J[Q];if(!W||!K)return 1/0;let G=(X||$())-K;return W-G},this.#P=(Y)=>{let Q=J[Y],W=Z[Y];return!!W&&!!Q&&(X||$())-Q>W}}#A=()=>{};#D=()=>{};#S=()=>{};#P=()=>!1;#m(){let Z=new zG(this.#Z);this.#G=0,this.#E=Z,this.#x=(J)=>{this.#G-=Z[J],Z[J]=0},this.#d=(J,X,$,Y)=>{if(this.#F(X))return 0;if(!e1($))if(Y){if(typeof Y!=="function")throw new TypeError("sizeCalculation must be a function");if($=Y(X,J),!e1($))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return $},this.#h=(J,X,$)=>{if(Z[J]=X,this.#X){let Y=this.#X-Z[J];while(this.#G>Y)this.#b(!0)}if(this.#G+=Z[J],$)$.entrySize=X,$.totalCalculatedSize=this.#G}}#x=(Z)=>{};#h=(Z,J,X)=>{};#d=(Z,J,X,$)=>{if(X||$)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#T({allowStale:Z=this.allowStale}={}){if(this.#K)for(let J=this.#O;;){if(!this.#u(J))break;if(Z||!this.#P(J))yield J;if(J===this.#B)break;else J=this.#L[J]}}*#I({allowStale:Z=this.allowStale}={}){if(this.#K)for(let J=this.#B;;){if(!this.#u(J))break;if(Z||!this.#P(J))yield J;if(J===this.#O)break;else J=this.#U[J]}}#u(Z){return Z!==void 0&&this.#H.get(this.#z[Z])===Z}*entries(){for(let Z of this.#T())if(this.#V[Z]!==void 0&&this.#z[Z]!==void 0&&!this.#F(this.#V[Z]))yield[this.#z[Z],this.#V[Z]]}*rentries(){for(let Z of this.#I())if(this.#V[Z]!==void 0&&this.#z[Z]!==void 0&&!this.#F(this.#V[Z]))yield[this.#z[Z],this.#V[Z]]}*keys(){for(let Z of this.#T()){let J=this.#z[Z];if(J!==void 0&&!this.#F(this.#V[Z]))yield J}}*rkeys(){for(let Z of this.#I()){let J=this.#z[Z];if(J!==void 0&&!this.#F(this.#V[Z]))yield J}}*values(){for(let Z of this.#T())if(this.#V[Z]!==void 0&&!this.#F(this.#V[Z]))yield this.#V[Z]}*rvalues(){for(let Z of this.#I())if(this.#V[Z]!==void 0&&!this.#F(this.#V[Z]))yield this.#V[Z]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(Z,J={}){for(let X of this.#T()){let $=this.#V[X],Y=this.#F($)?$.__staleWhileFetching:$;if(Y===void 0)continue;if(Z(Y,this.#z[X],this))return this.get(this.#z[X],J)}}forEach(Z,J=this){for(let X of this.#T()){let $=this.#V[X],Y=this.#F($)?$.__staleWhileFetching:$;if(Y===void 0)continue;Z.call(J,Y,this.#z[X],this)}}rforEach(Z,J=this){for(let X of this.#I()){let $=this.#V[X],Y=this.#F($)?$.__staleWhileFetching:$;if(Y===void 0)continue;Z.call(J,Y,this.#z[X],this)}}purgeStale(){let Z=!1;for(let J of this.#I({allowStale:!0}))if(this.#P(J))this.#_(this.#z[J],"expire"),Z=!0;return Z}info(Z){let J=this.#H.get(Z);if(J===void 0)return;let X=this.#V[J],$=this.#F(X)?X.__staleWhileFetching:X;if($===void 0)return;let Y={value:$};if(this.#M&&this.#R){let Q=this.#M[J],W=this.#R[J];if(Q&&W){let K=Q-(NW.now()-W);Y.ttl=K,Y.start=Date.now()}}if(this.#E)Y.size=this.#E[J];return Y}dump(){let Z=[];for(let J of this.#T({allowStale:!0})){let X=this.#z[J],$=this.#V[J],Y=this.#F($)?$.__staleWhileFetching:$;if(Y===void 0||X===void 0)continue;let Q={value:Y};if(this.#M&&this.#R){Q.ttl=this.#M[J];let W=NW.now()-this.#R[J];Q.start=Math.floor(Date.now()-W)}if(this.#E)Q.size=this.#E[J];Z.unshift([X,Q])}return Z}load(Z){this.clear();for(let[J,X]of Z){if(X.start){let $=Date.now()-X.start;X.start=NW.now()-$}this.set(J,X.value,X)}}set(Z,J,X={}){if(J===void 0)return this.delete(Z),this;let{ttl:$=this.ttl,start:Y,noDisposeOnSet:Q=this.noDisposeOnSet,sizeCalculation:W=this.sizeCalculation,status:K}=X,{noUpdateTTL:G=this.noUpdateTTL}=X,V=this.#d(Z,J,X.size||0,W);if(this.maxEntrySize&&V>this.maxEntrySize){if(K)K.set="miss",K.maxEntrySizeExceeded=!0;return this.#_(Z,"set"),this}let H=this.#K===0?void 0:this.#H.get(Z);if(H===void 0){if(H=this.#K===0?this.#O:this.#k.length!==0?this.#k.pop():this.#K===this.#Z?this.#b(!1):this.#K,this.#z[H]=Z,this.#V[H]=J,this.#H.set(Z,H),this.#U[this.#O]=H,this.#L[H]=this.#O,this.#O=H,this.#K++,this.#h(H,V,K),K)K.set="add";if(G=!1,this.#v)this.#$?.(J,Z,"add")}else{this.#y(H);let q=this.#V[H];if(J!==q){if(this.#C&&this.#F(q)){q.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:z}=q;if(z!==void 0&&!Q){if(this.#j)this.#J?.(z,Z,"set");if(this.#w)this.#N?.push([z,Z,"set"])}}else if(!Q){if(this.#j)this.#J?.(q,Z,"set");if(this.#w)this.#N?.push([q,Z,"set"])}if(this.#x(H),this.#h(H,V,K),this.#V[H]=J,K){K.set="replace";let z=q&&this.#F(q)?q.__staleWhileFetching:q;if(z!==void 0)K.oldValue=z}}else if(K)K.set="update";if(this.#v)this.onInsert?.(J,Z,J===q?"update":"replace")}if($!==0&&!this.#M)this.#q();if(this.#M){if(!G)this.#S(H,$,Y);if(K)this.#D(K,H)}if(!Q&&this.#w&&this.#N){let q=this.#N,z;while(z=q?.shift())this.#Y?.(...z)}return this}pop(){try{while(this.#K){let Z=this.#V[this.#B];if(this.#b(!0),this.#F(Z)){if(Z.__staleWhileFetching)return Z.__staleWhileFetching}else if(Z!==void 0)return Z}}finally{if(this.#w&&this.#N){let Z=this.#N,J;while(J=Z?.shift())this.#Y?.(...J)}}}#b(Z){let J=this.#B,X=this.#z[J],$=this.#V[J];if(this.#C&&this.#F($))$.__abortController.abort(new Error("evicted"));else if(this.#j||this.#w){if(this.#j)this.#J?.($,X,"evict");if(this.#w)this.#N?.push([$,X,"evict"])}if(this.#x(J),Z)this.#z[J]=void 0,this.#V[J]=void 0,this.#k.push(J);if(this.#K===1)this.#B=this.#O=0,this.#k.length=0;else this.#B=this.#U[J];return this.#H.delete(X),this.#K--,J}has(Z,J={}){let{updateAgeOnHas:X=this.updateAgeOnHas,status:$}=J,Y=this.#H.get(Z);if(Y!==void 0){let Q=this.#V[Y];if(this.#F(Q)&&Q.__staleWhileFetching===void 0)return!1;if(!this.#P(Y)){if(X)this.#A(Y);if($)$.has="hit",this.#D($,Y);return!0}else if($)$.has="stale",this.#D($,Y)}else if($)$.has="miss";return!1}peek(Z,J={}){let{allowStale:X=this.allowStale}=J,$=this.#H.get(Z);if($===void 0||!X&&this.#P($))return;let Y=this.#V[$];return this.#F(Y)?Y.__staleWhileFetching:Y}#f(Z,J,X,$){let Y=J===void 0?void 0:this.#V[J];if(this.#F(Y))return Y;let Q=new FF,{signal:W}=X;W?.addEventListener("abort",()=>Q.abort(W.reason),{signal:Q.signal});let K={signal:Q.signal,options:X,context:$},G=(U,L=!1)=>{let{aborted:B}=Q.signal,w=X.ignoreFetchAbort&&U!==void 0;if(X.status)if(B&&!L){if(X.status.fetchAborted=!0,X.status.fetchError=Q.signal.reason,w)X.status.fetchAbortIgnored=!0}else X.status.fetchResolved=!0;if(B&&!w&&!L)return H(Q.signal.reason);let O=z;if(this.#V[J]===z)if(U===void 0)if(O.__staleWhileFetching)this.#V[J]=O.__staleWhileFetching;else this.#_(Z,"fetch");else{if(X.status)X.status.fetchUpdated=!0;this.set(Z,U,K.options)}return U},V=(U)=>{if(X.status)X.status.fetchRejected=!0,X.status.fetchError=U;return H(U)},H=(U)=>{let{aborted:L}=Q.signal,B=L&&X.allowStaleOnFetchAbort,w=B||X.allowStaleOnFetchRejection,O=w||X.noDeleteOnFetchRejection,M=z;if(this.#V[J]===z){if(!O||M.__staleWhileFetching===void 0)this.#_(Z,"fetch");else if(!B)this.#V[J]=M.__staleWhileFetching}if(w){if(X.status&&M.__staleWhileFetching!==void 0)X.status.returnedStale=!0;return M.__staleWhileFetching}else if(M.__returned===M)throw U},q=(U,L)=>{let B=this.#Q?.(Z,Y,K);if(B&&B instanceof Promise)B.then((w)=>U(w===void 0?void 0:w),L);Q.signal.addEventListener("abort",()=>{if(!X.ignoreFetchAbort||X.allowStaleOnFetchAbort){if(U(void 0),X.allowStaleOnFetchAbort)U=(w)=>G(w,!0)}})};if(X.status)X.status.fetchDispatched=!0;let z=new Promise(q).then(G,V),F=Object.assign(z,{__abortController:Q,__staleWhileFetching:Y,__returned:void 0});if(J===void 0)this.set(Z,F,{...K.options,status:void 0}),J=this.#H.get(Z);else this.#V[J]=F;return F}#F(Z){if(!this.#C)return!1;let J=Z;return!!J&&J instanceof Promise&&J.hasOwnProperty("__staleWhileFetching")&&J.__abortController instanceof FF}async fetch(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:$=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,ttl:Q=this.ttl,noDisposeOnSet:W=this.noDisposeOnSet,size:K=0,sizeCalculation:G=this.sizeCalculation,noUpdateTTL:V=this.noUpdateTTL,noDeleteOnFetchRejection:H=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:q=this.allowStaleOnFetchRejection,ignoreFetchAbort:z=this.ignoreFetchAbort,allowStaleOnFetchAbort:F=this.allowStaleOnFetchAbort,context:U,forceRefresh:L=!1,status:B,signal:w}=J;if(!this.#C){if(B)B.fetch="get";return this.get(Z,{allowStale:X,updateAgeOnGet:$,noDeleteOnStaleGet:Y,status:B})}let O={allowStale:X,updateAgeOnGet:$,noDeleteOnStaleGet:Y,ttl:Q,noDisposeOnSet:W,size:K,sizeCalculation:G,noUpdateTTL:V,noDeleteOnFetchRejection:H,allowStaleOnFetchRejection:q,allowStaleOnFetchAbort:F,ignoreFetchAbort:z,status:B,signal:w},M=this.#H.get(Z);if(M===void 0){if(B)B.fetch="miss";let N=this.#f(Z,M,O,U);return N.__returned=N}else{let N=this.#V[M];if(this.#F(N)){let k=X&&N.__staleWhileFetching!==void 0;if(B){if(B.fetch="inflight",k)B.returnedStale=!0}return k?N.__staleWhileFetching:N.__returned=N}let P=this.#P(M);if(!L&&!P){if(B)B.fetch="hit";if(this.#y(M),$)this.#A(M);if(B)this.#D(B,M);return N}let D=this.#f(Z,M,O,U),T=D.__staleWhileFetching!==void 0&&X;if(B){if(B.fetch=P?"stale":"refresh",T&&P)B.returnedStale=!0}return T?D.__staleWhileFetching:D.__returned=D}}async forceFetch(Z,J={}){let X=await this.fetch(Z,J);if(X===void 0)throw new Error("fetch() returned undefined");return X}memo(Z,J={}){let X=this.#W;if(!X)throw new Error("no memoMethod provided to constructor");let{context:$,forceRefresh:Y,...Q}=J,W=this.get(Z,Q);if(!Y&&W!==void 0)return W;let K=X(Z,W,{options:Q,context:$});return this.set(Z,K,Q),K}get(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:$=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,status:Q}=J,W=this.#H.get(Z);if(W!==void 0){let K=this.#V[W],G=this.#F(K);if(Q)this.#D(Q,W);if(this.#P(W)){if(Q)Q.get="stale";if(!G){if(!Y)this.#_(Z,"expire");if(Q&&X)Q.returnedStale=!0;return X?K:void 0}else{if(Q&&X&&K.__staleWhileFetching!==void 0)Q.returnedStale=!0;return X?K.__staleWhileFetching:void 0}}else{if(Q)Q.get="hit";if(G)return K.__staleWhileFetching;if(this.#y(W),$)this.#A(W);return K}}else if(Q)Q.get="miss"}#c(Z,J){this.#L[J]=Z,this.#U[Z]=J}#y(Z){if(Z!==this.#O){if(Z===this.#B)this.#B=this.#U[Z];else this.#c(this.#L[Z],this.#U[Z]);this.#c(this.#O,Z),this.#O=Z}}delete(Z){return this.#_(Z,"delete")}#_(Z,J){let X=!1;if(this.#K!==0){let $=this.#H.get(Z);if($!==void 0)if(X=!0,this.#K===1)this.#g(J);else{this.#x($);let Y=this.#V[$];if(this.#F(Y))Y.__abortController.abort(new Error("deleted"));else if(this.#j||this.#w){if(this.#j)this.#J?.(Y,Z,J);if(this.#w)this.#N?.push([Y,Z,J])}if(this.#H.delete(Z),this.#z[$]=void 0,this.#V[$]=void 0,$===this.#O)this.#O=this.#L[$];else if($===this.#B)this.#B=this.#U[$];else{let Q=this.#L[$];this.#U[Q]=this.#U[$];let W=this.#U[$];this.#L[W]=this.#L[$]}this.#K--,this.#k.push($)}}if(this.#w&&this.#N?.length){let $=this.#N,Y;while(Y=$?.shift())this.#Y?.(...Y)}return X}clear(){return this.#g("delete")}#g(Z){for(let J of this.#I({allowStale:!0})){let X=this.#V[J];if(this.#F(X))X.__abortController.abort(new Error("deleted"));else{let $=this.#z[J];if(this.#j)this.#J?.(X,$,Z);if(this.#w)this.#N?.push([X,$,Z])}}if(this.#H.clear(),this.#V.fill(void 0),this.#z.fill(void 0),this.#M&&this.#R)this.#M.fill(0),this.#R.fill(0);if(this.#E)this.#E.fill(0);if(this.#B=0,this.#O=0,this.#k.length=0,this.#G=0,this.#K=0,this.#w&&this.#N){let J=this.#N,X;while(X=J?.shift())this.#Y?.(...X)}}}import{posix as lG5,win32 as PR}from"node:path";import{fileURLToPath as pG5}from"node:url";import{lstatSync as iG5,readdir as nG5,readdirSync as sG5,readlinkSync as aG5,realpathSync as rG5}from"fs";import*as oG5 from"node:fs";import{lstat as eG5,readdir as ZV5,readlink as JV5,realpath as XV5}from"node:fs/promises";import{EventEmitter as jR}from"node:events";import qu from"node:stream";import{StringDecoder as xG5}from"node:string_decoder";var Ku=typeof process==="object"&&process?process:{stdout:null,stderr:null},fG5=(Z)=>!!Z&&typeof Z==="object"&&(Z instanceof s$||Z instanceof qu||hG5(Z)||bG5(Z)),hG5=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof jR&&typeof Z.pipe==="function"&&Z.pipe!==qu.Writable.prototype.pipe,bG5=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof jR&&typeof Z.write==="function"&&typeof Z.end==="function",cJ=Symbol("EOF"),lJ=Symbol("maybeEmitEnd"),ZX=Symbol("emittedEnd"),UF=Symbol("emittingEnd"),UG=Symbol("emittedError"),BF=Symbol("closed"),Gu=Symbol("read"),LF=Symbol("flush"),Vu=Symbol("flushChunk"),YZ=Symbol("encoding"),MW=Symbol("decoder"),d8=Symbol("flowing"),BG=Symbol("paused"),RW=Symbol("resume"),u8=Symbol("buffer"),S6=Symbol("pipes"),c8=Symbol("bufferLength"),BR=Symbol("bufferPush"),wF=Symbol("bufferShift"),q6=Symbol("objectMode"),w8=Symbol("destroyed"),LR=Symbol("error"),wR=Symbol("emitData"),Hu=Symbol("emitEnd"),OR=Symbol("emitEnd2"),lZ=Symbol("async"),NR=Symbol("abort"),OF=Symbol("aborted"),LG=Symbol("signal"),n$=Symbol("dataListeners"),E7=Symbol("discarded"),wG=(Z)=>Promise.resolve().then(Z),yG5=(Z)=>Z(),gG5=(Z)=>Z==="end"||Z==="finish"||Z==="prefinish",mG5=(Z)=>Z instanceof ArrayBuffer||!!Z&&typeof Z==="object"&&Z.constructor&&Z.constructor.name==="ArrayBuffer"&&Z.byteLength>=0,dG5=(Z)=>!Buffer.isBuffer(Z)&&ArrayBuffer.isView(Z);class MR{src;dest;opts;ondrain;constructor(Z,J,X){this.src=Z,this.dest=J,this.opts=X,this.ondrain=()=>Z[RW](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(Z){}end(){if(this.unpipe(),this.opts.end)this.dest.end()}}class zu extends MR{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(Z,J,X){super(Z,J,X);this.proxyErrors=($)=>J.emit("error",$),Z.on("error",this.proxyErrors)}}var uG5=(Z)=>!!Z.objectMode,cG5=(Z)=>!Z.objectMode&&!!Z.encoding&&Z.encoding!=="buffer";class s$ extends jR{[d8]=!1;[BG]=!1;[S6]=[];[u8]=[];[q6];[YZ];[lZ];[MW];[cJ]=!1;[ZX]=!1;[UF]=!1;[BF]=!1;[UG]=null;[c8]=0;[w8]=!1;[LG];[OF]=!1;[n$]=0;[E7]=!1;writable=!0;readable=!0;constructor(...Z){let J=Z[0]||{};super();if(J.objectMode&&typeof J.encoding==="string")throw new TypeError("Encoding and objectMode may not be used together");if(uG5(J))this[q6]=!0,this[YZ]=null;else if(cG5(J))this[YZ]=J.encoding,this[q6]=!1;else this[q6]=!1,this[YZ]=null;if(this[lZ]=!!J.async,this[MW]=this[YZ]?new xG5(this[YZ]):null,J&&J.debugExposeBuffer===!0)Object.defineProperty(this,"buffer",{get:()=>this[u8]});if(J&&J.debugExposePipes===!0)Object.defineProperty(this,"pipes",{get:()=>this[S6]});let{signal:X}=J;if(X)if(this[LG]=X,X.aborted)this[NR]();else X.addEventListener("abort",()=>this[NR]())}get bufferLength(){return this[c8]}get encoding(){return this[YZ]}set encoding(Z){throw new Error("Encoding must be set at instantiation time")}setEncoding(Z){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[q6]}set objectMode(Z){throw new Error("objectMode must be set at instantiation time")}get["async"](){return this[lZ]}set["async"](Z){this[lZ]=this[lZ]||!!Z}[NR](){this[OF]=!0,this.emit("abort",this[LG]?.reason),this.destroy(this[LG]?.reason)}get aborted(){return this[OF]}set aborted(Z){}write(Z,J,X){if(this[OF])return!1;if(this[cJ])throw new Error("write after end");if(this[w8])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;if(typeof J==="function")X=J,J="utf8";if(!J)J="utf8";let $=this[lZ]?wG:yG5;if(!this[q6]&&!Buffer.isBuffer(Z)){if(dG5(Z))Z=Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength);else if(mG5(Z))Z=Buffer.from(Z);else if(typeof Z!=="string")throw new Error("Non-contiguous data written to non-objectMode stream")}if(this[q6]){if(this[d8]&&this[c8]!==0)this[LF](!0);if(this[d8])this.emit("data",Z);else this[BR](Z);if(this[c8]!==0)this.emit("readable");if(X)$(X);return this[d8]}if(!Z.length){if(this[c8]!==0)this.emit("readable");if(X)$(X);return this[d8]}if(typeof Z==="string"&&!(J===this[YZ]&&!this[MW]?.lastNeed))Z=Buffer.from(Z,J);if(Buffer.isBuffer(Z)&&this[YZ])Z=this[MW].write(Z);if(this[d8]&&this[c8]!==0)this[LF](!0);if(this[d8])this.emit("data",Z);else this[BR](Z);if(this[c8]!==0)this.emit("readable");if(X)$(X);return this[d8]}read(Z){if(this[w8])return null;if(this[E7]=!1,this[c8]===0||Z===0||Z&&Z>this[c8])return this[lJ](),null;if(this[q6])Z=null;if(this[u8].length>1&&!this[q6])this[u8]=[this[YZ]?this[u8].join(""):Buffer.concat(this[u8],this[c8])];let J=this[Gu](Z||null,this[u8][0]);return this[lJ](),J}[Gu](Z,J){if(this[q6])this[wF]();else{let X=J;if(Z===X.length||Z===null)this[wF]();else if(typeof X==="string")this[u8][0]=X.slice(Z),J=X.slice(0,Z),this[c8]-=Z;else this[u8][0]=X.subarray(Z),J=X.subarray(0,Z),this[c8]-=Z}if(this.emit("data",J),!this[u8].length&&!this[cJ])this.emit("drain");return J}end(Z,J,X){if(typeof Z==="function")X=Z,Z=void 0;if(typeof J==="function")X=J,J="utf8";if(Z!==void 0)this.write(Z,J);if(X)this.once("end",X);if(this[cJ]=!0,this.writable=!1,this[d8]||!this[BG])this[lJ]();return this}[RW](){if(this[w8])return;if(!this[n$]&&!this[S6].length)this[E7]=!0;if(this[BG]=!1,this[d8]=!0,this.emit("resume"),this[u8].length)this[LF]();else if(this[cJ])this[lJ]();else this.emit("drain")}resume(){return this[RW]()}pause(){this[d8]=!1,this[BG]=!0,this[E7]=!1}get destroyed(){return this[w8]}get flowing(){return this[d8]}get paused(){return this[BG]}[BR](Z){if(this[q6])this[c8]+=1;else this[c8]+=Z.length;this[u8].push(Z)}[wF](){if(this[q6])this[c8]-=1;else this[c8]-=this[u8][0].length;return this[u8].shift()}[LF](Z=!1){do;while(this[Vu](this[wF]())&&this[u8].length);if(!Z&&!this[u8].length&&!this[cJ])this.emit("drain")}[Vu](Z){return this.emit("data",Z),this[d8]}pipe(Z,J){if(this[w8])return Z;this[E7]=!1;let X=this[ZX];if(J=J||{},Z===Ku.stdout||Z===Ku.stderr)J.end=!1;else J.end=J.end!==!1;if(J.proxyErrors=!!J.proxyErrors,X){if(J.end)Z.end()}else if(this[S6].push(!J.proxyErrors?new MR(this,Z,J):new zu(this,Z,J)),this[lZ])wG(()=>this[RW]());else this[RW]();return Z}unpipe(Z){let J=this[S6].find((X)=>X.dest===Z);if(J){if(this[S6].length===1){if(this[d8]&&this[n$]===0)this[d8]=!1;this[S6]=[]}else this[S6].splice(this[S6].indexOf(J),1);J.unpipe()}}addListener(Z,J){return this.on(Z,J)}on(Z,J){let X=super.on(Z,J);if(Z==="data"){if(this[E7]=!1,this[n$]++,!this[S6].length&&!this[d8])this[RW]()}else if(Z==="readable"&&this[c8]!==0)super.emit("readable");else if(gG5(Z)&&this[ZX])super.emit(Z),this.removeAllListeners(Z);else if(Z==="error"&&this[UG]){let $=J;if(this[lZ])wG(()=>$.call(this,this[UG]));else $.call(this,this[UG])}return X}removeListener(Z,J){return this.off(Z,J)}off(Z,J){let X=super.off(Z,J);if(Z==="data"){if(this[n$]=this.listeners("data").length,this[n$]===0&&!this[E7]&&!this[S6].length)this[d8]=!1}return X}removeAllListeners(Z){let J=super.removeAllListeners(Z);if(Z==="data"||Z===void 0){if(this[n$]=0,!this[E7]&&!this[S6].length)this[d8]=!1}return J}get emittedEnd(){return this[ZX]}[lJ](){if(!this[UF]&&!this[ZX]&&!this[w8]&&this[u8].length===0&&this[cJ]){if(this[UF]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[BF])this.emit("close");this[UF]=!1}}emit(Z,...J){let X=J[0];if(Z!=="error"&&Z!=="close"&&Z!==w8&&this[w8])return!1;else if(Z==="data")return!this[q6]&&!X?!1:this[lZ]?(wG(()=>this[wR](X)),!0):this[wR](X);else if(Z==="end")return this[Hu]();else if(Z==="close"){if(this[BF]=!0,!this[ZX]&&!this[w8])return!1;let Y=super.emit("close");return this.removeAllListeners("close"),Y}else if(Z==="error"){this[UG]=X,super.emit(LR,X);let Y=!this[LG]||this.listeners("error").length?super.emit("error",X):!1;return this[lJ](),Y}else if(Z==="resume"){let Y=super.emit("resume");return this[lJ](),Y}else if(Z==="finish"||Z==="prefinish"){let Y=super.emit(Z);return this.removeAllListeners(Z),Y}let $=super.emit(Z,...J);return this[lJ](),$}[wR](Z){for(let X of this[S6])if(X.dest.write(Z)===!1)this.pause();let J=this[E7]?!1:super.emit("data",Z);return this[lJ](),J}[Hu](){if(this[ZX])return!1;return this[ZX]=!0,this.readable=!1,this[lZ]?(wG(()=>this[OR]()),!0):this[OR]()}[OR](){if(this[MW]){let J=this[MW].end();if(J){for(let X of this[S6])X.dest.write(J);if(!this[E7])super.emit("data",J)}}for(let J of this[S6])J.end();let Z=super.emit("end");return this.removeAllListeners("end"),Z}async collect(){let Z=Object.assign([],{dataLength:0});if(!this[q6])Z.dataLength=0;let J=this.promise();return this.on("data",(X)=>{if(Z.push(X),!this[q6])Z.dataLength+=X.length}),await J,Z}async concat(){if(this[q6])throw new Error("cannot concat in objectMode");let Z=await this.collect();return this[YZ]?Z.join(""):Buffer.concat(Z,Z.dataLength)}async promise(){return new Promise((Z,J)=>{this.on(w8,()=>J(new Error("stream destroyed"))),this.on("error",(X)=>J(X)),this.on("end",()=>Z())})}[Symbol.asyncIterator](){this[E7]=!1;let Z=!1,J=async()=>{return this.pause(),Z=!0,{value:void 0,done:!0}};return{next:()=>{if(Z)return J();let $=this.read();if($!==null)return Promise.resolve({done:!1,value:$});if(this[cJ])return J();let Y,Q,W=(H)=>{this.off("data",K),this.off("end",G),this.off(w8,V),J(),Q(H)},K=(H)=>{this.off("error",W),this.off("end",G),this.off(w8,V),this.pause(),Y({value:H,done:!!this[cJ]})},G=()=>{this.off("error",W),this.off("data",K),this.off(w8,V),J(),Y({done:!0,value:void 0})},V=()=>W(new Error("stream destroyed"));return new Promise((H,q)=>{Q=q,Y=H,this.once(w8,V),this.once("error",W),this.once("end",G),this.once("data",K)})},throw:J,return:J,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[E7]=!1;let Z=!1,J=()=>{return this.pause(),this.off(LR,J),this.off(w8,J),this.off("end",J),Z=!0,{done:!0,value:void 0}},X=()=>{if(Z)return J();let $=this.read();return $===null?J():{done:!1,value:$}};return this.once("end",J),this.once(LR,J),this.once(w8,J),{next:X,throw:J,return:J,[Symbol.iterator](){return this}}}destroy(Z){if(this[w8]){if(Z)this.emit("error",Z);else this.emit(w8);return this}this[w8]=!0,this[E7]=!0,this[u8].length=0,this[c8]=0;let J=this;if(typeof J.close==="function"&&!this[BF])J.close();if(Z)this.emit("error",Z);else this.emit(w8);return this}static get isStream(){return fG5}}var tG5=rG5.native,NG={lstatSync:iG5,readdir:nG5,readdirSync:sG5,readlinkSync:aG5,realpathSync:tG5,promises:{lstat:eG5,readdir:ZV5,readlink:JV5,realpath:XV5}},wu=(Z)=>!Z||Z===NG||Z===oG5?NG:{...NG,...Z,promises:{...NG.promises,...Z.promises||{}}},Ou=/^\\\\\?\\([a-z]:)\\?$/i,$V5=(Z)=>Z.replace(/\//g,"\\").replace(Ou,"$1\\"),YV5=/[\\\/]/,V9=0,Nu=1,ju=2,pZ=4,Mu=6,Ru=8,a$=10,Du=12,G9=15,OG=~G9,RR=16,Fu=32,jG=64,QZ=128,NF=256,MF=512,Uu=jG|QZ|MF,QV5=1023,DR=(Z)=>Z.isFile()?Ru:Z.isDirectory()?pZ:Z.isSymbolicLink()?a$:Z.isCharacterDevice()?ju:Z.isBlockDevice()?Mu:Z.isSocket()?Du:Z.isFIFO()?Nu:V9,Bu=new Map,MG=(Z)=>{let J=Bu.get(Z);if(J)return J;let X=Z.normalize("NFKD");return Bu.set(Z,X),X},Lu=new Map,jF=(Z)=>{let J=Lu.get(Z);if(J)return J;let X=MG(Z.toLowerCase());return Lu.set(Z,X),X};class CR extends FG{constructor(){super({max:256})}}class Pu extends FG{constructor(Z=16384){super({maxSize:Z,sizeCalculation:(J)=>J.length+1})}}var Cu=Symbol("PathScurry setAsCwd");class _6{name;root;roots;parent;nocase;isCWD=!1;#Z;#X;get dev(){return this.#X}#J;get mode(){return this.#J}#$;get nlink(){return this.#$}#Y;get uid(){return this.#Y}#Q;get gid(){return this.#Q}#W;get rdev(){return this.#W}#K;get blksize(){return this.#K}#G;get ino(){return this.#G}#H;get size(){return this.#H}#z;get blocks(){return this.#z}#V;get atimeMs(){return this.#V}#U;get mtimeMs(){return this.#U}#L;get ctimeMs(){return this.#L}#B;get birthtimeMs(){return this.#B}#O;get atime(){return this.#O}#k;get mtime(){return this.#k}#N;get ctime(){return this.#N}#E;get birthtime(){return this.#E}#R;#M;#j;#C;#w;#v;#q;#A;#D;#S;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(Z,J=V9,X,$,Y,Q,W){if(this.name=Z,this.#R=Y?jF(Z):MG(Z),this.#q=J&QV5,this.nocase=Y,this.roots=$,this.root=X||this,this.#A=Q,this.#j=W.fullpath,this.#w=W.relative,this.#v=W.relativePosix,this.parent=W.parent,this.parent)this.#Z=this.parent.#Z;else this.#Z=wu(W.fs)}depth(){if(this.#M!==void 0)return this.#M;if(!this.parent)return this.#M=0;return this.#M=this.parent.depth()+1}childrenCache(){return this.#A}resolve(Z){if(!Z)return this;let J=this.getRootString(Z),$=Z.substring(J.length).split(this.splitSep);return J?this.getRoot(J).#P($):this.#P($)}#P(Z){let J=this;for(let X of Z)J=J.child(X);return J}children(){let Z=this.#A.get(this);if(Z)return Z;let J=Object.assign([],{provisional:0});return this.#A.set(this,J),this.#q&=~RR,J}child(Z,J){if(Z===""||Z===".")return this;if(Z==="..")return this.parent||this;let X=this.children(),$=this.nocase?jF(Z):MG(Z);for(let K of X)if(K.#R===$)return K;let Y=this.parent?this.sep:"",Q=this.#j?this.#j+Y+Z:void 0,W=this.newChild(Z,V9,{...J,parent:this,fullpath:Q});if(!this.canReaddir())W.#q|=QZ;return X.push(W),W}relative(){if(this.isCWD)return"";if(this.#w!==void 0)return this.#w;let Z=this.name,J=this.parent;if(!J)return this.#w=this.name;let X=J.relative();return X+(!X||!J.parent?"":this.sep)+Z}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#v!==void 0)return this.#v;let Z=this.name,J=this.parent;if(!J)return this.#v=this.fullpathPosix();let X=J.relativePosix();return X+(!X||!J.parent?"":"/")+Z}fullpath(){if(this.#j!==void 0)return this.#j;let Z=this.name,J=this.parent;if(!J)return this.#j=this.name;let $=J.fullpath()+(!J.parent?"":this.sep)+Z;return this.#j=$}fullpathPosix(){if(this.#C!==void 0)return this.#C;if(this.sep==="/")return this.#C=this.fullpath();if(!this.parent){let $=this.fullpath().replace(/\\/g,"/");if(/^[a-z]:\//i.test($))return this.#C=`//?/${$}`;else return this.#C=$}let Z=this.parent,J=Z.fullpathPosix(),X=J+(!J||!Z.parent?"":"/")+this.name;return this.#C=X}isUnknown(){return(this.#q&G9)===V9}isType(Z){return this[`is${Z}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#q&G9)===Ru}isDirectory(){return(this.#q&G9)===pZ}isCharacterDevice(){return(this.#q&G9)===ju}isBlockDevice(){return(this.#q&G9)===Mu}isFIFO(){return(this.#q&G9)===Nu}isSocket(){return(this.#q&G9)===Du}isSymbolicLink(){return(this.#q&a$)===a$}lstatCached(){return this.#q&Fu?this:void 0}readlinkCached(){return this.#D}realpathCached(){return this.#S}readdirCached(){let Z=this.children();return Z.slice(0,Z.provisional)}canReadlink(){if(this.#D)return!0;if(!this.parent)return!1;let Z=this.#q&G9;return!(Z!==V9&&Z!==a$||this.#q&NF||this.#q&QZ)}calledReaddir(){return!!(this.#q&RR)}isENOENT(){return!!(this.#q&QZ)}isNamed(Z){return!this.nocase?this.#R===MG(Z):this.#R===jF(Z)}async readlink(){let Z=this.#D;if(Z)return Z;if(!this.canReadlink())return;if(!this.parent)return;try{let J=await this.#Z.promises.readlink(this.fullpath()),X=(await this.parent.realpath())?.resolve(J);if(X)return this.#D=X}catch(J){this.#b(J.code);return}}readlinkSync(){let Z=this.#D;if(Z)return Z;if(!this.canReadlink())return;if(!this.parent)return;try{let J=this.#Z.readlinkSync(this.fullpath()),X=this.parent.realpathSync()?.resolve(J);if(X)return this.#D=X}catch(J){this.#b(J.code);return}}#m(Z){this.#q|=RR;for(let J=Z.provisional;J<Z.length;J++){let X=Z[J];if(X)X.#x()}}#x(){if(this.#q&QZ)return;this.#q=(this.#q|QZ)&OG,this.#h()}#h(){let Z=this.children();Z.provisional=0;for(let J of Z)J.#x()}#d(){this.#q|=MF,this.#T()}#T(){if(this.#q&jG)return;let Z=this.#q;if((Z&G9)===pZ)Z&=OG;this.#q=Z|jG,this.#h()}#I(Z=""){if(Z==="ENOTDIR"||Z==="EPERM")this.#T();else if(Z==="ENOENT")this.#x();else this.children().provisional=0}#u(Z=""){if(Z==="ENOTDIR")this.parent.#T();else if(Z==="ENOENT")this.#x()}#b(Z=""){let J=this.#q;if(J|=NF,Z==="ENOENT")J|=QZ;if(Z==="EINVAL"||Z==="UNKNOWN")J&=OG;if(this.#q=J,Z==="ENOTDIR"&&this.parent)this.parent.#T()}#f(Z,J){return this.#c(Z,J)||this.#F(Z,J)}#F(Z,J){let X=DR(Z),$=this.newChild(Z.name,X,{parent:this}),Y=$.#q&G9;if(Y!==pZ&&Y!==a$&&Y!==V9)$.#q|=jG;return J.unshift($),J.provisional++,$}#c(Z,J){for(let X=J.provisional;X<J.length;X++){let $=J[X];if((this.nocase?jF(Z.name):MG(Z.name))!==$.#R)continue;return this.#y(Z,$,X,J)}}#y(Z,J,X,$){let Y=J.name;if(J.#q=J.#q&OG|DR(Z),Y!==Z.name)J.name=Z.name;if(X!==$.provisional){if(X===$.length-1)$.pop();else $.splice(X,1);$.unshift(J)}return $.provisional++,J}async lstat(){if((this.#q&QZ)===0)try{return this.#_(await this.#Z.promises.lstat(this.fullpath())),this}catch(Z){this.#u(Z.code)}}lstatSync(){if((this.#q&QZ)===0)try{return this.#_(this.#Z.lstatSync(this.fullpath())),this}catch(Z){this.#u(Z.code)}}#_(Z){let{atime:J,atimeMs:X,birthtime:$,birthtimeMs:Y,blksize:Q,blocks:W,ctime:K,ctimeMs:G,dev:V,gid:H,ino:q,mode:z,mtime:F,mtimeMs:U,nlink:L,rdev:B,size:w,uid:O}=Z;this.#O=J,this.#V=X,this.#E=$,this.#B=Y,this.#K=Q,this.#z=W,this.#N=K,this.#L=G,this.#X=V,this.#Q=H,this.#G=q,this.#J=z,this.#k=F,this.#U=U,this.#$=L,this.#W=B,this.#H=w,this.#Y=O;let M=DR(Z);if(this.#q=this.#q&OG|M|Fu,M!==V9&&M!==pZ&&M!==a$)this.#q|=jG}#g=[];#p=!1;#i(Z){this.#p=!1;let J=this.#g.slice();this.#g.length=0,J.forEach((X)=>X(null,Z))}readdirCB(Z,J=!1){if(!this.canReaddir()){if(J)Z(null,[]);else queueMicrotask(()=>Z(null,[]));return}let X=this.children();if(this.calledReaddir()){let Y=X.slice(0,X.provisional);if(J)Z(null,Y);else queueMicrotask(()=>Z(null,Y));return}if(this.#g.push(Z),this.#p)return;this.#p=!0;let $=this.fullpath();this.#Z.readdir($,{withFileTypes:!0},(Y,Q)=>{if(Y)this.#I(Y.code),X.provisional=0;else{for(let W of Q)this.#f(W,X);this.#m(X)}this.#i(X.slice(0,X.provisional));return})}#l;async readdir(){if(!this.canReaddir())return[];let Z=this.children();if(this.calledReaddir())return Z.slice(0,Z.provisional);let J=this.fullpath();if(this.#l)await this.#l;else{let X=()=>{};this.#l=new Promise(($)=>X=$);try{for(let $ of await this.#Z.promises.readdir(J,{withFileTypes:!0}))this.#f($,Z);this.#m(Z)}catch($){this.#I($.code),Z.provisional=0}this.#l=void 0,X()}return Z.slice(0,Z.provisional)}readdirSync(){if(!this.canReaddir())return[];let Z=this.children();if(this.calledReaddir())return Z.slice(0,Z.provisional);let J=this.fullpath();try{for(let X of this.#Z.readdirSync(J,{withFileTypes:!0}))this.#f(X,Z);this.#m(Z)}catch(X){this.#I(X.code),Z.provisional=0}return Z.slice(0,Z.provisional)}canReaddir(){if(this.#q&Uu)return!1;let Z=G9&this.#q;if(!(Z===V9||Z===pZ||Z===a$))return!1;return!0}shouldWalk(Z,J){return(this.#q&pZ)===pZ&&!(this.#q&Uu)&&!Z.has(this)&&(!J||J(this))}async realpath(){if(this.#S)return this.#S;if((MF|NF|QZ)&this.#q)return;try{let Z=await this.#Z.promises.realpath(this.fullpath());return this.#S=this.resolve(Z)}catch(Z){this.#d()}}realpathSync(){if(this.#S)return this.#S;if((MF|NF|QZ)&this.#q)return;try{let Z=this.#Z.realpathSync(this.fullpath());return this.#S=this.resolve(Z)}catch(Z){this.#d()}}[Cu](Z){if(Z===this)return;Z.isCWD=!1,this.isCWD=!0;let J=new Set([]),X=[],$=this;while($&&$.parent)J.add($),$.#w=X.join(this.sep),$.#v=X.join("/"),$=$.parent,X.push("..");$=Z;while($&&$.parent&&!J.has($))$.#w=void 0,$.#v=void 0,$=$.parent}}class RF extends _6{sep="\\";splitSep=YV5;constructor(Z,J=V9,X,$,Y,Q,W){super(Z,J,X,$,Y,Q,W)}newChild(Z,J=V9,X={}){return new RF(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}getRootString(Z){return PR.parse(Z).root}getRoot(Z){if(Z=$V5(Z.toUpperCase()),Z===this.root.name)return this.root;for(let[J,X]of Object.entries(this.roots))if(this.sameRoot(Z,J))return this.roots[Z]=X;return this.roots[Z]=new RG(Z,this).root}sameRoot(Z,J=this.root.name){return Z=Z.toUpperCase().replace(/\//g,"\\").replace(Ou,"$1\\"),Z===J}}class DF extends _6{splitSep="/";sep="/";constructor(Z,J=V9,X,$,Y,Q,W){super(Z,J,X,$,Y,Q,W)}getRootString(Z){return Z.startsWith("/")?"/":""}getRoot(Z){return this.root}newChild(Z,J=V9,X={}){return new DF(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}}class TR{root;rootPath;roots;cwd;#Z;#X;#J;nocase;#$;constructor(Z=process.cwd(),J,X,{nocase:$,childrenCacheSize:Y=16384,fs:Q=NG}={}){if(this.#$=wu(Q),Z instanceof URL||Z.startsWith("file://"))Z=pG5(Z);let W=J.resolve(Z);this.roots=Object.create(null),this.rootPath=this.parseRootPath(W),this.#Z=new CR,this.#X=new CR,this.#J=new Pu(Y);let K=W.substring(this.rootPath.length).split(X);if(K.length===1&&!K[0])K.pop();if($===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=$,this.root=this.newRoot(this.#$),this.roots[this.rootPath]=this.root;let G=this.root,V=K.length-1,H=J.sep,q=this.rootPath,z=!1;for(let F of K){let U=V--;G=G.child(F,{relative:new Array(U).fill("..").join(H),relativePosix:new Array(U).fill("..").join("/"),fullpath:q+=(z?"":H)+F}),z=!0}this.cwd=G}depth(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.depth()}childrenCache(){return this.#J}resolve(...Z){let J="";for(let Y=Z.length-1;Y>=0;Y--){let Q=Z[Y];if(!Q||Q===".")continue;if(J=J?`${Q}/${J}`:Q,this.isAbsolute(Q))break}let X=this.#Z.get(J);if(X!==void 0)return X;let $=this.cwd.resolve(J).fullpath();return this.#Z.set(J,$),$}resolvePosix(...Z){let J="";for(let Y=Z.length-1;Y>=0;Y--){let Q=Z[Y];if(!Q||Q===".")continue;if(J=J?`${Q}/${J}`:Q,this.isAbsolute(Q))break}let X=this.#X.get(J);if(X!==void 0)return X;let $=this.cwd.resolve(J).fullpathPosix();return this.#X.set(J,$),$}relative(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.relative()}relativePosix(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.relativePosix()}basename(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.name}dirname(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return(Z.parent||Z).fullpath()}async readdir(Z=this.cwd,J={withFileTypes:!0}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X}=J;if(!Z.canReaddir())return[];else{let $=await Z.readdir();return X?$:$.map((Y)=>Y.name)}}readdirSync(Z=this.cwd,J={withFileTypes:!0}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0}=J;if(!Z.canReaddir())return[];else if(X)return Z.readdirSync();else return Z.readdirSync().map(($)=>$.name)}async lstat(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.lstat()}lstatSync(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.lstatSync()}async readlink(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z.withFileTypes,Z=this.cwd;let X=await Z.readlink();return J?X:X?.fullpath()}readlinkSync(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z.withFileTypes,Z=this.cwd;let X=Z.readlinkSync();return J?X:X?.fullpath()}async realpath(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z.withFileTypes,Z=this.cwd;let X=await Z.realpath();return J?X:X?.fullpath()}realpathSync(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z.withFileTypes,Z=this.cwd;let X=Z.realpathSync();return J?X:X?.fullpath()}async walk(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,W=[];if(!Y||Y(Z))W.push(X?Z:Z.fullpath());let K=new Set,G=(H,q)=>{K.add(H),H.readdirCB((z,F)=>{if(z)return q(z);let U=F.length;if(!U)return q();let L=()=>{if(--U===0)q()};for(let B of F){if(!Y||Y(B))W.push(X?B:B.fullpath());if($&&B.isSymbolicLink())B.realpath().then((w)=>w?.isUnknown()?w.lstat():w).then((w)=>w?.shouldWalk(K,Q)?G(w,L):L());else if(B.shouldWalk(K,Q))G(B,L);else L()}},!0)},V=Z;return new Promise((H,q)=>{G(V,(z)=>{if(z)return q(z);H(W)})})}walkSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,W=[];if(!Y||Y(Z))W.push(X?Z:Z.fullpath());let K=new Set([Z]);for(let G of K){let V=G.readdirSync();for(let H of V){if(!Y||Y(H))W.push(X?H:H.fullpath());let q=H;if(H.isSymbolicLink()){if(!($&&(q=H.realpathSync())))continue;if(q.isUnknown())q.lstatSync()}if(q.shouldWalk(K,Q))K.add(q)}}return W}[Symbol.asyncIterator](){return this.iterate()}iterate(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;return this.stream(Z,J)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J;if(!Y||Y(Z))yield X?Z:Z.fullpath();let W=new Set([Z]);for(let K of W){let G=K.readdirSync();for(let V of G){if(!Y||Y(V))yield X?V:V.fullpath();let H=V;if(V.isSymbolicLink()){if(!($&&(H=V.realpathSync())))continue;if(H.isUnknown())H.lstatSync()}if(H.shouldWalk(W,Q))W.add(H)}}}stream(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,W=new s$({objectMode:!0});if(!Y||Y(Z))W.write(X?Z:Z.fullpath());let K=new Set,G=[Z],V=0,H=()=>{let q=!1;while(!q){let z=G.shift();if(!z){if(V===0)W.end();return}V++,K.add(z);let F=(L,B,w=!1)=>{if(L)return W.emit("error",L);if($&&!w){let O=[];for(let M of B)if(M.isSymbolicLink())O.push(M.realpath().then((N)=>N?.isUnknown()?N.lstat():N));if(O.length){Promise.all(O).then(()=>F(null,B,!0));return}}for(let O of B)if(O&&(!Y||Y(O))){if(!W.write(X?O:O.fullpath()))q=!0}V--;for(let O of B){let M=O.realpathCached()||O;if(M.shouldWalk(K,Q))G.push(M)}if(q&&!W.flowing)W.once("drain",H);else if(!U)H()},U=!0;z.readdirCB(F,!0),U=!1}};return H(),W}streamSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof _6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,W=new s$({objectMode:!0}),K=new Set;if(!Y||Y(Z))W.write(X?Z:Z.fullpath());let G=[Z],V=0,H=()=>{let q=!1;while(!q){let z=G.shift();if(!z){if(V===0)W.end();return}V++,K.add(z);let F=z.readdirSync();for(let U of F)if(!Y||Y(U)){if(!W.write(X?U:U.fullpath()))q=!0}V--;for(let U of F){let L=U;if(U.isSymbolicLink()){if(!($&&(L=U.realpathSync())))continue;if(L.isUnknown())L.lstatSync()}if(L.shouldWalk(K,Q))G.push(L)}}if(q&&!W.flowing)W.once("drain",H)};return H(),W}chdir(Z=this.cwd){let J=this.cwd;this.cwd=typeof Z==="string"?this.cwd.resolve(Z):Z,this.cwd[Cu](J)}}class RG extends TR{sep="\\";constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,PR,"\\",{...J,nocase:X});this.nocase=X;for(let $=this.cwd;$;$=$.parent)$.nocase=this.nocase}parseRootPath(Z){return PR.parse(Z).root.toUpperCase()}newRoot(Z){return new RF(this.rootPath,pZ,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")||Z.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(Z)}}class DG extends TR{sep="/";constructor(Z=process.cwd(),J={}){let{nocase:X=!1}=J;super(Z,lG5,"/",{...J,nocase:X});this.nocase=X}parseRootPath(Z){return"/"}newRoot(Z){return new DF(this.rootPath,pZ,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")}}class PF extends DG{constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,{...J,nocase:X})}}var g46=process.platform==="win32"?RF:DF,Tu=process.platform==="win32"?RG:process.platform==="darwin"?PF:DG;var WV5=(Z)=>Z.length>=1,KV5=(Z)=>Z.length>=1;class DW{#Z;#X;#J;length;#$;#Y;#Q;#W;#K;#G;#H=!0;constructor(Z,J,X,$){if(!WV5(Z))throw new TypeError("empty pattern list");if(!KV5(J))throw new TypeError("empty glob list");if(J.length!==Z.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=Z.length,X<0||X>=this.length)throw new TypeError("index out of range");if(this.#Z=Z,this.#X=J,this.#J=X,this.#$=$,this.#J===0){if(this.isUNC()){let[Y,Q,W,K,...G]=this.#Z,[V,H,q,z,...F]=this.#X;if(G[0]==="")G.shift(),F.shift();let U=[Y,Q,W,K,""].join("/"),L=[V,H,q,z,""].join("/");this.#Z=[U,...G],this.#X=[L,...F],this.length=this.#Z.length}else if(this.isDrive()||this.isAbsolute()){let[Y,...Q]=this.#Z,[W,...K]=this.#X;if(Q[0]==="")Q.shift(),K.shift();let G=Y+"/",V=W+"/";this.#Z=[G,...Q],this.#X=[V,...K],this.length=this.#Z.length}}}pattern(){return this.#Z[this.#J]}isString(){return typeof this.#Z[this.#J]==="string"}isGlobstar(){return this.#Z[this.#J]===J6}isRegExp(){return this.#Z[this.#J]instanceof RegExp}globString(){return this.#Q=this.#Q||(this.#J===0?this.isAbsolute()?this.#X[0]+this.#X.slice(1).join("/"):this.#X.join("/"):this.#X.slice(this.#J).join("/"))}hasMore(){return this.length>this.#J+1}rest(){if(this.#Y!==void 0)return this.#Y;if(!this.hasMore())return this.#Y=null;return this.#Y=new DW(this.#Z,this.#X,this.#J+1,this.#$),this.#Y.#G=this.#G,this.#Y.#K=this.#K,this.#Y.#W=this.#W,this.#Y}isUNC(){let Z=this.#Z;return this.#K!==void 0?this.#K:this.#K=this.#$==="win32"&&this.#J===0&&Z[0]===""&&Z[1]===""&&typeof Z[2]==="string"&&!!Z[2]&&typeof Z[3]==="string"&&!!Z[3]}isDrive(){let Z=this.#Z;return this.#W!==void 0?this.#W:this.#W=this.#$==="win32"&&this.#J===0&&this.length>1&&typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0])}isAbsolute(){let Z=this.#Z;return this.#G!==void 0?this.#G:this.#G=Z[0]===""&&Z.length>1||this.isDrive()||this.isUNC()}root(){let Z=this.#Z[0];return typeof Z==="string"&&this.isAbsolute()&&this.#J===0?Z:""}checkFollowGlobstar(){return!(this.#J===0||!this.isGlobstar()||!this.#H)}markFollowGlobstar(){if(this.#J===0||!this.isGlobstar()||!this.#H)return!1;return this.#H=!1,!0}}var GV5=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class PG{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(Z,{nobrace:J,nocase:X,noext:$,noglobstar:Y,platform:Q=GV5}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=Q,this.mmopts={dot:!0,nobrace:J,nocase:X,noext:$,noglobstar:Y,optimizationLevel:2,platform:Q,nocomment:!0,nonegate:!0};for(let W of Z)this.add(W)}add(Z){let J=new K9(Z,this.mmopts);for(let X=0;X<J.set.length;X++){let $=J.set[X],Y=J.globParts[X];if(!$||!Y)throw new Error("invalid pattern object");while($[0]==="."&&Y[0]===".")$.shift(),Y.shift();let Q=new DW($,Y,0,this.platform),W=new K9(Q.globString(),this.mmopts),K=Y[Y.length-1]==="**",G=Q.isAbsolute();if(G)this.absolute.push(W);else this.relative.push(W);if(K)if(G)this.absoluteChildren.push(W);else this.relativeChildren.push(W)}}ignored(Z){let J=Z.fullpath(),X=`${J}/`,$=Z.relative()||".",Y=`${$}/`;for(let Q of this.relative)if(Q.match($)||Q.match(Y))return!0;for(let Q of this.absolute)if(Q.match(J)||Q.match(X))return!0;return!1}childrenIgnored(Z){let J=Z.fullpath()+"/",X=(Z.relative()||".")+"/";for(let $ of this.relativeChildren)if($.match(X))return!0;for(let $ of this.absoluteChildren)if($.match(J))return!0;return!1}}class kR{store;constructor(Z=new Map){this.store=Z}copy(){return new kR(new Map(this.store))}hasWalked(Z,J){return this.store.get(Z.fullpath())?.has(J.globString())}storeWalked(Z,J){let X=Z.fullpath(),$=this.store.get(X);if($)$.add(J.globString());else this.store.set(X,new Set([J.globString()]))}}class ku{store=new Map;add(Z,J,X){let $=(J?2:0)|(X?1:0),Y=this.store.get(Z);this.store.set(Z,Y===void 0?$:$&Y)}entries(){return[...this.store.entries()].map(([Z,J])=>[Z,!!(J&2),!!(J&1)])}}class Eu{store=new Map;add(Z,J){if(!Z.canReaddir())return;let X=this.store.get(Z);if(X){if(!X.find(($)=>$.globString()===J.globString()))X.push(J)}else this.store.set(Z,[J])}get(Z){let J=this.store.get(Z);if(!J)throw new Error("attempting to walk unknown path");return J}entries(){return this.keys().map((Z)=>[Z,this.store.get(Z)])}keys(){return[...this.store.keys()].filter((Z)=>Z.canReaddir())}}class CG{hasWalkedCache;matches=new ku;subwalks=new Eu;patterns;follow;dot;opts;constructor(Z,J){this.opts=Z,this.follow=!!Z.follow,this.dot=!!Z.dot,this.hasWalkedCache=J?J.copy():new kR}processPatterns(Z,J){this.patterns=J;let X=J.map(($)=>[Z,$]);for(let[$,Y]of X){this.hasWalkedCache.storeWalked($,Y);let Q=Y.root(),W=Y.isAbsolute()&&this.opts.absolute!==!1;if(Q){$=$.resolve(Q==="/"&&this.opts.root!==void 0?this.opts.root:Q);let H=Y.rest();if(!H){this.matches.add($,!0,!1);continue}else Y=H}if($.isENOENT())continue;let K,G,V=!1;while(typeof(K=Y.pattern())==="string"&&(G=Y.rest()))$=$.resolve(K),Y=G,V=!0;if(K=Y.pattern(),G=Y.rest(),V){if(this.hasWalkedCache.hasWalked($,Y))continue;this.hasWalkedCache.storeWalked($,Y)}if(typeof K==="string"){let H=K===".."||K===""||K===".";this.matches.add($.resolve(K),W,H);continue}else if(K===J6){if(!$.isSymbolicLink()||this.follow||Y.checkFollowGlobstar())this.subwalks.add($,Y);let H=G?.pattern(),q=G?.rest();if(!G||(H===""||H===".")&&!q)this.matches.add($,W,H===""||H===".");else if(H===".."){let z=$.parent||$;if(!q)this.matches.add(z,W,!0);else if(!this.hasWalkedCache.hasWalked(z,q))this.subwalks.add(z,q)}}else if(K instanceof RegExp)this.subwalks.add($,Y)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new CG(this.opts,this.hasWalkedCache)}filterEntries(Z,J){let X=this.subwalks.get(Z),$=this.child();for(let Y of J)for(let Q of X){let W=Q.isAbsolute(),K=Q.pattern(),G=Q.rest();if(K===J6)$.testGlobstar(Y,Q,G,W);else if(K instanceof RegExp)$.testRegExp(Y,K,G,W);else $.testString(Y,K,G,W)}return $}testGlobstar(Z,J,X,$){if(this.dot||!Z.name.startsWith(".")){if(!J.hasMore())this.matches.add(Z,$,!1);if(Z.canReaddir()){if(this.follow||!Z.isSymbolicLink())this.subwalks.add(Z,J);else if(Z.isSymbolicLink()){if(X&&J.checkFollowGlobstar())this.subwalks.add(Z,X);else if(J.markFollowGlobstar())this.subwalks.add(Z,J)}}}if(X){let Y=X.pattern();if(typeof Y==="string"&&Y!==".."&&Y!==""&&Y!==".")this.testString(Z,Y,X.rest(),$);else if(Y===".."){let Q=Z.parent||Z;this.subwalks.add(Q,X)}else if(Y instanceof RegExp)this.testRegExp(Z,Y,X.rest(),$)}}testRegExp(Z,J,X,$){if(!J.test(Z.name))return;if(!X)this.matches.add(Z,$,!1);else this.subwalks.add(Z,X)}testString(Z,J,X,$){if(!Z.isNamed(J))return;if(!X)this.matches.add(Z,$,!1);else this.subwalks.add(Z,X)}}var VV5=(Z,J)=>typeof Z==="string"?new PG([Z],J):Array.isArray(Z)?new PG(Z,J):Z;class ER{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#Z=[];#X;#J;signal;maxDepth;includeChildMatches;constructor(Z,J,X){if(this.patterns=Z,this.path=J,this.opts=X,this.#J=!X.posix&&X.platform==="win32"?"\\":"/",this.includeChildMatches=X.includeChildMatches!==!1,X.ignore||!this.includeChildMatches){if(this.#X=VV5(X.ignore??[],X),!this.includeChildMatches&&typeof this.#X.add!=="function")throw new Error("cannot ignore child matches, ignore lacks add() method.")}if(this.maxDepth=X.maxDepth||1/0,X.signal)this.signal=X.signal,this.signal.addEventListener("abort",()=>{this.#Z.length=0})}#$(Z){return this.seen.has(Z)||!!this.#X?.ignored?.(Z)}#Y(Z){return!!this.#X?.childrenIgnored?.(Z)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let Z=void 0;while(!this.paused&&(Z=this.#Z.shift()))Z()}onResume(Z){if(this.signal?.aborted)return;if(!this.paused)Z();else this.#Z.push(Z)}async matchCheck(Z,J){if(J&&this.opts.nodir)return;let X;if(this.opts.realpath){if(X=Z.realpathCached()||await Z.realpath(),!X)return;Z=X}let Y=Z.isUnknown()||this.opts.stat?await Z.lstat():Z;if(this.opts.follow&&this.opts.nodir&&Y?.isSymbolicLink()){let Q=await Y.realpath();if(Q&&(Q.isUnknown()||this.opts.stat))await Q.lstat()}return this.matchCheckTest(Y,J)}matchCheckTest(Z,J){return Z&&(this.maxDepth===1/0||Z.depth()<=this.maxDepth)&&(!J||Z.canReaddir())&&(!this.opts.nodir||!Z.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!Z.isSymbolicLink()||!Z.realpathCached()?.isDirectory())&&!this.#$(Z)?Z:void 0}matchCheckSync(Z,J){if(J&&this.opts.nodir)return;let X;if(this.opts.realpath){if(X=Z.realpathCached()||Z.realpathSync(),!X)return;Z=X}let Y=Z.isUnknown()||this.opts.stat?Z.lstatSync():Z;if(this.opts.follow&&this.opts.nodir&&Y?.isSymbolicLink()){let Q=Y.realpathSync();if(Q&&(Q?.isUnknown()||this.opts.stat))Q.lstatSync()}return this.matchCheckTest(Y,J)}matchFinish(Z,J){if(this.#$(Z))return;if(!this.includeChildMatches&&this.#X?.add){let Y=`${Z.relativePosix()}/**`;this.#X.add(Y)}let X=this.opts.absolute===void 0?J:this.opts.absolute;this.seen.add(Z);let $=this.opts.mark&&Z.isDirectory()?this.#J:"";if(this.opts.withFileTypes)this.matchEmit(Z);else if(X){let Y=this.opts.posix?Z.fullpathPosix():Z.fullpath();this.matchEmit(Y+$)}else{let Y=this.opts.posix?Z.relativePosix():Z.relative(),Q=this.opts.dotRelative&&!Y.startsWith(".."+this.#J)?"."+this.#J:"";this.matchEmit(!Y?"."+$:Q+Y+$)}}async match(Z,J,X){let $=await this.matchCheck(Z,X);if($)this.matchFinish($,J)}matchSync(Z,J,X){let $=this.matchCheckSync(Z,X);if($)this.matchFinish($,J)}walkCB(Z,J,X){if(this.signal?.aborted)X();this.walkCB2(Z,J,new CG(this.opts),X)}walkCB2(Z,J,X,$){if(this.#Y(Z))return $();if(this.signal?.aborted)$();if(this.paused){this.onResume(()=>this.walkCB2(Z,J,X,$));return}X.processPatterns(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[W,K,G]of X.matches.entries()){if(this.#$(W))continue;Y++,this.match(W,K,G).then(()=>Q())}for(let W of X.subwalkTargets()){if(this.maxDepth!==1/0&&W.depth()>=this.maxDepth)continue;Y++;let K=W.readdirCached();if(W.calledReaddir())this.walkCB3(W,K,X,Q);else W.readdirCB((G,V)=>this.walkCB3(W,V,X,Q),!0)}Q()}walkCB3(Z,J,X,$){X=X.filterEntries(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[W,K,G]of X.matches.entries()){if(this.#$(W))continue;Y++,this.match(W,K,G).then(()=>Q())}for(let[W,K]of X.subwalks.entries())Y++,this.walkCB2(W,K,X.child(),Q);Q()}walkCBSync(Z,J,X){if(this.signal?.aborted)X();this.walkCB2Sync(Z,J,new CG(this.opts),X)}walkCB2Sync(Z,J,X,$){if(this.#Y(Z))return $();if(this.signal?.aborted)$();if(this.paused){this.onResume(()=>this.walkCB2Sync(Z,J,X,$));return}X.processPatterns(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[W,K,G]of X.matches.entries()){if(this.#$(W))continue;this.matchSync(W,K,G)}for(let W of X.subwalkTargets()){if(this.maxDepth!==1/0&&W.depth()>=this.maxDepth)continue;Y++;let K=W.readdirSync();this.walkCB3Sync(W,K,X,Q)}Q()}walkCB3Sync(Z,J,X,$){X=X.filterEntries(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[W,K,G]of X.matches.entries()){if(this.#$(W))continue;this.matchSync(W,K,G)}for(let[W,K]of X.subwalks.entries())Y++,this.walkCB2Sync(W,K,X.child(),Q);Q()}}class CF extends ER{matches=new Set;constructor(Z,J,X){super(Z,J,X)}matchEmit(Z){this.matches.add(Z)}async walk(){if(this.signal?.aborted)throw this.signal.reason;if(this.path.isUnknown())await this.path.lstat();return await new Promise((Z,J)=>{this.walkCB(this.path,this.patterns,()=>{if(this.signal?.aborted)J(this.signal.reason);else Z(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;if(this.path.isUnknown())this.path.lstatSync();return this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}}class TF extends ER{results;constructor(Z,J,X){super(Z,J,X);this.results=new s$({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(Z){if(this.results.write(Z),!this.results.flowing)this.pause()}stream(){let Z=this.path;if(Z.isUnknown())Z.lstat().then(()=>{this.walkCB(Z,this.patterns,()=>this.results.end())});else this.walkCB(Z,this.patterns,()=>this.results.end());return this.results}streamSync(){if(this.path.isUnknown())this.path.lstatSync();return this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}}var qV5=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class iZ{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(Z,J){if(!J)throw new TypeError("glob options required");if(this.withFileTypes=!!J.withFileTypes,this.signal=J.signal,this.follow=!!J.follow,this.dot=!!J.dot,this.dotRelative=!!J.dotRelative,this.nodir=!!J.nodir,this.mark=!!J.mark,!J.cwd)this.cwd="";else if(J.cwd instanceof URL||J.cwd.startsWith("file://"))J.cwd=HV5(J.cwd);if(this.cwd=J.cwd||"",this.root=J.root,this.magicalBraces=!!J.magicalBraces,this.nobrace=!!J.nobrace,this.noext=!!J.noext,this.realpath=!!J.realpath,this.absolute=J.absolute,this.includeChildMatches=J.includeChildMatches!==!1,this.noglobstar=!!J.noglobstar,this.matchBase=!!J.matchBase,this.maxDepth=typeof J.maxDepth==="number"?J.maxDepth:1/0,this.stat=!!J.stat,this.ignore=J.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof Z==="string")Z=[Z];if(this.windowsPathsNoEscape=!!J.windowsPathsNoEscape||J.allowWindowsEscape===!1,this.windowsPathsNoEscape)Z=Z.map((K)=>K.replace(/\\/g,"/"));if(this.matchBase){if(J.noglobstar)throw new TypeError("base matching requires globstar");Z=Z.map((K)=>K.includes("/")?K:`./**/${K}`)}if(this.pattern=Z,this.platform=J.platform||qV5,this.opts={...J,platform:this.platform},J.scurry){if(this.scurry=J.scurry,J.nocase!==void 0&&J.nocase!==J.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let K=J.platform==="win32"?RG:J.platform==="darwin"?PF:J.platform?DG:Tu;this.scurry=new K(this.cwd,{nocase:J.nocase,fs:J.fs})}this.nocase=this.scurry.nocase;let X=this.platform==="darwin"||this.platform==="win32",$={...J,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:X,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},Y=this.pattern.map((K)=>new K9(K,$)),[Q,W]=Y.reduce((K,G)=>{return K[0].push(...G.set),K[1].push(...G.globParts),K},[[],[]]);this.patterns=Q.map((K,G)=>{let V=W[G];if(!V)throw new Error("invalid pattern object");return new DW(K,V,0,this.platform)})}async walk(){return[...await new CF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new CF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new TF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new TF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}}var IR=(Z,J={})=>{if(!Array.isArray(Z))Z=[Z];for(let X of Z)if(new K9(X,J).hasMagic())return!0;return!1};function EF(Z,J={}){return new iZ(Z,J).streamSync()}function vu(Z,J={}){return new iZ(Z,J).stream()}function Su(Z,J={}){return new iZ(Z,J).walkSync()}async function Iu(Z,J={}){return new iZ(Z,J).walk()}function IF(Z,J={}){return new iZ(Z,J).iterateSync()}function _u(Z,J={}){return new iZ(Z,J).iterate()}var zV5=EF,FV5=Object.assign(vu,{sync:EF}),UV5=IF,BV5=Object.assign(_u,{sync:IF}),LV5=Object.assign(Su,{stream:EF,iterate:IF}),kF=Object.assign(Iu,{glob:Iu,globSync:Su,sync:LV5,globStream:vu,stream:FV5,globStreamSync:EF,streamSync:zV5,globIterate:_u,iterate:BV5,globIterateSync:IF,iterateSync:UV5,Glob:iZ,hasMagic:IR,escape:OW,unescape:$Z});kF.glob=kF;class vR{constructor(){this._listeners={}}addEventListener(Z,J){let X=this._listeners;if(X[Z]===void 0)X[Z]=[];if(X[Z].indexOf(J)===-1)X[Z].push(J);return this}removeEventListener(Z,J){let $=this._listeners[Z];if($!==void 0){let Y=$.indexOf(J);if(Y!==-1)$.splice(Y,1)}return this}dispatchEvent(Z){let X=this._listeners[Z.type];if(X!==void 0){let $=X.slice(0);for(let Y=0,Q=$.length;Y<Q;Y++)$[Y].call(this,Z)}return this}dispose(){for(let Z in this._listeners)delete this._listeners[Z]}}class Y7{constructor(Z,J,X,$={}){if(this._name=void 0,this._parent=void 0,this._child=void 0,this._attributes=void 0,this._disposed=!1,this._name=Z,this._parent=J,this._child=X,this._attributes=$,!J.isOnGraph(X))throw new Error("Cannot connect disconnected graphs.")}getName(){return this._name}getParent(){return this._parent}getChild(){return this._child}setChild(Z){return this._child=Z,this}getAttributes(){return this._attributes}dispose(){if(this._disposed)return;this._parent._destroyRef(this),this._disposed=!0}isDisposed(){return this._disposed}}class PW extends vR{constructor(...Z){super(...Z);this._emptySet=new Set,this._edges=new Set,this._parentEdges=new Map,this._childEdges=new Map}listEdges(){return Array.from(this._edges)}listParentEdges(Z){return Array.from(this._childEdges.get(Z)||this._emptySet)}listParents(Z){let J=new Set;for(let X of this.listParentEdges(Z))J.add(X.getParent());return Array.from(J)}listChildEdges(Z){return Array.from(this._parentEdges.get(Z)||this._emptySet)}listChildren(Z){let J=new Set;for(let X of this.listChildEdges(Z))J.add(X.getChild());return Array.from(J)}disconnectParents(Z,J){for(let X of this.listParentEdges(Z))if(!J||J(X.getParent()))X.dispose();return this}_createEdge(Z,J,X,$){let Y=new Y7(Z,J,X,$);this._edges.add(Y);let Q=Y.getParent();if(!this._parentEdges.has(Q))this._parentEdges.set(Q,new Set);this._parentEdges.get(Q).add(Y);let W=Y.getChild();if(!this._childEdges.has(W))this._childEdges.set(W,new Set);return this._childEdges.get(W).add(Y),Y}_destroyEdge(Z){return this._edges.delete(Z),this._parentEdges.get(Z.getParent()).delete(Z),this._childEdges.get(Z.getChild()).delete(Z),this}}function TG(){return TG=Object.assign||function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)if(Object.prototype.hasOwnProperty.call(X,$))Z[$]=X[$]}return Z},TG.apply(this,arguments)}class z6{constructor(Z){if(this.list=[],Z)for(let J of Z)this.list.push(J)}add(Z){this.list.push(Z)}remove(Z){let J=this.list.indexOf(Z);if(J>=0)this.list.splice(J,1)}removeChild(Z){let J=[];for(let X of this.list)if(X.getChild()===Z)J.push(X);for(let X of J)this.remove(X);return J}listRefsByChild(Z){let J=[];for(let X of this.list)if(X.getChild()===Z)J.push(X);return J}values(){return this.list}}class I0{constructor(Z){if(this.set=new Set,this.map=new Map,Z)for(let J of Z)this.add(J)}add(Z){let J=Z.getChild();this.removeChild(J),this.set.add(Z),this.map.set(J,Z)}remove(Z){this.set.delete(Z),this.map.delete(Z.getChild())}removeChild(Z){let J=this.map.get(Z)||null;if(J)this.remove(J);return J}getRefByChild(Z){return this.map.get(Z)||null}values(){return Array.from(this.set)}}class a5{constructor(Z){if(this.map={},Z)Object.assign(this.map,Z)}set(Z,J){this.map[Z]=J}delete(Z){delete this.map[Z]}get(Z){return this.map[Z]||null}keys(){return Object.keys(this.map)}values(){return Object.values(this.map)}}var y0=Symbol("attributes"),WZ=Symbol("immutableKeys");class CW extends vR{constructor(Z){super();this._disposed=!1,this.graph=void 0,this[y0]=void 0,this[WZ]=void 0,this.graph=Z,this[WZ]=new Set,this[y0]=this._createAttributes()}getDefaults(){return{}}_createAttributes(){let Z=this.getDefaults(),J={};for(let X in Z){let $=Z[X];if($ instanceof CW){let Y=this.graph._createEdge(X,this,$);this[WZ].add(X),J[X]=Y}else J[X]=$}return J}isOnGraph(Z){return this.graph===Z.graph}isDisposed(){return this._disposed}dispose(){if(this._disposed)return;this.graph.listChildEdges(this).forEach((Z)=>Z.dispose()),this.graph.disconnectParents(this),this._disposed=!0,this.dispatchEvent({type:"dispose"})}detach(){return this.graph.disconnectParents(this),this}swap(Z,J){for(let X in this[y0]){let $=this[y0][X];if($ instanceof Y7){let Y=$;if(Y.getChild()===Z)this.setRef(X,J,Y.getAttributes())}else if($ instanceof z6)for(let Y of $.listRefsByChild(Z)){let Q=Y.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}else if($ instanceof I0){let Y=$.getRefByChild(Z);if(Y){let Q=Y.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}}else if($ instanceof a5)for(let Y of $.keys()){let Q=$.get(Y);if(Q.getChild()===Z)this.setRefMap(X,Y,J,Q.getAttributes())}}return this}get(Z){return this[y0][Z]}set(Z,J){return this[y0][Z]=J,this.dispatchEvent({type:"change",attribute:Z})}getRef(Z){let J=this[y0][Z];return J?J.getChild():null}setRef(Z,J,X){if(this[WZ].has(Z))throw new Error(`Cannot overwrite immutable attribute, "${Z}".`);let $=this[y0][Z];if($)$.dispose();if(!J)return this;let Y=this.graph._createEdge(Z,this,J,X);return this[y0][Z]=Y,this.dispatchEvent({type:"change",attribute:Z})}listRefs(Z){return this.assertRefList(Z).values().map((X)=>X.getChild())}addRef(Z,J,X){let $=this.graph._createEdge(Z,this,J,X);return this.assertRefList(Z).add($),this.dispatchEvent({type:"change",attribute:Z})}removeRef(Z,J){let X=this.assertRefList(Z);if(X instanceof z6)for(let $ of X.listRefsByChild(J))$.dispose();else{let $=X.getRefByChild(J);if($)$.dispose()}return this}assertRefList(Z){let J=this[y0][Z];if(J instanceof z6||J instanceof I0)return J;throw new Error(`Expected RefList or RefSet for attribute "${Z}"`)}listRefMapKeys(Z){return this.assertRefMap(Z).keys()}listRefMapValues(Z){return this.assertRefMap(Z).values().map((J)=>J.getChild())}getRefMap(Z,J){let $=this.assertRefMap(Z).get(J);return $?$.getChild():null}setRefMap(Z,J,X,$){let Y=this.assertRefMap(Z),Q=Y.get(J);if(Q)Q.dispose();if(!X)return this;$=Object.assign($||{},{key:J});let W=this.graph._createEdge(Z,this,X,TG({},$,{key:J}));return Y.set(J,W),this.dispatchEvent({type:"change",attribute:Z,key:J})}assertRefMap(Z){let J=this[y0][Z];if(J instanceof a5)return J;throw new Error(`Expected RefMap for attribute "${Z}"`)}dispatchEvent(Z){return super.dispatchEvent(TG({},Z,{target:this})),this.graph.dispatchEvent(TG({},Z,{target:this,type:`node:${Z.type}`})),this}_destroyRef(Z){let J=Z.getName();if(this[y0][J]===Z){if(this[y0][J]=null,this[WZ].has(J))Z.getChild().dispose()}else if(this[y0][J]instanceof z6)this[y0][J].remove(Z);else if(this[y0][J]instanceof I0)this[y0][J].remove(Z);else if(this[y0][J]instanceof a5){let X=this[y0][J];for(let $ of X.keys())if(X.get($)===Z)X.delete($)}else return;this.graph._destroyEdge(Z),this.dispatchEvent({type:"change",attribute:J})}}var gu="v4.1.1",fF="@glb.bin",n;(function(Z){Z.ACCESSOR="Accessor",Z.ANIMATION="Animation",Z.ANIMATION_CHANNEL="AnimationChannel",Z.ANIMATION_SAMPLER="AnimationSampler",Z.BUFFER="Buffer",Z.CAMERA="Camera",Z.MATERIAL="Material",Z.MESH="Mesh",Z.PRIMITIVE="Primitive",Z.PRIMITIVE_TARGET="PrimitiveTarget",Z.NODE="Node",Z.ROOT="Root",Z.SCENE="Scene",Z.SKIN="Skin",Z.TEXTURE="Texture",Z.TEXTURE_INFO="TextureInfo"})(n||(n={}));var hF;(function(Z){Z.INTERLEAVED="interleaved",Z.SEPARATE="separate"})(hF||(hF={}));var I7;(function(Z){Z.ARRAY_BUFFER="ARRAY_BUFFER",Z.ELEMENT_ARRAY_BUFFER="ELEMENT_ARRAY_BUFFER",Z.INVERSE_BIND_MATRICES="INVERSE_BIND_MATRICES",Z.OTHER="OTHER",Z.SPARSE="SPARSE"})(I7||(I7={}));var bF;(function(Z){Z[Z.R=4096]="R",Z[Z.G=256]="G",Z[Z.B=16]="B",Z[Z.A=1]="A"})(bF||(bF={}));var pJ;(function(Z){Z.GLTF="GLTF",Z.GLB="GLB"})(pJ||(pJ={}));var $X={"5120":Int8Array,"5121":Uint8Array,"5122":Int16Array,"5123":Uint16Array,"5125":Uint32Array,"5126":Float32Array},_R=typeof Float32Array!=="undefined"?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var Z=0,J=arguments.length;while(J--)Z+=arguments[J]*arguments[J];return Math.sqrt(Z)};function wV5(){var Z=new _R(3);if(_R!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function SR(Z){var J=Z[0],X=Z[1],$=Z[2];return Math.hypot(J,X,$)}function OV5(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=X[3]*$+X[7]*Y+X[11]*Q+X[15];return W=W||1,Z[0]=(X[0]*$+X[4]*Y+X[8]*Q+X[12])/W,Z[1]=(X[1]*$+X[5]*Y+X[9]*Q+X[13])/W,Z[2]=(X[2]*$+X[6]*Y+X[10]*Q+X[14])/W,Z}(function(){var Z=wV5();return function(J,X,$,Y,Q,W){var K,G;if(!X)X=3;if(!$)$=0;if(Y)G=Math.min(Y*X+$,J.length);else G=J.length;for(K=$;K<G;K+=X)Z[0]=J[K],Z[1]=J[K+1],Z[2]=J[K+2],Q(Z,Z,W),J[K]=Z[0],J[K+1]=Z[1],J[K+2]=Z[2];return J}})();function hR(Z){let J=mu(),X=Z.propertyType===n.NODE?[Z]:Z.listChildren();for(let $ of X)$.traverse((Y)=>{let Q=Y.getMesh();if(!Q)return;let W=NV5(Q,Y.getWorldMatrix());if(W.min.every(isFinite)&&W.max.every(isFinite))AR(W.min,J),AR(W.max,J)});return J}function NV5(Z,J){let X=mu();for(let $ of Z.listPrimitives()){let Y=$.getAttribute("POSITION"),Q=$.getIndices();if(!Y)continue;let W=[0,0,0],K=[0,0,0];for(let G=0,V=Q?Q.getCount():Y.getCount();G<V;G++){let H=Q?Q.getScalar(G):G;W=Y.getElement(H,W),K=OV5(K,W,J),AR(K,X)}}return X}function AR(Z,J){for(let X=0;X<3;X++)J.min[X]=Math.min(Z[X],J.min[X]),J.max[X]=Math.max(Z[X],J.max[X])}function mu(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}class r0{static createBufferFromDataURI(Z){if(typeof Buffer==="undefined"){let J=atob(Z.split(",")[1]),X=new Uint8Array(J.length);for(let $=0;$<J.length;$++)X[$]=J.charCodeAt($);return X}else{let J=Z.split(",")[1],X=Z.indexOf("base64")>=0;return Buffer.from(J,X?"base64":"utf8")}}static encodeText(Z){return new TextEncoder().encode(Z)}static decodeText(Z){return new TextDecoder().decode(Z)}static concat(Z){let J=0;for(let Y of Z)J+=Y.byteLength;let X=new Uint8Array(J),$=0;for(let Y of Z)X.set(Y,$),$+=Y.byteLength;return X}static pad(Z,J=0){let X=this.padNumber(Z.byteLength);if(X===Z.byteLength)return Z;let $=new Uint8Array(X);if($.set(Z),J!==0)for(let Y=Z.byteLength;Y<X;Y++)$[Y]=J;return $}static padNumber(Z){return Math.ceil(Z/4)*4}static equals(Z,J){if(Z===J)return!0;if(Z.byteLength!==J.byteLength)return!1;let X=Z.byteLength;while(X--)if(Z[X]!==J[X])return!1;return!0}static toView(Z,J=0,X=1/0){return new Uint8Array(Z.buffer,Z.byteOffset+J,Math.min(Z.byteLength,X))}static assertView(Z){if(Z&&!ArrayBuffer.isView(Z))throw new Error(`Method requires Uint8Array parameter; received "${typeof Z}".`);return Z}}class bR{static hexToFactor(Z,J){Z=Math.floor(Z);let X=J;return X[0]=(Z>>16&255)/255,X[1]=(Z>>8&255)/255,X[2]=(Z&255)/255,this.convertSRGBToLinear(J,J)}static factorToHex(Z){let J=[...Z],[X,$,Y]=this.convertLinearToSRGB(Z,J);return X*255<<16^$*255<<8^Y*255<<0}static convertSRGBToLinear(Z,J){let X=Z,$=J;for(let Y=0;Y<3;Y++)$[Y]=X[Y]<0.04045?X[Y]*0.0773993808:Math.pow(X[Y]*0.9478672986+0.0521327014,2.4);return J}static convertLinearToSRGB(Z,J){let X=Z,$=J;for(let Y=0;Y<3;Y++)$[Y]=X[Y]<0.0031308?X[Y]*12.92:1.055*Math.pow(X[Y],0.41666)-0.055;return J}}class du{match(Z){return Z.length>=3&&Z[0]===255&&Z[1]===216&&Z[2]===255}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset+4),X,$;while(J.byteLength){if(X=J.getUint16(0,!1),jV5(J,X),$=J.getUint8(X+1),$===192||$===193||$===194)return[J.getUint16(X+7,!1),J.getUint16(X+5,!1)];J=new DataView(Z.buffer,J.byteOffset+X+2)}throw new TypeError("Invalid JPG, no size found")}getChannels(Z){return 3}}class mF{match(Z){return Z.length>=8&&Z[0]===137&&Z[1]===80&&Z[2]===78&&Z[3]===71&&Z[4]===13&&Z[5]===10&&Z[6]===26&&Z[7]===10}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset);if(r0.decodeText(Z.slice(12,16))===mF.PNG_FRIED_CHUNK_NAME)return[J.getUint32(32,!1),J.getUint32(36,!1)];return[J.getUint32(16,!1),J.getUint32(20,!1)]}getChannels(Z){return 4}}mF.PNG_FRIED_CHUNK_NAME="CgBI";class iJ{static registerFormat(Z,J){this.impls[Z]=J}static getMimeType(Z){for(let J in this.impls)if(this.impls[J].match(Z))return J;return null}static getSize(Z,J){if(!this.impls[J])return null;return this.impls[J].getSize(Z)}static getChannels(Z,J){if(!this.impls[J])return null;return this.impls[J].getChannels(Z)}static getVRAMByteLength(Z,J){if(!this.impls[J])return null;if(this.impls[J].getVRAMByteLength)return this.impls[J].getVRAMByteLength(Z);let X=0,$=4,Y=this.getSize(Z,J);if(!Y)return null;while(Y[0]>1||Y[1]>1)X+=Y[0]*Y[1]*$,Y[0]=Math.max(Math.floor(Y[0]/2),1),Y[1]=Math.max(Math.floor(Y[1]/2),1);return X+=1*$,X}static mimeTypeToExtension(Z){if(Z==="image/jpeg")return"jpg";return Z.split("/").pop()}static extensionToMimeType(Z){if(Z==="jpg")return"image/jpeg";if(!Z)return"";return`image/${Z}`}}iJ.impls={"image/jpeg":new du,"image/png":new mF};function jV5(Z,J){if(J>Z.byteLength)throw new TypeError("Corrupt JPG, exceeded buffer limits");if(Z.getUint8(J)!==255)throw new TypeError("Invalid JPG, marker table corrupted");return Z}class nJ{static basename(Z){let J=Z.split(/[\\/]/).pop();return J.substring(0,J.lastIndexOf("."))}static extension(Z){if(Z.startsWith("data:image/")){let J=Z.match(/data:(image\/\w+)/)[1];return iJ.mimeTypeToExtension(J)}else if(Z.startsWith("data:model/gltf+json"))return"gltf";else if(Z.startsWith("data:model/gltf-binary"))return"glb";else if(Z.startsWith("data:application/"))return"bin";return Z.split(/[\\/]/).pop().split(/[.]/).pop()}}function Au(Z){return Object.prototype.toString.call(Z)==="[object Object]"}function r$(Z){if(Au(Z)===!1)return!1;let J=Z.constructor;if(J===void 0)return!0;let X=J.prototype;if(Au(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}var xR,kG;(function(Z){Z[Z.SILENT=4]="SILENT",Z[Z.ERROR=3]="ERROR",Z[Z.WARN=2]="WARN",Z[Z.INFO=1]="INFO",Z[Z.DEBUG=0]="DEBUG"})(kG||(kG={}));class W7{constructor(Z){this.verbosity=void 0,this.verbosity=Z}debug(Z){if(this.verbosity<=W7.Verbosity.DEBUG)console.debug(Z)}info(Z){if(this.verbosity<=W7.Verbosity.INFO)console.info(Z)}warn(Z){if(this.verbosity<=W7.Verbosity.WARN)console.warn(Z)}error(Z){if(this.verbosity<=W7.Verbosity.ERROR)console.error(Z)}}xR=W7;W7.Verbosity=kG;W7.DEFAULT_INSTANCE=new xR(xR.Verbosity.INFO);function MV5(Z){var J=Z[0],X=Z[1],$=Z[2],Y=Z[3],Q=Z[4],W=Z[5],K=Z[6],G=Z[7],V=Z[8],H=Z[9],q=Z[10],z=Z[11],F=Z[12],U=Z[13],L=Z[14],B=Z[15],w=J*W-X*Q,O=J*K-$*Q,M=J*G-Y*Q,N=X*K-$*W,P=X*G-Y*W,D=$*G-Y*K,C=V*U-H*F,T=V*L-q*F,k=V*B-z*F,A=H*L-q*U,v=H*B-z*U,x=q*B-z*L;return w*x-O*v+M*A+N*k-P*T+D*C}function RV5(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=J[3],K=J[4],G=J[5],V=J[6],H=J[7],q=J[8],z=J[9],F=J[10],U=J[11],L=J[12],B=J[13],w=J[14],O=J[15],M=X[0],N=X[1],P=X[2],D=X[3];return Z[0]=M*$+N*K+P*q+D*L,Z[1]=M*Y+N*G+P*z+D*B,Z[2]=M*Q+N*V+P*F+D*w,Z[3]=M*W+N*H+P*U+D*O,M=X[4],N=X[5],P=X[6],D=X[7],Z[4]=M*$+N*K+P*q+D*L,Z[5]=M*Y+N*G+P*z+D*B,Z[6]=M*Q+N*V+P*F+D*w,Z[7]=M*W+N*H+P*U+D*O,M=X[8],N=X[9],P=X[10],D=X[11],Z[8]=M*$+N*K+P*q+D*L,Z[9]=M*Y+N*G+P*z+D*B,Z[10]=M*Q+N*V+P*F+D*w,Z[11]=M*W+N*H+P*U+D*O,M=X[12],N=X[13],P=X[14],D=X[15],Z[12]=M*$+N*K+P*q+D*L,Z[13]=M*Y+N*G+P*z+D*B,Z[14]=M*Q+N*V+P*F+D*w,Z[15]=M*W+N*H+P*U+D*O,Z}function DV5(Z,J){var X=J[0],$=J[1],Y=J[2],Q=J[4],W=J[5],K=J[6],G=J[8],V=J[9],H=J[10];return Z[0]=Math.hypot(X,$,Y),Z[1]=Math.hypot(Q,W,K),Z[2]=Math.hypot(G,V,H),Z}function PV5(Z,J){var X=new _R(3);DV5(X,J);var $=1/X[0],Y=1/X[1],Q=1/X[2],W=J[0]*$,K=J[1]*Y,G=J[2]*Q,V=J[4]*$,H=J[5]*Y,q=J[6]*Q,z=J[8]*$,F=J[9]*Y,U=J[10]*Q,L=W+H+U,B=0;if(L>0)B=Math.sqrt(L+1)*2,Z[3]=0.25*B,Z[0]=(q-F)/B,Z[1]=(z-G)/B,Z[2]=(K-V)/B;else if(W>H&&W>U)B=Math.sqrt(1+W-H-U)*2,Z[3]=(q-F)/B,Z[0]=0.25*B,Z[1]=(K+V)/B,Z[2]=(z+G)/B;else if(H>U)B=Math.sqrt(1+H-W-U)*2,Z[3]=(z-G)/B,Z[0]=(K+V)/B,Z[1]=0.25*B,Z[2]=(q+F)/B;else B=Math.sqrt(1+U-W-H)*2,Z[3]=(K-V)/B,Z[0]=(z+G)/B,Z[1]=(q+F)/B,Z[2]=0.25*B;return Z}class i0{static identity(Z){return Z}static eq(Z,J,X=0.00001){if(Z.length!==J.length)return!1;for(let $=0;$<Z.length;$++)if(Math.abs(Z[$]-J[$])>X)return!1;return!0}static clamp(Z,J,X){if(Z<J)return J;if(Z>X)return X;return Z}static decodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Z/65535;case 5121:return Z/255;case 5122:return Math.max(Z/32767,-1);case 5120:return Math.max(Z/127,-1);default:throw new Error("Invalid component type.")}}static encodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Math.round(i0.clamp(Z,0,1)*65535);case 5121:return Math.round(i0.clamp(Z,0,1)*255);case 5122:return Math.round(i0.clamp(Z,-1,1)*32767);case 5120:return Math.round(i0.clamp(Z,-1,1)*127);default:throw new Error("Invalid component type.")}}static decompose(Z,J,X,$){let Y=SR([Z[0],Z[1],Z[2]]),Q=SR([Z[4],Z[5],Z[6]]),W=SR([Z[8],Z[9],Z[10]]);if(MV5(Z)<0)Y=-Y;J[0]=Z[12],J[1]=Z[13],J[2]=Z[14];let G=Z.slice(),V=1/Y,H=1/Q,q=1/W;G[0]*=V,G[1]*=V,G[2]*=V,G[4]*=H,G[5]*=H,G[6]*=H,G[8]*=q,G[9]*=q,G[10]*=q,PV5(X,G),$[0]=Y,$[1]=Q,$[2]=W}static compose(Z,J,X,$){let Y=$,Q=J[0],W=J[1],K=J[2],G=J[3],V=Q+Q,H=W+W,q=K+K,z=Q*V,F=Q*H,U=Q*q,L=W*H,B=W*q,w=K*q,O=G*V,M=G*H,N=G*q,P=X[0],D=X[1],C=X[2];return Y[0]=(1-(L+w))*P,Y[1]=(F+N)*P,Y[2]=(U-M)*P,Y[3]=0,Y[4]=(F-N)*D,Y[5]=(1-(z+w))*D,Y[6]=(B+O)*D,Y[7]=0,Y[8]=(U+M)*C,Y[9]=(B-O)*C,Y[10]=(1-(z+L))*C,Y[11]=0,Y[12]=Z[0],Y[13]=Z[1],Y[14]=Z[2],Y[15]=1,Y}}function CV5(Z,J){if(!!Z!==!!J)return!1;let X=Z.getChild(),$=J.getChild();return X===$||X.equals($)}function TV5(Z,J){if(!!Z!==!!J)return!1;let X=Z.values(),$=J.values();if(X.length!==$.length)return!1;for(let Y=0;Y<X.length;Y++){let Q=X[Y],W=$[Y];if(Q.getChild()===W.getChild())continue;if(!Q.getChild().equals(W.getChild()))return!1}return!0}function kV5(Z,J){if(!!Z!==!!J)return!1;let X=Z.keys(),$=J.keys();if(X.length!==$.length)return!1;for(let Y of X){let Q=Z.get(Y),W=J.get(Y);if(!!Q!==!!W)return!1;let K=Q.getChild(),G=W.getChild();if(K===G)continue;if(!K.equals(G))return!1}return!0}function uu(Z,J){if(Z===J)return!0;if(!!Z!==!!J||!Z||!J)return!1;if(Z.length!==J.length)return!1;for(let X=0;X<Z.length;X++)if(Z[X]!==J[X])return!1;return!0}function cu(Z,J){if(Z===J)return!0;if(!!Z!==!!J)return!1;if(!r$(Z)||!r$(J))return Z===J;let X=Z,$=J,Y=0,Q=0,W;for(W in X)Y++;for(W in $)Q++;if(Y!==Q)return!1;for(W in X){let K=X[W],G=$[W];if(yF(K)&&yF(G)){if(!uu(K,G))return!1}else if(r$(K)&&r$(G)){if(!cu(K,G))return!1}else if(K!==G)return!1}return!0}function yF(Z){return Array.isArray(Z)||ArrayBuffer.isView(Z)}var xu="23456789abdegjkmnpqrvwxyzABDEGJKMNPQRVWXYZ",EV5=999,IV5=6,fu=new Set,vV5=function Z(){let J="";for(let X=0;X<IV5;X++)J+=xu.charAt(Math.floor(Math.random()*xu.length));return J},lu=function Z(){for(let J=0;J<EV5;J++){let X=vV5();if(!fu.has(X))return fu.add(X),X}return""},hu="https://null.example";class H9{static dirname(Z){let J=Z.lastIndexOf("/");if(J===-1)return"./";return Z.substring(0,J+1)}static basename(Z){return nJ.basename(new URL(Z,hu).pathname)}static extension(Z){return nJ.extension(new URL(Z,hu).pathname)}static resolve(Z,J){if(!this.isRelativePath(J))return J;let X=Z.split("/"),$=J.split("/");X.pop();for(let Y=0;Y<$.length;Y++){if($[Y]===".")continue;if($[Y]==="..")X.pop();else X.push($[Y])}return X.join("/")}static isAbsoluteURL(Z){return this.PROTOCOL_REGEXP.test(Z)}static isRelativePath(Z){return!/^(?:[a-zA-Z]+:)?\//.test(Z)}}H9.DEFAULT_INIT={};H9.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;var XX=(Z)=>Z,SV5=new Set;class dF extends CW{constructor(Z,J=""){super(Z);this[y0].name=J,this.init(),this.dispatchEvent({type:"create"})}getGraph(){return this.graph}getDefaults(){return Object.assign(super.getDefaults(),{name:"",extras:{}})}set(Z,J){if(Array.isArray(J))J=J.slice();return super.set(Z,J)}getName(){return this.get("name")}setName(Z){return this.set("name",Z)}getExtras(){return this.get("extras")}setExtras(Z){return this.set("extras",Z)}clone(){return new this.constructor(this.graph).copy(this,XX)}copy(Z,J=XX){for(let X in this[y0]){let $=this[y0][X];if($ instanceof Y7){if(!this[WZ].has(X))$.dispose()}else if($ instanceof z6||$ instanceof I0)for(let Y of $.values())Y.dispose();else if($ instanceof a5)for(let Y of $.values())Y.dispose()}for(let X in Z[y0]){let $=this[y0][X],Y=Z[y0][X];if(Y instanceof Y7)if(this[WZ].has(X))$.getChild().copy(J(Y.getChild()),J);else this.setRef(X,J(Y.getChild()),Y.getAttributes());else if(Y instanceof I0||Y instanceof z6)for(let Q of Y.values())this.addRef(X,J(Q.getChild()),Q.getAttributes());else if(Y instanceof a5)for(let Q of Y.keys()){let W=Y.get(Q);this.setRefMap(X,Q,J(W.getChild()),W.getAttributes())}else if(r$(Y))this[y0][X]=JSON.parse(JSON.stringify(Y));else if(Array.isArray(Y)||Y instanceof ArrayBuffer||ArrayBuffer.isView(Y))this[y0][X]=Y.slice();else this[y0][X]=Y}return this}equals(Z,J=SV5){if(this===Z)return!0;if(this.propertyType!==Z.propertyType)return!1;for(let X in this[y0]){if(J.has(X))continue;let $=this[y0][X],Y=Z[y0][X];if($ instanceof Y7||Y instanceof Y7){if(!CV5($,Y))return!1}else if($ instanceof I0||Y instanceof I0||$ instanceof z6||Y instanceof z6){if(!TV5($,Y))return!1}else if($ instanceof a5||Y instanceof a5){if(!kV5($,Y))return!1}else if(r$($)||r$(Y)){if(!cu($,Y))return!1}else if(yF($)||yF(Y)){if(!uu($,Y))return!1}else if($!==Y)return!1}return!0}detach(){return this.graph.disconnectParents(this,(Z)=>Z.propertyType!=="Root"),this}listParents(){return this.graph.listParents(this)}}class U6 extends dF{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new a5})}getExtension(Z){return this.getRefMap("extensions",Z)}setExtension(Z,J){if(J)J._validateParent(this);return this.setRefMap("extensions",Z,J)}listExtensions(){return this.listRefMapValues("extensions")}}class f0 extends U6{init(){this.propertyType=n.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:f0.Type.SCALAR,componentType:f0.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(Z){switch(Z){case f0.Type.SCALAR:return 1;case f0.Type.VEC2:return 2;case f0.Type.VEC3:return 3;case f0.Type.VEC4:return 4;case f0.Type.MAT2:return 4;case f0.Type.MAT3:return 9;case f0.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+Z)}}static getComponentSize(Z){switch(Z){case f0.ComponentType.BYTE:return 1;case f0.ComponentType.UNSIGNED_BYTE:return 1;case f0.ComponentType.SHORT:return 2;case f0.ComponentType.UNSIGNED_SHORT:return 2;case f0.ComponentType.UNSIGNED_INT:return 4;case f0.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+Z)}}getMinNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),$=this.getComponentType();if(this.getMin(Z),J)for(let Y=0;Y<X;Y++)Z[Y]=i0.decodeNormalizedInt(Z[Y],$);return Z}getMin(Z){let J=this.getArray(),X=this.getCount(),$=this.getElementSize();for(let Y=0;Y<$;Y++)Z[Y]=1/0;for(let Y=0;Y<X*$;Y+=$)for(let Q=0;Q<$;Q++){let W=J[Y+Q];if(Number.isFinite(W))Z[Q]=Math.min(Z[Q],W)}return Z}getMaxNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),$=this.getComponentType();if(this.getMax(Z),J)for(let Y=0;Y<X;Y++)Z[Y]=i0.decodeNormalizedInt(Z[Y],$);return Z}getMax(Z){let J=this.get("array"),X=this.getCount(),$=this.getElementSize();for(let Y=0;Y<$;Y++)Z[Y]=-1/0;for(let Y=0;Y<X*$;Y+=$)for(let Q=0;Q<$;Q++){let W=J[Y+Q];if(Number.isFinite(W))Z[Q]=Math.max(Z[Q],W)}return Z}getCount(){let Z=this.get("array");return Z?Z.length/this.getElementSize():0}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getElementSize(){return f0.getElementSize(this.get("type"))}getComponentSize(){return this.get("array").BYTES_PER_ELEMENT}getComponentType(){return this.get("componentType")}getNormalized(){return this.get("normalized")}setNormalized(Z){return this.set("normalized",Z)}getScalar(Z){let J=this.getElementSize(),X=this.getComponentType(),$=this.getArray();if(this.getNormalized())return i0.decodeNormalizedInt($[Z*J],X);return $[Z*J]}setScalar(Z,J){let X=this.getElementSize(),$=this.getComponentType(),Y=this.getArray();if(this.getNormalized())Y[Z*X]=i0.encodeNormalizedInt(J,$);else Y[Z*X]=J;return this}getElement(Z,J){let X=this.getNormalized(),$=this.getElementSize(),Y=this.getComponentType(),Q=this.getArray();for(let W=0;W<$;W++)if(X)J[W]=i0.decodeNormalizedInt(Q[Z*$+W],Y);else J[W]=Q[Z*$+W];return J}setElement(Z,J){let X=this.getNormalized(),$=this.getElementSize(),Y=this.getComponentType(),Q=this.getArray();for(let W=0;W<$;W++)if(X)Q[Z*$+W]=i0.encodeNormalizedInt(J[W],Y);else Q[Z*$+W]=J[W];return this}getSparse(){return this.get("sparse")}setSparse(Z){return this.set("sparse",Z)}getBuffer(){return this.getRef("buffer")}setBuffer(Z){return this.setRef("buffer",Z)}getArray(){return this.get("array")}setArray(Z){return this.set("componentType",Z?_V5(Z):f0.ComponentType.FLOAT),this.set("array",Z),this}getByteLength(){let Z=this.get("array");return Z?Z.byteLength:0}}f0.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};f0.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};function _V5(Z){switch(Z.constructor){case Float32Array:return f0.ComponentType.FLOAT;case Uint32Array:return f0.ComponentType.UNSIGNED_INT;case Uint16Array:return f0.ComponentType.UNSIGNED_SHORT;case Uint8Array:return f0.ComponentType.UNSIGNED_BYTE;case Int16Array:return f0.ComponentType.SHORT;case Int8Array:return f0.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}class yR extends U6{init(){this.propertyType=n.ANIMATION}getDefaults(){return Object.assign(super.getDefaults(),{channels:new I0,samplers:new I0})}addChannel(Z){return this.addRef("channels",Z)}removeChannel(Z){return this.removeRef("channels",Z)}listChannels(){return this.listRefs("channels")}addSampler(Z){return this.addRef("samplers",Z)}removeSampler(Z){return this.removeRef("samplers",Z)}listSamplers(){return this.listRefs("samplers")}}class o$ extends U6{init(){this.propertyType=n.ANIMATION_CHANNEL}getDefaults(){return Object.assign(super.getDefaults(),{targetPath:null,targetNode:null,sampler:null})}getTargetPath(){return this.get("targetPath")}setTargetPath(Z){return this.set("targetPath",Z)}getTargetNode(){return this.getRef("targetNode")}setTargetNode(Z){return this.setRef("targetNode",Z)}getSampler(){return this.getRef("sampler")}setSampler(Z){return this.setRef("sampler",Z)}}o$.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class TW extends U6{init(){this.propertyType=n.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:TW.Interpolation.LINEAR,input:null,output:null})}getInterpolation(){return this.get("interpolation")}setInterpolation(Z){return this.set("interpolation",Z)}getInput(){return this.getRef("input")}setInput(Z){return this.setRef("input",Z,{usage:I7.OTHER})}getOutput(){return this.getRef("output")}setOutput(Z){return this.setRef("output",Z,{usage:I7.OTHER})}}TW.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class gR extends U6{init(){this.propertyType=n.BUFFER}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(Z){return this.set("uri",Z)}}class t$ extends U6{init(){this.propertyType=n.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:t$.Type.PERSPECTIVE,znear:0.1,zfar:100,aspectRatio:null,yfov:Math.PI*2*50/360,xmag:1,ymag:1})}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getZNear(){return this.get("znear")}setZNear(Z){return this.set("znear",Z)}getZFar(){return this.get("zfar")}setZFar(Z){return this.set("zfar",Z)}getAspectRatio(){return this.get("aspectRatio")}setAspectRatio(Z){return this.set("aspectRatio",Z)}getYFov(){return this.get("yfov")}setYFov(Z){return this.set("yfov",Z)}getXMag(){return this.get("xmag")}setXMag(Z){return this.set("xmag",Z)}getYMag(){return this.get("ymag")}setYMag(Z){return this.set("ymag",Z)}}t$.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class kW extends dF{_validateParent(Z){if(!this.parentTypes.includes(Z.propertyType))throw new Error(`Parent "${Z.propertyType}" invalid for child "${this.propertyType}".`)}}kW.EXTENSION_NAME=void 0;class Q7 extends U6{init(){this.propertyType=n.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:Q7.WrapMode.REPEAT,wrapT:Q7.WrapMode.REPEAT})}getTexCoord(){return this.get("texCoord")}setTexCoord(Z){return this.set("texCoord",Z)}getMagFilter(){return this.get("magFilter")}setMagFilter(Z){return this.set("magFilter",Z)}getMinFilter(){return this.get("minFilter")}setMinFilter(Z){return this.set("minFilter",Z)}getWrapS(){return this.get("wrapS")}setWrapS(Z){return this.set("wrapS",Z)}getWrapT(){return this.get("wrapT")}setWrapT(Z){return this.set("wrapT",Z)}}Q7.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};Q7.MagFilter={NEAREST:9728,LINEAR:9729};Q7.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};var{R:vF,G:SF,B:_F,A:AV5}=bF;class nZ extends U6{init(){this.propertyType=n.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:nZ.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new Q7(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new Q7(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new Q7(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new Q7(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new Q7(this.graph,"metallicRoughnessTextureInfo")})}getDoubleSided(){return this.get("doubleSided")}setDoubleSided(Z){return this.set("doubleSided",Z)}getAlpha(){return this.get("baseColorFactor")[3]}setAlpha(Z){let J=this.get("baseColorFactor").slice();return J[3]=Z,this.set("baseColorFactor",J)}getAlphaMode(){return this.get("alphaMode")}setAlphaMode(Z){return this.set("alphaMode",Z)}getAlphaCutoff(){return this.get("alphaCutoff")}setAlphaCutoff(Z){return this.set("alphaCutoff",Z)}getBaseColorFactor(){return this.get("baseColorFactor")}setBaseColorFactor(Z){return this.set("baseColorFactor",Z)}getBaseColorTexture(){return this.getRef("baseColorTexture")}getBaseColorTextureInfo(){return this.getRef("baseColorTexture")?this.getRef("baseColorTextureInfo"):null}setBaseColorTexture(Z){return this.setRef("baseColorTexture",Z,{channels:vF|SF|_F|AV5,isColor:!0})}getEmissiveFactor(){return this.get("emissiveFactor")}setEmissiveFactor(Z){return this.set("emissiveFactor",Z)}getEmissiveTexture(){return this.getRef("emissiveTexture")}getEmissiveTextureInfo(){return this.getRef("emissiveTexture")?this.getRef("emissiveTextureInfo"):null}setEmissiveTexture(Z){return this.setRef("emissiveTexture",Z,{channels:vF|SF|_F,isColor:!0})}getNormalScale(){return this.get("normalScale")}setNormalScale(Z){return this.set("normalScale",Z)}getNormalTexture(){return this.getRef("normalTexture")}getNormalTextureInfo(){return this.getRef("normalTexture")?this.getRef("normalTextureInfo"):null}setNormalTexture(Z){return this.setRef("normalTexture",Z,{channels:vF|SF|_F})}getOcclusionStrength(){return this.get("occlusionStrength")}setOcclusionStrength(Z){return this.set("occlusionStrength",Z)}getOcclusionTexture(){return this.getRef("occlusionTexture")}getOcclusionTextureInfo(){return this.getRef("occlusionTexture")?this.getRef("occlusionTextureInfo"):null}setOcclusionTexture(Z){return this.setRef("occlusionTexture",Z,{channels:vF})}getRoughnessFactor(){return this.get("roughnessFactor")}setRoughnessFactor(Z){return this.set("roughnessFactor",Z)}getMetallicFactor(){return this.get("metallicFactor")}setMetallicFactor(Z){return this.set("metallicFactor",Z)}getMetallicRoughnessTexture(){return this.getRef("metallicRoughnessTexture")}getMetallicRoughnessTextureInfo(){return this.getRef("metallicRoughnessTexture")?this.getRef("metallicRoughnessTextureInfo"):null}setMetallicRoughnessTexture(Z){return this.setRef("metallicRoughnessTexture",Z,{channels:SF|_F})}}nZ.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class IG extends U6{init(){this.propertyType=n.MESH}getDefaults(){return Object.assign(super.getDefaults(),{weights:[],primitives:new I0})}addPrimitive(Z){return this.addRef("primitives",Z)}removePrimitive(Z){return this.removeRef("primitives",Z)}listPrimitives(){return this.listRefs("primitives")}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}}class uF extends U6{init(){this.propertyType=n.NODE}getDefaults(){return Object.assign(super.getDefaults(),{translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1],weights:[],camera:null,mesh:null,skin:null,children:new I0})}copy(Z,J=XX){if(J===XX)throw new Error("Node cannot be copied.");return super.copy(Z,J)}getTranslation(){return this.get("translation")}getRotation(){return this.get("rotation")}getScale(){return this.get("scale")}setTranslation(Z){return this.set("translation",Z)}setRotation(Z){return this.set("rotation",Z)}setScale(Z){return this.set("scale",Z)}getMatrix(){return i0.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(Z){let J=this.get("translation").slice(),X=this.get("rotation").slice(),$=this.get("scale").slice();return i0.decompose(Z,J,X,$),this.set("translation",J).set("rotation",X).set("scale",$)}getWorldTranslation(){let Z=[0,0,0];return i0.decompose(this.getWorldMatrix(),Z,[0,0,0,1],[1,1,1]),Z}getWorldRotation(){let Z=[0,0,0,1];return i0.decompose(this.getWorldMatrix(),[0,0,0],Z,[1,1,1]),Z}getWorldScale(){let Z=[1,1,1];return i0.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],Z),Z}getWorldMatrix(){let Z=[];for(let $=this;$!=null;$=$.getParentNode())Z.push($);let J,X=Z.pop().getMatrix();while(J=Z.pop())RV5(X,X,J.getMatrix());return X}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);for(let X of Z.listParents())if(X.propertyType===n.SCENE)X.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}getParentNode(){for(let Z of this.listParents())if(Z.propertyType===n.NODE)return Z;return null}getMesh(){return this.getRef("mesh")}setMesh(Z){return this.setRef("mesh",Z)}getCamera(){return this.getRef("camera")}setCamera(Z){return this.setRef("camera",Z)}getSkin(){return this.getRef("skin")}setSkin(Z){return this.setRef("skin",Z)}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}traverse(Z){Z(this);for(let J of this.listChildren())J.traverse(Z);return this}}class O8 extends U6{init(){this.propertyType=n.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:O8.Mode.TRIANGLES,material:null,indices:null,attributes:new a5,targets:new I0})}getIndices(){return this.getRef("indices")}setIndices(Z){return this.setRef("indices",Z,{usage:I7.ELEMENT_ARRAY_BUFFER})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:I7.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}getMaterial(){return this.getRef("material")}setMaterial(Z){return this.setRef("material",Z)}getMode(){return this.get("mode")}setMode(Z){return this.set("mode",Z)}listTargets(){return this.listRefs("targets")}addTarget(Z){return this.addRef("targets",Z)}removeTarget(Z){return this.removeRef("targets",Z)}}O8.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class mR extends dF{init(){this.propertyType=n.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new a5})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:I7.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function A6(){return A6=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)({}).hasOwnProperty.call(X,$)&&(Z[$]=X[$])}return Z},A6.apply(null,arguments)}class EW extends U6{init(){this.propertyType=n.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:new I0})}copy(Z,J=XX){if(J===XX)throw new Error("Scene cannot be copied.");return super.copy(Z,J)}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}traverse(Z){for(let J of this.listChildren())J.traverse(Z);return this}}class dR extends U6{init(){this.propertyType=n.SKIN}getDefaults(){return Object.assign(super.getDefaults(),{skeleton:null,inverseBindMatrices:null,joints:new I0})}getSkeleton(){return this.getRef("skeleton")}setSkeleton(Z){return this.setRef("skeleton",Z)}getInverseBindMatrices(){return this.getRef("inverseBindMatrices")}setInverseBindMatrices(Z){return this.setRef("inverseBindMatrices",Z,{usage:I7.INVERSE_BIND_MATRICES})}addJoint(Z){return this.addRef("joints",Z)}removeJoint(Z){return this.removeRef("joints",Z)}listJoints(){return this.listRefs("joints")}}class e$ extends U6{init(){this.propertyType=n.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||iJ.extensionToMimeType(nJ.extension(this.get("uri")))}setMimeType(Z){return this.set("mimeType",Z)}getURI(){return this.get("uri")}setURI(Z){this.set("uri",Z);let J=iJ.extensionToMimeType(nJ.extension(Z));if(J)this.set("mimeType",J);return this}getImage(){return this.get("image")}setImage(Z){return this.set("image",r0.assertView(Z))}getSize(){let Z=this.get("image");if(!Z)return null;return iJ.getSize(Z,this.getMimeType())}}class ZY extends U6{init(){this.propertyType=n.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${gu}`,version:"2.0"},defaultScene:null,accessors:new I0,animations:new I0,buffers:new I0,cameras:new I0,materials:new I0,meshes:new I0,nodes:new I0,scenes:new I0,skins:new I0,textures:new I0})}constructor(Z){super(Z);this._extensions=new Set,Z.addEventListener("node:create",(J)=>{this._addChildOfRoot(J.target)})}clone(){throw new Error("Root cannot be cloned.")}copy(Z,J=XX){if(J===XX)throw new Error("Root cannot be copied.");this.set("asset",A6({},Z.get("asset"))),this.setName(Z.getName()),this.setExtras(A6({},Z.getExtras())),this.setDefaultScene(Z.getDefaultScene()?J(Z.getDefaultScene()):null);for(let X of Z.listRefMapKeys("extensions")){let $=Z.getExtension(X);this.setExtension(X,J($))}return this}_addChildOfRoot(Z){if(Z instanceof EW)this.addRef("scenes",Z);else if(Z instanceof uF)this.addRef("nodes",Z);else if(Z instanceof t$)this.addRef("cameras",Z);else if(Z instanceof dR)this.addRef("skins",Z);else if(Z instanceof IG)this.addRef("meshes",Z);else if(Z instanceof nZ)this.addRef("materials",Z);else if(Z instanceof e$)this.addRef("textures",Z);else if(Z instanceof yR)this.addRef("animations",Z);else if(Z instanceof f0)this.addRef("accessors",Z);else if(Z instanceof gR)this.addRef("buffers",Z);return this}getAsset(){return this.get("asset")}listExtensionsUsed(){return Array.from(this._extensions)}listExtensionsRequired(){return this.listExtensionsUsed().filter((Z)=>Z.isRequired())}_enableExtension(Z){return this._extensions.add(Z),this}_disableExtension(Z){return this._extensions.delete(Z),this}listScenes(){return this.listRefs("scenes")}setDefaultScene(Z){return this.setRef("defaultScene",Z)}getDefaultScene(){return this.getRef("defaultScene")}listNodes(){return this.listRefs("nodes")}listCameras(){return this.listRefs("cameras")}listSkins(){return this.listRefs("skins")}listMeshes(){return this.listRefs("meshes")}listMaterials(){return this.listRefs("materials")}listTextures(){return this.listRefs("textures")}listAnimations(){return this.listRefs("animations")}listAccessors(){return this.listRefs("accessors")}listBuffers(){return this.listRefs("buffers")}}class F6{static fromGraph(Z){return F6._GRAPH_DOCUMENTS.get(Z)||null}constructor(){this._graph=new PW,this._root=new ZY(this._graph),this._logger=W7.DEFAULT_INSTANCE,F6._GRAPH_DOCUMENTS.set(this._graph,this)}getRoot(){return this._root}getGraph(){return this._graph}getLogger(){return this._logger}setLogger(Z){return this._logger=Z,this}clone(){throw new Error("Use 'cloneDocument(source)' from '@gltf-transform/functions'.")}merge(Z){throw new Error("Use 'mergeDocuments(target, source)' from '@gltf-transform/functions'.")}async transform(...Z){let J=Z.map((X)=>X.name);for(let X of Z)await X(this,{stack:J});return this}createExtension(Z){let J=Z.EXTENSION_NAME;return this.getRoot().listExtensionsUsed().find(($)=>$.extensionName===J)||new Z(this)}createScene(Z=""){return new EW(this._graph,Z)}createNode(Z=""){return new uF(this._graph,Z)}createCamera(Z=""){return new t$(this._graph,Z)}createSkin(Z=""){return new dR(this._graph,Z)}createMesh(Z=""){return new IG(this._graph,Z)}createPrimitive(){return new O8(this._graph)}createPrimitiveTarget(Z=""){return new mR(this._graph,Z)}createMaterial(Z=""){return new nZ(this._graph,Z)}createTexture(Z=""){return new e$(this._graph,Z)}createAnimation(Z=""){return new yR(this._graph,Z)}createAnimationChannel(Z=""){return new o$(this._graph,Z)}createAnimationSampler(Z=""){return new TW(this._graph,Z)}createAccessor(Z="",J=null){if(!J)J=this.getRoot().listBuffers()[0];return new f0(this._graph,Z).setBuffer(J)}createBuffer(Z=""){return new gR(this._graph,Z)}}F6._GRAPH_DOCUMENTS=new WeakMap;class pu{constructor(Z){this.extensionName="",this.prereadTypes=[],this.prewriteTypes=[],this.readDependencies=[],this.writeDependencies=[],this.document=void 0,this.required=!1,this.properties=new Set,this._listener=void 0,this.document=Z,Z.getRoot()._enableExtension(this),this._listener=(X)=>{let $=X,Y=$.target;if(Y instanceof kW&&Y.extensionName===this.extensionName){if($.type==="node:create")this._addExtensionProperty(Y);if($.type==="node:dispose")this._removeExtensionProperty(Y)}};let J=Z.getGraph();J.addEventListener("node:create",this._listener),J.addEventListener("node:dispose",this._listener)}dispose(){this.document.getRoot()._disableExtension(this);let Z=this.document.getGraph();Z.removeEventListener("node:create",this._listener),Z.removeEventListener("node:dispose",this._listener);for(let J of this.properties)J.dispose()}static register(){}isRequired(){return this.required}setRequired(Z){return this.required=Z,this}listProperties(){return Array.from(this.properties)}_addExtensionProperty(Z){return this.properties.add(Z),this}_removeExtensionProperty(Z){return this.properties.delete(Z),this}install(Z,J){return this}preread(Z,J){return this}prewrite(Z,J){return this}}pu.EXTENSION_NAME=void 0;class iu{constructor(Z){this.jsonDoc=void 0,this.buffers=[],this.bufferViews=[],this.bufferViewBuffers=[],this.accessors=[],this.textures=[],this.textureInfos=new Map,this.materials=[],this.meshes=[],this.cameras=[],this.nodes=[],this.skins=[],this.animations=[],this.scenes=[],this.jsonDoc=Z}setTextureInfo(Z,J){if(this.textureInfos.set(Z,J),J.texCoord!==void 0)Z.setTexCoord(J.texCoord);if(J.extras!==void 0)Z.setExtras(J.extras);let X=this.jsonDoc.json.textures[J.index];if(X.sampler===void 0)return;let $=this.jsonDoc.json.samplers[X.sampler];if($.magFilter!==void 0)Z.setMagFilter($.magFilter);if($.minFilter!==void 0)Z.setMinFilter($.minFilter);if($.wrapS!==void 0)Z.setWrapS($.wrapS);if($.wrapT!==void 0)Z.setWrapT($.wrapT)}}var bu={logger:W7.DEFAULT_INSTANCE,extensions:[],dependencies:{}},xV5=new Set([n.BUFFER,n.TEXTURE,n.MATERIAL,n.MESH,n.PRIMITIVE,n.NODE,n.SCENE]);class nu{static read(Z,J=bu){let X=A6({},bu,J),{json:$}=Z,Y=new F6().setLogger(X.logger);this.validate(Z,X);let Q=new iu(Z),W=$.asset,K=Y.getRoot().getAsset();if(W.copyright)K.copyright=W.copyright;if(W.extras)K.extras=W.extras;if($.extras!==void 0)Y.getRoot().setExtras(A6({},$.extras));let G=$.extensionsUsed||[],V=$.extensionsRequired||[];X.extensions.sort((D,C)=>D.EXTENSION_NAME>C.EXTENSION_NAME?1:-1);for(let D of X.extensions)if(G.includes(D.EXTENSION_NAME)){let C=Y.createExtension(D).setRequired(V.includes(D.EXTENSION_NAME)),T=C.prereadTypes.filter((k)=>!xV5.has(k));if(T.length)X.logger.warn(`Preread hooks for some types (${T.join()}), requested by extension ${C.extensionName}, are unsupported. Please file an issue or a PR.`);for(let k of C.readDependencies)C.install(k,X.dependencies[k])}let H=$.buffers||[];Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.BUFFER)).forEach((D)=>D.preread(Q,n.BUFFER)),Q.buffers=H.map((D)=>{let C=Y.createBuffer(D.name);if(D.extras)C.setExtras(D.extras);if(D.uri&&D.uri.indexOf("__")!==0)C.setURI(D.uri);return C});let q=$.bufferViews||[];Q.bufferViewBuffers=q.map((D,C)=>{if(!Q.bufferViews[C]){let T=Z.json.buffers[D.buffer],k=T.uri?Z.resources[T.uri]:Z.resources[fF],A=D.byteOffset||0;Q.bufferViews[C]=r0.toView(k,A,D.byteLength)}return Q.buffers[D.buffer]});let z=$.accessors||[];Q.accessors=z.map((D)=>{let C=Q.bufferViewBuffers[D.bufferView],T=Y.createAccessor(D.name,C).setType(D.type);if(D.extras)T.setExtras(D.extras);if(D.normalized!==void 0)T.setNormalized(D.normalized);if(D.bufferView===void 0)return T;return T.setArray(xF(D,Q)),T});let F=$.images||[],U=$.textures||[];Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.TEXTURE)).forEach((D)=>D.preread(Q,n.TEXTURE)),Q.textures=F.map((D)=>{let C=Y.createTexture(D.name);if(D.extras)C.setExtras(D.extras);if(D.bufferView!==void 0){let T=$.bufferViews[D.bufferView],k=Z.json.buffers[T.buffer],A=k.uri?Z.resources[k.uri]:Z.resources[fF],v=T.byteOffset||0,x=T.byteLength,I=A.slice(v,v+x);C.setImage(I)}else if(D.uri!==void 0){if(C.setImage(Z.resources[D.uri]),D.uri.indexOf("__")!==0)C.setURI(D.uri)}if(D.mimeType!==void 0)C.setMimeType(D.mimeType);else if(D.uri){let T=nJ.extension(D.uri);C.setMimeType(iJ.extensionToMimeType(T))}return C}),Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.MATERIAL)).forEach((D)=>D.preread(Q,n.MATERIAL));let L=$.materials||[];Q.materials=L.map((D)=>{let C=Y.createMaterial(D.name);if(D.extras)C.setExtras(D.extras);if(D.alphaMode!==void 0)C.setAlphaMode(D.alphaMode);if(D.alphaCutoff!==void 0)C.setAlphaCutoff(D.alphaCutoff);if(D.doubleSided!==void 0)C.setDoubleSided(D.doubleSided);let T=D.pbrMetallicRoughness||{};if(T.baseColorFactor!==void 0)C.setBaseColorFactor(T.baseColorFactor);if(D.emissiveFactor!==void 0)C.setEmissiveFactor(D.emissiveFactor);if(T.metallicFactor!==void 0)C.setMetallicFactor(T.metallicFactor);if(T.roughnessFactor!==void 0)C.setRoughnessFactor(T.roughnessFactor);if(T.baseColorTexture!==void 0){let k=T.baseColorTexture,A=Q.textures[U[k.index].source];C.setBaseColorTexture(A),Q.setTextureInfo(C.getBaseColorTextureInfo(),k)}if(D.emissiveTexture!==void 0){let k=D.emissiveTexture,A=Q.textures[U[k.index].source];C.setEmissiveTexture(A),Q.setTextureInfo(C.getEmissiveTextureInfo(),k)}if(D.normalTexture!==void 0){let k=D.normalTexture,A=Q.textures[U[k.index].source];if(C.setNormalTexture(A),Q.setTextureInfo(C.getNormalTextureInfo(),k),D.normalTexture.scale!==void 0)C.setNormalScale(D.normalTexture.scale)}if(D.occlusionTexture!==void 0){let k=D.occlusionTexture,A=Q.textures[U[k.index].source];if(C.setOcclusionTexture(A),Q.setTextureInfo(C.getOcclusionTextureInfo(),k),D.occlusionTexture.strength!==void 0)C.setOcclusionStrength(D.occlusionTexture.strength)}if(T.metallicRoughnessTexture!==void 0){let k=T.metallicRoughnessTexture,A=Q.textures[U[k.index].source];C.setMetallicRoughnessTexture(A),Q.setTextureInfo(C.getMetallicRoughnessTextureInfo(),k)}return C}),Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.MESH)).forEach((D)=>D.preread(Q,n.MESH));let B=$.meshes||[];Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.PRIMITIVE)).forEach((D)=>D.preread(Q,n.PRIMITIVE)),Q.meshes=B.map((D)=>{let C=Y.createMesh(D.name);if(D.extras)C.setExtras(D.extras);if(D.weights!==void 0)C.setWeights(D.weights);return(D.primitives||[]).forEach((k)=>{let A=Y.createPrimitive();if(k.extras)A.setExtras(k.extras);if(k.material!==void 0)A.setMaterial(Q.materials[k.material]);if(k.mode!==void 0)A.setMode(k.mode);for(let[I,S]of Object.entries(k.attributes||{}))A.setAttribute(I,Q.accessors[S]);if(k.indices!==void 0)A.setIndices(Q.accessors[k.indices]);let v=D.extras&&D.extras.targetNames||[];(k.targets||[]).forEach((I,S)=>{let g=v[S]||S.toString(),m=Y.createPrimitiveTarget(g);for(let[i,r]of Object.entries(I))m.setAttribute(i,Q.accessors[r]);A.addTarget(m)}),C.addPrimitive(A)}),C});let w=$.cameras||[];Q.cameras=w.map((D)=>{let C=Y.createCamera(D.name).setType(D.type);if(D.extras)C.setExtras(D.extras);if(D.type===t$.Type.PERSPECTIVE){let T=D.perspective;if(C.setYFov(T.yfov),C.setZNear(T.znear),T.zfar!==void 0)C.setZFar(T.zfar);if(T.aspectRatio!==void 0)C.setAspectRatio(T.aspectRatio)}else{let T=D.orthographic;C.setZNear(T.znear).setZFar(T.zfar).setXMag(T.xmag).setYMag(T.ymag)}return C});let O=$.nodes||[];Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.NODE)).forEach((D)=>D.preread(Q,n.NODE)),Q.nodes=O.map((D)=>{let C=Y.createNode(D.name);if(D.extras)C.setExtras(D.extras);if(D.translation!==void 0)C.setTranslation(D.translation);if(D.rotation!==void 0)C.setRotation(D.rotation);if(D.scale!==void 0)C.setScale(D.scale);if(D.matrix!==void 0){let T=[0,0,0],k=[0,0,0,1],A=[1,1,1];i0.decompose(D.matrix,T,k,A),C.setTranslation(T),C.setRotation(k),C.setScale(A)}if(D.weights!==void 0)C.setWeights(D.weights);return C});let M=$.skins||[];Q.skins=M.map((D)=>{let C=Y.createSkin(D.name);if(D.extras)C.setExtras(D.extras);if(D.inverseBindMatrices!==void 0)C.setInverseBindMatrices(Q.accessors[D.inverseBindMatrices]);if(D.skeleton!==void 0)C.setSkeleton(Q.nodes[D.skeleton]);for(let T of D.joints)C.addJoint(Q.nodes[T]);return C}),O.map((D,C)=>{let T=Q.nodes[C];if((D.children||[]).forEach((A)=>T.addChild(Q.nodes[A])),D.mesh!==void 0)T.setMesh(Q.meshes[D.mesh]);if(D.camera!==void 0)T.setCamera(Q.cameras[D.camera]);if(D.skin!==void 0)T.setSkin(Q.skins[D.skin])});let N=$.animations||[];Q.animations=N.map((D)=>{let C=Y.createAnimation(D.name);if(D.extras)C.setExtras(D.extras);let k=(D.samplers||[]).map((v)=>{let x=Y.createAnimationSampler().setInput(Q.accessors[v.input]).setOutput(Q.accessors[v.output]).setInterpolation(v.interpolation||TW.Interpolation.LINEAR);if(v.extras)x.setExtras(v.extras);return C.addSampler(x),x});return(D.channels||[]).forEach((v)=>{let x=Y.createAnimationChannel().setSampler(k[v.sampler]).setTargetPath(v.target.path);if(v.target.node!==void 0)x.setTargetNode(Q.nodes[v.target.node]);if(v.extras)x.setExtras(v.extras);C.addChannel(x)}),C});let P=$.scenes||[];if(Y.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(n.SCENE)).forEach((D)=>D.preread(Q,n.SCENE)),Q.scenes=P.map((D)=>{let C=Y.createScene(D.name);if(D.extras)C.setExtras(D.extras);return(D.nodes||[]).map((k)=>Q.nodes[k]).forEach((k)=>C.addChild(k)),C}),$.scene!==void 0)Y.getRoot().setDefaultScene(Q.scenes[$.scene]);return Y.getRoot().listExtensionsUsed().forEach((D)=>D.read(Q)),z.forEach((D,C)=>{let T=Q.accessors[C],k=!!D.sparse,A=!D.bufferView&&!T.getArray();if(k||A)T.setSparse(!0).setArray(hV5(D,Q))}),Y}static validate(Z,J){let X=Z.json;if(X.asset.version!=="2.0")throw new Error(`Unsupported glTF version, "${X.asset.version}".`);if(X.extensionsRequired){for(let $ of X.extensionsRequired)if(!J.extensions.find((Y)=>Y.EXTENSION_NAME===$))throw new Error(`Missing required extension, "${$}".`)}if(X.extensionsUsed){for(let $ of X.extensionsUsed)if(!J.extensions.find((Y)=>Y.EXTENSION_NAME===$))J.logger.warn(`Missing optional extension, "${$}".`)}}}function fV5(Z,J){let X=J.jsonDoc,$=J.bufferViews[Z.bufferView],Y=X.json.bufferViews[Z.bufferView],Q=$X[Z.componentType],W=f0.getElementSize(Z.type),K=Q.BYTES_PER_ELEMENT,G=Z.byteOffset||0,V=new Q(Z.count*W),H=new DataView($.buffer,$.byteOffset,$.byteLength),q=Y.byteStride;for(let z=0;z<Z.count;z++)for(let F=0;F<W;F++){let U=G+z*q+F*K,L;switch(Z.componentType){case f0.ComponentType.FLOAT:L=H.getFloat32(U,!0);break;case f0.ComponentType.UNSIGNED_INT:L=H.getUint32(U,!0);break;case f0.ComponentType.UNSIGNED_SHORT:L=H.getUint16(U,!0);break;case f0.ComponentType.UNSIGNED_BYTE:L=H.getUint8(U);break;case f0.ComponentType.SHORT:L=H.getInt16(U,!0);break;case f0.ComponentType.BYTE:L=H.getInt8(U);break;default:throw new Error(`Unexpected componentType "${Z.componentType}".`)}V[z*W+F]=L}return V}function xF(Z,J){let X=J.jsonDoc,$=J.bufferViews[Z.bufferView],Y=X.json.bufferViews[Z.bufferView],Q=$X[Z.componentType],W=f0.getElementSize(Z.type),K=Q.BYTES_PER_ELEMENT,G=W*K;if(Y.byteStride!==void 0&&Y.byteStride!==G)return fV5(Z,J);let V=$.byteOffset+(Z.byteOffset||0),H=Z.count*W*K;return new Q($.buffer.slice(V,V+H))}function hV5(Z,J){let X=$X[Z.componentType],$=f0.getElementSize(Z.type),Y;if(Z.bufferView!==void 0)Y=xF(Z,J);else Y=new X(Z.count*$);let Q=Z.sparse;if(!Q)return Y;let W=Q.count,K=A6({},Z,Q.indices,{count:W,type:"SCALAR"}),G=A6({},Z,Q.values,{count:W}),V=xF(K,J),H=xF(G,J);for(let q=0;q<K.count;q++)for(let z=0;z<$;z++)Y[V[q]*$+z]=H[q*$+z];return Y}var EG;(function(Z){Z[Z.ARRAY_BUFFER=34962]="ARRAY_BUFFER",Z[Z.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"})(EG||(EG={}));class JX{constructor(Z,J,X){this._doc=void 0,this.jsonDoc=void 0,this.options=void 0,this.accessorIndexMap=new Map,this.animationIndexMap=new Map,this.bufferIndexMap=new Map,this.cameraIndexMap=new Map,this.skinIndexMap=new Map,this.materialIndexMap=new Map,this.meshIndexMap=new Map,this.nodeIndexMap=new Map,this.imageIndexMap=new Map,this.textureDefIndexMap=new Map,this.textureInfoDefMap=new Map,this.samplerDefIndexMap=new Map,this.sceneIndexMap=new Map,this.imageBufferViews=[],this.otherBufferViews=new Map,this.otherBufferViewsIndexMap=new Map,this.extensionData={},this.bufferURIGenerator=void 0,this.imageURIGenerator=void 0,this.logger=void 0,this._accessorUsageMap=new Map,this.accessorUsageGroupedByParent=new Set(["ARRAY_BUFFER"]),this.accessorParents=new Map,this._doc=Z,this.jsonDoc=J,this.options=X;let $=Z.getRoot(),Y=$.listBuffers().length,Q=$.listTextures().length;this.bufferURIGenerator=new fR(Y>1,()=>X.basename||"buffer"),this.imageURIGenerator=new fR(Q>1,(W)=>bV5(Z,W)||X.basename||"texture"),this.logger=Z.getLogger()}createTextureInfoDef(Z,J){let X={magFilter:J.getMagFilter()||void 0,minFilter:J.getMinFilter()||void 0,wrapS:J.getWrapS(),wrapT:J.getWrapT()},$=JSON.stringify(X);if(!this.samplerDefIndexMap.has($))this.samplerDefIndexMap.set($,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(X);let Y={source:this.imageIndexMap.get(Z),sampler:this.samplerDefIndexMap.get($)},Q=JSON.stringify(Y);if(!this.textureDefIndexMap.has(Q))this.textureDefIndexMap.set(Q,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push(Y);let W={index:this.textureDefIndexMap.get(Q)};if(J.getTexCoord()!==0)W.texCoord=J.getTexCoord();if(Object.keys(J.getExtras()).length>0)W.extras=J.getExtras();return this.textureInfoDefMap.set(J,W),W}createPropertyDef(Z){let J={};if(Z.getName())J.name=Z.getName();if(Object.keys(Z.getExtras()).length>0)J.extras=Z.getExtras();return J}createAccessorDef(Z){let J=this.createPropertyDef(Z);if(J.type=Z.getType(),J.componentType=Z.getComponentType(),J.count=Z.getCount(),this._doc.getGraph().listParentEdges(Z).some(($)=>$.getName()==="attributes"&&$.getAttributes().key==="POSITION"||$.getName()==="input"))J.max=Z.getMax([]).map(Math.fround),J.min=Z.getMin([]).map(Math.fround);if(Z.getNormalized())J.normalized=Z.getNormalized();return J}createImageData(Z,J,X){if(this.options.format===pJ.GLB)this.imageBufferViews.push(J),Z.bufferView=this.jsonDoc.json.bufferViews.length,this.jsonDoc.json.bufferViews.push({buffer:0,byteOffset:-1,byteLength:J.byteLength});else{let $=iJ.mimeTypeToExtension(X.getMimeType());Z.uri=this.imageURIGenerator.createURI(X,$),this.assignResourceURI(Z.uri,J,!1)}}assignResourceURI(Z,J,X){let $=this.jsonDoc.resources;if(!(Z in $)){$[Z]=J;return}if(J===$[Z]){this.logger.warn(`Duplicate resource URI, "${Z}".`);return}let Y=`Resource URI "${Z}" already assigned to different data.`;if(!X){this.logger.warn(Y);return}throw new Error(Y)}getAccessorUsage(Z){let J=this._accessorUsageMap.get(Z);if(J)return J;if(Z.getSparse())return I7.SPARSE;for(let X of this._doc.getGraph().listParentEdges(Z)){let{usage:$}=X.getAttributes();if($)return $;if(X.getParent().propertyType!==n.ROOT)this.logger.warn(`Missing attribute ".usage" on edge, "${X.getName()}".`)}return I7.OTHER}addAccessorToUsageGroup(Z,J){let X=this._accessorUsageMap.get(Z);if(X&&X!==J)throw new Error(`Accessor with usage "${X}" cannot be reused as "${J}".`);return this._accessorUsageMap.set(Z,J),this}}JX.BufferViewTarget=EG;JX.BufferViewUsage=I7;JX.USAGE_TO_TARGET={[I7.ARRAY_BUFFER]:EG.ARRAY_BUFFER,[I7.ELEMENT_ARRAY_BUFFER]:EG.ELEMENT_ARRAY_BUFFER};class fR{constructor(Z,J){this.multiple=void 0,this.basename=void 0,this.counter={},this.multiple=Z,this.basename=J}createURI(Z,J){if(Z.getURI())return Z.getURI();else if(!this.multiple)return`${this.basename(Z)}.${J}`;else{let X=this.basename(Z);return this.counter[X]=this.counter[X]||1,`${X}_${this.counter[X]++}.${J}`}}}function bV5(Z,J){let X=Z.getGraph().listParentEdges(J).find(($)=>$.getParent()!==Z.getRoot());return X?X.getName().replace(/texture$/i,""):""}var{BufferViewUsage:AF}=JX,{UNSIGNED_INT:yV5,UNSIGNED_SHORT:gV5,UNSIGNED_BYTE:mV5}=f0.ComponentType,dV5=new Set([n.ACCESSOR,n.BUFFER,n.MATERIAL,n.MESH]);class su{static write(Z,J){let X=Z.getGraph(),$=Z.getRoot(),Y={asset:A6({generator:`glTF-Transform ${gu}`},$.getAsset()),extras:A6({},$.getExtras())},Q={json:Y,resources:{}},W=new JX(Z,Q,J),K=J.logger||W7.DEFAULT_INSTANCE,G=new Set(J.extensions.map((B)=>B.EXTENSION_NAME)),V=Z.getRoot().listExtensionsUsed().filter((B)=>G.has(B.extensionName)).sort((B,w)=>B.extensionName>w.extensionName?1:-1),H=Z.getRoot().listExtensionsRequired().filter((B)=>G.has(B.extensionName)).sort((B,w)=>B.extensionName>w.extensionName?1:-1);if(V.length<Z.getRoot().listExtensionsUsed().length)K.warn("Some extensions were not registered for I/O, and will not be written.");for(let B of V){let w=B.prewriteTypes.filter((O)=>!dV5.has(O));if(w.length)K.warn(`Prewrite hooks for some types (${w.join()}), requested by extension ${B.extensionName}, are unsupported. Please file an issue or a PR.`);for(let O of B.writeDependencies)B.install(O,J.dependencies[O])}function q(B,w,O,M){let N=[],P=0;for(let T of B){let k=W.createAccessorDef(T);k.bufferView=Y.bufferViews.length;let A=T.getArray(),v=r0.pad(r0.toView(A));k.byteOffset=P,P+=v.byteLength,N.push(v),W.accessorIndexMap.set(T,Y.accessors.length),Y.accessors.push(k)}let D=r0.concat(N),C={buffer:w,byteOffset:O,byteLength:D.byteLength};if(M)C.target=M;return Y.bufferViews.push(C),{buffers:N,byteLength:P}}function z(B,w,O){let M=B[0].getCount(),N=0;for(let k of B){let A=W.createAccessorDef(k);A.bufferView=Y.bufferViews.length,A.byteOffset=N;let v=k.getElementSize(),x=k.getComponentSize();N+=r0.padNumber(v*x),W.accessorIndexMap.set(k,Y.accessors.length),Y.accessors.push(A)}let P=M*N,D=new ArrayBuffer(P),C=new DataView(D);for(let k=0;k<M;k++){let A=0;for(let v of B){let x=v.getElementSize(),I=v.getComponentSize(),S=v.getComponentType(),g=v.getArray();for(let m=0;m<x;m++){let i=k*N+A+m*I,r=g[k*x+m];switch(S){case f0.ComponentType.FLOAT:C.setFloat32(i,r,!0);break;case f0.ComponentType.BYTE:C.setInt8(i,r);break;case f0.ComponentType.SHORT:C.setInt16(i,r,!0);break;case f0.ComponentType.UNSIGNED_BYTE:C.setUint8(i,r);break;case f0.ComponentType.UNSIGNED_SHORT:C.setUint16(i,r,!0);break;case f0.ComponentType.UNSIGNED_INT:C.setUint32(i,r,!0);break;default:throw new Error("Unexpected component type: "+S)}}A+=r0.padNumber(x*I)}}let T={buffer:w,byteOffset:O,byteLength:P,byteStride:N,target:JX.BufferViewTarget.ARRAY_BUFFER};return Y.bufferViews.push(T),{byteLength:P,buffers:[new Uint8Array(D)]}}function F(B,w,O){let M=[],N=0,P=new Map,D=-1/0,C=!1;for(let S of B){let g=W.createAccessorDef(S);Y.accessors.push(g),W.accessorIndexMap.set(S,Y.accessors.length-1);let m=[],i=[],r=[],Q0=new Array(S.getElementSize()).fill(0);for(let o0=0,T8=S.getCount();o0<T8;o0++){if(S.getElement(o0,r),i0.eq(r,Q0,0))continue;D=Math.max(o0,D),m.push(o0);for(let n5=0;n5<r.length;n5++)i.push(r[n5])}let F0=m.length,_0={accessorDef:g,count:F0};if(P.set(S,_0),F0===0)continue;if(F0>S.getCount()/2)C=!0;let A0=$X[S.getComponentType()];_0.indices=m,_0.values=new A0(i)}if(!Number.isFinite(D))return{buffers:M,byteLength:N};if(C)K.warn("Some sparse accessors have >50% non-zero elements, which may increase file size.");let T=D<255?Uint8Array:D<65535?Uint16Array:Uint32Array,k=D<255?mV5:D<65535?gV5:yV5,A={buffer:w,byteOffset:O+N,byteLength:0};for(let S of B){let g=P.get(S);if(g.count===0)continue;g.indicesByteOffset=A.byteLength;let m=r0.pad(r0.toView(new T(g.indices)));M.push(m),N+=m.byteLength,A.byteLength+=m.byteLength}Y.bufferViews.push(A);let v=Y.bufferViews.length-1,x={buffer:w,byteOffset:O+N,byteLength:0};for(let S of B){let g=P.get(S);if(g.count===0)continue;g.valuesByteOffset=x.byteLength;let m=r0.pad(r0.toView(g.values));M.push(m),N+=m.byteLength,x.byteLength+=m.byteLength}Y.bufferViews.push(x);let I=Y.bufferViews.length-1;for(let S of B){let g=P.get(S);if(g.count===0)continue;g.accessorDef.sparse={count:g.count,indices:{bufferView:v,byteOffset:g.indicesByteOffset,componentType:k},values:{bufferView:I,byteOffset:g.valuesByteOffset}}}return{buffers:M,byteLength:N}}if(Y.accessors=[],Y.bufferViews=[],Y.samplers=[],Y.textures=[],Y.images=$.listTextures().map((B,w)=>{let O=W.createPropertyDef(B);if(B.getMimeType())O.mimeType=B.getMimeType();let M=B.getImage();if(M)W.createImageData(O,M,B);return W.imageIndexMap.set(B,w),O}),V.filter((B)=>B.prewriteTypes.includes(n.ACCESSOR)).forEach((B)=>B.prewrite(W,n.ACCESSOR)),$.listAccessors().forEach((B)=>{let{accessorUsageGroupedByParent:w,accessorParents:O}=W;if(W.accessorIndexMap.has(B))return;let M=W.getAccessorUsage(B);if(W.addAccessorToUsageGroup(B,M),w.has(M)){let N=X.listParents(B).find((P)=>P.propertyType!==n.ROOT);O.set(B,N)}}),V.filter((B)=>B.prewriteTypes.includes(n.BUFFER)).forEach((B)=>B.prewrite(W,n.BUFFER)),($.listAccessors().length>0||W.otherBufferViews.size>0||$.listTextures().length>0&&J.format===pJ.GLB)&&$.listBuffers().length===0)throw new Error("Buffer required for Document resources, but none was found.");if(Y.buffers=[],$.listBuffers().forEach((B,w)=>{let O=W.createPropertyDef(B),M=W.accessorUsageGroupedByParent,N=B.listParents().filter((x)=>x instanceof f0),P=new Set(N.map((x)=>W.accessorParents.get(x))),D=new Map(Array.from(P).map((x,I)=>[x,I])),C={};for(let x of N){var T;if(W.accessorIndexMap.has(x))continue;let I=W.getAccessorUsage(x),S=I;if(M.has(I)){let g=W.accessorParents.get(x);S+=`:${D.get(g)}`}C[T=S]||(C[T]={usage:I,accessors:[]}),C[S].accessors.push(x)}let k=[],A=Y.buffers.length,v=0;for(let{usage:x,accessors:I}of Object.values(C))if(x===AF.ARRAY_BUFFER&&J.vertexLayout===hF.INTERLEAVED){let S=z(I,A,v);v+=S.byteLength;for(let g of S.buffers)k.push(g)}else if(x===AF.ARRAY_BUFFER)for(let S of I){let g=z([S],A,v);v+=g.byteLength;for(let m of g.buffers)k.push(m)}else if(x===AF.SPARSE){let S=F(I,A,v);v+=S.byteLength;for(let g of S.buffers)k.push(g)}else if(x===AF.ELEMENT_ARRAY_BUFFER){let S=JX.BufferViewTarget.ELEMENT_ARRAY_BUFFER,g=q(I,A,v,S);v+=g.byteLength;for(let m of g.buffers)k.push(m)}else{let S=q(I,A,v);v+=S.byteLength;for(let g of S.buffers)k.push(g)}if(W.imageBufferViews.length&&w===0){for(let x=0;x<W.imageBufferViews.length;x++)if(Y.bufferViews[Y.images[x].bufferView].byteOffset=v,v+=W.imageBufferViews[x].byteLength,k.push(W.imageBufferViews[x]),v%8){let I=8-v%8;v+=I,k.push(new Uint8Array(I))}}if(W.otherBufferViews.has(B))for(let x of W.otherBufferViews.get(B))Y.bufferViews.push({buffer:A,byteOffset:v,byteLength:x.byteLength}),W.otherBufferViewsIndexMap.set(x,Y.bufferViews.length-1),v+=x.byteLength,k.push(x);if(v){let x;if(J.format===pJ.GLB)x=fF;else x=W.bufferURIGenerator.createURI(B,"bin"),O.uri=x;O.byteLength=v,W.assignResourceURI(x,r0.concat(k),!0)}Y.buffers.push(O),W.bufferIndexMap.set(B,w)}),$.listAccessors().find((B)=>!B.getBuffer()))K.warn("Skipped writing one or more Accessors: no Buffer assigned.");V.filter((B)=>B.prewriteTypes.includes(n.MATERIAL)).forEach((B)=>B.prewrite(W,n.MATERIAL)),Y.materials=$.listMaterials().map((B,w)=>{let O=W.createPropertyDef(B);if(B.getAlphaMode()!==nZ.AlphaMode.OPAQUE)O.alphaMode=B.getAlphaMode();if(B.getAlphaMode()===nZ.AlphaMode.MASK)O.alphaCutoff=B.getAlphaCutoff();if(B.getDoubleSided())O.doubleSided=!0;if(O.pbrMetallicRoughness={},!i0.eq(B.getBaseColorFactor(),[1,1,1,1]))O.pbrMetallicRoughness.baseColorFactor=B.getBaseColorFactor();if(!i0.eq(B.getEmissiveFactor(),[0,0,0]))O.emissiveFactor=B.getEmissiveFactor();if(B.getRoughnessFactor()!==1)O.pbrMetallicRoughness.roughnessFactor=B.getRoughnessFactor();if(B.getMetallicFactor()!==1)O.pbrMetallicRoughness.metallicFactor=B.getMetallicFactor();if(B.getBaseColorTexture()){let M=B.getBaseColorTexture(),N=B.getBaseColorTextureInfo();O.pbrMetallicRoughness.baseColorTexture=W.createTextureInfoDef(M,N)}if(B.getEmissiveTexture()){let M=B.getEmissiveTexture(),N=B.getEmissiveTextureInfo();O.emissiveTexture=W.createTextureInfoDef(M,N)}if(B.getNormalTexture()){let M=B.getNormalTexture(),N=B.getNormalTextureInfo(),P=W.createTextureInfoDef(M,N);if(B.getNormalScale()!==1)P.scale=B.getNormalScale();O.normalTexture=P}if(B.getOcclusionTexture()){let M=B.getOcclusionTexture(),N=B.getOcclusionTextureInfo(),P=W.createTextureInfoDef(M,N);if(B.getOcclusionStrength()!==1)P.strength=B.getOcclusionStrength();O.occlusionTexture=P}if(B.getMetallicRoughnessTexture()){let M=B.getMetallicRoughnessTexture(),N=B.getMetallicRoughnessTextureInfo();O.pbrMetallicRoughness.metallicRoughnessTexture=W.createTextureInfoDef(M,N)}return W.materialIndexMap.set(B,w),O}),V.filter((B)=>B.prewriteTypes.includes(n.MESH)).forEach((B)=>B.prewrite(W,n.MESH)),Y.meshes=$.listMeshes().map((B,w)=>{let O=W.createPropertyDef(B),M=null;if(O.primitives=B.listPrimitives().map((N)=>{let P={attributes:{}};P.mode=N.getMode();let D=N.getMaterial();if(D)P.material=W.materialIndexMap.get(D);if(Object.keys(N.getExtras()).length)P.extras=N.getExtras();let C=N.getIndices();if(C)P.indices=W.accessorIndexMap.get(C);for(let T of N.listSemantics())P.attributes[T]=W.accessorIndexMap.get(N.getAttribute(T));for(let T of N.listTargets()){let k={};for(let A of T.listSemantics())k[A]=W.accessorIndexMap.get(T.getAttribute(A));P.targets=P.targets||[],P.targets.push(k)}if(N.listTargets().length&&!M)M=N.listTargets().map((T)=>T.getName());return P}),B.getWeights().length)O.weights=B.getWeights();if(M)O.extras=O.extras||{},O.extras.targetNames=M;return W.meshIndexMap.set(B,w),O}),Y.cameras=$.listCameras().map((B,w)=>{let O=W.createPropertyDef(B);if(O.type=B.getType(),O.type===t$.Type.PERSPECTIVE){O.perspective={znear:B.getZNear(),zfar:B.getZFar(),yfov:B.getYFov()};let M=B.getAspectRatio();if(M!==null)O.perspective.aspectRatio=M}else O.orthographic={znear:B.getZNear(),zfar:B.getZFar(),xmag:B.getXMag(),ymag:B.getYMag()};return W.cameraIndexMap.set(B,w),O}),Y.nodes=$.listNodes().map((B,w)=>{let O=W.createPropertyDef(B);if(!i0.eq(B.getTranslation(),[0,0,0]))O.translation=B.getTranslation();if(!i0.eq(B.getRotation(),[0,0,0,1]))O.rotation=B.getRotation();if(!i0.eq(B.getScale(),[1,1,1]))O.scale=B.getScale();if(B.getWeights().length)O.weights=B.getWeights();return W.nodeIndexMap.set(B,w),O}),Y.skins=$.listSkins().map((B,w)=>{let O=W.createPropertyDef(B),M=B.getInverseBindMatrices();if(M)O.inverseBindMatrices=W.accessorIndexMap.get(M);let N=B.getSkeleton();if(N)O.skeleton=W.nodeIndexMap.get(N);return O.joints=B.listJoints().map((P)=>W.nodeIndexMap.get(P)),W.skinIndexMap.set(B,w),O}),$.listNodes().forEach((B,w)=>{let O=Y.nodes[w],M=B.getMesh();if(M)O.mesh=W.meshIndexMap.get(M);let N=B.getCamera();if(N)O.camera=W.cameraIndexMap.get(N);let P=B.getSkin();if(P)O.skin=W.skinIndexMap.get(P);if(B.listChildren().length>0)O.children=B.listChildren().map((D)=>W.nodeIndexMap.get(D))}),Y.animations=$.listAnimations().map((B,w)=>{let O=W.createPropertyDef(B),M=new Map;return O.samplers=B.listSamplers().map((N,P)=>{let D=W.createPropertyDef(N);return D.input=W.accessorIndexMap.get(N.getInput()),D.output=W.accessorIndexMap.get(N.getOutput()),D.interpolation=N.getInterpolation(),M.set(N,P),D}),O.channels=B.listChannels().map((N)=>{let P=W.createPropertyDef(N);return P.sampler=M.get(N.getSampler()),P.target={node:W.nodeIndexMap.get(N.getTargetNode()),path:N.getTargetPath()},P}),W.animationIndexMap.set(B,w),O}),Y.scenes=$.listScenes().map((B,w)=>{let O=W.createPropertyDef(B);return O.nodes=B.listChildren().map((M)=>W.nodeIndexMap.get(M)),W.sceneIndexMap.set(B,w),O});let L=$.getDefaultScene();if(L)Y.scene=$.listScenes().indexOf(L);return Y.extensionsUsed=V.map((B)=>B.extensionName),Y.extensionsRequired=H.map((B)=>B.extensionName),V.forEach((B)=>B.write(W)),uV5(Y),Q}}function uV5(Z){let J=[];for(let X in Z){let $=Z[X];if(Array.isArray($)&&$.length===0)J.push(X);else if($===null||$==="")J.push(X);else if($&&typeof $==="object"&&Object.keys($).length===0)J.push(X)}for(let X of J)delete Z[X]}var gF;(function(Z){Z[Z.JSON=1313821514]="JSON",Z[Z.BIN=5130562]="BIN"})(gF||(gF={}));class au{constructor(){this._logger=W7.DEFAULT_INSTANCE,this._extensions=new Set,this._dependencies={},this._vertexLayout=hF.INTERLEAVED,this.lastReadBytes=0,this.lastWriteBytes=0}setLogger(Z){return this._logger=Z,this}registerExtensions(Z){for(let J of Z)this._extensions.add(J),J.register();return this}registerDependencies(Z){return Object.assign(this._dependencies,Z),this}setVertexLayout(Z){return this._vertexLayout=Z,this}async read(Z){return await this.readJSON(await this.readAsJSON(Z))}async readAsJSON(Z){let J=await this.readURI(Z,"view");this.lastReadBytes=J.byteLength;let X=yu(J)?this._binaryToJSON(J):{json:JSON.parse(r0.decodeText(J)),resources:{}};return await this._readResourcesExternal(X,this.dirname(Z)),this._readResourcesInternal(X),X}async readJSON(Z){return Z=this._copyJSON(Z),this._readResourcesInternal(Z),nu.read(Z,{extensions:Array.from(this._extensions),dependencies:this._dependencies,logger:this._logger})}async binaryToJSON(Z){let J=this._binaryToJSON(r0.assertView(Z));this._readResourcesInternal(J);let X=J.json;if(X.buffers&&X.buffers.some(($)=>cV5(J,$)))throw new Error("Cannot resolve external buffers with binaryToJSON().");else if(X.images&&X.images.some(($)=>lV5(J,$)))throw new Error("Cannot resolve external images with binaryToJSON().");return J}async readBinary(Z){return this.readJSON(await this.binaryToJSON(r0.assertView(Z)))}async writeJSON(Z,J={}){if(J.format===pJ.GLB&&Z.getRoot().listBuffers().length>1)throw new Error("GLB must have 0–1 buffers.");return su.write(Z,{format:J.format||pJ.GLTF,basename:J.basename||"",logger:this._logger,vertexLayout:this._vertexLayout,dependencies:A6({},this._dependencies),extensions:Array.from(this._extensions)})}async writeBinary(Z){let{json:J,resources:X}=await this.writeJSON(Z,{format:pJ.GLB}),$=new Uint32Array([1179937895,2,12]),Y=JSON.stringify(J),Q=r0.pad(r0.encodeText(Y),32),W=r0.toView(new Uint32Array([Q.byteLength,1313821514])),K=r0.concat([W,Q]);$[$.length-1]+=K.byteLength;let G=Object.values(X)[0];if(!G||!G.byteLength)return r0.concat([r0.toView($),K]);let V=r0.pad(G,0),H=r0.toView(new Uint32Array([V.byteLength,5130562])),q=r0.concat([H,V]);return $[$.length-1]+=q.byteLength,r0.concat([r0.toView($),K,q])}async _readResourcesExternal(Z,J){var X=this;let $=Z.json.images||[],Y=Z.json.buffers||[],Q=[...$,...Y].map(async function(W){let K=W.uri;if(!K||K.match(/data:/))return Promise.resolve();Z.resources[K]=await X.readURI(X.resolve(J,K),"view"),X.lastReadBytes+=Z.resources[K].byteLength});await Promise.all(Q)}_readResourcesInternal(Z){function J(Y){if(!Y.uri)return;if(Y.uri in Z.resources){r0.assertView(Z.resources[Y.uri]);return}if(Y.uri.match(/data:/)){let Q=`__${lu()}.${nJ.extension(Y.uri)}`;Z.resources[Q]=r0.createBufferFromDataURI(Y.uri),Y.uri=Q}}(Z.json.images||[]).forEach((Y)=>{if(Y.bufferView===void 0&&Y.uri===void 0)throw new Error("Missing resource URI or buffer view.");J(Y)}),(Z.json.buffers||[]).forEach(J)}_copyJSON(Z){let{images:J,buffers:X}=Z.json;if(Z={json:A6({},Z.json),resources:A6({},Z.resources)},J)Z.json.images=J.map(($)=>A6({},$));if(X)Z.json.buffers=X.map(($)=>A6({},$));return Z}_binaryToJSON(Z){if(!yu(Z))throw new Error("Invalid glTF 2.0 binary.");let J=new Uint32Array(Z.buffer,Z.byteOffset+12,2);if(J[1]!==gF.JSON)throw new Error("Missing required GLB JSON chunk.");let X=20,$=J[0],Y=r0.decodeText(r0.toView(Z,X,$)),Q=JSON.parse(Y),W=X+$;if(Z.byteLength<=W)return{json:Q,resources:{}};let K=new Uint32Array(Z.buffer,Z.byteOffset+W,2);if(K[1]!==gF.BIN)return{json:Q,resources:{}};let G=K[0],V=r0.toView(Z,W+8,G);return{json:Q,resources:{[fF]:V}}}}function cV5(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)}function lV5(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)&&J.bufferView===void 0}function yu(Z){if(Z.byteLength<3*Uint32Array.BYTES_PER_ELEMENT)return!1;let J=new Uint32Array(Z.buffer,Z.byteOffset,3);return J[0]===1179937895&&J[1]===2}class uR extends au{constructor(Z=null,J=H9.DEFAULT_INIT){super();this._fetch=void 0,this._fetchConfig=void 0,this._init=void 0,this._fetchEnabled=!1,this._fetch=Z,this._fetchConfig=J,this._init=this.init()}async init(){if(this._init)return this._init;return Promise.all([import("fs"),import("path")]).then(([Z,J])=>{this._fs=Z.promises,this._path=J})}setAllowNetwork(Z){if(Z&&!this._fetch)throw new Error("NodeIO requires a Fetch API implementation for HTTP requests.");return this._fetchEnabled=Z,this}async readURI(Z,J){if(await this.init(),H9.isAbsoluteURL(Z)){if(!this._fetchEnabled||!this._fetch)throw new Error("Network request blocked. Allow HTTP requests explicitly, if needed.");let X=await this._fetch(Z,this._fetchConfig);switch(J){case"view":return new Uint8Array(await X.arrayBuffer());case"text":return X.text()}}else switch(J){case"view":return this._fs.readFile(Z);case"text":return this._fs.readFile(Z,"utf8")}}resolve(Z,J){if(H9.isAbsoluteURL(Z)||H9.isAbsoluteURL(J))return H9.resolve(Z,J);return this._path.resolve(Z,decodeURIComponent(J))}dirname(Z){if(H9.isAbsoluteURL(Z))return H9.dirname(Z);return this._path.dirname(Z)}async write(Z,J){await this.init(),await(!!Z.match(/\.glb$/)?this._writeGLB(Z,J):this._writeGLTF(Z,J))}async _writeGLTF(Z,J){var X=this;this.lastWriteBytes=0;let{json:$,resources:Y}=await this.writeJSON(J,{format:pJ.GLTF,basename:nJ.basename(Z)}),{_fs:Q,_path:W}=this,K=W.dirname(Z),G=JSON.stringify($,null,2);await Q.writeFile(Z,G),this.lastWriteBytes+=G.length;for(let V of pV5(Object.keys(Y),10))await Promise.all(V.map(async function(H){if(H9.isAbsoluteURL(H)){if(H9.extension(H)==="bin")throw new Error(`Cannot write buffer to path "${H}".`);return}let q=W.join(K,decodeURIComponent(H));await Q.mkdir(W.dirname(q),{recursive:!0}),await Q.writeFile(q,Y[H]),X.lastWriteBytes+=Y[H].byteLength}))}async _writeGLB(Z,J){let X=await this.writeBinary(J);await this._fs.writeFile(Z,X),this.lastWriteBytes=X.byteLength}}function pV5(Z,J){let X=[];for(let $=0,Y=Z.length;$<Y;$+=J){let Q=[];for(let W=0;W<J&&$+W<Y;W++)Q.push(Z[$+W]);X.push(Q)}return X}var pp=e(cR(),1),ip=e(Ep(),1),hF5=e(lp(),1);async function bF5(Z,J){if(!(Z instanceof Uint8Array))throw new Error("[ndarray-pixels] Input must be Uint8Array or Buffer.");let{data:X,info:$}=await ip.default(Z).ensureAlpha().raw().toBuffer({resolveWithObject:!0});return pp.default(new Uint8Array(X),[$.width,$.height,4],[4,4*$.width|0,1],0)}async function np(Z,J){return bF5(Z)}var yF5="v4.1.3",MD="@glb.bin",s;(function(Z){Z.ACCESSOR="Accessor",Z.ANIMATION="Animation",Z.ANIMATION_CHANNEL="AnimationChannel",Z.ANIMATION_SAMPLER="AnimationSampler",Z.BUFFER="Buffer",Z.CAMERA="Camera",Z.MATERIAL="Material",Z.MESH="Mesh",Z.PRIMITIVE="Primitive",Z.PRIMITIVE_TARGET="PrimitiveTarget",Z.NODE="Node",Z.ROOT="Root",Z.SCENE="Scene",Z.SKIN="Skin",Z.TEXTURE="Texture",Z.TEXTURE_INFO="TextureInfo"})(s||(s={}));var sp;(function(Z){Z.INTERLEAVED="interleaved",Z.SEPARATE="separate"})(sp||(sp={}));var _7;(function(Z){Z.ARRAY_BUFFER="ARRAY_BUFFER",Z.ELEMENT_ARRAY_BUFFER="ELEMENT_ARRAY_BUFFER",Z.INVERSE_BIND_MATRICES="INVERSE_BIND_MATRICES",Z.OTHER="OTHER",Z.SPARSE="SPARSE"})(_7||(_7={}));var A7;(function(Z){Z[Z.R=4096]="R",Z[Z.G=256]="G",Z[Z.B=16]="B",Z[Z.A=1]="A"})(A7||(A7={}));var BD;(function(Z){Z.GLTF="GLTF",Z.GLB="GLB"})(BD||(BD={}));var LD=typeof Float32Array!=="undefined"?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var Z=0,J=arguments.length;while(J--)Z+=arguments[J]*arguments[J];return Math.sqrt(Z)};function gF5(){var Z=new LD(3);if(LD!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function UD(Z){var J=Z[0],X=Z[1],$=Z[2];return Math.hypot(J,X,$)}function mF5(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=X[3]*$+X[7]*Y+X[11]*Q+X[15];return W=W||1,Z[0]=(X[0]*$+X[4]*Y+X[8]*Q+X[12])/W,Z[1]=(X[1]*$+X[5]*Y+X[9]*Q+X[13])/W,Z[2]=(X[2]*$+X[6]*Y+X[10]*Q+X[14])/W,Z}(function(){var Z=gF5();return function(J,X,$,Y,Q,W){var K,G;if(!X)X=3;if(!$)$=0;if(Y)G=Math.min(Y*X+$,J.length);else G=J.length;for(K=$;K<G;K+=X)Z[0]=J[K],Z[1]=J[K+1],Z[2]=J[K+2],Q(Z,Z,W),J[K]=Z[0],J[K+1]=Z[1],J[K+2]=Z[2];return J}})();function tp(Z){let J=ep(),X=Z.propertyType===s.NODE?[Z]:Z.listChildren();for(let $ of X)$.traverse((Y)=>{let Q=Y.getMesh();if(!Q)return;let W=dF5(Q,Y.getWorldMatrix());if(W.min.every(isFinite)&&W.max.every(isFinite))wD(W.min,J),wD(W.max,J)});return J}function dF5(Z,J){let X=ep();for(let $ of Z.listPrimitives()){let Y=$.getAttribute("POSITION"),Q=$.getIndices();if(!Y)continue;let W=[0,0,0],K=[0,0,0];for(let G=0,V=Q?Q.getCount():Y.getCount();G<V;G++){let H=Q?Q.getScalar(G):G;W=Y.getElement(H,W),K=mF5(K,W,J),wD(K,X)}}return X}function wD(Z,J){for(let X=0;X<3;X++)J.min[X]=Math.min(Z[X],J.min[X]),J.max[X]=Math.max(Z[X],J.max[X])}function ep(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}class B6{static createBufferFromDataURI(Z){if(typeof Buffer==="undefined"){let J=atob(Z.split(",")[1]),X=new Uint8Array(J.length);for(let $=0;$<J.length;$++)X[$]=J.charCodeAt($);return X}else{let J=Z.split(",")[1],X=Z.indexOf("base64")>=0;return Buffer.from(J,X?"base64":"utf8")}}static encodeText(Z){return new TextEncoder().encode(Z)}static decodeText(Z){return new TextDecoder().decode(Z)}static concat(Z){let J=0;for(let Y of Z)J+=Y.byteLength;let X=new Uint8Array(J),$=0;for(let Y of Z)X.set(Y,$),$+=Y.byteLength;return X}static pad(Z,J=0){let X=this.padNumber(Z.byteLength);if(X===Z.byteLength)return Z;let $=new Uint8Array(X);if($.set(Z),J!==0)for(let Y=Z.byteLength;Y<X;Y++)$[Y]=J;return $}static padNumber(Z){return Math.ceil(Z/4)*4}static equals(Z,J){if(Z===J)return!0;if(Z.byteLength!==J.byteLength)return!1;let X=Z.byteLength;while(X--)if(Z[X]!==J[X])return!1;return!0}static toView(Z,J=0,X=1/0){return new Uint8Array(Z.buffer,Z.byteOffset+J,Math.min(Z.byteLength,X))}static assertView(Z){if(Z&&!ArrayBuffer.isView(Z))throw new Error(`Method requires Uint8Array parameter; received "${typeof Z}".`);return Z}}class Zi{match(Z){return Z.length>=3&&Z[0]===255&&Z[1]===216&&Z[2]===255}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset+4),X,$;while(J.byteLength){if(X=J.getUint16(0,!1),uF5(J,X),$=J.getUint8(X+1),$===192||$===193||$===194)return[J.getUint16(X+7,!1),J.getUint16(X+5,!1)];J=new DataView(Z.buffer,J.byteOffset+X+2)}throw new TypeError("Invalid JPG, no size found")}getChannels(Z){return 3}}class wU{match(Z){return Z.length>=8&&Z[0]===137&&Z[1]===80&&Z[2]===78&&Z[3]===71&&Z[4]===13&&Z[5]===10&&Z[6]===26&&Z[7]===10}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset);if(B6.decodeText(Z.slice(12,16))===wU.PNG_FRIED_CHUNK_NAME)return[J.getUint32(32,!1),J.getUint32(36,!1)];return[J.getUint32(16,!1),J.getUint32(20,!1)]}getChannels(Z){return 4}}wU.PNG_FRIED_CHUNK_NAME="CgBI";class GZ{static registerFormat(Z,J){this.impls[Z]=J}static getMimeType(Z){for(let J in this.impls)if(this.impls[J].match(Z))return J;return null}static getSize(Z,J){if(!this.impls[J])return null;return this.impls[J].getSize(Z)}static getChannels(Z,J){if(!this.impls[J])return null;return this.impls[J].getChannels(Z)}static getVRAMByteLength(Z,J){if(!this.impls[J])return null;if(this.impls[J].getVRAMByteLength)return this.impls[J].getVRAMByteLength(Z);let X=0,$=4,Y=this.getSize(Z,J);if(!Y)return null;while(Y[0]>1||Y[1]>1)X+=Y[0]*Y[1]*$,Y[0]=Math.max(Math.floor(Y[0]/2),1),Y[1]=Math.max(Math.floor(Y[1]/2),1);return X+=1*$,X}static mimeTypeToExtension(Z){if(Z==="image/jpeg")return"jpg";return Z.split("/").pop()}static extensionToMimeType(Z){if(Z==="jpg")return"image/jpeg";if(!Z)return"";return`image/${Z}`}}GZ.impls={"image/jpeg":new Zi,"image/png":new wU};function uF5(Z,J){if(J>Z.byteLength)throw new TypeError("Corrupt JPG, exceeded buffer limits");if(Z.getUint8(J)!==255)throw new TypeError("Invalid JPG, marker table corrupted");return Z}class gG{static basename(Z){let J=Z.split(/[\\/]/).pop();return J.substring(0,J.lastIndexOf("."))}static extension(Z){if(Z.startsWith("data:image/")){let J=Z.match(/data:(image\/\w+)/)[1];return GZ.mimeTypeToExtension(J)}else if(Z.startsWith("data:model/gltf+json"))return"gltf";else if(Z.startsWith("data:model/gltf-binary"))return"glb";else if(Z.startsWith("data:application/"))return"bin";return Z.split(/[\\/]/).pop().split(/[.]/).pop()}}function ap(Z){return Object.prototype.toString.call(Z)==="[object Object]"}function YY(Z){if(ap(Z)===!1)return!1;let J=Z.constructor;if(J===void 0)return!0;let X=J.prototype;if(ap(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}var OD,ND;(function(Z){Z[Z.SILENT=4]="SILENT",Z[Z.ERROR=3]="ERROR",Z[Z.WARN=2]="WARN",Z[Z.INFO=1]="INFO",Z[Z.DEBUG=0]="DEBUG"})(ND||(ND={}));class eZ{constructor(Z){this.verbosity=void 0,this.verbosity=Z}debug(Z){if(this.verbosity<=eZ.Verbosity.DEBUG)console.debug(Z)}info(Z){if(this.verbosity<=eZ.Verbosity.INFO)console.info(Z)}warn(Z){if(this.verbosity<=eZ.Verbosity.WARN)console.warn(Z)}error(Z){if(this.verbosity<=eZ.Verbosity.ERROR)console.error(Z)}}OD=eZ;eZ.Verbosity=ND;eZ.DEFAULT_INSTANCE=new OD(OD.Verbosity.INFO);function cF5(Z){var J=Z[0],X=Z[1],$=Z[2],Y=Z[3],Q=Z[4],W=Z[5],K=Z[6],G=Z[7],V=Z[8],H=Z[9],q=Z[10],z=Z[11],F=Z[12],U=Z[13],L=Z[14],B=Z[15],w=J*W-X*Q,O=J*K-$*Q,M=J*G-Y*Q,N=X*K-$*W,P=X*G-Y*W,D=$*G-Y*K,C=V*U-H*F,T=V*L-q*F,k=V*B-z*F,A=H*L-q*U,v=H*B-z*U,x=q*B-z*L;return w*x-O*v+M*A+N*k-P*T+D*C}function lF5(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=J[3],K=J[4],G=J[5],V=J[6],H=J[7],q=J[8],z=J[9],F=J[10],U=J[11],L=J[12],B=J[13],w=J[14],O=J[15],M=X[0],N=X[1],P=X[2],D=X[3];return Z[0]=M*$+N*K+P*q+D*L,Z[1]=M*Y+N*G+P*z+D*B,Z[2]=M*Q+N*V+P*F+D*w,Z[3]=M*W+N*H+P*U+D*O,M=X[4],N=X[5],P=X[6],D=X[7],Z[4]=M*$+N*K+P*q+D*L,Z[5]=M*Y+N*G+P*z+D*B,Z[6]=M*Q+N*V+P*F+D*w,Z[7]=M*W+N*H+P*U+D*O,M=X[8],N=X[9],P=X[10],D=X[11],Z[8]=M*$+N*K+P*q+D*L,Z[9]=M*Y+N*G+P*z+D*B,Z[10]=M*Q+N*V+P*F+D*w,Z[11]=M*W+N*H+P*U+D*O,M=X[12],N=X[13],P=X[14],D=X[15],Z[12]=M*$+N*K+P*q+D*L,Z[13]=M*Y+N*G+P*z+D*B,Z[14]=M*Q+N*V+P*F+D*w,Z[15]=M*W+N*H+P*U+D*O,Z}function pF5(Z,J){var X=J[0],$=J[1],Y=J[2],Q=J[4],W=J[5],K=J[6],G=J[8],V=J[9],H=J[10];return Z[0]=Math.hypot(X,$,Y),Z[1]=Math.hypot(Q,W,K),Z[2]=Math.hypot(G,V,H),Z}function iF5(Z,J){var X=new LD(3);pF5(X,J);var $=1/X[0],Y=1/X[1],Q=1/X[2],W=J[0]*$,K=J[1]*Y,G=J[2]*Q,V=J[4]*$,H=J[5]*Y,q=J[6]*Q,z=J[8]*$,F=J[9]*Y,U=J[10]*Q,L=W+H+U,B=0;if(L>0)B=Math.sqrt(L+1)*2,Z[3]=0.25*B,Z[0]=(q-F)/B,Z[1]=(z-G)/B,Z[2]=(K-V)/B;else if(W>H&&W>U)B=Math.sqrt(1+W-H-U)*2,Z[3]=(q-F)/B,Z[0]=0.25*B,Z[1]=(K+V)/B,Z[2]=(z+G)/B;else if(H>U)B=Math.sqrt(1+H-W-U)*2,Z[3]=(z-G)/B,Z[0]=(K+V)/B,Z[1]=0.25*B,Z[2]=(q+F)/B;else B=Math.sqrt(1+U-W-H)*2,Z[3]=(K-V)/B,Z[0]=(z+G)/B,Z[1]=(q+F)/B,Z[2]=0.25*B;return Z}class $8{static identity(Z){return Z}static eq(Z,J,X=0.00001){if(Z.length!==J.length)return!1;for(let $=0;$<Z.length;$++)if(Math.abs(Z[$]-J[$])>X)return!1;return!0}static clamp(Z,J,X){if(Z<J)return J;if(Z>X)return X;return Z}static decodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Z/65535;case 5121:return Z/255;case 5122:return Math.max(Z/32767,-1);case 5120:return Math.max(Z/127,-1);default:throw new Error("Invalid component type.")}}static encodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Math.round($8.clamp(Z,0,1)*65535);case 5121:return Math.round($8.clamp(Z,0,1)*255);case 5122:return Math.round($8.clamp(Z,-1,1)*32767);case 5120:return Math.round($8.clamp(Z,-1,1)*127);default:throw new Error("Invalid component type.")}}static decompose(Z,J,X,$){let Y=UD([Z[0],Z[1],Z[2]]),Q=UD([Z[4],Z[5],Z[6]]),W=UD([Z[8],Z[9],Z[10]]);if(cF5(Z)<0)Y=-Y;J[0]=Z[12],J[1]=Z[13],J[2]=Z[14];let G=Z.slice(),V=1/Y,H=1/Q,q=1/W;G[0]*=V,G[1]*=V,G[2]*=V,G[4]*=H,G[5]*=H,G[6]*=H,G[8]*=q,G[9]*=q,G[10]*=q,iF5(X,G),$[0]=Y,$[1]=Q,$[2]=W}static compose(Z,J,X,$){let Y=$,Q=J[0],W=J[1],K=J[2],G=J[3],V=Q+Q,H=W+W,q=K+K,z=Q*V,F=Q*H,U=Q*q,L=W*H,B=W*q,w=K*q,O=G*V,M=G*H,N=G*q,P=X[0],D=X[1],C=X[2];return Y[0]=(1-(L+w))*P,Y[1]=(F+N)*P,Y[2]=(U-M)*P,Y[3]=0,Y[4]=(F-N)*D,Y[5]=(1-(z+w))*D,Y[6]=(B+O)*D,Y[7]=0,Y[8]=(U+M)*C,Y[9]=(B-O)*C,Y[10]=(1-(z+L))*C,Y[11]=0,Y[12]=Z[0],Y[13]=Z[1],Y[14]=Z[2],Y[15]=1,Y}}function nF5(Z,J){if(!!Z!==!!J)return!1;let X=Z.getChild(),$=J.getChild();return X===$||X.equals($)}function sF5(Z,J){if(!!Z!==!!J)return!1;let X=Z.values(),$=J.values();if(X.length!==$.length)return!1;for(let Y=0;Y<X.length;Y++){let Q=X[Y],W=$[Y];if(Q.getChild()===W.getChild())continue;if(!Q.getChild().equals(W.getChild()))return!1}return!0}function aF5(Z,J){if(!!Z!==!!J)return!1;let X=Z.keys(),$=J.keys();if(X.length!==$.length)return!1;for(let Y of X){let Q=Z.get(Y),W=J.get(Y);if(!!Q!==!!W)return!1;let K=Q.getChild(),G=W.getChild();if(K===G)continue;if(!K.equals(G))return!1}return!0}function Ji(Z,J){if(Z===J)return!0;if(!!Z!==!!J||!Z||!J)return!1;if(Z.length!==J.length)return!1;for(let X=0;X<Z.length;X++)if(Z[X]!==J[X])return!1;return!0}function Xi(Z,J){if(Z===J)return!0;if(!!Z!==!!J)return!1;if(!YY(Z)||!YY(J))return Z===J;let X=Z,$=J,Y=0,Q=0,W;for(W in X)Y++;for(W in $)Q++;if(Y!==Q)return!1;for(W in X){let K=X[W],G=$[W];if(UU(K)&&UU(G)){if(!Ji(K,G))return!1}else if(YY(K)&&YY(G)){if(!Xi(K,G))return!1}else if(K!==G)return!1}return!0}function UU(Z){return Array.isArray(Z)||ArrayBuffer.isView(Z)}var rp="https://null.example";class RD{static dirname(Z){let J=Z.lastIndexOf("/");if(J===-1)return"./";return Z.substring(0,J+1)}static basename(Z){return gG.basename(new URL(Z,rp).pathname)}static extension(Z){return gG.extension(new URL(Z,rp).pathname)}static resolve(Z,J){if(!this.isRelativePath(J))return J;let X=Z.split("/"),$=J.split("/");X.pop();for(let Y=0;Y<$.length;Y++){if($[Y]===".")continue;if($[Y]==="..")X.pop();else X.push($[Y])}return X.join("/")}static isAbsoluteURL(Z){return this.PROTOCOL_REGEXP.test(Z)}static isRelativePath(Z){return!/^(?:[a-zA-Z]+:)?\//.test(Z)}}RD.DEFAULT_INIT={};RD.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;var VX=(Z)=>Z,rF5=new Set;class OU extends CW{constructor(Z,J=""){super(Z);this[y0].name=J,this.init(),this.dispatchEvent({type:"create"})}getGraph(){return this.graph}getDefaults(){return Object.assign(super.getDefaults(),{name:"",extras:{}})}set(Z,J){if(Array.isArray(J))J=J.slice();return super.set(Z,J)}getName(){return this.get("name")}setName(Z){return this.set("name",Z)}getExtras(){return this.get("extras")}setExtras(Z){return this.set("extras",Z)}clone(){return new this.constructor(this.graph).copy(this,VX)}copy(Z,J=VX){for(let X in this[y0]){let $=this[y0][X];if($ instanceof Y7){if(!this[WZ].has(X))$.dispose()}else if($ instanceof z6||$ instanceof I0)for(let Y of $.values())Y.dispose();else if($ instanceof a5)for(let Y of $.values())Y.dispose()}for(let X in Z[y0]){let $=this[y0][X],Y=Z[y0][X];if(Y instanceof Y7)if(this[WZ].has(X))$.getChild().copy(J(Y.getChild()),J);else this.setRef(X,J(Y.getChild()),Y.getAttributes());else if(Y instanceof I0||Y instanceof z6)for(let Q of Y.values())this.addRef(X,J(Q.getChild()),Q.getAttributes());else if(Y instanceof a5)for(let Q of Y.keys()){let W=Y.get(Q);this.setRefMap(X,Q,J(W.getChild()),W.getAttributes())}else if(YY(Y))this[y0][X]=JSON.parse(JSON.stringify(Y));else if(Array.isArray(Y)||Y instanceof ArrayBuffer||ArrayBuffer.isView(Y))this[y0][X]=Y.slice();else this[y0][X]=Y}return this}equals(Z,J=rF5){if(this===Z)return!0;if(this.propertyType!==Z.propertyType)return!1;for(let X in this[y0]){if(J.has(X))continue;let $=this[y0][X],Y=Z[y0][X];if($ instanceof Y7||Y instanceof Y7){if(!nF5($,Y))return!1}else if($ instanceof I0||Y instanceof I0||$ instanceof z6||Y instanceof z6){if(!sF5($,Y))return!1}else if($ instanceof a5||Y instanceof a5){if(!aF5($,Y))return!1}else if(YY($)||YY(Y)){if(!Xi($,Y))return!1}else if(UU($)||UU(Y)){if(!Ji($,Y))return!1}else if($!==Y)return!1}return!0}detach(){return this.graph.disconnectParents(this,(Z)=>Z.propertyType!=="Root"),this}listParents(){return this.graph.listParents(this)}}class L6 extends OU{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new a5})}getExtension(Z){return this.getRefMap("extensions",Z)}setExtension(Z,J){if(J)J._validateParent(this);return this.setRefMap("extensions",Z,J)}listExtensions(){return this.listRefMapValues("extensions")}}class k0 extends L6{init(){this.propertyType=s.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:k0.Type.SCALAR,componentType:k0.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(Z){switch(Z){case k0.Type.SCALAR:return 1;case k0.Type.VEC2:return 2;case k0.Type.VEC3:return 3;case k0.Type.VEC4:return 4;case k0.Type.MAT2:return 4;case k0.Type.MAT3:return 9;case k0.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+Z)}}static getComponentSize(Z){switch(Z){case k0.ComponentType.BYTE:return 1;case k0.ComponentType.UNSIGNED_BYTE:return 1;case k0.ComponentType.SHORT:return 2;case k0.ComponentType.UNSIGNED_SHORT:return 2;case k0.ComponentType.UNSIGNED_INT:return 4;case k0.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+Z)}}getMinNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),$=this.getComponentType();if(this.getMin(Z),J)for(let Y=0;Y<X;Y++)Z[Y]=$8.decodeNormalizedInt(Z[Y],$);return Z}getMin(Z){let J=this.getArray(),X=this.getCount(),$=this.getElementSize();for(let Y=0;Y<$;Y++)Z[Y]=1/0;for(let Y=0;Y<X*$;Y+=$)for(let Q=0;Q<$;Q++){let W=J[Y+Q];if(Number.isFinite(W))Z[Q]=Math.min(Z[Q],W)}return Z}getMaxNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),$=this.getComponentType();if(this.getMax(Z),J)for(let Y=0;Y<X;Y++)Z[Y]=$8.decodeNormalizedInt(Z[Y],$);return Z}getMax(Z){let J=this.get("array"),X=this.getCount(),$=this.getElementSize();for(let Y=0;Y<$;Y++)Z[Y]=-1/0;for(let Y=0;Y<X*$;Y+=$)for(let Q=0;Q<$;Q++){let W=J[Y+Q];if(Number.isFinite(W))Z[Q]=Math.max(Z[Q],W)}return Z}getCount(){let Z=this.get("array");return Z?Z.length/this.getElementSize():0}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getElementSize(){return k0.getElementSize(this.get("type"))}getComponentSize(){return this.get("array").BYTES_PER_ELEMENT}getComponentType(){return this.get("componentType")}getNormalized(){return this.get("normalized")}setNormalized(Z){return this.set("normalized",Z)}getScalar(Z){let J=this.getElementSize(),X=this.getComponentType(),$=this.getArray();if(this.getNormalized())return $8.decodeNormalizedInt($[Z*J],X);return $[Z*J]}setScalar(Z,J){let X=this.getElementSize(),$=this.getComponentType(),Y=this.getArray();if(this.getNormalized())Y[Z*X]=$8.encodeNormalizedInt(J,$);else Y[Z*X]=J;return this}getElement(Z,J){let X=this.getNormalized(),$=this.getElementSize(),Y=this.getComponentType(),Q=this.getArray();for(let W=0;W<$;W++)if(X)J[W]=$8.decodeNormalizedInt(Q[Z*$+W],Y);else J[W]=Q[Z*$+W];return J}setElement(Z,J){let X=this.getNormalized(),$=this.getElementSize(),Y=this.getComponentType(),Q=this.getArray();for(let W=0;W<$;W++)if(X)Q[Z*$+W]=$8.encodeNormalizedInt(J[W],Y);else Q[Z*$+W]=J[W];return this}getSparse(){return this.get("sparse")}setSparse(Z){return this.set("sparse",Z)}getBuffer(){return this.getRef("buffer")}setBuffer(Z){return this.setRef("buffer",Z)}getArray(){return this.get("array")}setArray(Z){return this.set("componentType",Z?oF5(Z):k0.ComponentType.FLOAT),this.set("array",Z),this}getByteLength(){let Z=this.get("array");return Z?Z.byteLength:0}}k0.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};k0.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};function oF5(Z){switch(Z.constructor){case Float32Array:return k0.ComponentType.FLOAT;case Uint32Array:return k0.ComponentType.UNSIGNED_INT;case Uint16Array:return k0.ComponentType.UNSIGNED_SHORT;case Uint8Array:return k0.ComponentType.UNSIGNED_BYTE;case Int16Array:return k0.ComponentType.SHORT;case Int8Array:return k0.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}class DD extends L6{init(){this.propertyType=s.ANIMATION}getDefaults(){return Object.assign(super.getDefaults(),{channels:new I0,samplers:new I0})}addChannel(Z){return this.addRef("channels",Z)}removeChannel(Z){return this.removeRef("channels",Z)}listChannels(){return this.listRefs("channels")}addSampler(Z){return this.addRef("samplers",Z)}removeSampler(Z){return this.removeRef("samplers",Z)}listSamplers(){return this.listRefs("samplers")}}class dG extends L6{init(){this.propertyType=s.ANIMATION_CHANNEL}getDefaults(){return Object.assign(super.getDefaults(),{targetPath:null,targetNode:null,sampler:null})}getTargetPath(){return this.get("targetPath")}setTargetPath(Z){return this.set("targetPath",Z)}getTargetNode(){return this.getRef("targetNode")}setTargetNode(Z){return this.setRef("targetNode",Z)}getSampler(){return this.getRef("sampler")}setSampler(Z){return this.setRef("sampler",Z)}}dG.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class yW extends L6{init(){this.propertyType=s.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:yW.Interpolation.LINEAR,input:null,output:null})}getInterpolation(){return this.get("interpolation")}setInterpolation(Z){return this.set("interpolation",Z)}getInput(){return this.getRef("input")}setInput(Z){return this.setRef("input",Z,{usage:_7.OTHER})}getOutput(){return this.getRef("output")}setOutput(Z){return this.setRef("output",Z,{usage:_7.OTHER})}}yW.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class PD extends L6{init(){this.propertyType=s.BUFFER}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(Z){return this.set("uri",Z)}}class uG extends L6{init(){this.propertyType=s.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:uG.Type.PERSPECTIVE,znear:0.1,zfar:100,aspectRatio:null,yfov:Math.PI*2*50/360,xmag:1,ymag:1})}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getZNear(){return this.get("znear")}setZNear(Z){return this.set("znear",Z)}getZFar(){return this.get("zfar")}setZFar(Z){return this.set("zfar",Z)}getAspectRatio(){return this.get("aspectRatio")}setAspectRatio(Z){return this.set("aspectRatio",Z)}getYFov(){return this.get("yfov")}setYFov(Z){return this.set("yfov",Z)}getXMag(){return this.get("xmag")}setXMag(Z){return this.set("xmag",Z)}getYMag(){return this.get("ymag")}setYMag(Z){return this.set("ymag",Z)}}uG.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class c5 extends OU{_validateParent(Z){if(!this.parentTypes.includes(Z.propertyType))throw new Error(`Parent "${Z.propertyType}" invalid for child "${this.propertyType}".`)}}c5.EXTENSION_NAME=void 0;class R5 extends L6{init(){this.propertyType=s.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:R5.WrapMode.REPEAT,wrapT:R5.WrapMode.REPEAT})}getTexCoord(){return this.get("texCoord")}setTexCoord(Z){return this.set("texCoord",Z)}getMagFilter(){return this.get("magFilter")}setMagFilter(Z){return this.set("magFilter",Z)}getMinFilter(){return this.get("minFilter")}setMinFilter(Z){return this.set("minFilter",Z)}getWrapS(){return this.get("wrapS")}setWrapS(Z){return this.set("wrapS",Z)}getWrapT(){return this.get("wrapT")}setWrapT(Z){return this.set("wrapT",Z)}}R5.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};R5.MagFilter={NEAREST:9728,LINEAR:9729};R5.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};var{R:qU,G:zU,B:FU,A:tF5}=A7;class cG extends L6{init(){this.propertyType=s.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:cG.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new R5(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new R5(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new R5(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new R5(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new R5(this.graph,"metallicRoughnessTextureInfo")})}getDoubleSided(){return this.get("doubleSided")}setDoubleSided(Z){return this.set("doubleSided",Z)}getAlpha(){return this.get("baseColorFactor")[3]}setAlpha(Z){let J=this.get("baseColorFactor").slice();return J[3]=Z,this.set("baseColorFactor",J)}getAlphaMode(){return this.get("alphaMode")}setAlphaMode(Z){return this.set("alphaMode",Z)}getAlphaCutoff(){return this.get("alphaCutoff")}setAlphaCutoff(Z){return this.set("alphaCutoff",Z)}getBaseColorFactor(){return this.get("baseColorFactor")}setBaseColorFactor(Z){return this.set("baseColorFactor",Z)}getBaseColorTexture(){return this.getRef("baseColorTexture")}getBaseColorTextureInfo(){return this.getRef("baseColorTexture")?this.getRef("baseColorTextureInfo"):null}setBaseColorTexture(Z){return this.setRef("baseColorTexture",Z,{channels:qU|zU|FU|tF5,isColor:!0})}getEmissiveFactor(){return this.get("emissiveFactor")}setEmissiveFactor(Z){return this.set("emissiveFactor",Z)}getEmissiveTexture(){return this.getRef("emissiveTexture")}getEmissiveTextureInfo(){return this.getRef("emissiveTexture")?this.getRef("emissiveTextureInfo"):null}setEmissiveTexture(Z){return this.setRef("emissiveTexture",Z,{channels:qU|zU|FU,isColor:!0})}getNormalScale(){return this.get("normalScale")}setNormalScale(Z){return this.set("normalScale",Z)}getNormalTexture(){return this.getRef("normalTexture")}getNormalTextureInfo(){return this.getRef("normalTexture")?this.getRef("normalTextureInfo"):null}setNormalTexture(Z){return this.setRef("normalTexture",Z,{channels:qU|zU|FU})}getOcclusionStrength(){return this.get("occlusionStrength")}setOcclusionStrength(Z){return this.set("occlusionStrength",Z)}getOcclusionTexture(){return this.getRef("occlusionTexture")}getOcclusionTextureInfo(){return this.getRef("occlusionTexture")?this.getRef("occlusionTextureInfo"):null}setOcclusionTexture(Z){return this.setRef("occlusionTexture",Z,{channels:qU})}getRoughnessFactor(){return this.get("roughnessFactor")}setRoughnessFactor(Z){return this.set("roughnessFactor",Z)}getMetallicFactor(){return this.get("metallicFactor")}setMetallicFactor(Z){return this.set("metallicFactor",Z)}getMetallicRoughnessTexture(){return this.getRef("metallicRoughnessTexture")}getMetallicRoughnessTextureInfo(){return this.getRef("metallicRoughnessTexture")?this.getRef("metallicRoughnessTextureInfo"):null}setMetallicRoughnessTexture(Z){return this.setRef("metallicRoughnessTexture",Z,{channels:zU|FU})}}cG.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class CD extends L6{init(){this.propertyType=s.MESH}getDefaults(){return Object.assign(super.getDefaults(),{weights:[],primitives:new I0})}addPrimitive(Z){return this.addRef("primitives",Z)}removePrimitive(Z){return this.removeRef("primitives",Z)}listPrimitives(){return this.listRefs("primitives")}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}}class TD extends L6{init(){this.propertyType=s.NODE}getDefaults(){return Object.assign(super.getDefaults(),{translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1],weights:[],camera:null,mesh:null,skin:null,children:new I0})}copy(Z,J=VX){if(J===VX)throw new Error("Node cannot be copied.");return super.copy(Z,J)}getTranslation(){return this.get("translation")}getRotation(){return this.get("rotation")}getScale(){return this.get("scale")}setTranslation(Z){return this.set("translation",Z)}setRotation(Z){return this.set("rotation",Z)}setScale(Z){return this.set("scale",Z)}getMatrix(){return $8.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(Z){let J=this.get("translation").slice(),X=this.get("rotation").slice(),$=this.get("scale").slice();return $8.decompose(Z,J,X,$),this.set("translation",J).set("rotation",X).set("scale",$)}getWorldTranslation(){let Z=[0,0,0];return $8.decompose(this.getWorldMatrix(),Z,[0,0,0,1],[1,1,1]),Z}getWorldRotation(){let Z=[0,0,0,1];return $8.decompose(this.getWorldMatrix(),[0,0,0],Z,[1,1,1]),Z}getWorldScale(){let Z=[1,1,1];return $8.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],Z),Z}getWorldMatrix(){let Z=[];for(let $=this;$!=null;$=$.getParentNode())Z.push($);let J,X=Z.pop().getMatrix();while(J=Z.pop())lF5(X,X,J.getMatrix());return X}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);for(let X of Z.listParents())if(X.propertyType===s.SCENE)X.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}getParentNode(){for(let Z of this.listParents())if(Z.propertyType===s.NODE)return Z;return null}getMesh(){return this.getRef("mesh")}setMesh(Z){return this.setRef("mesh",Z)}getCamera(){return this.getRef("camera")}setCamera(Z){return this.setRef("camera",Z)}getSkin(){return this.getRef("skin")}setSkin(Z){return this.setRef("skin",Z)}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}traverse(Z){Z(this);for(let J of this.listChildren())J.traverse(Z);return this}}class HX extends L6{init(){this.propertyType=s.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:HX.Mode.TRIANGLES,material:null,indices:null,attributes:new a5,targets:new I0})}getIndices(){return this.getRef("indices")}setIndices(Z){return this.setRef("indices",Z,{usage:_7.ELEMENT_ARRAY_BUFFER})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:_7.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}getMaterial(){return this.getRef("material")}setMaterial(Z){return this.setRef("material",Z)}getMode(){return this.get("mode")}setMode(Z){return this.set("mode",Z)}listTargets(){return this.listRefs("targets")}addTarget(Z){return this.addRef("targets",Z)}removeTarget(Z){return this.removeRef("targets",Z)}}HX.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class $i extends OU{init(){this.propertyType=s.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new a5})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:_7.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function BU(){return BU=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)({}).hasOwnProperty.call(X,$)&&(Z[$]=X[$])}return Z},BU.apply(null,arguments)}class kD extends L6{init(){this.propertyType=s.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:new I0})}copy(Z,J=VX){if(J===VX)throw new Error("Scene cannot be copied.");return super.copy(Z,J)}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}traverse(Z){for(let J of this.listChildren())J.traverse(Z);return this}}class ED extends L6{init(){this.propertyType=s.SKIN}getDefaults(){return Object.assign(super.getDefaults(),{skeleton:null,inverseBindMatrices:null,joints:new I0})}getSkeleton(){return this.getRef("skeleton")}setSkeleton(Z){return this.setRef("skeleton",Z)}getInverseBindMatrices(){return this.getRef("inverseBindMatrices")}setInverseBindMatrices(Z){return this.setRef("inverseBindMatrices",Z,{usage:_7.INVERSE_BIND_MATRICES})}addJoint(Z){return this.addRef("joints",Z)}removeJoint(Z){return this.removeRef("joints",Z)}listJoints(){return this.listRefs("joints")}}class ID extends L6{init(){this.propertyType=s.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||GZ.extensionToMimeType(gG.extension(this.get("uri")))}setMimeType(Z){return this.set("mimeType",Z)}getURI(){return this.get("uri")}setURI(Z){this.set("uri",Z);let J=GZ.extensionToMimeType(gG.extension(Z));if(J)this.set("mimeType",J);return this}getImage(){return this.get("image")}setImage(Z){return this.set("image",B6.assertView(Z))}getSize(){let Z=this.get("image");if(!Z)return null;return GZ.getSize(Z,this.getMimeType())}}class NU extends L6{init(){this.propertyType=s.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${yF5}`,version:"2.0"},defaultScene:null,accessors:new I0,animations:new I0,buffers:new I0,cameras:new I0,materials:new I0,meshes:new I0,nodes:new I0,scenes:new I0,skins:new I0,textures:new I0})}constructor(Z){super(Z);this._extensions=new Set,Z.addEventListener("node:create",(J)=>{this._addChildOfRoot(J.target)})}clone(){throw new Error("Root cannot be cloned.")}copy(Z,J=VX){if(J===VX)throw new Error("Root cannot be copied.");this.set("asset",BU({},Z.get("asset"))),this.setName(Z.getName()),this.setExtras(BU({},Z.getExtras())),this.setDefaultScene(Z.getDefaultScene()?J(Z.getDefaultScene()):null);for(let X of Z.listRefMapKeys("extensions")){let $=Z.getExtension(X);this.setExtension(X,J($))}return this}_addChildOfRoot(Z){if(Z instanceof kD)this.addRef("scenes",Z);else if(Z instanceof TD)this.addRef("nodes",Z);else if(Z instanceof uG)this.addRef("cameras",Z);else if(Z instanceof ED)this.addRef("skins",Z);else if(Z instanceof CD)this.addRef("meshes",Z);else if(Z instanceof cG)this.addRef("materials",Z);else if(Z instanceof ID)this.addRef("textures",Z);else if(Z instanceof DD)this.addRef("animations",Z);else if(Z instanceof k0)this.addRef("accessors",Z);else if(Z instanceof PD)this.addRef("buffers",Z);return this}getAsset(){return this.get("asset")}listExtensionsUsed(){return Array.from(this._extensions)}listExtensionsRequired(){return this.listExtensionsUsed().filter((Z)=>Z.isRequired())}_enableExtension(Z){return this._extensions.add(Z),this}_disableExtension(Z){return this._extensions.delete(Z),this}listScenes(){return this.listRefs("scenes")}setDefaultScene(Z){return this.setRef("defaultScene",Z)}getDefaultScene(){return this.getRef("defaultScene")}listNodes(){return this.listRefs("nodes")}listCameras(){return this.listRefs("cameras")}listSkins(){return this.listRefs("skins")}listMeshes(){return this.listRefs("meshes")}listMaterials(){return this.listRefs("materials")}listTextures(){return this.listRefs("textures")}listAnimations(){return this.listRefs("animations")}listAccessors(){return this.listRefs("accessors")}listBuffers(){return this.listRefs("buffers")}}class LU{static fromGraph(Z){return LU._GRAPH_DOCUMENTS.get(Z)||null}constructor(){this._graph=new PW,this._root=new NU(this._graph),this._logger=eZ.DEFAULT_INSTANCE,LU._GRAPH_DOCUMENTS.set(this._graph,this)}getRoot(){return this._root}getGraph(){return this._graph}getLogger(){return this._logger}setLogger(Z){return this._logger=Z,this}clone(){throw new Error("Use 'cloneDocument(source)' from '@gltf-transform/functions'.")}merge(Z){throw new Error("Use 'mergeDocuments(target, source)' from '@gltf-transform/functions'.")}async transform(...Z){let J=Z.map((X)=>X.name);for(let X of Z)await X(this,{stack:J});return this}createExtension(Z){let J=Z.EXTENSION_NAME;return this.getRoot().listExtensionsUsed().find(($)=>$.extensionName===J)||new Z(this)}createScene(Z=""){return new kD(this._graph,Z)}createNode(Z=""){return new TD(this._graph,Z)}createCamera(Z=""){return new uG(this._graph,Z)}createSkin(Z=""){return new ED(this._graph,Z)}createMesh(Z=""){return new CD(this._graph,Z)}createPrimitive(){return new HX(this._graph)}createPrimitiveTarget(Z=""){return new $i(this._graph,Z)}createMaterial(Z=""){return new cG(this._graph,Z)}createTexture(Z=""){return new ID(this._graph,Z)}createAnimation(Z=""){return new DD(this._graph,Z)}createAnimationChannel(Z=""){return new dG(this._graph,Z)}createAnimationSampler(Z=""){return new yW(this._graph,Z)}createAccessor(Z="",J=null){if(!J)J=this.getRoot().listBuffers()[0];return new k0(this._graph,Z).setBuffer(J)}createBuffer(Z=""){return new PD(this._graph,Z)}}LU._GRAPH_DOCUMENTS=new WeakMap;class P5{constructor(Z){this.extensionName="",this.prereadTypes=[],this.prewriteTypes=[],this.readDependencies=[],this.writeDependencies=[],this.document=void 0,this.required=!1,this.properties=new Set,this._listener=void 0,this.document=Z,Z.getRoot()._enableExtension(this),this._listener=(X)=>{let $=X,Y=$.target;if(Y instanceof c5&&Y.extensionName===this.extensionName){if($.type==="node:create")this._addExtensionProperty(Y);if($.type==="node:dispose")this._removeExtensionProperty(Y)}};let J=Z.getGraph();J.addEventListener("node:create",this._listener),J.addEventListener("node:dispose",this._listener)}dispose(){this.document.getRoot()._disableExtension(this);let Z=this.document.getGraph();Z.removeEventListener("node:create",this._listener),Z.removeEventListener("node:dispose",this._listener);for(let J of this.properties)J.dispose()}static register(){}isRequired(){return this.required}setRequired(Z){return this.required=Z,this}listProperties(){return Array.from(this.properties)}_addExtensionProperty(Z){return this.properties.add(Z),this}_removeExtensionProperty(Z){return this.properties.delete(Z),this}install(Z,J){return this}preread(Z,J){return this}prewrite(Z,J){return this}}P5.EXTENSION_NAME=void 0;var jV6={logger:eZ.DEFAULT_INSTANCE,extensions:[],dependencies:{}},MV6=new Set([s.BUFFER,s.TEXTURE,s.MATERIAL,s.MESH,s.PRIMITIVE,s.NODE,s.SCENE]);var mG;(function(Z){Z[Z.ARRAY_BUFFER=34962]="ARRAY_BUFFER",Z[Z.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"})(mG||(mG={}));class qX{constructor(Z,J,X){this._doc=void 0,this.jsonDoc=void 0,this.options=void 0,this.accessorIndexMap=new Map,this.animationIndexMap=new Map,this.bufferIndexMap=new Map,this.cameraIndexMap=new Map,this.skinIndexMap=new Map,this.materialIndexMap=new Map,this.meshIndexMap=new Map,this.nodeIndexMap=new Map,this.imageIndexMap=new Map,this.textureDefIndexMap=new Map,this.textureInfoDefMap=new Map,this.samplerDefIndexMap=new Map,this.sceneIndexMap=new Map,this.imageBufferViews=[],this.otherBufferViews=new Map,this.otherBufferViewsIndexMap=new Map,this.extensionData={},this.bufferURIGenerator=void 0,this.imageURIGenerator=void 0,this.logger=void 0,this._accessorUsageMap=new Map,this.accessorUsageGroupedByParent=new Set(["ARRAY_BUFFER"]),this.accessorParents=new Map,this._doc=Z,this.jsonDoc=J,this.options=X;let $=Z.getRoot(),Y=$.listBuffers().length,Q=$.listTextures().length;this.bufferURIGenerator=new jD(Y>1,()=>X.basename||"buffer"),this.imageURIGenerator=new jD(Q>1,(W)=>eF5(Z,W)||X.basename||"texture"),this.logger=Z.getLogger()}createTextureInfoDef(Z,J){let X={magFilter:J.getMagFilter()||void 0,minFilter:J.getMinFilter()||void 0,wrapS:J.getWrapS(),wrapT:J.getWrapT()},$=JSON.stringify(X);if(!this.samplerDefIndexMap.has($))this.samplerDefIndexMap.set($,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(X);let Y={source:this.imageIndexMap.get(Z),sampler:this.samplerDefIndexMap.get($)},Q=JSON.stringify(Y);if(!this.textureDefIndexMap.has(Q))this.textureDefIndexMap.set(Q,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push(Y);let W={index:this.textureDefIndexMap.get(Q)};if(J.getTexCoord()!==0)W.texCoord=J.getTexCoord();if(Object.keys(J.getExtras()).length>0)W.extras=J.getExtras();return this.textureInfoDefMap.set(J,W),W}createPropertyDef(Z){let J={};if(Z.getName())J.name=Z.getName();if(Object.keys(Z.getExtras()).length>0)J.extras=Z.getExtras();return J}createAccessorDef(Z){let J=this.createPropertyDef(Z);if(J.type=Z.getType(),J.componentType=Z.getComponentType(),J.count=Z.getCount(),this._doc.getGraph().listParentEdges(Z).some(($)=>$.getName()==="attributes"&&$.getAttributes().key==="POSITION"||$.getName()==="input"))J.max=Z.getMax([]).map(Math.fround),J.min=Z.getMin([]).map(Math.fround);if(Z.getNormalized())J.normalized=Z.getNormalized();return J}createImageData(Z,J,X){if(this.options.format===BD.GLB)this.imageBufferViews.push(J),Z.bufferView=this.jsonDoc.json.bufferViews.length,this.jsonDoc.json.bufferViews.push({buffer:0,byteOffset:-1,byteLength:J.byteLength});else{let $=GZ.mimeTypeToExtension(X.getMimeType());Z.uri=this.imageURIGenerator.createURI(X,$),this.assignResourceURI(Z.uri,J,!1)}}assignResourceURI(Z,J,X){let $=this.jsonDoc.resources;if(!(Z in $)){$[Z]=J;return}if(J===$[Z]){this.logger.warn(`Duplicate resource URI, "${Z}".`);return}let Y=`Resource URI "${Z}" already assigned to different data.`;if(!X){this.logger.warn(Y);return}throw new Error(Y)}getAccessorUsage(Z){let J=this._accessorUsageMap.get(Z);if(J)return J;if(Z.getSparse())return _7.SPARSE;for(let X of this._doc.getGraph().listParentEdges(Z)){let{usage:$}=X.getAttributes();if($)return $;if(X.getParent().propertyType!==s.ROOT)this.logger.warn(`Missing attribute ".usage" on edge, "${X.getName()}".`)}return _7.OTHER}addAccessorToUsageGroup(Z,J){let X=this._accessorUsageMap.get(Z);if(X&&X!==J)throw new Error(`Accessor with usage "${X}" cannot be reused as "${J}".`);return this._accessorUsageMap.set(Z,J),this}}qX.BufferViewTarget=mG;qX.BufferViewUsage=_7;qX.USAGE_TO_TARGET={[_7.ARRAY_BUFFER]:mG.ARRAY_BUFFER,[_7.ELEMENT_ARRAY_BUFFER]:mG.ELEMENT_ARRAY_BUFFER};class jD{constructor(Z,J){this.multiple=void 0,this.basename=void 0,this.counter={},this.multiple=Z,this.basename=J}createURI(Z,J){if(Z.getURI())return Z.getURI();else if(!this.multiple)return`${this.basename(Z)}.${J}`;else{let X=this.basename(Z);return this.counter[X]=this.counter[X]||1,`${X}_${this.counter[X]++}.${J}`}}}function eF5(Z,J){let X=Z.getGraph().listParentEdges(J).find(($)=>$.getParent()!==Z.getRoot());return X?X.getName().replace(/texture$/i,""):""}var{UNSIGNED_INT:RV6,UNSIGNED_SHORT:DV6,UNSIGNED_BYTE:PV6}=k0.ComponentType,CV6=new Set([s.ACCESSOR,s.BUFFER,s.MATERIAL,s.MESH]);var op;(function(Z){Z[Z.JSON=1313821514]="JSON",Z[Z.BIN=5130562]="BIN"})(op||(op={}));var Qi=163,Wi=166;function ZU5(){return{vkFormat:0,typeSize:1,pixelWidth:0,pixelHeight:0,pixelDepth:0,layerCount:0,faceCount:1,supercompressionScheme:0,levels:[],dataFormatDescriptor:[{vendorId:0,descriptorType:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],keyValue:{},globalData:null}}class gW{constructor(Z,J,X,$){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(Z.buffer,Z.byteOffset+J,X),this._littleEndian=$,this._offset=0}_nextUint8(){let Z=this._dataView.getUint8(this._offset);return this._offset+=1,Z}_nextUint16(){let Z=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,Z}_nextUint32(){let Z=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,Z}_nextUint64(){let Z=this._dataView.getUint32(this._offset,this._littleEndian),J=this._dataView.getUint32(this._offset+4,this._littleEndian),X=Z+4294967296*J;return this._offset+=8,X}_nextInt32(){let Z=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,Z}_nextUint8Array(Z){let J=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,Z);return this._offset+=Z,J}_skip(Z){return this._offset+=Z,this}_scan(Z,J=0){let X=this._offset,$=0;while(this._dataView.getUint8(this._offset)!==J&&$<Z)$++,this._offset++;if($<Z)this._offset++;return new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+X,$)}}var EV6=new Uint8Array([0]),b6=[171,75,84,88,32,50,48,187,13,10,26,10];function Yi(Z){return new TextDecoder().decode(Z)}function jU(Z){let J=new Uint8Array(Z.buffer,Z.byteOffset,b6.length);if(J[0]!==b6[0]||J[1]!==b6[1]||J[2]!==b6[2]||J[3]!==b6[3]||J[4]!==b6[4]||J[5]!==b6[5]||J[6]!==b6[6]||J[7]!==b6[7]||J[8]!==b6[8]||J[9]!==b6[9]||J[10]!==b6[10]||J[11]!==b6[11])throw new Error("Missing KTX 2.0 identifier.");let X=ZU5(),$=17*Uint32Array.BYTES_PER_ELEMENT,Y=new gW(Z,b6.length,$,!0);X.vkFormat=Y._nextUint32(),X.typeSize=Y._nextUint32(),X.pixelWidth=Y._nextUint32(),X.pixelHeight=Y._nextUint32(),X.pixelDepth=Y._nextUint32(),X.layerCount=Y._nextUint32(),X.faceCount=Y._nextUint32();let Q=Y._nextUint32();X.supercompressionScheme=Y._nextUint32();let W=Y._nextUint32(),K=Y._nextUint32(),G=Y._nextUint32(),V=Y._nextUint32(),H=Y._nextUint64(),q=Y._nextUint64(),z=Q*3*8,F=new gW(Z,b6.length+$,z,!0);for(let t8=0;t8<Q;t8++)X.levels.push({levelData:new Uint8Array(Z.buffer,Z.byteOffset+F._nextUint64(),F._nextUint64()),uncompressedByteLength:F._nextUint64()});let U=new gW(Z,W,K,!0);U._skip(4);let L=U._nextUint16(),B=U._nextUint16(),w=U._nextUint16(),O=U._nextUint16(),M=U._nextUint8(),N=U._nextUint8(),P=U._nextUint8(),D=U._nextUint8(),C=[U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8()],T=[U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8()],A={vendorId:L,descriptorType:B,versionNumber:w,colorModel:M,colorPrimaries:N,transferFunction:P,flags:D,texelBlockDimension:C,bytesPlane:T,samples:[]},v=6,x=4,I=(O/4-v)/x;for(let t8=0;t8<I;t8++){let _J={bitOffset:U._nextUint16(),bitLength:U._nextUint8(),channelType:U._nextUint8(),samplePosition:[U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8()],sampleLower:Number.NEGATIVE_INFINITY,sampleUpper:Number.POSITIVE_INFINITY};if(_J.channelType&64)_J.sampleLower=U._nextInt32(),_J.sampleUpper=U._nextInt32();else _J.sampleLower=U._nextUint32(),_J.sampleUpper=U._nextUint32();A.samples[t8]=_J}X.dataFormatDescriptor.length=0,X.dataFormatDescriptor.push(A);let S=new gW(Z,G,V,!0);while(S._offset<V){let t8=S._nextUint32(),_J=S._scan(t8),Oz=Yi(_J);if(X.keyValue[Oz]=S._nextUint8Array(t8-_J.byteLength-1),Oz.match(/^ktx/i)){let _f=Yi(X.keyValue[Oz]);X.keyValue[Oz]=_f.substring(0,_f.lastIndexOf("\x00"))}let X15=t8%4?4-t8%4:0;S._skip(X15)}if(q<=0)return X;let g=new gW(Z,H,q,!0),m=g._nextUint16(),i=g._nextUint16(),r=g._nextUint32(),Q0=g._nextUint32(),F0=g._nextUint32(),_0=g._nextUint32(),A0=[];for(let t8=0;t8<Q;t8++)A0.push({imageFlags:g._nextUint32(),rgbSliceByteOffset:g._nextUint32(),rgbSliceByteLength:g._nextUint32(),alphaSliceByteOffset:g._nextUint32(),alphaSliceByteLength:g._nextUint32()});let o0=H+g._offset,T8=o0+r,n5=T8+Q0,hZ=n5+F0,a9=new Uint8Array(Z.buffer,Z.byteOffset+o0,r),oQ=new Uint8Array(Z.buffer,Z.byteOffset+T8,Q0),tQ=new Uint8Array(Z.buffer,Z.byteOffset+n5,F0),x$=new Uint8Array(Z.buffer,Z.byteOffset+hZ,_0);return X.globalData={endpointCount:m,selectorCount:i,imageDescs:A0,endpointsData:a9,selectorsData:oQ,tablesData:tQ,extendedData:x$},X}var xD="EXT_mesh_gpu_instancing",SD="EXT_meshopt_compression",JU5="EXT_texture_webp",XU5="EXT_texture_avif",ji="KHR_draco_mesh_compression",fD="KHR_lights_punctual",hD="KHR_materials_anisotropy",bD="KHR_materials_clearcoat",yD="KHR_materials_diffuse_transmission",gD="KHR_materials_dispersion",mD="KHR_materials_emissive_strength",dD="KHR_materials_ior",uD="KHR_materials_iridescence",cD="KHR_materials_pbrSpecularGlossiness",lD="KHR_materials_sheen",pD="KHR_materials_specular",iD="KHR_materials_transmission",nD="KHR_materials_unlit",sD="KHR_materials_volume",NY="KHR_materials_variants",$U5="KHR_mesh_quantization",YU5="KHR_texture_basisu",aD="KHR_texture_transform",MU="KHR_xmp_json_ld",_D="INSTANCE_ATTRIBUTE";class rD extends c5{init(){this.extensionName=xD,this.propertyType="InstancedMesh",this.parentTypes=[s.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new a5})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:_D})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}rD.EXTENSION_NAME=xD;var QY=xD;class PU extends P5{constructor(...Z){super(...Z);this.extensionName=QY,this.provideTypes=[s.NODE],this.prewriteTypes=[s.ACCESSOR]}createInstancedMesh(){return new rD(this.document.getGraph())}read(Z){return(Z.jsonDoc.json.nodes||[]).forEach(($,Y)=>{if(!$.extensions||!$.extensions[QY])return;let Q=$.extensions[QY],W=this.createInstancedMesh();for(let K in Q.attributes)W.setAttribute(K,Z.accessors[Q.attributes[K]]);Z.nodes[Y].setExtension(QY,W)}),this}prewrite(Z){Z.accessorUsageGroupedByParent.add(_D);for(let J of this.properties)for(let X of J.listAttributes())Z.addAccessorToUsageGroup(X,_D);return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listNodes().forEach((X)=>{let $=X.getExtension(QY);if($){let Y=Z.nodeIndexMap.get(X),Q=J.json.nodes[Y],W={attributes:{}};$.listSemantics().forEach((K)=>{let G=$.getAttribute(K);W.attributes[K]=Z.accessorIndexMap.get(G)}),Q.extensions=Q.extensions||{},Q.extensions[QY]=W}}),this}}PU.EXTENSION_NAME=QY;function oJ(){return oJ=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)({}).hasOwnProperty.call(X,$)&&(Z[$]=X[$])}return Z},oJ.apply(null,arguments)}var nG;(function(Z){Z.QUANTIZE="quantize",Z.FILTER="filter"})(nG||(nG={}));var dW;(function(Z){Z.ATTRIBUTES="ATTRIBUTES",Z.TRIANGLES="TRIANGLES",Z.INDICES="INDICES"})(dW||(dW={}));var Y8;(function(Z){Z.NONE="NONE",Z.OCTAHEDRAL="OCTAHEDRAL",Z.QUATERNION="QUATERNION",Z.EXPONENTIAL="EXPONENTIAL"})(Y8||(Y8={}));var{BYTE:QU5,SHORT:Ki,FLOAT:WU5}=k0.ComponentType,{encodeNormalizedInt:Gi,decodeNormalizedInt:AD}=$8;function KU5(Z,J,X,$){let{filter:Y,bits:Q}=$,W={array:Z.getArray(),byteStride:Z.getElementSize()*Z.getComponentSize(),componentType:Z.getComponentType(),normalized:Z.getNormalized()};if(X!==dW.ATTRIBUTES)return W;if(Y!==Y8.NONE){let K=Z.getNormalized()?GU5(Z):new Float32Array(W.array);switch(Y){case Y8.EXPONENTIAL:W.byteStride=Z.getElementSize()*4,W.componentType=WU5,W.normalized=!1,W.array=J.encodeFilterExp(K,Z.getCount(),W.byteStride,Q);break;case Y8.OCTAHEDRAL:W.byteStride=Q>8?8:4,W.componentType=Q>8?Ki:QU5,W.normalized=!0,K=Z.getElementSize()===3?HU5(K):K,W.array=J.encodeFilterOct(K,Z.getCount(),W.byteStride,Q);break;case Y8.QUATERNION:W.byteStride=8,W.componentType=Ki,W.normalized=!0,W.array=J.encodeFilterQuat(K,Z.getCount(),W.byteStride,Q);break;default:throw new Error("Invalid filter.")}if(W.min=Z.getMin([]),W.max=Z.getMax([]),Z.getNormalized())W.min=W.min.map((G)=>AD(G,Z.getComponentType())),W.max=W.max.map((G)=>AD(G,Z.getComponentType()));if(W.normalized)W.min=W.min.map((G)=>Gi(G,W.componentType)),W.max=W.max.map((G)=>Gi(G,W.componentType))}else if(W.byteStride%4)W.array=VU5(W.array,Z.getElementSize()),W.byteStride=W.array.byteLength/Z.getCount();return W}function GU5(Z){let J=Z.getComponentType(),X=Z.getArray(),$=new Float32Array(X.length);for(let Y=0;Y<X.length;Y++)$[Y]=AD(X[Y],J);return $}function VU5(Z,J){let $=B6.padNumber(Z.BYTES_PER_ELEMENT*J)/Z.BYTES_PER_ELEMENT,Y=Z.length/J,Q=new Z.constructor(Y*$);for(let W=0;W*J<Z.length;W++)for(let K=0;K<J;K++)Q[W*$+K]=Z[W*J+K];return Q}function HU5(Z){let J=new Float32Array(Z.length*4/3);for(let X=0,$=Z.length/3;X<$;X++)J[X*4]=Z[X*3],J[X*4+1]=Z[X*3+1],J[X*4+2]=Z[X*3+2];return J}function qU5(Z,J){if(J===qX.BufferViewUsage.ELEMENT_ARRAY_BUFFER)return Z.listParents().some(($)=>{return $ instanceof HX&&$.getMode()===HX.Mode.TRIANGLES})?dW.TRIANGLES:dW.INDICES;return dW.ATTRIBUTES}function zU5(Z,J){let X=J.getGraph().listParentEdges(Z).filter(($)=>!($.getParent()instanceof NU));for(let $ of X){let Y=$.getName(),Q=$.getAttributes().key||"",W=$.getParent().propertyType===s.PRIMITIVE_TARGET;if(Y==="indices")return{filter:Y8.NONE};if(Y==="attributes"){if(Q==="POSITION")return{filter:Y8.NONE};if(Q==="TEXCOORD_0")return{filter:Y8.NONE};if(Q.startsWith("JOINTS_"))return{filter:Y8.NONE};if(Q.startsWith("WEIGHTS_"))return{filter:Y8.NONE};if(Q==="NORMAL"||Q==="TANGENT")return W?{filter:Y8.NONE}:{filter:Y8.OCTAHEDRAL,bits:8}}if(Y==="output"){let K=Mi(Z);if(K==="rotation")return{filter:Y8.QUATERNION,bits:16};if(K==="translation")return{filter:Y8.EXPONENTIAL,bits:12};if(K==="scale")return{filter:Y8.EXPONENTIAL,bits:12};return{filter:Y8.NONE}}if(Y==="input")return{filter:Y8.NONE};if(Y==="inverseBindMatrices")return{filter:Y8.NONE}}return{filter:Y8.NONE}}function Mi(Z){for(let J of Z.listParents()){if(!(J instanceof yW))continue;for(let X of J.listParents()){if(!(X instanceof dG))continue;return X.getTargetPath()}}return null}function FU5(Z){if(!Z.extensions||!Z.extensions[SD])return!1;return!!Z.extensions[SD].fallback}var y6=SD,Vi={method:nG.QUANTIZE};class aG extends P5{constructor(...Z){super(...Z);this.extensionName=y6,this.prereadTypes=[s.BUFFER,s.PRIMITIVE],this.prewriteTypes=[s.BUFFER,s.ACCESSOR],this.readDependencies=["meshopt.decoder"],this.writeDependencies=["meshopt.encoder"],this._decoder=null,this._decoderFallbackBufferMap=new Map,this._encoder=null,this._encoderOptions=Vi,this._encoderFallbackBuffer=null,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={}}install(Z,J){if(Z==="meshopt.decoder")this._decoder=J;if(Z==="meshopt.encoder")this._encoder=J;return this}setEncoderOptions(Z){return this._encoderOptions=oJ({},Vi,Z),this}preread(Z,J){if(!this._decoder){if(!this.isRequired())return this;throw new Error(`[${y6}] Please install extension dependency, "meshopt.decoder".`)}if(!this._decoder.supported){if(!this.isRequired())return this;throw new Error(`[${y6}]: Missing WASM support.`)}if(J===s.BUFFER)this._prereadBuffers(Z);else if(J===s.PRIMITIVE)this._prereadPrimitives(Z);return this}_prereadBuffers(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach(($,Y)=>{if(!$.extensions||!$.extensions[y6])return;let Q=$.extensions[y6],W=Q.byteOffset||0,K=Q.byteLength||0,G=Q.count,V=Q.byteStride,H=new Uint8Array(G*V),q=J.json.buffers[Q.buffer],z=q.uri?J.resources[q.uri]:J.resources[MD],F=B6.toView(z,W,K);this._decoder.decodeGltfBuffer(H,G,V,F,Q.mode,Q.filter),Z.bufferViews[Y]=H})}_prereadPrimitives(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach(($)=>{if(!$.extensions||!$.extensions[y6])return;let Y=$.extensions[y6],Q=Z.buffers[Y.buffer],W=Z.buffers[$.buffer],K=J.json.buffers[$.buffer];if(FU5(K))this._decoderFallbackBufferMap.set(W,Q)})}read(Z){if(!this.isRequired())return this;for(let[J,X]of this._decoderFallbackBufferMap){for(let $ of J.listParents())if($ instanceof k0)$.swap(J,X);J.dispose()}return this}prewrite(Z,J){if(J===s.ACCESSOR)this._prewriteAccessors(Z);else if(J===s.BUFFER)this._prewriteBuffers(Z);return this}_prewriteAccessors(Z){let J=Z.jsonDoc.json,X=this._encoder,$=this._encoderOptions,Y=this.document.getGraph(),Q=this.document.createBuffer(),W=this.document.getRoot().listBuffers().indexOf(Q),K=1,G=new Map,V=(H)=>{for(let q of Y.listParents(H)){if(q.propertyType===s.ROOT)continue;let z=G.get(H);if(z===void 0)G.set(H,z=K++);return z}return-1};this._encoderFallbackBuffer=Q,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={};for(let H of this.document.getRoot().listAccessors()){if(Mi(H)==="weights")continue;if(H.getSparse())continue;let q=Z.getAccessorUsage(H),z=Z.accessorUsageGroupedByParent.has(q)?V(H):null,F=qU5(H,q),U=$.method===nG.FILTER?zU5(H,this.document):{filter:Y8.NONE},L=KU5(H,X,F,U),{array:B,byteStride:w}=L,O=H.getBuffer();if(!O)throw new Error(`${y6}: Missing buffer for accessor.`);let M=this.document.getRoot().listBuffers().indexOf(O),N=[q,z,F,U.filter,w,M].join(":"),P=this._encoderBufferViews[N],D=this._encoderBufferViewData[N],C=this._encoderBufferViewAccessors[N];if(!P||!D)C=this._encoderBufferViewAccessors[N]=[],D=this._encoderBufferViewData[N]=[],P=this._encoderBufferViews[N]={buffer:W,target:qX.USAGE_TO_TARGET[q],byteOffset:0,byteLength:0,byteStride:q===qX.BufferViewUsage.ARRAY_BUFFER?w:void 0,extensions:{[y6]:{buffer:M,byteOffset:0,byteLength:0,mode:F,filter:U.filter!==Y8.NONE?U.filter:void 0,byteStride:w,count:0}}};let T=Z.createAccessorDef(H);if(T.componentType=L.componentType,T.normalized=L.normalized,T.byteOffset=P.byteLength,T.min&&L.min)T.min=L.min;if(T.max&&L.max)T.max=L.max;Z.accessorIndexMap.set(H,J.accessors.length),J.accessors.push(T),C.push(T),D.push(new Uint8Array(B.buffer,B.byteOffset,B.byteLength)),P.byteLength+=B.byteLength,P.extensions.EXT_meshopt_compression.count+=H.getCount()}}_prewriteBuffers(Z){let J=this._encoder;for(let X in this._encoderBufferViews){let $=this._encoderBufferViews[X],Y=this._encoderBufferViewData[X],Q=this.document.getRoot().listBuffers()[$.extensions[y6].buffer],W=Z.otherBufferViews.get(Q)||[],{count:K,byteStride:G,mode:V}=$.extensions[y6],H=B6.concat(Y),q=J.encodeGltfBuffer(H,K,G,V),z=B6.pad(q);$.extensions[y6].byteLength=q.byteLength,Y.length=0,Y.push(z),W.push(z),Z.otherBufferViews.set(Q,W)}}write(Z){let J=0;for(let Q in this._encoderBufferViews){let W=this._encoderBufferViews[Q],K=this._encoderBufferViewData[Q][0],G=Z.otherBufferViewsIndexMap.get(K),V=this._encoderBufferViewAccessors[Q];for(let F of V)F.bufferView=G;let H=Z.jsonDoc.json.bufferViews[G],q=H.byteOffset||0;Object.assign(H,W),H.byteOffset=J;let z=H.extensions[y6];z.byteOffset=q,J+=B6.padNumber(W.byteLength)}let X=this._encoderFallbackBuffer,$=Z.bufferIndexMap.get(X),Y=Z.jsonDoc.json.buffers[$];return Y.byteLength=J,Y.extensions={[y6]:{fallback:!0}},X.dispose(),this}}aG.EXTENSION_NAME=y6;aG.EncoderMethod=nG;var lG=XU5;class Ri{match(Z){return Z.length>=12&&B6.decodeText(Z.slice(4,12))==="ftypavif"}getSize(Z){if(!this.match(Z))return null;let J=new DataView(Z.buffer,Z.byteOffset,Z.byteLength),X=Hi(J,0);if(!X)return null;let $=X.end;while(X=Hi(J,$))if(X.type==="meta")$=X.start+4;else if(X.type==="iprp"||X.type==="ipco")$=X.start;else if(X.type==="ispe")return[J.getUint32(X.start+4),J.getUint32(X.start+8)];else if(X.type==="mdat")break;else $=X.end;return null}getChannels(Z){return 4}}class CU extends P5{constructor(...Z){super(...Z);this.extensionName=lG,this.prereadTypes=[s.TEXTURE]}static register(){GZ.registerFormat("image/avif",new Ri)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[lG])X.source=X.extensions[lG].source}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/avif"){let $=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===$)Q.extensions=Q.extensions||{},Q.extensions[lG]={source:Q.source},delete Q.source})}}),this}}CU.EXTENSION_NAME=lG;function Hi(Z,J){if(Z.byteLength<4+J)return null;let X=Z.getUint32(J);if(Z.byteLength<X+J||X<8)return null;return{type:B6.decodeText(new Uint8Array(Z.buffer,Z.byteOffset+J+4,4)),start:J+8,end:J+X}}var pG=JU5;class Di{match(Z){return Z.length>=12&&Z[8]===87&&Z[9]===69&&Z[10]===66&&Z[11]===80}getSize(Z){let J=B6.decodeText(Z.slice(0,4)),X=B6.decodeText(Z.slice(8,12));if(J!=="RIFF"||X!=="WEBP")return null;let $=new DataView(Z.buffer,Z.byteOffset),Y=12;while(Y<$.byteLength){let Q=B6.decodeText(new Uint8Array([$.getUint8(Y),$.getUint8(Y+1),$.getUint8(Y+2),$.getUint8(Y+3)])),W=$.getUint32(Y+4,!0);if(Q==="VP8 "){let K=$.getInt16(Y+14,!0)&16383,G=$.getInt16(Y+16,!0)&16383;return[K,G]}else if(Q==="VP8L"){let K=$.getUint8(Y+9),G=$.getUint8(Y+10),V=$.getUint8(Y+11),H=$.getUint8(Y+12),q=1+((G&63)<<8|K),z=1+((H&15)<<10|V<<2|(G&192)>>6);return[q,z]}Y+=8+W+W%2}return null}getChannels(Z){return 4}}class TU extends P5{constructor(...Z){super(...Z);this.extensionName=pG,this.prereadTypes=[s.TEXTURE]}static register(){GZ.registerFormat("image/webp",new Di)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[pG])X.source=X.extensions[pG].source}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/webp"){let $=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===$)Q.extensions=Q.extensions||{},Q.extensions[pG]={source:Q.source},delete Q.source})}}),this}}TU.EXTENSION_NAME=pG;var qi=ji,f8,Pi,Ci;function UU5(Z,J){let X=new f8.DecoderBuffer;try{if(X.Init(J,J.length),Z.GetEncodedGeometryType(X)!==f8.TRIANGULAR_MESH)throw new Error(`[${qi}] Unknown geometry type.`);let Y=new f8.Mesh;if(!Z.DecodeBufferToMesh(X,Y).ok()||Y.ptr===0)throw new Error(`[${qi}] Decoding failure.`);return Y}finally{f8.destroy(X)}}function BU5(Z,J){let $=J.num_faces()*3,Y,Q;if(J.num_points()<=65534){let W=$*Uint16Array.BYTES_PER_ELEMENT;Y=f8._malloc(W),Z.GetTrianglesUInt16Array(J,W,Y),Q=new Uint16Array(f8.HEAPU16.buffer,Y,$).slice()}else{let W=$*Uint32Array.BYTES_PER_ELEMENT;Y=f8._malloc(W),Z.GetTrianglesUInt32Array(J,W,Y),Q=new Uint32Array(f8.HEAPU32.buffer,Y,$).slice()}return f8._free(Y),Q}function LU5(Z,J,X,$){let Y=Ci[$.componentType],Q=Pi[$.componentType],W=X.num_components(),G=J.num_points()*W,V=G*Q.BYTES_PER_ELEMENT,H=f8._malloc(V);Z.GetAttributeDataArrayForAllPoints(J,X,Y,V,H);let q=new Q(f8.HEAPF32.buffer,H,G).slice();return f8._free(H),q}function wU5(Z){f8=Z,Pi={[k0.ComponentType.FLOAT]:Float32Array,[k0.ComponentType.UNSIGNED_INT]:Uint32Array,[k0.ComponentType.UNSIGNED_SHORT]:Uint16Array,[k0.ComponentType.UNSIGNED_BYTE]:Uint8Array,[k0.ComponentType.SHORT]:Int16Array,[k0.ComponentType.BYTE]:Int8Array},Ci={[k0.ComponentType.FLOAT]:f8.DT_FLOAT32,[k0.ComponentType.UNSIGNED_INT]:f8.DT_UINT32,[k0.ComponentType.UNSIGNED_SHORT]:f8.DT_UINT16,[k0.ComponentType.UNSIGNED_BYTE]:f8.DT_UINT8,[k0.ComponentType.SHORT]:f8.DT_INT16,[k0.ComponentType.BYTE]:f8.DT_INT8}}var z9,sG;(function(Z){Z[Z.EDGEBREAKER=1]="EDGEBREAKER",Z[Z.SEQUENTIAL=0]="SEQUENTIAL"})(sG||(sG={}));var F9;(function(Z){Z.POSITION="POSITION",Z.NORMAL="NORMAL",Z.COLOR="COLOR",Z.TEX_COORD="TEX_COORD",Z.GENERIC="GENERIC"})(F9||(F9={}));var Ti={[F9.POSITION]:14,[F9.NORMAL]:10,[F9.COLOR]:8,[F9.TEX_COORD]:12,[F9.GENERIC]:12},zi={decodeSpeed:5,encodeSpeed:5,method:sG.EDGEBREAKER,quantizationBits:Ti,quantizationVolume:"mesh"};function OU5(Z){z9=Z}function NU5(Z,J=zi){let X=oJ({},zi,J);X.quantizationBits=oJ({},Ti,J.quantizationBits);let $=new z9.MeshBuilder,Y=new z9.Mesh,Q=new z9.ExpertEncoder(Y),W={},K=new z9.DracoInt8Array,G=Z.listTargets().length>0,V=!1;for(let L of Z.listSemantics()){let B=Z.getAttribute(L);if(B.getSparse()){V=!0;continue}let w=jU5(L),O=MU5($,B.getComponentType(),Y,z9[w],B.getCount(),B.getElementSize(),B.getArray());if(O===-1)throw new Error(`Error compressing "${L}" attribute.`);if(W[L]=O,X.quantizationVolume==="mesh"||L!=="POSITION")Q.SetAttributeQuantization(O,X.quantizationBits[w]);else if(typeof X.quantizationVolume==="object"){let{quantizationVolume:M}=X,N=Math.max(M.max[0]-M.min[0],M.max[1]-M.min[1],M.max[2]-M.min[2]);Q.SetAttributeExplicitQuantization(O,X.quantizationBits[w],B.getElementSize(),M.min,N)}else throw new Error("Invalid quantization volume state.")}let H=Z.getIndices();if(!H)throw new RU("Primitive must have indices.");if($.AddFacesToMesh(Y,H.getCount()/3,H.getArray()),Q.SetSpeedOptions(X.encodeSpeed,X.decodeSpeed),Q.SetTrackEncodedProperties(!0),X.method===sG.SEQUENTIAL||G||V)Q.SetEncodingMethod(z9.MESH_SEQUENTIAL_ENCODING);else Q.SetEncodingMethod(z9.MESH_EDGEBREAKER_ENCODING);let q=Q.EncodeToDracoBuffer(!(G||V),K);if(q<=0)throw new RU("Error applying Draco compression.");let z=new Uint8Array(q);for(let L=0;L<q;++L)z[L]=K.GetValue(L);let F=Q.GetNumberOfEncodedPoints(),U=Q.GetNumberOfEncodedFaces()*3;return z9.destroy(K),z9.destroy(Y),z9.destroy($),z9.destroy(Q),{numVertices:F,numIndices:U,data:z,attributeIDs:W}}function jU5(Z){if(Z==="POSITION")return F9.POSITION;else if(Z==="NORMAL")return F9.NORMAL;else if(Z.startsWith("COLOR_"))return F9.COLOR;else if(Z.startsWith("TEXCOORD_"))return F9.TEX_COORD;return F9.GENERIC}function MU5(Z,J,X,$,Y,Q,W){switch(J){case k0.ComponentType.UNSIGNED_BYTE:return Z.AddUInt8Attribute(X,$,Y,Q,W);case k0.ComponentType.BYTE:return Z.AddInt8Attribute(X,$,Y,Q,W);case k0.ComponentType.UNSIGNED_SHORT:return Z.AddUInt16Attribute(X,$,Y,Q,W);case k0.ComponentType.SHORT:return Z.AddInt16Attribute(X,$,Y,Q,W);case k0.ComponentType.UNSIGNED_INT:return Z.AddUInt32Attribute(X,$,Y,Q,W);case k0.ComponentType.FLOAT:return Z.AddFloatAttribute(X,$,Y,Q,W);default:throw new Error(`Unexpected component type, "${J}".`)}}class RU extends Error{}var j8=ji;class rG extends P5{constructor(...Z){super(...Z);this.extensionName=j8,this.prereadTypes=[s.PRIMITIVE],this.prewriteTypes=[s.ACCESSOR],this.readDependencies=["draco3d.decoder"],this.writeDependencies=["draco3d.encoder"],this._decoderModule=null,this._encoderModule=null,this._encoderOptions={}}install(Z,J){if(Z==="draco3d.decoder")this._decoderModule=J,wU5(this._decoderModule);if(Z==="draco3d.encoder")this._encoderModule=J,OU5(this._encoderModule);return this}setEncoderOptions(Z){return this._encoderOptions=Z,this}preread(Z){if(!this._decoderModule)throw new Error(`[${j8}] Please install extension dependency, "draco3d.decoder".`);let J=this.document.getLogger(),X=Z.jsonDoc,$=new Map;try{let Y=X.json.meshes||[];for(let Q of Y)for(let W of Q.primitives){if(!W.extensions||!W.extensions[j8])continue;let K=W.extensions[j8],[G,V]=$.get(K.bufferView)||[];if(!V||!G){let H=X.json.bufferViews[K.bufferView],q=X.json.buffers[H.buffer],z=q.uri?X.resources[q.uri]:X.resources[MD],F=H.byteOffset||0,U=H.byteLength,L=B6.toView(z,F,U);G=new this._decoderModule.Decoder,V=UU5(G,L),$.set(K.bufferView,[G,V]),J.debug(`[${j8}] Decompressed ${L.byteLength} bytes.`)}for(let H in K.attributes){let q=Z.jsonDoc.json.accessors[W.attributes[H]],z=G.GetAttributeByUniqueId(V,K.attributes[H]),F=LU5(G,V,z,q);Z.accessors[W.attributes[H]].setArray(F)}if(W.indices!==void 0)Z.accessors[W.indices].setArray(BU5(G,V))}}finally{for(let[Y,Q]of Array.from($.values()))this._decoderModule.destroy(Y),this._decoderModule.destroy(Q)}return this}read(Z){return this}prewrite(Z,J){if(!this._encoderModule)throw new Error(`[${j8}] Please install extension dependency, "draco3d.encoder".`);let X=this.document.getLogger();X.debug(`[${j8}] Compression options: ${JSON.stringify(this._encoderOptions)}`);let $=RU5(this.document),Y=new Map,Q="mesh";if(this._encoderOptions.quantizationVolume==="scene")if(this.document.getRoot().listScenes().length!==1)X.warn(`[${j8}]: quantizationVolume=scene requires exactly 1 scene.`);else Q=tp(this.document.getRoot().listScenes().pop());for(let W of Array.from($.keys())){let K=$.get(W);if(!K)throw new Error("Unexpected primitive.");if(Y.has(K)){Y.set(K,Y.get(K));continue}let G=W.getIndices(),V=Z.jsonDoc.json.accessors,H;try{H=NU5(W,oJ({},this._encoderOptions,{quantizationVolume:Q}))}catch(F){if(F instanceof RU){X.warn(`[${j8}]: ${F.message} Skipping primitive compression.`);continue}throw F}Y.set(K,H);let q=Z.createAccessorDef(G);if(q.count=H.numIndices,Z.accessorIndexMap.set(G,V.length),V.push(q),H.numVertices>65534&&k0.getComponentSize(q.componentType)<=2)q.componentType=k0.ComponentType.UNSIGNED_INT;else if(H.numVertices>254&&k0.getComponentSize(q.componentType)<=1)q.componentType=k0.ComponentType.UNSIGNED_SHORT;for(let F of W.listSemantics()){let U=W.getAttribute(F);if(H.attributeIDs[F]===void 0)continue;let L=Z.createAccessorDef(U);L.count=H.numVertices,Z.accessorIndexMap.set(U,V.length),V.push(L)}let z=W.getAttribute("POSITION").getBuffer()||this.document.getRoot().listBuffers()[0];if(!Z.otherBufferViews.has(z))Z.otherBufferViews.set(z,[]);Z.otherBufferViews.get(z).push(H.data)}return X.debug(`[${j8}] Compressed ${$.size} primitives.`),Z.extensionData[j8]={primitiveHashMap:$,primitiveEncodingMap:Y},this}write(Z){let J=Z.extensionData[j8];for(let X of this.document.getRoot().listMeshes()){let $=Z.jsonDoc.json.meshes[Z.meshIndexMap.get(X)];for(let Y=0;Y<X.listPrimitives().length;Y++){let Q=X.listPrimitives()[Y],W=$.primitives[Y],K=J.primitiveHashMap.get(Q);if(!K)continue;let G=J.primitiveEncodingMap.get(K);if(!G)continue;W.extensions=W.extensions||{},W.extensions[j8]={bufferView:Z.otherBufferViewsIndexMap.get(G.data),attributes:G.attributeIDs}}}if(!J.primitiveHashMap.size){let X=Z.jsonDoc.json;X.extensionsUsed=(X.extensionsUsed||[]).filter(($)=>$!==j8),X.extensionsRequired=(X.extensionsRequired||[]).filter(($)=>$!==j8)}return this}}rG.EXTENSION_NAME=j8;rG.EncoderMethod=sG;function RU5(Z){let J=Z.getLogger(),X=new Set,$=new Set,Y=0,Q=0;for(let q of Z.getRoot().listMeshes())for(let z of q.listPrimitives())if(!z.getIndices())$.add(z),Y++;else if(z.getMode()!==HX.Mode.TRIANGLES)$.add(z),Q++;else X.add(z);if(Y>0)J.warn(`[${j8}] Skipping Draco compression of ${Y} non-indexed primitives.`);if(Q>0)J.warn(`[${j8}] Skipping Draco compression of ${Q} non-TRIANGLES primitives.`);let W=Z.getRoot().listAccessors(),K=new Map;for(let q=0;q<W.length;q++)K.set(W[q],q);let G=new Map,V=new Set,H=new Map;for(let q of Array.from(X)){let z=Fi(q,K);if(V.has(z)){H.set(q,z);continue}if(G.has(q.getIndices())){let F=q.getIndices(),U=F.clone();K.set(U,Z.getRoot().listAccessors().length-1),q.swap(F,U)}for(let F of q.listAttributes())if(G.has(F)){let U=F.clone();K.set(U,Z.getRoot().listAccessors().length-1),q.swap(F,U)}z=Fi(q,K),V.add(z),H.set(q,z),G.set(q.getIndices(),z);for(let F of q.listAttributes())G.set(F,z)}for(let q of Array.from(G.keys())){let z=new Set(q.listParents().map((F)=>F.propertyType));if(z.size!==2||!z.has(s.PRIMITIVE)||!z.has(s.ROOT))throw new Error(`[${j8}] Compressed accessors must only be used as indices or vertex attributes.`)}for(let q of Array.from(X)){let z=H.get(q),F=q.getIndices();if(G.get(F)!==z||q.listAttributes().some((U)=>G.get(U)!==z))throw new Error(`[${j8}] Draco primitives must share all, or no, accessors.`)}for(let q of Array.from($)){let z=q.getIndices();if(G.has(z)||q.listAttributes().some((F)=>G.has(F)))throw new Error(`[${j8}] Accessor cannot be shared by compressed and uncompressed primitives.`)}return H}function Fi(Z,J){let X=[],$=Z.getIndices();X.push(J.get($));for(let Y of Z.listAttributes())X.push(J.get(Y));return X.sort().join("|")}class uW extends c5{init(){this.extensionName=fD,this.propertyType="Light",this.parentTypes=[s.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{color:[1,1,1],intensity:1,type:uW.Type.POINT,range:null,innerConeAngle:0,outerConeAngle:Math.PI/4})}getColor(){return this.get("color")}setColor(Z){return this.set("color",Z)}getIntensity(){return this.get("intensity")}setIntensity(Z){return this.set("intensity",Z)}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getRange(){return this.get("range")}setRange(Z){return this.set("range",Z)}getInnerConeAngle(){return this.get("innerConeAngle")}setInnerConeAngle(Z){return this.set("innerConeAngle",Z)}getOuterConeAngle(){return this.get("outerConeAngle")}setOuterConeAngle(Z){return this.set("outerConeAngle",Z)}}uW.EXTENSION_NAME=fD;uW.Type={POINT:"point",SPOT:"spot",DIRECTIONAL:"directional"};var ZJ=fD;class oD extends P5{constructor(...Z){super(...Z);this.extensionName=ZJ}createLight(Z=""){return new uW(this.document.getGraph(),Z)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[ZJ])return this;let Y=(J.json.extensions[ZJ].lights||[]).map((Q)=>{var W,K;let G=this.createLight().setName(Q.name||"").setType(Q.type);if(Q.color!==void 0)G.setColor(Q.color);if(Q.intensity!==void 0)G.setIntensity(Q.intensity);if(Q.range!==void 0)G.setRange(Q.range);if(((W=Q.spot)==null?void 0:W.innerConeAngle)!==void 0)G.setInnerConeAngle(Q.spot.innerConeAngle);if(((K=Q.spot)==null?void 0:K.outerConeAngle)!==void 0)G.setOuterConeAngle(Q.spot.outerConeAngle);return G});return J.json.nodes.forEach((Q,W)=>{if(!Q.extensions||!Q.extensions[ZJ])return;let K=Q.extensions[ZJ];Z.nodes[W].setExtension(ZJ,Y[K.light])}),this}write(Z){let J=Z.jsonDoc;if(this.properties.size===0)return this;let X=[],$=new Map;for(let Y of this.properties){let Q=Y,W={type:Q.getType()};if(!$8.eq(Q.getColor(),[1,1,1]))W.color=Q.getColor();if(Q.getIntensity()!==1)W.intensity=Q.getIntensity();if(Q.getRange()!=null)W.range=Q.getRange();if(Q.getName())W.name=Q.getName();if(Q.getType()===uW.Type.SPOT)W.spot={innerConeAngle:Q.getInnerConeAngle(),outerConeAngle:Q.getOuterConeAngle()};X.push(W),$.set(Q,X.length-1)}return this.document.getRoot().listNodes().forEach((Y)=>{let Q=Y.getExtension(ZJ);if(Q){let W=Z.nodeIndexMap.get(Y),K=J.json.nodes[W];K.extensions=K.extensions||{},K.extensions[ZJ]={light:$.get(Q)}}}),J.json.extensions=J.json.extensions||{},J.json.extensions[ZJ]={lights:X},this}}oD.EXTENSION_NAME=ZJ;var{R:DU5,G:PU5,B:CU5}=A7;class tD extends c5{init(){this.extensionName=hD,this.propertyType="Anisotropy",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{anisotropyStrength:0,anisotropyRotation:0,anisotropyTexture:null,anisotropyTextureInfo:new R5(this.graph,"anisotropyTextureInfo")})}getAnisotropyStrength(){return this.get("anisotropyStrength")}setAnisotropyStrength(Z){return this.set("anisotropyStrength",Z)}getAnisotropyRotation(){return this.get("anisotropyRotation")}setAnisotropyRotation(Z){return this.set("anisotropyRotation",Z)}getAnisotropyTexture(){return this.getRef("anisotropyTexture")}getAnisotropyTextureInfo(){return this.getRef("anisotropyTexture")?this.getRef("anisotropyTextureInfo"):null}setAnisotropyTexture(Z){return this.setRef("anisotropyTexture",Z,{channels:DU5|PU5|CU5})}}tD.EXTENSION_NAME=hD;var WY=hD;class eD extends P5{constructor(...Z){super(...Z);this.extensionName=WY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createAnisotropy(){return new tD(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[WY]){let W=this.createAnisotropy();Z.materials[Q].setExtension(WY,W);let K=Y.extensions[WY];if(K.anisotropyStrength!==void 0)W.setAnisotropyStrength(K.anisotropyStrength);if(K.anisotropyRotation!==void 0)W.setAnisotropyRotation(K.anisotropyRotation);if(K.anisotropyTexture!==void 0){let G=K.anisotropyTexture,V=Z.textures[$[G.index].source];W.setAnisotropyTexture(V),Z.setTextureInfo(W.getAnisotropyTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(WY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[WY]={};if($.getAnisotropyStrength()>0)W.anisotropyStrength=$.getAnisotropyStrength();if($.getAnisotropyRotation()!==0)W.anisotropyRotation=$.getAnisotropyRotation();if($.getAnisotropyTexture()){let K=$.getAnisotropyTexture(),G=$.getAnisotropyTextureInfo();W.anisotropyTexture=Z.createTextureInfoDef(K,G)}}}),this}}eD.EXTENSION_NAME=WY;var{R:Ui,G:Bi,B:TU5}=A7;class ZP extends c5{init(){this.extensionName=bD,this.propertyType="Clearcoat",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{clearcoatFactor:0,clearcoatTexture:null,clearcoatTextureInfo:new R5(this.graph,"clearcoatTextureInfo"),clearcoatRoughnessFactor:0,clearcoatRoughnessTexture:null,clearcoatRoughnessTextureInfo:new R5(this.graph,"clearcoatRoughnessTextureInfo"),clearcoatNormalScale:1,clearcoatNormalTexture:null,clearcoatNormalTextureInfo:new R5(this.graph,"clearcoatNormalTextureInfo")})}getClearcoatFactor(){return this.get("clearcoatFactor")}setClearcoatFactor(Z){return this.set("clearcoatFactor",Z)}getClearcoatTexture(){return this.getRef("clearcoatTexture")}getClearcoatTextureInfo(){return this.getRef("clearcoatTexture")?this.getRef("clearcoatTextureInfo"):null}setClearcoatTexture(Z){return this.setRef("clearcoatTexture",Z,{channels:Ui})}getClearcoatRoughnessFactor(){return this.get("clearcoatRoughnessFactor")}setClearcoatRoughnessFactor(Z){return this.set("clearcoatRoughnessFactor",Z)}getClearcoatRoughnessTexture(){return this.getRef("clearcoatRoughnessTexture")}getClearcoatRoughnessTextureInfo(){return this.getRef("clearcoatRoughnessTexture")?this.getRef("clearcoatRoughnessTextureInfo"):null}setClearcoatRoughnessTexture(Z){return this.setRef("clearcoatRoughnessTexture",Z,{channels:Bi})}getClearcoatNormalScale(){return this.get("clearcoatNormalScale")}setClearcoatNormalScale(Z){return this.set("clearcoatNormalScale",Z)}getClearcoatNormalTexture(){return this.getRef("clearcoatNormalTexture")}getClearcoatNormalTextureInfo(){return this.getRef("clearcoatNormalTexture")?this.getRef("clearcoatNormalTextureInfo"):null}setClearcoatNormalTexture(Z){return this.setRef("clearcoatNormalTexture",Z,{channels:Ui|Bi|TU5})}}ZP.EXTENSION_NAME=bD;var KY=bD;class JP extends P5{constructor(...Z){super(...Z);this.extensionName=KY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createClearcoat(){return new ZP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[KY]){let W=this.createClearcoat();Z.materials[Q].setExtension(KY,W);let K=Y.extensions[KY];if(K.clearcoatFactor!==void 0)W.setClearcoatFactor(K.clearcoatFactor);if(K.clearcoatRoughnessFactor!==void 0)W.setClearcoatRoughnessFactor(K.clearcoatRoughnessFactor);if(K.clearcoatTexture!==void 0){let G=K.clearcoatTexture,V=Z.textures[$[G.index].source];W.setClearcoatTexture(V),Z.setTextureInfo(W.getClearcoatTextureInfo(),G)}if(K.clearcoatRoughnessTexture!==void 0){let G=K.clearcoatRoughnessTexture,V=Z.textures[$[G.index].source];W.setClearcoatRoughnessTexture(V),Z.setTextureInfo(W.getClearcoatRoughnessTextureInfo(),G)}if(K.clearcoatNormalTexture!==void 0){let G=K.clearcoatNormalTexture,V=Z.textures[$[G.index].source];if(W.setClearcoatNormalTexture(V),Z.setTextureInfo(W.getClearcoatNormalTextureInfo(),G),G.scale!==void 0)W.setClearcoatNormalScale(G.scale)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(KY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[KY]={clearcoatFactor:$.getClearcoatFactor(),clearcoatRoughnessFactor:$.getClearcoatRoughnessFactor()};if($.getClearcoatTexture()){let K=$.getClearcoatTexture(),G=$.getClearcoatTextureInfo();W.clearcoatTexture=Z.createTextureInfoDef(K,G)}if($.getClearcoatRoughnessTexture()){let K=$.getClearcoatRoughnessTexture(),G=$.getClearcoatRoughnessTextureInfo();W.clearcoatRoughnessTexture=Z.createTextureInfoDef(K,G)}if($.getClearcoatNormalTexture()){let K=$.getClearcoatNormalTexture(),G=$.getClearcoatNormalTextureInfo();if(W.clearcoatNormalTexture=Z.createTextureInfoDef(K,G),$.getClearcoatNormalScale()!==1)W.clearcoatNormalTexture.scale=$.getClearcoatNormalScale()}}}),this}}JP.EXTENSION_NAME=KY;var{R:kU5,G:EU5,B:IU5,A:vU5}=A7;class XP extends c5{init(){this.extensionName=yD,this.propertyType="DiffuseTransmission",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseTransmissionFactor:0,diffuseTransmissionTexture:null,diffuseTransmissionTextureInfo:new R5(this.graph,"diffuseTransmissionTextureInfo"),diffuseTransmissionColorFactor:[1,1,1],diffuseTransmissionColorTexture:null,diffuseTransmissionColorTextureInfo:new R5(this.graph,"diffuseTransmissionColorTextureInfo")})}getDiffuseTransmissionFactor(){return this.get("diffuseTransmissionFactor")}setDiffuseTransmissionFactor(Z){return this.set("diffuseTransmissionFactor",Z)}getDiffuseTransmissionTexture(){return this.getRef("diffuseTransmissionTexture")}getDiffuseTransmissionTextureInfo(){return this.getRef("diffuseTransmissionTexture")?this.getRef("diffuseTransmissionTextureInfo"):null}setDiffuseTransmissionTexture(Z){return this.setRef("diffuseTransmissionTexture",Z,{channels:vU5})}getDiffuseTransmissionColorFactor(){return this.get("diffuseTransmissionColorFactor")}setDiffuseTransmissionColorFactor(Z){return this.set("diffuseTransmissionColorFactor",Z)}getDiffuseTransmissionColorTexture(){return this.getRef("diffuseTransmissionColorTexture")}getDiffuseTransmissionColorTextureInfo(){return this.getRef("diffuseTransmissionColorTexture")?this.getRef("diffuseTransmissionColorTextureInfo"):null}setDiffuseTransmissionColorTexture(Z){return this.setRef("diffuseTransmissionColorTexture",Z,{channels:kU5|EU5|IU5})}}XP.EXTENSION_NAME=yD;var GY=yD;class $P extends P5{constructor(...Z){super(...Z);this.extensionName=GY}createDiffuseTransmission(){return new XP(this.document.getGraph())}read(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[GY]){let W=this.createDiffuseTransmission();Z.materials[Q].setExtension(GY,W);let K=Y.extensions[GY];if(K.diffuseTransmissionFactor!==void 0)W.setDiffuseTransmissionFactor(K.diffuseTransmissionFactor);if(K.diffuseTransmissionColorFactor!==void 0)W.setDiffuseTransmissionColorFactor(K.diffuseTransmissionColorFactor);if(K.diffuseTransmissionTexture!==void 0){let G=K.diffuseTransmissionTexture,V=Z.textures[$[G.index].source];W.setDiffuseTransmissionTexture(V),Z.setTextureInfo(W.getDiffuseTransmissionTextureInfo(),G)}if(K.diffuseTransmissionColorTexture!==void 0){let G=K.diffuseTransmissionColorTexture,V=Z.textures[$[G.index].source];W.setDiffuseTransmissionColorTexture(V),Z.setTextureInfo(W.getDiffuseTransmissionColorTextureInfo(),G)}}}),this}write(Z){let J=Z.jsonDoc;for(let X of this.document.getRoot().listMaterials()){let $=X.getExtension(GY);if(!$)continue;let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[GY]={diffuseTransmissionFactor:$.getDiffuseTransmissionFactor(),diffuseTransmissionColorFactor:$.getDiffuseTransmissionColorFactor()};if($.getDiffuseTransmissionTexture()){let K=$.getDiffuseTransmissionTexture(),G=$.getDiffuseTransmissionTextureInfo();W.diffuseTransmissionTexture=Z.createTextureInfoDef(K,G)}if($.getDiffuseTransmissionColorTexture()){let K=$.getDiffuseTransmissionColorTexture(),G=$.getDiffuseTransmissionColorTextureInfo();W.diffuseTransmissionColorTexture=Z.createTextureInfoDef(K,G)}}return this}}$P.EXTENSION_NAME=GY;class YP extends c5{init(){this.extensionName=gD,this.propertyType="Dispersion",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{dispersion:0})}getDispersion(){return this.get("dispersion")}setDispersion(Z){return this.set("dispersion",Z)}}YP.EXTENSION_NAME=gD;var VY=gD;class QP extends P5{constructor(...Z){super(...Z);this.extensionName=VY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createDispersion(){return new YP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach(($,Y)=>{if($.extensions&&$.extensions[VY]){let Q=this.createDispersion();Z.materials[Y].setExtension(VY,Q);let W=$.extensions[VY];if(W.dispersion!==void 0)Q.setDispersion(W.dispersion)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(VY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{},Q.extensions[VY]={dispersion:$.getDispersion()}}}),this}}QP.EXTENSION_NAME=VY;class WP extends c5{init(){this.extensionName=mD,this.propertyType="EmissiveStrength",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{emissiveStrength:1})}getEmissiveStrength(){return this.get("emissiveStrength")}setEmissiveStrength(Z){return this.set("emissiveStrength",Z)}}WP.EXTENSION_NAME=mD;var HY=mD;class KP extends P5{constructor(...Z){super(...Z);this.extensionName=HY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createEmissiveStrength(){return new WP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach(($,Y)=>{if($.extensions&&$.extensions[HY]){let Q=this.createEmissiveStrength();Z.materials[Y].setExtension(HY,Q);let W=$.extensions[HY];if(W.emissiveStrength!==void 0)Q.setEmissiveStrength(W.emissiveStrength)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(HY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{},Q.extensions[HY]={emissiveStrength:$.getEmissiveStrength()}}}),this}}KP.EXTENSION_NAME=HY;class GP extends c5{init(){this.extensionName=dD,this.propertyType="IOR",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{ior:1.5})}getIOR(){return this.get("ior")}setIOR(Z){return this.set("ior",Z)}}GP.EXTENSION_NAME=dD;var qY=dD;class kU extends P5{constructor(...Z){super(...Z);this.extensionName=qY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createIOR(){return new GP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach(($,Y)=>{if($.extensions&&$.extensions[qY]){let Q=this.createIOR();Z.materials[Y].setExtension(qY,Q);let W=$.extensions[qY];if(W.ior!==void 0)Q.setIOR(W.ior)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(qY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{},Q.extensions[qY]={ior:$.getIOR()}}}),this}}kU.EXTENSION_NAME=qY;var{R:SU5,G:_U5}=A7;class VP extends c5{init(){this.extensionName=uD,this.propertyType="Iridescence",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{iridescenceFactor:0,iridescenceTexture:null,iridescenceTextureInfo:new R5(this.graph,"iridescenceTextureInfo"),iridescenceIOR:1.3,iridescenceThicknessMinimum:100,iridescenceThicknessMaximum:400,iridescenceThicknessTexture:null,iridescenceThicknessTextureInfo:new R5(this.graph,"iridescenceThicknessTextureInfo")})}getIridescenceFactor(){return this.get("iridescenceFactor")}setIridescenceFactor(Z){return this.set("iridescenceFactor",Z)}getIridescenceTexture(){return this.getRef("iridescenceTexture")}getIridescenceTextureInfo(){return this.getRef("iridescenceTexture")?this.getRef("iridescenceTextureInfo"):null}setIridescenceTexture(Z){return this.setRef("iridescenceTexture",Z,{channels:SU5})}getIridescenceIOR(){return this.get("iridescenceIOR")}setIridescenceIOR(Z){return this.set("iridescenceIOR",Z)}getIridescenceThicknessMinimum(){return this.get("iridescenceThicknessMinimum")}setIridescenceThicknessMinimum(Z){return this.set("iridescenceThicknessMinimum",Z)}getIridescenceThicknessMaximum(){return this.get("iridescenceThicknessMaximum")}setIridescenceThicknessMaximum(Z){return this.set("iridescenceThicknessMaximum",Z)}getIridescenceThicknessTexture(){return this.getRef("iridescenceThicknessTexture")}getIridescenceThicknessTextureInfo(){return this.getRef("iridescenceThicknessTexture")?this.getRef("iridescenceThicknessTextureInfo"):null}setIridescenceThicknessTexture(Z){return this.setRef("iridescenceThicknessTexture",Z,{channels:_U5})}}VP.EXTENSION_NAME=uD;var zY=uD;class HP extends P5{constructor(...Z){super(...Z);this.extensionName=zY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createIridescence(){return new VP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[zY]){let W=this.createIridescence();Z.materials[Q].setExtension(zY,W);let K=Y.extensions[zY];if(K.iridescenceFactor!==void 0)W.setIridescenceFactor(K.iridescenceFactor);if(K.iridescenceIor!==void 0)W.setIridescenceIOR(K.iridescenceIor);if(K.iridescenceThicknessMinimum!==void 0)W.setIridescenceThicknessMinimum(K.iridescenceThicknessMinimum);if(K.iridescenceThicknessMaximum!==void 0)W.setIridescenceThicknessMaximum(K.iridescenceThicknessMaximum);if(K.iridescenceTexture!==void 0){let G=K.iridescenceTexture,V=Z.textures[$[G.index].source];W.setIridescenceTexture(V),Z.setTextureInfo(W.getIridescenceTextureInfo(),G)}if(K.iridescenceThicknessTexture!==void 0){let G=K.iridescenceThicknessTexture,V=Z.textures[$[G.index].source];W.setIridescenceThicknessTexture(V),Z.setTextureInfo(W.getIridescenceThicknessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(zY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[zY]={};if($.getIridescenceFactor()>0)W.iridescenceFactor=$.getIridescenceFactor();if($.getIridescenceIOR()!==1.3)W.iridescenceIor=$.getIridescenceIOR();if($.getIridescenceThicknessMinimum()!==100)W.iridescenceThicknessMinimum=$.getIridescenceThicknessMinimum();if($.getIridescenceThicknessMaximum()!==400)W.iridescenceThicknessMaximum=$.getIridescenceThicknessMaximum();if($.getIridescenceTexture()){let K=$.getIridescenceTexture(),G=$.getIridescenceTextureInfo();W.iridescenceTexture=Z.createTextureInfoDef(K,G)}if($.getIridescenceThicknessTexture()){let K=$.getIridescenceThicknessTexture(),G=$.getIridescenceThicknessTextureInfo();W.iridescenceThicknessTexture=Z.createTextureInfoDef(K,G)}}}),this}}HP.EXTENSION_NAME=zY;var{R:Li,G:wi,B:Oi,A:Ni}=A7;class qP extends c5{init(){this.extensionName=cD,this.propertyType="PBRSpecularGlossiness",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseFactor:[1,1,1,1],diffuseTexture:null,diffuseTextureInfo:new R5(this.graph,"diffuseTextureInfo"),specularFactor:[1,1,1],glossinessFactor:1,specularGlossinessTexture:null,specularGlossinessTextureInfo:new R5(this.graph,"specularGlossinessTextureInfo")})}getDiffuseFactor(){return this.get("diffuseFactor")}setDiffuseFactor(Z){return this.set("diffuseFactor",Z)}getDiffuseTexture(){return this.getRef("diffuseTexture")}getDiffuseTextureInfo(){return this.getRef("diffuseTexture")?this.getRef("diffuseTextureInfo"):null}setDiffuseTexture(Z){return this.setRef("diffuseTexture",Z,{channels:Li|wi|Oi|Ni,isColor:!0})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(Z){return this.set("specularFactor",Z)}getGlossinessFactor(){return this.get("glossinessFactor")}setGlossinessFactor(Z){return this.set("glossinessFactor",Z)}getSpecularGlossinessTexture(){return this.getRef("specularGlossinessTexture")}getSpecularGlossinessTextureInfo(){return this.getRef("specularGlossinessTexture")?this.getRef("specularGlossinessTextureInfo"):null}setSpecularGlossinessTexture(Z){return this.setRef("specularGlossinessTexture",Z,{channels:Li|wi|Oi|Ni})}}qP.EXTENSION_NAME=cD;var FY=cD;class EU extends P5{constructor(...Z){super(...Z);this.extensionName=FY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createPBRSpecularGlossiness(){return new qP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[FY]){let W=this.createPBRSpecularGlossiness();Z.materials[Q].setExtension(FY,W);let K=Y.extensions[FY];if(K.diffuseFactor!==void 0)W.setDiffuseFactor(K.diffuseFactor);if(K.specularFactor!==void 0)W.setSpecularFactor(K.specularFactor);if(K.glossinessFactor!==void 0)W.setGlossinessFactor(K.glossinessFactor);if(K.diffuseTexture!==void 0){let G=K.diffuseTexture,V=Z.textures[$[G.index].source];W.setDiffuseTexture(V),Z.setTextureInfo(W.getDiffuseTextureInfo(),G)}if(K.specularGlossinessTexture!==void 0){let G=K.specularGlossinessTexture,V=Z.textures[$[G.index].source];W.setSpecularGlossinessTexture(V),Z.setTextureInfo(W.getSpecularGlossinessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(FY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[FY]={diffuseFactor:$.getDiffuseFactor(),specularFactor:$.getSpecularFactor(),glossinessFactor:$.getGlossinessFactor()};if($.getDiffuseTexture()){let K=$.getDiffuseTexture(),G=$.getDiffuseTextureInfo();W.diffuseTexture=Z.createTextureInfoDef(K,G)}if($.getSpecularGlossinessTexture()){let K=$.getSpecularGlossinessTexture(),G=$.getSpecularGlossinessTextureInfo();W.specularGlossinessTexture=Z.createTextureInfoDef(K,G)}}}),this}}EU.EXTENSION_NAME=FY;var{R:AU5,G:xU5,B:fU5,A:hU5}=A7;class zP extends c5{init(){this.extensionName=lD,this.propertyType="Sheen",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{sheenColorFactor:[0,0,0],sheenColorTexture:null,sheenColorTextureInfo:new R5(this.graph,"sheenColorTextureInfo"),sheenRoughnessFactor:0,sheenRoughnessTexture:null,sheenRoughnessTextureInfo:new R5(this.graph,"sheenRoughnessTextureInfo")})}getSheenColorFactor(){return this.get("sheenColorFactor")}setSheenColorFactor(Z){return this.set("sheenColorFactor",Z)}getSheenColorTexture(){return this.getRef("sheenColorTexture")}getSheenColorTextureInfo(){return this.getRef("sheenColorTexture")?this.getRef("sheenColorTextureInfo"):null}setSheenColorTexture(Z){return this.setRef("sheenColorTexture",Z,{channels:AU5|xU5|fU5,isColor:!0})}getSheenRoughnessFactor(){return this.get("sheenRoughnessFactor")}setSheenRoughnessFactor(Z){return this.set("sheenRoughnessFactor",Z)}getSheenRoughnessTexture(){return this.getRef("sheenRoughnessTexture")}getSheenRoughnessTextureInfo(){return this.getRef("sheenRoughnessTexture")?this.getRef("sheenRoughnessTextureInfo"):null}setSheenRoughnessTexture(Z){return this.setRef("sheenRoughnessTexture",Z,{channels:hU5})}}zP.EXTENSION_NAME=lD;var UY=lD;class FP extends P5{constructor(...Z){super(...Z);this.extensionName=UY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createSheen(){return new zP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[UY]){let W=this.createSheen();Z.materials[Q].setExtension(UY,W);let K=Y.extensions[UY];if(K.sheenColorFactor!==void 0)W.setSheenColorFactor(K.sheenColorFactor);if(K.sheenRoughnessFactor!==void 0)W.setSheenRoughnessFactor(K.sheenRoughnessFactor);if(K.sheenColorTexture!==void 0){let G=K.sheenColorTexture,V=Z.textures[$[G.index].source];W.setSheenColorTexture(V),Z.setTextureInfo(W.getSheenColorTextureInfo(),G)}if(K.sheenRoughnessTexture!==void 0){let G=K.sheenRoughnessTexture,V=Z.textures[$[G.index].source];W.setSheenRoughnessTexture(V),Z.setTextureInfo(W.getSheenRoughnessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(UY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[UY]={sheenColorFactor:$.getSheenColorFactor(),sheenRoughnessFactor:$.getSheenRoughnessFactor()};if($.getSheenColorTexture()){let K=$.getSheenColorTexture(),G=$.getSheenColorTextureInfo();W.sheenColorTexture=Z.createTextureInfoDef(K,G)}if($.getSheenRoughnessTexture()){let K=$.getSheenRoughnessTexture(),G=$.getSheenRoughnessTextureInfo();W.sheenRoughnessTexture=Z.createTextureInfoDef(K,G)}}}),this}}FP.EXTENSION_NAME=UY;var{R:bU5,G:yU5,B:gU5,A:mU5}=A7;class UP extends c5{init(){this.extensionName=pD,this.propertyType="Specular",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{specularFactor:1,specularTexture:null,specularTextureInfo:new R5(this.graph,"specularTextureInfo"),specularColorFactor:[1,1,1],specularColorTexture:null,specularColorTextureInfo:new R5(this.graph,"specularColorTextureInfo")})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(Z){return this.set("specularFactor",Z)}getSpecularColorFactor(){return this.get("specularColorFactor")}setSpecularColorFactor(Z){return this.set("specularColorFactor",Z)}getSpecularTexture(){return this.getRef("specularTexture")}getSpecularTextureInfo(){return this.getRef("specularTexture")?this.getRef("specularTextureInfo"):null}setSpecularTexture(Z){return this.setRef("specularTexture",Z,{channels:mU5})}getSpecularColorTexture(){return this.getRef("specularColorTexture")}getSpecularColorTextureInfo(){return this.getRef("specularColorTexture")?this.getRef("specularColorTextureInfo"):null}setSpecularColorTexture(Z){return this.setRef("specularColorTexture",Z,{channels:bU5|yU5|gU5,isColor:!0})}}UP.EXTENSION_NAME=pD;var BY=pD;class IU extends P5{constructor(...Z){super(...Z);this.extensionName=BY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createSpecular(){return new UP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[BY]){let W=this.createSpecular();Z.materials[Q].setExtension(BY,W);let K=Y.extensions[BY];if(K.specularFactor!==void 0)W.setSpecularFactor(K.specularFactor);if(K.specularColorFactor!==void 0)W.setSpecularColorFactor(K.specularColorFactor);if(K.specularTexture!==void 0){let G=K.specularTexture,V=Z.textures[$[G.index].source];W.setSpecularTexture(V),Z.setTextureInfo(W.getSpecularTextureInfo(),G)}if(K.specularColorTexture!==void 0){let G=K.specularColorTexture,V=Z.textures[$[G.index].source];W.setSpecularColorTexture(V),Z.setTextureInfo(W.getSpecularColorTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(BY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[BY]={};if($.getSpecularFactor()!==1)W.specularFactor=$.getSpecularFactor();if(!$8.eq($.getSpecularColorFactor(),[1,1,1]))W.specularColorFactor=$.getSpecularColorFactor();if($.getSpecularTexture()){let K=$.getSpecularTexture(),G=$.getSpecularTextureInfo();W.specularTexture=Z.createTextureInfoDef(K,G)}if($.getSpecularColorTexture()){let K=$.getSpecularColorTexture(),G=$.getSpecularColorTextureInfo();W.specularColorTexture=Z.createTextureInfoDef(K,G)}}}),this}}IU.EXTENSION_NAME=BY;var{R:dU5}=A7;class BP extends c5{init(){this.extensionName=iD,this.propertyType="Transmission",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{transmissionFactor:0,transmissionTexture:null,transmissionTextureInfo:new R5(this.graph,"transmissionTextureInfo")})}getTransmissionFactor(){return this.get("transmissionFactor")}setTransmissionFactor(Z){return this.set("transmissionFactor",Z)}getTransmissionTexture(){return this.getRef("transmissionTexture")}getTransmissionTextureInfo(){return this.getRef("transmissionTexture")?this.getRef("transmissionTextureInfo"):null}setTransmissionTexture(Z){return this.setRef("transmissionTexture",Z,{channels:dU5})}}BP.EXTENSION_NAME=iD;var LY=iD;class LP extends P5{constructor(...Z){super(...Z);this.extensionName=LY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createTransmission(){return new BP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[LY]){let W=this.createTransmission();Z.materials[Q].setExtension(LY,W);let K=Y.extensions[LY];if(K.transmissionFactor!==void 0)W.setTransmissionFactor(K.transmissionFactor);if(K.transmissionTexture!==void 0){let G=K.transmissionTexture,V=Z.textures[$[G.index].source];W.setTransmissionTexture(V),Z.setTextureInfo(W.getTransmissionTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(LY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[LY]={transmissionFactor:$.getTransmissionFactor()};if($.getTransmissionTexture()){let K=$.getTransmissionTexture(),G=$.getTransmissionTextureInfo();W.transmissionTexture=Z.createTextureInfoDef(K,G)}}}),this}}LP.EXTENSION_NAME=LY;class wP extends c5{init(){this.extensionName=nD,this.propertyType="Unlit",this.parentTypes=[s.MATERIAL]}}wP.EXTENSION_NAME=nD;var mW=nD;class vU extends P5{constructor(...Z){super(...Z);this.extensionName=mW,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createUnlit(){return new wP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((X,$)=>{if(X.extensions&&X.extensions[mW])Z.materials[$].setExtension(mW,this.createUnlit())}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{if(X.getExtension(mW)){let $=Z.materialIndexMap.get(X),Y=J.json.materials[$];Y.extensions=Y.extensions||{},Y.extensions[mW]={}}}),this}}vU.EXTENSION_NAME=mW;class OP extends c5{init(){this.extensionName=NY,this.propertyType="Mapping",this.parentTypes=["MappingList"]}getDefaults(){return Object.assign(super.getDefaults(),{material:null,variants:new I0})}getMaterial(){return this.getRef("material")}setMaterial(Z){return this.setRef("material",Z)}addVariant(Z){return this.addRef("variants",Z)}removeVariant(Z){return this.removeRef("variants",Z)}listVariants(){return this.listRefs("variants")}}OP.EXTENSION_NAME=NY;class NP extends c5{init(){this.extensionName=NY,this.propertyType="MappingList",this.parentTypes=[s.PRIMITIVE]}getDefaults(){return Object.assign(super.getDefaults(),{mappings:new I0})}addMapping(Z){return this.addRef("mappings",Z)}removeMapping(Z){return this.removeRef("mappings",Z)}listMappings(){return this.listRefs("mappings")}}NP.EXTENSION_NAME=NY;class DU extends c5{init(){this.extensionName=NY,this.propertyType="Variant",this.parentTypes=["MappingList"]}}DU.EXTENSION_NAME=NY;var JJ=NY;class jP extends P5{constructor(...Z){super(...Z);this.extensionName=JJ}createMappingList(){return new NP(this.document.getGraph())}createVariant(Z=""){return new DU(this.document.getGraph(),Z)}createMapping(){return new OP(this.document.getGraph())}listVariants(){return Array.from(this.properties).filter((Z)=>Z instanceof DU)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[JJ])return this;let Y=(J.json.extensions[JJ].variants||[]).map((W)=>this.createVariant().setName(W.name||""));return(J.json.meshes||[]).forEach((W,K)=>{let G=Z.meshes[K];(W.primitives||[]).forEach((H,q)=>{if(!H.extensions||!H.extensions[JJ])return;let z=this.createMappingList(),F=H.extensions[JJ];for(let U of F.mappings){let L=this.createMapping();if(U.material!==void 0)L.setMaterial(Z.materials[U.material]);for(let B of U.variants||[])L.addVariant(Y[B]);z.addMapping(L)}G.listPrimitives()[q].setExtension(JJ,z)})}),this}write(Z){let J=Z.jsonDoc,X=this.listVariants();if(!X.length)return this;let $=[],Y=new Map;for(let Q of X)Y.set(Q,$.length),$.push(Z.createPropertyDef(Q));for(let Q of this.document.getRoot().listMeshes()){let W=Z.meshIndexMap.get(Q);Q.listPrimitives().forEach((K,G)=>{let V=K.getExtension(JJ);if(!V)return;let H=Z.jsonDoc.json.meshes[W].primitives[G],q=V.listMappings().map((z)=>{let F=Z.createPropertyDef(z),U=z.getMaterial();if(U)F.material=Z.materialIndexMap.get(U);return F.variants=z.listVariants().map((L)=>Y.get(L)),F});H.extensions=H.extensions||{},H.extensions[JJ]={mappings:q}})}return J.json.extensions=J.json.extensions||{},J.json.extensions[JJ]={variants:$},this}}jP.EXTENSION_NAME=JJ;var{G:uU5}=A7;class MP extends c5{init(){this.extensionName=sD,this.propertyType="Volume",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{thicknessFactor:0,thicknessTexture:null,thicknessTextureInfo:new R5(this.graph,"thicknessTexture"),attenuationDistance:1/0,attenuationColor:[1,1,1]})}getThicknessFactor(){return this.get("thicknessFactor")}setThicknessFactor(Z){return this.set("thicknessFactor",Z)}getThicknessTexture(){return this.getRef("thicknessTexture")}getThicknessTextureInfo(){return this.getRef("thicknessTexture")?this.getRef("thicknessTextureInfo"):null}setThicknessTexture(Z){return this.setRef("thicknessTexture",Z,{channels:uU5})}getAttenuationDistance(){return this.get("attenuationDistance")}setAttenuationDistance(Z){return this.set("attenuationDistance",Z)}getAttenuationColor(){return this.get("attenuationColor")}setAttenuationColor(Z){return this.set("attenuationColor",Z)}}MP.EXTENSION_NAME=sD;var wY=sD;class RP extends P5{constructor(...Z){super(...Z);this.extensionName=wY,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createVolume(){return new MP(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[wY]){let W=this.createVolume();Z.materials[Q].setExtension(wY,W);let K=Y.extensions[wY];if(K.thicknessFactor!==void 0)W.setThicknessFactor(K.thicknessFactor);if(K.attenuationDistance!==void 0)W.setAttenuationDistance(K.attenuationDistance);if(K.attenuationColor!==void 0)W.setAttenuationColor(K.attenuationColor);if(K.thicknessTexture!==void 0){let G=K.thicknessTexture,V=Z.textures[$[G.index].source];W.setThicknessTexture(V),Z.setTextureInfo(W.getThicknessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(wY);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let W=Q.extensions[wY]={};if($.getThicknessFactor()>0)W.thicknessFactor=$.getThicknessFactor();if(Number.isFinite($.getAttenuationDistance()))W.attenuationDistance=$.getAttenuationDistance();if(!$8.eq($.getAttenuationColor(),[1,1,1]))W.attenuationColor=$.getAttenuationColor();if($.getThicknessTexture()){let K=$.getThicknessTexture(),G=$.getThicknessTextureInfo();W.thicknessTexture=Z.createTextureInfoDef(K,G)}}}),this}}RP.EXTENSION_NAME=wY;var ki=$U5;class oG extends P5{constructor(...Z){super(...Z);this.extensionName=ki}read(Z){return this}write(Z){return this}}oG.EXTENSION_NAME=ki;var iG=YU5;class Ei{match(Z){return Z[0]===171&&Z[1]===75&&Z[2]===84&&Z[3]===88&&Z[4]===32&&Z[5]===50&&Z[6]===48&&Z[7]===187&&Z[8]===13&&Z[9]===10&&Z[10]===26&&Z[11]===10}getSize(Z){let J=jU(Z);return[J.pixelWidth,J.pixelHeight]}getChannels(Z){let X=jU(Z).dataFormatDescriptor[0];if(X.colorModel===Qi)return X.samples.length===2&&(X.samples[1].channelType&15)===15?4:3;else if(X.colorModel===Wi)return(X.samples[0].channelType&15)===3?4:3;throw new Error(`Unexpected KTX2 colorModel, "${X.colorModel}".`)}getVRAMByteLength(Z){let J=jU(Z),X=this.getChannels(Z)>3,$=0;for(let Y=0;Y<J.levels.length;Y++){let Q=J.levels[Y];if(Q.uncompressedByteLength)$+=Q.uncompressedByteLength;else{let W=Math.max(1,Math.floor(J.pixelWidth/Math.pow(2,Y))),K=Math.max(1,Math.floor(J.pixelHeight/Math.pow(2,Y))),G=X?16:8;$+=W/4*(K/4)*G}}return $}}class DP extends P5{constructor(...Z){super(...Z);this.extensionName=iG,this.prereadTypes=[s.TEXTURE]}static register(){GZ.registerFormat("image/ktx2",new Ei)}preread(Z){return Z.jsonDoc.json.textures.forEach((J)=>{if(J.extensions&&J.extensions[iG]){let X=J.extensions[iG];J.source=X.source}}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/ktx2"){let $=Z.imageIndexMap.get(X);J.json.textures.forEach((Y)=>{if(Y.source===$)Y.extensions=Y.extensions||{},Y.extensions[iG]={source:Y.source},delete Y.source})}}),this}}DP.EXTENSION_NAME=iG;class PP extends c5{init(){this.extensionName=aD,this.propertyType="Transform",this.parentTypes=[s.TEXTURE_INFO]}getDefaults(){return Object.assign(super.getDefaults(),{offset:[0,0],rotation:0,scale:[1,1],texCoord:null})}getOffset(){return this.get("offset")}setOffset(Z){return this.set("offset",Z)}getRotation(){return this.get("rotation")}setRotation(Z){return this.set("rotation",Z)}getScale(){return this.get("scale")}setScale(Z){return this.set("scale",Z)}getTexCoord(){return this.get("texCoord")}setTexCoord(Z){return this.set("texCoord",Z)}}PP.EXTENSION_NAME=aD;var OY=aD;class CP extends P5{constructor(...Z){super(...Z);this.extensionName=OY}createTransform(){return new PP(this.document.getGraph())}read(Z){for(let[J,X]of Array.from(Z.textureInfos.entries())){if(!X.extensions||!X.extensions[OY])continue;let $=this.createTransform(),Y=X.extensions[OY];if(Y.offset!==void 0)$.setOffset(Y.offset);if(Y.rotation!==void 0)$.setRotation(Y.rotation);if(Y.scale!==void 0)$.setScale(Y.scale);if(Y.texCoord!==void 0)$.setTexCoord(Y.texCoord);J.setExtension(OY,$)}return this}write(Z){let J=Array.from(Z.textureInfoDefMap.entries());for(let[X,$]of J){let Y=X.getExtension(OY);if(!Y)continue;$.extensions=$.extensions||{};let Q={},W=$8.eq;if(!W(Y.getOffset(),[0,0]))Q.offset=Y.getOffset();if(Y.getRotation()!==0)Q.rotation=Y.getRotation();if(!W(Y.getScale(),[1,1]))Q.scale=Y.getScale();if(Y.getTexCoord()!=null)Q.texCoord=Y.getTexCoord();$.extensions[OY]=Q}return this}}CP.EXTENSION_NAME=OY;var cU5=[s.ROOT,s.SCENE,s.NODE,s.MESH,s.MATERIAL,s.TEXTURE,s.ANIMATION];class TP extends c5{init(){this.extensionName=MU,this.propertyType="Packet",this.parentTypes=cU5}getDefaults(){return Object.assign(super.getDefaults(),{context:{},properties:{}})}getContext(){return this.get("context")}setContext(Z){return this.set("context",oJ({},Z))}listProperties(){return Object.keys(this.get("properties"))}getProperty(Z){let J=this.get("properties");return Z in J?J[Z]:null}setProperty(Z,J){this._assertContext(Z);let X=oJ({},this.get("properties"));if(J)X[Z]=J;else delete X[Z];return this.set("properties",X)}toJSONLD(){let Z=vD(this.get("context")),J=vD(this.get("properties"));return oJ({"@context":Z},J)}fromJSONLD(Z){Z=vD(Z);let J=Z["@context"];if(J)this.set("context",J);return delete Z["@context"],this.set("properties",Z)}_assertContext(Z){if(!(Z.split(":")[0]in this.get("context")))throw new Error(`${MU}: Missing context for term, "${Z}".`)}}TP.EXTENSION_NAME=MU;function vD(Z){return JSON.parse(JSON.stringify(Z))}var rJ=MU;class kP extends P5{constructor(...Z){super(...Z);this.extensionName=rJ}createPacket(){return new TP(this.document.getGraph())}listPackets(){return Array.from(this.properties)}read(Z){var J;let X=(J=Z.jsonDoc.json.extensions)==null?void 0:J[rJ];if(!X||!X.packets)return this;let $=Z.jsonDoc.json,Y=this.document.getRoot(),Q=X.packets.map((G)=>this.createPacket().fromJSONLD(G)),W=[[$.asset],$.scenes,$.nodes,$.meshes,$.materials,$.images,$.animations],K=[[Y],Y.listScenes(),Y.listNodes(),Y.listMeshes(),Y.listMaterials(),Y.listTextures(),Y.listAnimations()];for(let G=0;G<W.length;G++){let V=W[G]||[];for(let H=0;H<V.length;H++){let q=V[H];if(q.extensions&&q.extensions[rJ]){let z=q.extensions[rJ];K[G][H].setExtension(rJ,Q[z.packet])}}}return this}write(Z){let{json:J}=Z.jsonDoc,X=[];for(let $ of this.properties){X.push($.toJSONLD());for(let Y of $.listParents()){let Q;switch(Y.propertyType){case s.ROOT:Q=J.asset;break;case s.SCENE:Q=J.scenes[Z.sceneIndexMap.get(Y)];break;case s.NODE:Q=J.nodes[Z.nodeIndexMap.get(Y)];break;case s.MESH:Q=J.meshes[Z.meshIndexMap.get(Y)];break;case s.MATERIAL:Q=J.materials[Z.materialIndexMap.get(Y)];break;case s.TEXTURE:Q=J.images[Z.imageIndexMap.get(Y)];break;case s.ANIMATION:Q=J.animations[Z.animationIndexMap.get(Y)];break;default:Q=null,this.document.getLogger().warn(`[${rJ}]: Unsupported parent property, "${Y.propertyType}"`);break}if(!Q)continue;Q.extensions=Q.extensions||{},Q.extensions[rJ]={packet:X.length-1}}}if(X.length>0)J.extensions=J.extensions||{},J.extensions[rJ]={packets:X};return this}}kP.EXTENSION_NAME=rJ;var lU5=[rG,oD,eD,JP,$P,QP,KP,kU,HP,EU,IU,FP,LP,vU,jP,RP,oG,DP,CP,kP],_V6=[PU,aG,CU,TU,...lU5];var pU5=e(cR(),1);function pW(){return pW=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)({}).hasOwnProperty.call(X,$)&&(Z[$]=X[$])}return Z},pW.apply(null,arguments)}var{POINTS:Ii,LINES:SU,LINE_STRIP:iU5,LINE_LOOP:nU5,TRIANGLES:_U,TRIANGLE_STRIP:sU5,TRIANGLE_FAN:aU5}=O8.Mode;function BX(Z,J){return Object.defineProperty(J,"name",{value:Z}),J}function XJ(Z,J){let X=pW({},Z);for(let $ in J)if(J[$]!==void 0)X[$]=J[$];return X}function ai(Z){let J=Z.getIndices(),X=Z.getAttribute("POSITION");switch(Z.getMode()){case O8.Mode.POINTS:return J?J.getCount():X.getCount();case O8.Mode.LINES:return J?J.getCount()/2:X.getCount()/2;case O8.Mode.LINE_LOOP:return J?J.getCount():X.getCount();case O8.Mode.LINE_STRIP:return J?J.getCount()-1:X.getCount()-1;case O8.Mode.TRIANGLES:return J?J.getCount()/3:X.getCount()/3;case O8.Mode.TRIANGLE_STRIP:case O8.Mode.TRIANGLE_FAN:return J?J.getCount()-2:X.getCount()-2;default:throw new Error("Unexpected mode: "+Z.getMode())}}var rU5=new Intl.NumberFormat(void 0,{maximumFractionDigits:0});function SP(Z){return rU5.format(Z)}function oU5(Z,J,X=2){let $=Z>J?"–":"+",Y="%";return $+(Math.abs(Z-J)/Z*100).toFixed(X)+"%"}function bU(Z,J){return`${SP(Z)} → ${SP(J)} (${oU5(Z,J)})`}function yP(Z){let J=[];for(let X of Z.listAttributes())J.push(X);for(let X of Z.listTargets())for(let $ of X.listAttributes())J.push($);return Array.from(new Set(J))}function tU5(Z,J,X){Z.swap(J,X);for(let $ of Z.listTargets())$.swap(J,X)}function eU5(Z,J){if(Z==null&&J==null)return!0;if(Z==null||J==null)return!1;if(Z.length!==J.length)return!1;for(let X=0;X<Z.length;X++)if(Z[X]!==J[X])return!1;return!0}function tJ(Z,J){return Z.createAccessor(J.getName()).setArray(J.getArray()).setType(J.getType()).setBuffer(J.getBuffer()).setNormalized(J.getNormalized()).setSparse(J.getSparse())}function ZB5(Z,J=Z){let X=gP(Z,J);for(let $=0;$<X.length;$++)X[$]=$;return X}function gP(Z,J=Z){return J<=65534?new Uint16Array(Z):new Uint32Array(Z)}function JB5(Z){return Z.listParents().some((J)=>J.propertyType!==n.ROOT)}function ri(Z){for(let J in Z)return!1;return!0}function oi(Z){let J=F6.fromGraph(Z.getGraph()),X=Z.getMaterial(),$=J.getRoot().listMaterials().indexOf(X),Y=$B5[Z.getMode()],Q=!!Z.getIndices(),W=Z.listSemantics().sort().map((G)=>{let V=Z.getAttribute(G),H=V.getElementSize(),q=V.getComponentType();return`${G}:${H}:${q}`}).join("+"),K=Z.listTargets().map((G)=>{return G.listSemantics().sort().map((V)=>{let H=Z.getAttribute(V),q=H.getElementSize(),z=H.getComponentType();return`${V}:${q}:${z}`}).join("+")}).join("~");return`${$}|${Y}|${Q}|${W}|${K}`}function XB5(Z){return Math.pow(2,Math.ceil(Math.log(Z)/Math.LN2))}var $B5={[Ii]:Ii,[SU]:SU,[iU5]:SU,[nU5]:SU,[_U]:_U,[sU5]:_U,[aU5]:_U},cW="center",vi={pivot:"center"};function ti(Z=vi){let J=XJ(vi,Z);return BX(cW,(X)=>{let $=X.getLogger(),Y=X.getRoot(),Q=Y.listAnimations().length>0||Y.listSkins().length>0;X.getRoot().listScenes().forEach((W,K)=>{$.debug(`${cW}: Scene ${K+1} / ${Y.listScenes().length}.`);let G;if(typeof J.pivot==="string"){let H=hR(W);if(G=[(H.max[0]-H.min[0])/2+H.min[0],(H.max[1]-H.min[1])/2+H.min[1],(H.max[2]-H.min[2])/2+H.min[2]],J.pivot==="above")G[1]=H.max[1];if(J.pivot==="below")G[1]=H.min[1]}else G=J.pivot;$.debug(`${cW}: Pivot "${G.join(", ")}".`);let V=[-1*G[0],-1*G[1],-1*G[2]];if(Q){$.debug(`${cW}: Model contains animation or skin. Adding a wrapper node.`);let H=X.createNode("Pivot").setTranslation(V);W.listChildren().forEach((q)=>H.addChild(q)),W.addChild(H)}else $.debug(`${cW}: Skipping wrapper, offsetting all root nodes.`),W.listChildren().forEach((H)=>{let q=H.getTranslation();H.setTranslation([q[0]+V[0],q[1]+V[1],q[2]+V[2]])})}),$.debug(`${cW}: Complete.`)})}function YB5(Z){let J=new Set,X=Z,$;while($=X.getParentNode()){if(J.has($))throw new Error("Circular dependency in scene graph.");J.add($),X=$}return X.listParents().filter((Y)=>Y instanceof EW)}function QB5(Z){let J=YB5(Z),X=Z.getParentNode();if(!X)return Z;Z.setMatrix(Z.getWorldMatrix()),X.removeChild(Z);for(let $ of J)$.addChild(Z);return Z}var iW=typeof Float32Array!=="undefined"?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var Z=0,J=arguments.length;while(J--)Z+=arguments[J]*arguments[J];return Math.sqrt(Z)};function WB5(Z,J){var X=J[0],$=J[1],Y=J[2],Q=J[3],W=J[4],K=J[5],G=J[6],V=J[7],H=J[8],q=J[9],z=J[10],F=J[11],U=J[12],L=J[13],B=J[14],w=J[15],O=X*K-$*W,M=X*G-Y*W,N=X*V-Q*W,P=$*G-Y*K,D=$*V-Q*K,C=Y*V-Q*G,T=H*L-q*U,k=H*B-z*U,A=H*w-F*U,v=q*B-z*L,x=q*w-F*L,I=z*w-F*B,S=O*I-M*x+N*v+P*A-D*k+C*T;if(!S)return null;return S=1/S,Z[0]=(K*I-G*x+V*v)*S,Z[1]=(Y*x-$*I-Q*v)*S,Z[2]=(L*C-B*D+w*P)*S,Z[3]=(z*D-q*C-F*P)*S,Z[4]=(G*A-W*I-V*k)*S,Z[5]=(X*I-Y*A+Q*k)*S,Z[6]=(B*N-U*C-w*M)*S,Z[7]=(H*C-z*N+F*M)*S,Z[8]=(W*x-K*A+V*T)*S,Z[9]=($*A-X*x-Q*T)*S,Z[10]=(U*D-L*N+w*O)*S,Z[11]=(q*N-H*D-F*O)*S,Z[12]=(K*k-W*v-G*T)*S,Z[13]=(X*v-$*k+Y*T)*S,Z[14]=(L*M-U*P-B*O)*S,Z[15]=(H*P-q*M+z*O)*S,Z}function KB5(Z){var J=Z[0],X=Z[1],$=Z[2],Y=Z[3],Q=Z[4],W=Z[5],K=Z[6],G=Z[7],V=Z[8],H=Z[9],q=Z[10],z=Z[11],F=Z[12],U=Z[13],L=Z[14],B=Z[15],w=J*W-X*Q,O=J*K-$*Q,M=J*G-Y*Q,N=X*K-$*W,P=X*G-Y*W,D=$*G-Y*K,C=V*U-H*F,T=V*L-q*F,k=V*B-z*F,A=H*L-q*U,v=H*B-z*U,x=q*B-z*L;return w*x-O*v+M*A+N*k-P*T+D*C}function ei(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=J[3],K=J[4],G=J[5],V=J[6],H=J[7],q=J[8],z=J[9],F=J[10],U=J[11],L=J[12],B=J[13],w=J[14],O=J[15],M=X[0],N=X[1],P=X[2],D=X[3];return Z[0]=M*$+N*K+P*q+D*L,Z[1]=M*Y+N*G+P*z+D*B,Z[2]=M*Q+N*V+P*F+D*w,Z[3]=M*W+N*H+P*U+D*O,M=X[4],N=X[5],P=X[6],D=X[7],Z[4]=M*$+N*K+P*q+D*L,Z[5]=M*Y+N*G+P*z+D*B,Z[6]=M*Q+N*V+P*F+D*w,Z[7]=M*W+N*H+P*U+D*O,M=X[8],N=X[9],P=X[10],D=X[11],Z[8]=M*$+N*K+P*q+D*L,Z[9]=M*Y+N*G+P*z+D*B,Z[10]=M*Q+N*V+P*F+D*w,Z[11]=M*W+N*H+P*U+D*O,M=X[12],N=X[13],P=X[14],D=X[15],Z[12]=M*$+N*K+P*q+D*L,Z[13]=M*Y+N*G+P*z+D*B,Z[14]=M*Q+N*V+P*F+D*w,Z[15]=M*W+N*H+P*U+D*O,Z}function GB5(){var Z=new iW(9);if(iW!=Float32Array)Z[1]=0,Z[2]=0,Z[3]=0,Z[5]=0,Z[6]=0,Z[7]=0;return Z[0]=1,Z[4]=1,Z[8]=1,Z}function VB5(Z,J){return Z[0]=J[0],Z[1]=J[1],Z[2]=J[2],Z[3]=J[4],Z[4]=J[5],Z[5]=J[6],Z[6]=J[8],Z[7]=J[9],Z[8]=J[10],Z}function HB5(Z,J){if(Z===J){var X=J[1],$=J[2],Y=J[5];Z[1]=J[3],Z[2]=J[6],Z[3]=X,Z[5]=J[7],Z[6]=$,Z[7]=Y}else Z[0]=J[0],Z[1]=J[3],Z[2]=J[6],Z[3]=J[1],Z[4]=J[4],Z[5]=J[7],Z[6]=J[2],Z[7]=J[5],Z[8]=J[8];return Z}function qB5(Z,J){var X=J[0],$=J[1],Y=J[2],Q=J[3],W=J[4],K=J[5],G=J[6],V=J[7],H=J[8],q=H*W-K*V,z=-H*Q+K*G,F=V*Q-W*G,U=X*q+$*z+Y*F;if(!U)return null;return U=1/U,Z[0]=q*U,Z[1]=(-H*$+Y*V)*U,Z[2]=(K*$-Y*W)*U,Z[3]=z*U,Z[4]=(H*X-Y*G)*U,Z[5]=(-K*X+Y*Q)*U,Z[6]=F*U,Z[7]=(-V*X+$*G)*U,Z[8]=(W*X-$*Q)*U,Z}function yU(){var Z=new iW(3);if(iW!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function zB5(Z,J,X){return Z[0]=J[0]*X[0],Z[1]=J[1]*X[1],Z[2]=J[2]*X[2],Z}function Zn(Z,J){var X=J[0],$=J[1],Y=J[2],Q=X*X+$*$+Y*Y;if(Q>0)Q=1/Math.sqrt(Q);return Z[0]=J[0]*Q,Z[1]=J[1]*Q,Z[2]=J[2]*Q,Z}function FB5(Z,J,X){var $=J[0],Y=J[1],Q=J[2],W=X[3]*$+X[7]*Y+X[11]*Q+X[15];return W=W||1,Z[0]=(X[0]*$+X[4]*Y+X[8]*Q+X[12])/W,Z[1]=(X[1]*$+X[5]*Y+X[9]*Q+X[13])/W,Z[2]=(X[2]*$+X[6]*Y+X[10]*Q+X[14])/W,Z}function UB5(Z,J,X){var $=J[0],Y=J[1],Q=J[2];return Z[0]=$*X[0]+Y*X[3]+Q*X[6],Z[1]=$*X[1]+Y*X[4]+Q*X[7],Z[2]=$*X[2]+Y*X[5]+Q*X[8],Z}var BB5=zB5;(function(){var Z=yU();return function(J,X,$,Y,Q,W){var K,G;if(!X)X=3;if(!$)$=0;if(Y)G=Math.min(Y*X+$,J.length);else G=J.length;for(K=$;K<G;K+=X)Z[0]=J[K],Z[1]=J[K+1],Z[2]=J[K+2],Q(Z,Z,W),J[K]=Z[0],J[K+1]=Z[1],J[K+2]=Z[2];return J}})();var FX="dedup",EP={keepUniqueNames:!1,propertyTypes:[n.ACCESSOR,n.MESH,n.TEXTURE,n.MATERIAL,n.SKIN]};function Jn(Z=EP){let J=XJ(EP,Z),X=new Set(J.propertyTypes);for(let $ of J.propertyTypes)if(!EP.propertyTypes.includes($))throw new Error(`${FX}: Unsupported deduplication on type "${$}".`);return BX(FX,($)=>{let Y=$.getLogger();if(X.has(n.ACCESSOR))LB5($);if(X.has(n.TEXTURE))OB5($,J);if(X.has(n.MATERIAL))NB5($,J);if(X.has(n.MESH))wB5($,J);if(X.has(n.SKIN))jB5($,J);Y.debug(`${FX}: Complete.`)})}function LB5(Z){let J=Z.getLogger(),X=new Map,$=new Map,Y=new Map,Q=new Map,W=Z.getRoot().listMeshes();W.forEach((q)=>{q.listPrimitives().forEach((z)=>{z.listAttributes().forEach((F)=>K(F,$)),K(z.getIndices(),X)})});for(let q of Z.getRoot().listAnimations())for(let z of q.listSamplers())K(z.getInput(),Y),K(z.getOutput(),Q);function K(q,z){if(!q)return;let F=[q.getCount(),q.getType(),q.getComponentType(),q.getNormalized(),q.getSparse()].join(":"),U=z.get(F);if(!U)z.set(F,U=new Set);U.add(q)}function G(q,z){for(let F=0;F<q.length;F++){let U=q[F],L=r0.toView(U.getArray());if(z.has(U))continue;for(let B=F+1;B<q.length;B++){let w=q[B];if(z.has(w))continue;if(r0.equals(L,r0.toView(w.getArray())))z.set(w,U)}}}let V=0,H=new Map;for(let q of[$,X,Y,Q])for(let z of q.values())V+=z.size,G(Array.from(z),H);J.debug(`${FX}: Merged ${H.size} of ${V} accessors.`),W.forEach((q)=>{q.listPrimitives().forEach((z)=>{z.listAttributes().forEach((U)=>{if(H.has(U))z.swap(U,H.get(U))});let F=z.getIndices();if(F&&H.has(F))z.swap(F,H.get(F))})});for(let q of Z.getRoot().listAnimations())for(let z of q.listSamplers()){let F=z.getInput(),U=z.getOutput();if(F&&H.has(F))z.swap(F,H.get(F));if(U&&H.has(U))z.swap(U,H.get(U))}Array.from(H.keys()).forEach((q)=>q.dispose())}function wB5(Z,J){let X=Z.getLogger(),$=Z.getRoot(),Y=new Map;$.listAccessors().forEach((K,G)=>Y.set(K,G)),$.listMaterials().forEach((K,G)=>Y.set(K,G));let Q=$.listMeshes().length,W=new Map;for(let K of $.listMeshes()){let G=[];for(let H of K.listPrimitives())G.push(Xn(H,Y));let V="";if(J.keepUniqueNames)V+=K.getName()+";";if(V+=G.join(";"),W.has(V)){let H=W.get(V);K.listParents().forEach((q)=>{if(q.propertyType!==n.ROOT)q.swap(K,H)}),K.dispose()}else W.set(V,K)}X.debug(`${FX}: Merged ${Q-W.size} of ${Q} meshes.`)}function OB5(Z,J){let X=Z.getLogger(),$=Z.getRoot(),Y=$.listTextures(),Q=new Map;for(let W=0;W<Y.length;W++){let K=Y[W],G=K.getImage();if(Q.has(K))continue;for(let V=W+1;V<Y.length;V++){let H=Y[V],q=H.getImage();if(Q.has(H))continue;if(K.getMimeType()!==H.getMimeType())continue;if(J.keepUniqueNames&&K.getName()!==H.getName())continue;let z=K.getSize(),F=H.getSize();if(!z||!F)continue;if(z[0]!==F[0])continue;if(z[1]!==F[1])continue;if(!G||!q)continue;if(r0.equals(G,q))Q.set(H,K)}}X.debug(`${FX}: Merged ${Q.size} of ${$.listTextures().length} textures.`),Array.from(Q.entries()).forEach(([W,K])=>{W.listParents().forEach((G)=>{if(!(G instanceof ZY))G.swap(W,K)}),W.dispose()})}function NB5(Z,J){let X=Z.getLogger(),Y=Z.getRoot().listMaterials(),Q=new Map,W=new Map,K=new Set;if(!J.keepUniqueNames)K.add("name");for(let G=0;G<Y.length;G++){let V=Y[G];if(Q.has(V))continue;if(Si(V,W))continue;for(let H=G+1;H<Y.length;H++){let q=Y[H];if(Q.has(q))continue;if(Si(q,W))continue;if(V.equals(q,K))Q.set(q,V)}}X.debug(`${FX}: Merged ${Q.size} of ${Y.length} materials.`),Array.from(Q.entries()).forEach(([G,V])=>{G.listParents().forEach((H)=>{if(!(H instanceof ZY))H.swap(G,V)}),G.dispose()})}function jB5(Z,J){let X=Z.getLogger(),Y=Z.getRoot().listSkins(),Q=new Map,W=new Set(["joints"]);if(!J.keepUniqueNames)W.add("name");for(let K=0;K<Y.length;K++){let G=Y[K];if(Q.has(G))continue;for(let V=K+1;V<Y.length;V++){let H=Y[V];if(Q.has(H))continue;if(G.equals(H,W)&&eU5(G.listJoints(),H.listJoints()))Q.set(H,G)}}X.debug(`${FX}: Merged ${Q.size} of ${Y.length} skins.`),Array.from(Q.entries()).forEach(([K,G])=>{K.listParents().forEach((V)=>{if(!(V instanceof ZY))V.swap(K,G)}),K.dispose()})}function Xn(Z,J){let X=[];for(let $ of Z.listSemantics()){let Y=Z.getAttribute($);X.push($+":"+J.get(Y))}if(Z instanceof O8){let $=Z.getIndices();if($)X.push("indices:"+J.get($));let Y=Z.getMaterial();if(Y)X.push("material:"+J.get(Y));X.push("mode:"+Z.getMode());for(let Q of Z.listTargets())X.push("target:"+Xn(Q,J))}return X.join(",")}function Si(Z,J){if(J.has(Z))return J.get(Z);let X=Z.getGraph(),$=new Set,Y=X.listParentEdges(Z);while(Y.length>0){let Q=Y.pop();if(Q.getAttributes().modifyChild===!0)return J.set(Z,!0),!0;let W=Q.getChild();if($.has(W))continue;for(let K of X.listChildEdges(W))Y.push(K)}return J.set(Z,!1),!1}function $n(){var Z=new iW(4);if(iW!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0,Z[3]=0;return Z}function MB5(Z,J,X){return Z[0]=J[0]+X[0],Z[1]=J[1]+X[1],Z[2]=J[2]+X[2],Z[3]=J[3]+X[3],Z}function RB5(Z,J,X){return Z[0]=J[0]-X[0],Z[1]=J[1]-X[1],Z[2]=J[2]-X[2],Z[3]=J[3]-X[3],Z}function DB5(Z,J,X){return Z[0]=J[0]*X[0],Z[1]=J[1]*X[1],Z[2]=J[2]*X[2],Z[3]=J[3]*X[3],Z}function PB5(Z,J,X){return Z[0]=J[0]*X,Z[1]=J[1]*X,Z[2]=J[2]*X,Z[3]=J[3]*X,Z}function CB5(Z){var J=Z[0],X=Z[1],$=Z[2],Y=Z[3];return Math.hypot(J,X,$,Y)}var Yn=RB5,TB5=DB5,Qn=CB5;(function(){var Z=$n();return function(J,X,$,Y,Q,W){var K,G;if(!X)X=4;if(!$)$=0;if(Y)G=Math.min(Y*X+$,J.length);else G=J.length;for(K=$;K<G;K+=X)Z[0]=J[K],Z[1]=J[K+1],Z[2]=J[K+2],Z[3]=J[K+3],Q(Z,Z,W),J[K]=Z[0],J[K+1]=Z[1],J[K+2]=Z[2],J[K+3]=Z[3];return J}})();var kB5=/color|emissive|diffuse/i;function EB5(Z){return Z.getGraph().listParentEdges(Z).some((Y)=>{return Y.getAttributes().isColor||kB5.test(Y.getName())})?"srgb":null}function IB5(Z){let J=Z.getGraph(),X=new Set,$=new Set;function Y(Q){let W=new Set;for(let K of J.listChildEdges(Q))if(K.getChild()instanceof e$)W.add(K.getName()+"Info");for(let K of J.listChildEdges(Q)){let G=K.getChild();if(X.has(G))continue;if(X.add(G),G instanceof Q7&&W.has(K.getName()))$.add(G);else if(G instanceof kW)Y(G)}}return Y(Z),Array.from($)}function vB5(Z){let X=F6.fromGraph(Z.getGraph()).getRoot(),$=Z.getGraph().listParentEdges(Z).filter((Y)=>Y.getParent()!==X).map((Y)=>Y.getName());return Array.from(new Set($))}var lW="prune",_P=0.011764705882352941,_i={propertyTypes:[n.NODE,n.SKIN,n.MESH,n.CAMERA,n.PRIMITIVE,n.PRIMITIVE_TARGET,n.ANIMATION,n.MATERIAL,n.TEXTURE,n.ACCESSOR,n.BUFFER],keepLeaves:!1,keepAttributes:!1,keepIndices:!1,keepSolidTextures:!1,keepExtras:!1};function gU(Z=_i){let J=XJ(_i,Z),X=new Set(J.propertyTypes),$=J.keepExtras;return BX(lW,async(Y)=>{let Q=Y.getLogger(),W=Y.getRoot(),K=Y.getGraph(),G=new Wn,V=(H)=>G.dispose(H.target);if(K.addEventListener("node:dispose",V),X.has(n.MESH))for(let H of W.listMeshes()){if(H.listPrimitives().length>0)continue;H.dispose()}if(X.has(n.NODE)){if(!J.keepLeaves)for(let H of W.listScenes())Kn(K,H,$);for(let H of W.listNodes())U9(H,$)}if(X.has(n.SKIN))for(let H of W.listSkins())U9(H,$);if(X.has(n.MESH))for(let H of W.listMeshes())U9(H,$);if(X.has(n.CAMERA))for(let H of W.listCameras())U9(H,$);if(X.has(n.PRIMITIVE))Ai(K,n.PRIMITIVE,$);if(X.has(n.PRIMITIVE_TARGET))Ai(K,n.PRIMITIVE_TARGET,$);if(!J.keepAttributes&&X.has(n.ACCESSOR)){let H=new Map;for(let q of W.listMeshes())for(let z of q.listPrimitives()){let F=z.getMaterial();if(!F)continue;let U=Gn(Y,z,F),L=_B5(z,U);xi(z,L),z.listTargets().forEach((B)=>xi(B,L)),H.has(F)?H.get(F).add(z):H.set(F,new Set([z]))}for(let[q,z]of H)AB5(q,Array.from(z))}if(!J.keepIndices&&X.has(n.ACCESSOR))for(let H of W.listMeshes())for(let q of H.listPrimitives())SB5(q);if(X.has(n.ANIMATION))for(let H of W.listAnimations()){for(let q of H.listChannels())if(!q.getTargetNode())q.dispose();if(!H.listChannels().length){let q=H.listSamplers();U9(H,$),q.forEach((z)=>U9(z,$))}else H.listSamplers().forEach((q)=>U9(q,$))}if(X.has(n.MATERIAL))W.listMaterials().forEach((H)=>U9(H,$));if(X.has(n.TEXTURE)){if(W.listTextures().forEach((H)=>U9(H,$)),!J.keepSolidTextures)await xB5(Y)}if(X.has(n.ACCESSOR))W.listAccessors().forEach((H)=>U9(H,$));if(X.has(n.BUFFER))W.listBuffers().forEach((H)=>U9(H,$));if(K.removeEventListener("node:dispose",V),!G.empty()){let H=G.entries().map(([q,z])=>`${q} (${z})`).join(", ");Q.info(`${lW}: Removed types... ${H}`)}else Q.debug(`${lW}: No unused properties found.`);Q.debug(`${lW}: Complete.`)})}class Wn{constructor(){this.disposed={}}empty(){for(let Z in this.disposed)return!1;return!0}entries(){return Object.entries(this.disposed)}dispose(Z){this.disposed[Z.propertyType]=this.disposed[Z.propertyType]||0,this.disposed[Z.propertyType]++}}function U9(Z,J){let X=Z.listParents().filter((Y)=>!(Y instanceof ZY||Y instanceof o$)),$=J&&!ri(Z.getExtras());if(!X.length&&!$)Z.dispose()}function Ai(Z,J,X){for(let $ of Z.listEdges()){let Y=$.getParent();if(Y.propertyType===J)U9(Y,X)}}function Kn(Z,J,X){if(J.listChildren().forEach((W)=>Kn(Z,W,X)),J instanceof EW)return;let $=Z.listParentEdges(J).some((W)=>{let K=W.getParent().propertyType;return K!==n.ROOT&&K!==n.SCENE&&K!==n.NODE}),Y=Z.listChildren(J).length===0,Q=X&&!ri(J.getExtras());if(Y&&!$&&!Q)J.dispose()}function xi(Z,J){for(let X of J)Z.setAttribute(X,null)}function SB5(Z){let J=Z.getIndices(),X=J&&J.getArray(),$=Z.listAttributes()[0];if(!X||!$)return;if(J.getCount()!==$.getCount())return;for(let Y=0,Q=X.length;Y<Q;Y++)if(Y!==X[Y])return;Z.setIndices(null)}function _B5(Z,J){let X=[];for(let $ of Z.listSemantics())if($==="NORMAL"&&!J.has($))X.push($);else if($==="TANGENT"&&!J.has($))X.push($);else if($.startsWith("TEXCOORD_")&&!J.has($))X.push($);else if($.startsWith("COLOR_")&&$!=="COLOR_0")X.push($);return X}function Gn(Z,J,X,$=new Set){let Q=Z.getGraph().listChildEdges(X),W=new Set;for(let V of Q)if(V.getChild()instanceof e$)W.add(V.getName());for(let V of Q){let H=V.getName(),q=V.getChild();if(q instanceof Q7){if(W.has(H.replace(/Info$/,"")))$.add(`TEXCOORD_${q.getTexCoord()}`)}if(q instanceof e$&&H.match(/normalTexture/i))$.add("TANGENT");if(q instanceof kW)Gn(Z,J,q,$)}let K=X instanceof nZ&&!X.getExtension("KHR_materials_unlit"),G=J.getMode()===O8.Mode.POINTS;if(K&&!G)$.add("NORMAL");return $}function AB5(Z,J){let X=IB5(Z),$=new Set(X.map((G)=>G.getTexCoord())),Y=Array.from($).sort(),Q=new Map(Y.map((G,V)=>[G,V])),W=new Map(Y.map((G,V)=>[`TEXCOORD_${G}`,`TEXCOORD_${V}`]));for(let G of X){let V=G.getTexCoord();G.setTexCoord(Q.get(V))}for(let G of J){let V=G.listSemantics().filter((H)=>H.startsWith("TEXCOORD_")).sort();K(G,V),G.listTargets().forEach((H)=>K(H,V))}function K(G,V){for(let H of V){let q=G.getAttribute(H);if(!q)continue;let z=W.get(H);if(z===H)continue;G.setAttribute(z,q),G.setAttribute(H,null)}}}async function xB5(Z){let J=Z.getRoot(),X=Z.getGraph(),$=Z.getLogger(),Q=J.listTextures().map(async(W)=>{var K;let G=await hB5(W);if(!G)return;if(EB5(W)==="srgb")bR.convertSRGBToLinear(G,G);let V=W.getName()||W.getURI(),H=(K=W.getSize())==null?void 0:K.join("x"),q=vB5(W);for(let z of X.listParentEdges(W)){let F=z.getParent();if(F!==J&&fB5(F,G,z.getName(),$))z.dispose()}if(W.listParents().length===1)W.dispose(),$.debug(`${lW}: Removed solid-color texture "${V}" (${H}px ${q.join(", ")})`)});await Promise.all(Q)}function fB5(Z,J,X,$){if(Z instanceof nZ)switch(X){case"baseColorTexture":return Z.setBaseColorFactor(TB5(J,J,Z.getBaseColorFactor())),!0;case"emissiveTexture":return Z.setEmissiveFactor(BB5([0,0,0],J.slice(0,3),Z.getEmissiveFactor())),!0;case"occlusionTexture":return Math.abs(J[0]-1)<=_P;case"metallicRoughnessTexture":return Z.setRoughnessFactor(J[1]*Z.getRoughnessFactor()),Z.setMetallicFactor(J[2]*Z.getMetallicFactor()),!0;case"normalTexture":return Qn(Yn($n(),J,[0.5,0.5,1,1]))<=_P}return $.warn(`${lW}: Detected single-color ${X} texture. Pruning ${X} not yet supported.`),!1}async function hB5(Z){let J=await bB5(Z);if(!J)return null;let X=[1/0,1/0,1/0,1/0],$=[-1/0,-1/0,-1/0,-1/0],Y=[0,0,0,0],[Q,W]=J.shape;for(let K=0;K<Q;K++){for(let G=0;G<W;G++)for(let V=0;V<4;V++)X[V]=Math.min(X[V],J.get(K,G,V)),$[V]=Math.max($[V],J.get(K,G,V));if(Qn(Yn(Y,$,X))/255>_P)return null}return PB5(Y,MB5(Y,$,X),0.00196078431372549)}async function bB5(Z){try{return await np(Z.getImage(),Z.getMimeType())}catch(J){return null}}var zX=4294967295;class Vn{constructor(Z){this.attributes=[],this.u8=void 0,this.u32=void 0;let J=0;for(let X of yP(Z))J+=this._initAttribute(X);this.u8=new Uint8Array(J),this.u32=new Uint32Array(this.u8.buffer)}_initAttribute(Z){let J=Z.getArray(),X=new Uint8Array(J.buffer,J.byteOffset,J.byteLength),$=Z.getElementSize()*Z.getComponentSize(),Y=r0.padNumber($);return this.attributes.push({u8:X,byteStride:$,paddedByteStride:Y}),Y}hash(Z){let J=0;for(let{u8:X,byteStride:$,paddedByteStride:Y}of this.attributes){for(let Q=0;Q<Y;Q++)if(Q<$)this.u8[J+Q]=X[Z*$+Q];else this.u8[J+Q]=0;J+=Y}return yB5(0,this.u32)}equal(Z,J){for(let{u8:X,byteStride:$}of this.attributes)for(let Y=0;Y<$;Y++)if(X[Z*$+Y]!==X[J*$+Y])return!1;return!0}}function yB5(Z,J){for(let Y=0,Q=J.length;Y<Q;Y++){let W=J[Y];W=Math.imul(W,1540483477)>>>0,W=(W^W>>24)>>>0,W=Math.imul(W,1540483477)>>>0,Z=Math.imul(Z,1540483477)>>>0,Z=(Z^W)>>>0}return Z}function gB5(Z,J,X,$,Y=zX){let Q=J-1,K=X.hash($)&Q;for(let G=0;G<=Q;G++){let V=Z[K];if(V===Y||X.equal(V,$))return K;K=K+G+1&Q}throw new Error("Hash table full.")}var X6;(function(Z){Z.RENDER="render",Z.RENDER_CACHED="render-cached",Z.UPLOAD="upload",Z.UPLOAD_NAIVE="upload-naive",Z.DISTINCT="distinct",Z.DISTINCT_POSITION="distinct-position",Z.UNUSED="unused"})(X6||(X6={}));function UX(Z,J){let X=Z.getAttribute("POSITION"),$=Z.getIndices();switch(J){case X6.RENDER:return $?$.getCount():X.getCount();case X6.RENDER_CACHED:return $?new Set($.getArray()).size:X.getCount();case X6.UPLOAD_NAIVE:case X6.UPLOAD:return X.getCount();case X6.DISTINCT:case X6.DISTINCT_POSITION:return mB5(J);case X6.UNUSED:return $?X.getCount()-new Set($.getArray()).size:0;default:return dB5(J)}}function mB5(Z){throw new Error(`Not implemented: ${Z}`)}function dB5(Z){throw new Error(`Unexpected value: ${Z}`)}function eG(Z,J,X){let $=F6.fromGraph(Z.getGraph());if(!J||!X)[J,X]=uB5(Z);let Y=Z.getIndices(),Q=Y?Y.getArray():null,W=UX(Z,X6.RENDER),K=$.createAccessor(),G=W,V=gP(G,X);for(let q=0;q<G;q++)V[q]=J[Q?Q[q]:q];Z.setIndices(K.setArray(V));let H=yP(Z);for(let q of Z.listAttributes()){let z=tJ($,q);AP(q,Y,J,z,X),Z.swap(q,z)}for(let q of Z.listTargets())for(let z of q.listAttributes()){let F=tJ($,z);AP(z,Y,J,F,X),q.swap(z,F)}if(Y&&Y.listParents().length===1)Y.dispose();for(let q of H)if(q.listParents().length===1)q.dispose();return Z}function AP(Z,J,X,$,Y){let Q=Z.getElementSize(),W=Z.getArray(),K=J?J.getArray():null,G=J?J.getCount():Z.getCount(),V=new W.constructor(Y*Q),H=new Uint8Array(Y);for(let q=0;q<G;q++){let z=K?K[q]:q,F=X[z];if(H[F])continue;for(let U=0;U<Q;U++)V[F*Q+U]=W[z*Q+U];H[F]=1}return $.setArray(V)}function uB5(Z){let J=UX(Z,X6.UPLOAD),X=Z.getIndices(),$=X?X.getArray():null;if(!X||!$)return[ZB5(J,1e6),J];let Y=new Uint32Array(J).fill(zX),Q=0;for(let W=0;W<$.length;W++){let K=$[W];if(Y[K]===zX)Y[K]=Q++}return[Y,Q]}var xP="weld",xU={overwrite:!0,cleanup:!0};function mP(Z=xU){let J=XJ(xU,Z);return BX(xP,async(X)=>{let $=X.getLogger();for(let Y of X.getRoot().listMeshes()){for(let Q of Y.listPrimitives())if(mU(Q,J),UX(Q,X6.RENDER)===0)Q.dispose();if(Y.listPrimitives().length===0)Y.dispose()}if(J.cleanup)await X.transform(gU({propertyTypes:[n.ACCESSOR,n.NODE],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}),Jn({propertyTypes:[n.ACCESSOR]}));$.debug(`${xP}: Complete.`)})}function mU(Z,J=xU){let X=Z.getGraph(),Y=F6.fromGraph(X).getLogger(),Q=pW({},xU,J);if(Z.getIndices()&&!Q.overwrite)return;if(Z.getMode()===O8.Mode.POINTS)return;let W=Z.getAttribute("POSITION").getCount(),K=Z.getIndices(),G=K==null?void 0:K.getArray(),V=K?K.getCount():W,H=new Vn(Z),q=XB5(W+W/4),z=new Uint32Array(q).fill(zX),F=new Uint32Array(W).fill(zX),U=0;for(let L=0;L<V;L++){let B=G?G[L]:L;if(F[B]!==zX)continue;let w=gB5(z,q,H,B,zX),O=z[w];if(O===zX)z[w]=B,F[B]=U++;else F[B]=F[O]}Y.debug(`${xP}: ${bU(W,U)} vertices.`),eG(Z,F,U)}var{FLOAT:cB5}=f0.ComponentType;function Hn(Z,J){let X=Z.getAttribute("POSITION");if(X)fi(J,X);let $=Z.getAttribute("NORMAL");if($)hi(J,$);let Y=Z.getAttribute("TANGENT");if(Y)bi(J,Y);for(let Q of Z.listTargets()){let W=Q.getAttribute("POSITION");if(W)fi(J,W);let K=Q.getAttribute("NORMAL");if(K)hi(J,K);let G=Q.getAttribute("TANGENT");if(G)bi(J,G)}if(KB5(J)<0)lB5(Z)}function fi(Z,J){let X=J.getComponentType(),$=J.getNormalized(),Y=J.getArray(),Q=X===cB5?Y:new Float32Array(Y.length),W=yU();for(let K=0,G=J.getCount();K<G;K++){if($)W[0]=i0.decodeNormalizedInt(Y[K*3],X),W[1]=i0.decodeNormalizedInt(Y[K*3+1],X),W[2]=i0.decodeNormalizedInt(Y[K*3+2],X);else W[0]=Y[K*3],W[1]=Y[K*3+1],W[2]=Y[K*3+2];FB5(W,W,Z),Q[K*3]=W[0],Q[K*3+1]=W[1],Q[K*3+2]=W[2]}J.setArray(Q).setNormalized(!1)}function hi(Z,J){let X=J.getArray(),$=J.getNormalized(),Y=J.getComponentType(),Q=GB5();VB5(Q,Z),qB5(Q,Q),HB5(Q,Q);let W=yU();for(let K=0,G=J.getCount();K<G;K++){if($)W[0]=i0.decodeNormalizedInt(X[K*3],Y),W[1]=i0.decodeNormalizedInt(X[K*3+1],Y),W[2]=i0.decodeNormalizedInt(X[K*3+2],Y);else W[0]=X[K*3],W[1]=X[K*3+1],W[2]=X[K*3+2];if(UB5(W,W,Q),Zn(W,W),$)X[K*3]=i0.decodeNormalizedInt(W[0],Y),X[K*3+1]=i0.decodeNormalizedInt(W[1],Y),X[K*3+2]=i0.decodeNormalizedInt(W[2],Y);else X[K*3]=W[0],X[K*3+1]=W[1],X[K*3+2]=W[2]}}function bi(Z,J){let X=J.getArray(),$=J.getNormalized(),Y=J.getComponentType(),Q=yU();for(let W=0,K=J.getCount();W<K;W++){if($)Q[0]=i0.decodeNormalizedInt(X[W*4],Y),Q[1]=i0.decodeNormalizedInt(X[W*4+1],Y),Q[2]=i0.decodeNormalizedInt(X[W*4+2],Y);else Q[0]=X[W*4],Q[1]=X[W*4+1],Q[2]=X[W*4+2];if(Q[0]=Z[0]*Q[0]+Z[4]*Q[1]+Z[8]*Q[2],Q[1]=Z[1]*Q[0]+Z[5]*Q[1]+Z[9]*Q[2],Q[2]=Z[2]*Q[0]+Z[6]*Q[1]+Z[10]*Q[2],Zn(Q,Q),$)X[W*4]=i0.decodeNormalizedInt(Q[0],Y),X[W*4+1]=i0.decodeNormalizedInt(Q[1],Y),X[W*4+2]=i0.decodeNormalizedInt(Q[2],Y);else X[W*4]=Q[0],X[W*4+1]=Q[1],X[W*4+2]=Q[2]}}function lB5(Z){if(Z.getMode()!==O8.Mode.TRIANGLES)return;if(!Z.getIndices())mU(Z);let J=Z.getIndices();for(let X=0,$=J.getCount();X<$;X+=3){let Y=J.getScalar(X),Q=J.getScalar(X+2);J.setScalar(X,Q),J.setScalar(X+2,Y)}}function pB5(Z,J){for(let X of Z.listPrimitives()){let $=iB5(X,Z);if(X!==$)Z.removePrimitive(X).addPrimitive($)}for(let X of Z.listPrimitives())eG(X),Hn(X,J)}function iB5(Z,J){if(Z.listParents().some(($)=>$ instanceof IG&&$!==J))Z=Z.clone();for(let $ of Z.listTargets())if($.listParents().some((Q)=>Q instanceof O8&&Q!==Z))Z.removeTarget($).addTarget($.clone());return Z}var yi=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function qn(Z){let J=Z.getMesh(),X=Z.getMatrix();if(J&&!i0.eq(X,yi))pB5(J,X);for(let $ of Z.listChildren()){let Y=$.getMatrix();ei(Y,Y,X),$.setMatrix(Y)}return Z.setMatrix(yi)}var{LINES:nB5,LINE_STRIP:sB5,LINE_LOOP:aB5,TRIANGLES:rB5,TRIANGLE_STRIP:oB5,TRIANGLE_FAN:tB5}=O8.Mode;function eB5(Z){let J=Z.getGraph(),X=F6.fromGraph(J);if(!Z.getIndices())mU(Z);let $=Z.getIndices(),Y=$.getArray(),Q=ai(Z),K=new $X[$.getComponentType()](Q*2),G=Z.getMode();if(G===sB5)for(let H=0;H<Q;H++)K[H*2]=Y[H],K[H*2+1]=Y[H+1];else if(G===aB5)for(let H=0;H<Q;H++)if(H<Q-1)K[H*2]=Y[H],K[H*2+1]=Y[H+1];else K[H*2]=Y[H],K[H*2+1]=Y[0];else throw new Error("Only LINE_STRIP and LINE_LOOP may be converted to LINES.");Z.setMode(nB5);let V=X.getRoot();if($.listParents().some((H)=>H!==V&&H!==Z))Z.setIndices(tJ(X,$).setArray(K));else $.setArray(K)}function zn(Z){let J=Z.getGraph(),X=F6.fromGraph(J);if(!Z.getIndices())mU(Z);let $=Z.getIndices(),Y=$.getArray(),Q=ai(Z),K=new $X[$.getComponentType()](Q*3),G=Z.getMode();if(G===oB5)for(let H=0,q=Y.length;H<q-2;H++)if(H%2)K[H*3]=Y[H+1],K[H*3+1]=Y[H],K[H*3+2]=Y[H+2];else K[H*3]=Y[H],K[H*3+1]=Y[H+1],K[H*3+2]=Y[H+2];else if(G===tB5)for(let H=0;H<Q;H++)K[H*3]=Y[0],K[H*3+1]=Y[H+1],K[H*3+2]=Y[H+2];else throw new Error("Only TRIANGLE_STRIP and TRIANGLE_FAN may be converted to TRIANGLES.");Z.setMode(rB5);let V=X.getRoot();if($.listParents().some((H)=>H!==V&&H!==Z))Z.setIndices(tJ(X,$).setArray(K));else $.setArray(K)}var gi="dequantize",fU={pattern:/^((?!JOINTS_).)*$/};function Fn(Z=fU){let J=XJ(fU,Z);return BX(gi,(X)=>{let $=X.getLogger();for(let Y of X.getRoot().listMeshes())for(let Q of Y.listPrimitives())ZL5(Q,J);X.createExtension(oG).dispose(),$.debug(`${gi}: Complete.`)})}function ZL5(Z,J=fU){let X=XJ(fU,J);for(let $ of Z.listSemantics())if(X.pattern.test($))fP(Z.getAttribute($));for(let $ of Z.listTargets())for(let Y of $.listSemantics())if(X.pattern.test(Y))fP($.getAttribute(Y))}function fP(Z){let J=Z.getArray();if(!J)return;let X=hU(J,Z.getComponentType(),Z.getNormalized());Z.setArray(X).setNormalized(!1)}function hU(Z,J,X){let $=new Float32Array(Z.length);for(let Y=0,Q=Z.length;Y<Q;Y++)if(X)$[Y]=i0.decodeNormalizedInt(Z[Y],J);else $[Y]=Z[Y];return $}var{TEXTURE_INFO:Un,ROOT:yV6}=n;function Bn(Z){let J=new F6().setLogger(Z.getLogger()),X=dP(J,Z);return JL5(J,Z,X),J.getRoot().copy(Z.getRoot(),X),J}function JL5(Z,J,X){X||(X=dP(Z,J));for(let $ of J.getRoot().listExtensionsUsed()){let Y=Z.createExtension($.constructor);if($.isRequired())Y.setRequired(!0)}return XL5(Z,J,$L5(J),X)}function XL5(Z,J,X,$){$||($=dP(Z,J));let Y=new Map;for(let Q of X)if(!Y.has(Q)&&Q.propertyType!==Un)Y.set(Q,$(Q));for(let[Q,W]of Y.entries())W.copy(Q,$);return Y}function dP(Z,J){let X=new Map([[J.getRoot(),Z.getRoot()]]);return($)=>{if($.propertyType===Un)return $;let Y=X.get($);if(!Y)Y=new $.constructor(Z.getGraph()),X.set($,Y);return Y}}function $L5(Z){let J=new Set;for(let X of Z.getGraph().listEdges())J.add(X.getChild());return Array.from(J)}var IP="flatten",mi={cleanup:!0};function Ln(Z=mi){let J=XJ(mi,Z);return BX(IP,async(X)=>{let $=X.getRoot(),Y=X.getLogger(),Q=new Set;for(let V of $.listSkins())for(let H of V.listJoints())Q.add(H);let W=new Set;for(let V of $.listAnimations())for(let H of V.listChannels()){let q=H.getTargetNode();if(q&&H.getTargetPath()!=="weights")W.add(q)}let K=new Set,G=new Set;for(let V of $.listScenes())V.traverse((H)=>{let q=H.getParentNode();if(!q)return;if(Q.has(q)||K.has(q))K.add(H);if(W.has(q)||G.has(q))G.add(H)});for(let V of $.listScenes())V.traverse((H)=>{if(W.has(H))return;if(K.has(H))return;if(G.has(H))return;QB5(H)});if(W.size)Y.debug(`${IP}: Flattening node hierarchies with TRS animation not yet supported.`);if(J.cleanup)await X.transform(gU({propertyTypes:[n.NODE],keepLeaves:!1}));Y.debug(`${IP}: Complete.`)})}function wn(Z){return hR(Z)}var YL5={skipValidation:!1},di=4294967295,{LINE_STRIP:QL5,LINE_LOOP:WL5,TRIANGLE_STRIP:KL5,TRIANGLE_FAN:GL5}=O8.Mode;function VL5(Z,J={}){let X=XJ(YL5,J),$=Z[0],Y=F6.fromGraph($.getGraph());if(!X.skipValidation&&new Set(Z.map(oi)).size>1)throw new Error("Requires >=2 Primitives, sharing the same Material and Mode, with compatible vertex attributes and indices.");for(let F of Z)switch(F.getMode()){case QL5:case WL5:eB5(F);break;case KL5:case GL5:zn(F);break}let Q=[],W=new Uint32Array(Z.length),K=0,G=0;for(let F=0;F<Z.length;F++){let U=Z[F],L=U.getIndices(),B=U.getAttribute("POSITION").getCount(),w=L?L.getArray():null,O=L?L.getCount():B,M=new Uint32Array(B).fill(di);for(let N=0;N<O;N++){let P=w?w[N]:N;if(M[P]===di)M[P]=K++,W[F]++}Q.push(M),G+=O}let V=Y.createPrimitive().setMode($.getMode()).setMaterial($.getMaterial());for(let F of $.listSemantics()){let U=$.getAttribute(F),L=$X[U.getComponentType()],B=tJ(Y,U).setArray(new L(K*U.getElementSize()));V.setAttribute(F,B)}let H=$.getIndices(),q=H?tJ(Y,H).setArray(gP(G,K)):null;V.setIndices(q);let z=0;for(let F=0;F<Q.length;F++){let U=Z[F],L=U.getIndices(),B=L?L.getCount():-1,w=Q[F];if(L&&q)qL5(L,w,q,z),z+=B;for(let O of V.listSemantics()){let M=U.getAttribute(O),N=V.getAttribute(O);HL5(M,L,w,N)}}return V}function HL5(Z,J,X,$){let Y=Z.getElementSize(),Q=J?J.getArray():null,W=Z.getCount(),K=Z.getArray(),G=$.getArray(),V=new Uint8Array(Z.getCount());for(let H=0,q=J?J.getCount():W;H<q;H++){let z=Q?Q[H]:H,F=X[z];if(V[F])continue;for(let U=0;U<Y;U++)G[F*Y+U]=K[z*Y+U];V[F]=1}}function qL5(Z,J,X,$){let Y=Z.getCount(),Q=Z.getArray(),W=X.getArray();for(let K=0;K<Y;K++){let G=Q[K],V=J[G];W[$+K]=V}}var hP="join",{ROOT:zL5,NODE:FL5,MESH:UL5,PRIMITIVE:BL5,ACCESSOR:LL5}=n,vP=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],ui={keepMeshes:!1,keepNamed:!1,cleanup:!0};function On(Z=ui){let J=XJ(ui,Z);return BX(hP,async(X)=>{let $=X.getRoot(),Y=X.getLogger();for(let Q of $.listScenes())ci(X,Q,J),Q.traverse((W)=>ci(X,W,J));if(J.cleanup)await X.transform(gU({propertyTypes:[FL5,UL5,BL5,LL5],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}));Y.debug(`${hP}: Complete.`)})}function ci(Z,J,X){let $=Z.getLogger(),Y={},Q=J.listChildren();for(let G=0;G<Q.length;G++){let V=Q[G];if(V.listParents().some((z)=>z instanceof o$))continue;let q=V.getMesh();if(!q)continue;if(V.getExtension("EXT_mesh_gpu_instancing"))continue;if(V.getSkin())continue;for(let z of q.listPrimitives()){if(z.listTargets().length>0)continue;let F=z.getMaterial();if(F&&F.getExtension("KHR_materials_volume"))continue;eG(z),OL5(z);let U=oi(z),L=q.getName()||V.getName();if(X.keepMeshes||X.keepNamed&&L)U+=`|${G}`;if(!(U in Y))Y[U]={prims:[],primMeshes:[],primNodes:[],dstNode:V,dstMesh:void 0};let B=Y[U];B.prims.push(z),B.primNodes.push(V)}}let W=Object.values(Y).filter(({prims:G})=>G.length>1),K=new Set(W.flatMap((G)=>G.primNodes));for(let G of K){let V=G.getMesh();if(V.listParents().some((q)=>{return q.propertyType!==zL5&&G!==q}))G.setMesh(V.clone())}for(let G of W){let{dstNode:V,primNodes:H}=G;G.dstMesh=V.getMesh(),G.primMeshes=H.map((q)=>q.getMesh())}for(let G of W){let{prims:V,primNodes:H,primMeshes:q,dstNode:z,dstMesh:F}=G,U=z.getMatrix();for(let w=0;w<V.length;w++){let O=H[w],M=q[w],N=V[w];if(M.removePrimitive(N),JB5(N))N=V[w]=wL5(V[w]);if(O!==z)ei(vP,WB5(vP,U),O.getMatrix()),Hn(N,vP)}let L=VL5(V),B=L.listAttributes()[0].getCount();F.addPrimitive(L),$.debug(`${hP}: Joined Primitives (${V.length}) containing ${SP(B)} vertices under Node "${z.getName()}".`)}}function wL5(Z){let J=Z.clone();for(let $ of J.listSemantics())J.setAttribute($,J.getAttribute($).clone());let X=J.getIndices();if(X)J.setIndices(X.clone());return J}function OL5(Z){for(let J of["POSITION","NORMAL","TANGENT"]){let X=Z.getAttribute(J);if(X)fP(X)}}var{TRANSLATION:gV6,ROTATION:mV6,SCALE:dV6,WEIGHTS:uV6}=o$.TargetPath;var NL5={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12,normalizeWeights:!0,cleanup:!0};var cV6=pW({level:"high"},NL5);var jL5="unweld";function ML5(Z,J=new Map){let X=Z.getIndices();if(!X)return;let $=Z.getGraph(),Y=F6.fromGraph($),Q=Y.getLogger(),W=Z.getAttribute("POSITION").getCount();for(let G of Z.listAttributes())if(Z.swap(G,li(Y,G,X,J)),G.listParents().length===1)G.dispose();for(let G of Z.listTargets())for(let V of G.listAttributes())if(G.swap(V,li(Y,V,X,J)),V.listParents().length===1)V.dispose();let K=Z.getAttribute("POSITION").getCount();if(Q.debug(`${jL5}: ${bU(W,K)} vertices.`),Z.setIndices(null),X.listParents().length===1)X.dispose()}function li(Z,J,X,$){if($.has(J)&&$.get(J).has(X))return $.get(J).get(X);let Y=J.getArray(),W=new Y.constructor(X.getCount()*J.getElementSize()),K=X.getArray(),G=J.getElementSize();for(let H=0,q=X.getCount();H<q;H++)for(let z=0;z<G;z++)W[H*G+z]=Y[K[H]*G+z];if(!$.has(J))$.set(J,new Map);let V=tJ(Z,J).setArray(W);return $.get(J).set(X,V),V}var pi;(function(Z){Z[Z.STEP=0]="STEP",Z[Z.LERP=1]="LERP",Z[Z.SLERP=2]="SLERP"})(pi||(pi={}));var RL5=0.000001;function DL5(Z,J,X,$=0.0001){let Y=J.length/Z.length,Q=new Array(Y).fill(0),W=new Array(Y).fill(0),K=new Array(Y).fill(0),G=new Array(Y).fill(0),V=Z.length-1,H=1;for(let q=1;q<V;++q){let z=Z[H-1],F=Z[q],U=Z[q+1],L=(F-z)/(U-z),B=!1;if(F!==U&&(q!==1||F!==Z[0])){if(tG(J,H-1,G),tG(J,q,W),tG(J,q+1,K),X==="slerp"){let w=TL5(Q,G,K,L),O=ni(G,W)+ni(W,K);B=!AU(W,w,$)||O+Number.EPSILON>=Math.PI}else if(X==="lerp"){let w=CL5(Q,G,K,L);B=!AU(W,w,$)}else if(X==="step")B=!AU(W,G)||!AU(W,K)}if(B){if(q!==H)Z[H]=Z[q],ii(J,H,tG(J,q,Q));H++}}if(V>0)Z[H]=Z[V],ii(J,H,tG(J,V,Q)),H++;return H}function tG(Z,J,X){for(let $=0,Y=X.length;$<Y;$++)X[$]=Z[J*Y+$];return X}function ii(Z,J,X){for(let $=0,Y=X.length;$<Y;$++)Z[J*Y+$]=X[$]}function AU(Z,J,X=0){if(Z.length!==J.length)return!1;for(let $=0;$<Z.length;$++)if(Math.abs(Z[$]-J[$])>X)return!1;return!0}function PL5(Z,J,X){return Z*(1-X)+J*X}function CL5(Z,J,X,$){for(let Y=0;Y<J.length;Y++)Z[Y]=PL5(J[Y],X[Y],$);return Z}function TL5(Z,J,X,$){let Y=J[0],Q=J[1],W=J[2],K=J[3],G=X[0],V=X[1],H=X[2],q=X[3],z,F,U,L,B;if(F=Y*G+Q*V+W*H+K*q,F<0)F=-F,G=-G,V=-V,H=-H,q=-q;if(1-F>RL5)z=Math.acos(F),U=Math.sin(z),L=Math.sin((1-$)*z)/U,B=Math.sin($*z)/U;else L=1-$,B=$;return Z[0]=L*Y+B*G,Z[1]=L*Q+B*V,Z[2]=L*W+B*H,Z[3]=L*K+B*q,Z}function ni(Z,J){let X=kL5(Z,J);return Math.acos(2*X*X-1)}function kL5(Z,J){return Z[0]*J[0]+Z[1]*J[1]+Z[2]*J[2]+Z[3]*J[3]}var lV6=new Float32Array(0),pV6={ready:Promise.resolve(),resample:DL5,tolerance:0.0001,cleanup:!0};var jY="simplify",{POINTS:Nn,LINES:EL5,LINE_STRIP:IL5,LINE_LOOP:vL5,TRIANGLES:SL5,TRIANGLE_STRIP:jn,TRIANGLE_FAN:Mn}=O8.Mode,Rn={ratio:0,error:0.0001,lockBorder:!1,cleanup:!0};function Dn(Z){let J=XJ(Rn,Z),X=J.simplifier;if(!X)throw new Error(`${jY}: simplifier dependency required — install "meshoptimizer".`);return BX(jY,async($)=>{let Y=$.getLogger();await X.ready,await $.transform(mP({overwrite:!1,cleanup:J.cleanup}));let Q=0;for(let W of $.getRoot().listMeshes()){for(let K of W.listPrimitives()){let G=K.getMode();if(G===SL5||G===jn||G===Mn){if(si(K,J),UX(K,X6.RENDER)===0)K.dispose()}else if(K.getMode()===Nn&&!!X.simplifyPoints){if(si(K,J),UX(K,X6.RENDER)===0)K.dispose()}else Q++}if(W.listPrimitives().length===0)W.dispose()}if(Q>0)Y.warn(`${jY}: Skipping simplification of ${Q} primitives: Unsupported draw mode.`);if(J.cleanup)await $.transform(gU({propertyTypes:[n.ACCESSOR,n.NODE],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}),Jn({propertyTypes:[n.ACCESSOR]}));Y.debug(`${jY}: Complete.`)})}function si(Z,J){let X=pW({},Rn,J),$=X.simplifier,Y=Z.getGraph(),Q=F6.fromGraph(Y),W=Q.getLogger();switch(Z.getMode()){case Nn:return _L5(Q,Z,X);case EL5:case IL5:case vL5:return W.warn(`${jY}: Skipping primitive simplification: Unsupported draw mode.`),Z;case jn:case Mn:zn(Z);break}let K=UX(Z,X6.UPLOAD),G=UX(Z,X6.RENDER);if(G<K/2)eG(Z);let V=Z.getAttribute("POSITION"),H=Z.getIndices(),q=V.getArray(),z=H.getArray();if(!(q instanceof Float32Array))q=hU(q,V.getComponentType(),V.getNormalized());if(!(z instanceof Uint32Array))z=new Uint32Array(z);let F=Math.floor(X.ratio*G/3)*3,U=X.lockBorder?["LockBorder"]:[],[L,B]=$.simplify(z,q,3,F,X.error,U);if(Z.setIndices(tJ(Q,H).setArray(L)),H.listParents().length===1)H.dispose();eG(Z);let w=UX(Z,X6.UPLOAD);if(w<=65534)Z.getIndices().setArray(new Uint16Array(Z.getIndices().getArray()));return W.debug(`${jY}: ${bU(K,w)} vertices, error: ${B.toFixed(4)}.`),Z}function _L5(Z,J,X){let $=X.simplifier,Y=Z.getLogger();if(J.getIndices())ML5(J);let W=J.getAttribute("POSITION"),K=J.getAttribute("COLOR_0"),G=W.getCount(),V=W.getArray(),H=K?K.getArray():void 0,q=K?K.getComponentSize():void 0;if(!(V instanceof Float32Array))V=hU(V,W.getComponentType(),W.getNormalized());if(H&&!(H instanceof Float32Array))H=hU(H,W.getComponentType(),W.getNormalized());$.useExperimentalFeatures=!0;let z=Math.floor(X.ratio*G),F=$.simplifyPoints(V,3,z,H,q);$.useExperimentalFeatures=!1;let[U,L]=$.compactMesh(F);Y.debug(`${jY}: ${bU(W.getCount(),L)} vertices.`);for(let B of yP(J)){let w=tJ(Z,B);if(AP(B,null,U,w,L),tU5(J,B,w),B.listParents().length===1)B.dispose()}return J}var bP;(function(Z){Z.LANCZOS3="lanczos3",Z.LANCZOS2="lanczos2"})(bP||(bP={}));var iV6={resizeFilter:bP.LANCZOS3,pattern:void 0,formats:void 0,slots:void 0,quality:void 0,effort:void 0,lossless:!1,nearLossless:!1,limitInputPixels:!0};var vn=e(In(),1);var nW={OPTIMIZED_DIR:".optimized",CHECKSUM_EXT:".md5",DIRECTORIES:[(()=>{try{return x7.dirname(a.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js"))}catch{return null}})(),x7.resolve(process.cwd(),"assets")].filter(Boolean),OPTIMIZER_RUNS:[{suffix:"",options:["--compress","false","--instance","false","--simplify","false"]},{suffix:"-named-nodes",options:["--compress","false","--instance","false","--simplify","false","--join","true","--join-named","false"]}]};class V7{static instance=new V7;optimize=!0;optimizeEveryStart=!1;_modelUriDocuments=new Map;_modelUriBoundingBoxes=new Map;_modelUriNodeNames=new Map;_modelUriTrimeshes=new Map;constructor(){}async preloadModels(){let Z=await this._getAbsoluteModelPaths();console.log(`ModelRegistry.preloadModels(): Preloading ${Z.length} models...`);for(let J of Z){if(this.optimize)await this._resolveOptimizedModelPath(J);await this._loadModelData(J)}console.log(`ModelRegistry.preloadModels(): Preloaded ${Z.length} models!`)}getAnimationNames(Z){let J=this._modelUriDocuments.get(Z);if(!J)u.fatalError(`ModelRegistry.getAnimationNames(): Model ${Z} not found!`);return J.getRoot().listAnimations().map(($)=>$.getName())}getBoundingBox(Z){let J=this._modelUriBoundingBoxes.get(Z);if(!J)u.fatalError(`ModelRegistry.getBoundingBox(): Model ${Z} not found!`);return J}getDepth(Z){let J=this.getBoundingBox(Z);return J.max.z-J.min.z}getHeight(Z){let J=this.getBoundingBox(Z);return J.max.y-J.min.y}getNodeNames(Z){let J=this._modelUriNodeNames.get(Z);if(!J)u.fatalError(`ModelRegistry.getNodeNames(): Model ${Z} not found!`);return J}getTrimesh(Z,J=1){let X=this._modelUriTrimeshes.get(Z);if(!X){u.error(`ModelRegistry.getTrimesh(): Model ${Z} not found!`);return}let $=X.vertices;if(J!==1){$=new Float32Array($.length);for(let Y=0;Y<$.length;Y++)$[Y]=X.vertices[Y]*J}return{vertices:$,indices:X.indices}}getWidth(Z){let J=this.getBoundingBox(Z);return J.max.x-J.min.x}modelHasNode(Z,J){let X=this._modelUriNodeNames.get(Z);if(!X)u.fatalError(`ModelRegistry.modelHasNode(): Model ${Z} not found!`);return X.includes(J)}_absoluteModelPathToModelUri(Z){let J=x7.normalize(Z);for(let X of nW.DIRECTORIES){let $=x7.normalize(X);if(J.startsWith($))return x7.relative($,J).replace(/\\/g,"/")}return x7.basename(J)}async _getAbsoluteModelPaths(){let Z=[];for(let J of nW.DIRECTORIES){let X=x7.resolve(process.cwd(),J);if(!LX.existsSync(X))continue;let $=await kF("**/*.{gltf,glb}",{cwd:X,follow:!0});for(let Y of $)Z.push(x7.join(X,Y))}return Z}async _loadModelData(Z){let J=await new uR().read(Z),X=wn(J.getRoot().listScenes()[0]),$=J.getRoot().listNodes().map((Q)=>Q.getName()),Y=this._absoluteModelPathToModelUri(Z);this._modelUriDocuments.set(Y,J),this._modelUriBoundingBoxes.set(Y,{min:{x:X.min[0],y:X.min[1],z:X.min[2]},max:{x:X.max[0],y:X.max[1],z:X.max[2]}}),this._modelUriNodeNames.set(Y,$),this._modelUriTrimeshes.set(Y,await this._buildTrimesh(Y))}async _resolveOptimizedModelPath(Z){let J=this._buildOptimizedModelPath(Z);if(!this.optimizeEveryStart&&this._isOptimizedVersionValid(Z))return J;return await this._optimizeModel(Z,J)}_isOptimizedVersionValid(Z){let J=`${this._buildOptimizedModelPath(Z)}${nW.CHECKSUM_EXT}`;if(!LX.existsSync(J))return!1;let X=this._calculateChecksum(Z),$=LX.readFileSync(J,"utf8");return X===$}_calculateChecksum(Z){if(!LX.existsSync(Z))return"";let J=LX.readFileSync(Z);return bL5.createHash("sha256").update(J.toString("base64")).digest("hex")}_buildOptimizedModelPath(Z){let J=x7.basename(Z),X=J.replace(/\.[^/.]+$/,""),$=x7.dirname(Z),Y=x7.join($,nW.OPTIMIZED_DIR,X);return x7.join(Y,J)}async _buildTrimesh(Z,J=1,X=0.001){let $=this._modelUriDocuments.get(Z);if(!$)u.fatalError(`ModelRegistry._buildTrimesh(): Model ${Z} not found!`);let Y=Bn($);Y.setLogger(new W7(kG.WARN)),await Y.transform(ti({pivot:"center"}),Ln(),On(),mP(),Dn({simplifier:vn.MeshoptSimplifier,ratio:J,error:X}),Fn());for(let V of Y.getRoot().listScenes())for(let H of V.listChildren())qn(H);let Q=Y.getRoot().listMeshes()[0];if(!Q){u.error(`ModelRegistry._buildTrimesh(): Model ${Z} has no root mesh!`);return}let W=Q.listPrimitives()[0];if(!W){u.error(`ModelRegistry._buildTrimesh(): Model ${Z} has no root primitive!`);return}let K=W.getAttribute("POSITION"),G=W.getIndices();if(!K||!G){u.error(`ModelRegistry._buildTrimesh(): Model ${Z} missing required geometry data!`);return}return{vertices:K.getArray(),indices:G.getArray()}}async _optimizeModel(Z,J){let X=x7.dirname(J);LX.rmSync(X,{recursive:!0,force:!0}),LX.mkdirSync(X,{recursive:!0}),console.log(`ModelRegistry: Optimizing model ${this._absoluteModelPathToModelUri(Z)}...`);for(let $ of nW.OPTIMIZER_RUNS){let Y=J.replace(/(\.[^/.]+)$/,`${$.suffix}$1`),{stderr:Q}=await _d("npx",["@gltf-transform/cli","optimize",Z,Y,...$.options]);if(Q)return u.warning(`ModelRegistry._optimizeModel(): Error optimizing model ${this._absoluteModelPathToModelUri(Z)}, defaulting to unoptimized model. Error: ${Q}`),Z}return LX.writeFileSync(`${J}${nW.CHECKSUM_EXT}`,this._calculateChecksum(Z)),J}}var YV;((Y)=>{Y.DYNAMIC="dynamic";Y.FIXED="fixed";Y.KINEMATIC_POSITION="kinematic_position";Y.KINEMATIC_VELOCITY="kinematic_velocity"})(YV||={});var iP=0.001,Sn="dynamic";class MY extends D0{_additionalMass=0;_colliders=new Set;_explicitSleep=!1;_enabledPositions={x:!0,y:!0,z:!0};_enabledRotations={x:!0,y:!0,z:!0};_rigidBody;_rigidBodyDesc;_rigidBodyType;_simulation;constructor(Z){super();Z.type??=Sn,this._rigidBodyDesc=this._createRigidBodyDesc(Z),this._rigidBodyType=Z.type,this._applyRigidBodyOptions(Z),this._autoAddToSimulation(Z)}get additionalMass(){if(!this._requireNotRemoved("additionalMass"))return 0;return this._additionalMass}get additionalSolverIterations(){if(!this._requireNotRemoved("additionalSolverIterations"))return 0;return this._rigidBody?this._rigidBody.additionalSolverIterations():this._rigidBodyDesc.additionalSolverIterations}get angularDamping(){if(!this._requireNotRemoved("angularDamping"))return 0;return this._rigidBody?this._rigidBody.angularDamping():this._rigidBodyDesc.angularDamping}get angularVelocity(){if(!this._requireNotRemoved("angularVelocity"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.angvel():this._rigidBodyDesc.angvel}get colliders(){return this._colliders}get dominanceGroup(){if(!this._requireNotRemoved("dominanceGroup"))return 0;return this._rigidBody?this._rigidBody.dominanceGroup():this._rigidBodyDesc.dominanceGroup}get directionFromRotation(){let{x:Z,y:J,z:X,w:$}=this.rotation;return{x:-2*(Z*X+$*J),y:-2*(J*X-$*Z),z:-(1-2*(Z*Z+J*J))}}get effectiveAngularInertia(){if(!this._requireNotRemoved("effectiveAngularInertia"))return;return this._rigidBody?this._rigidBody.effectiveAngularInertia():void 0}get effectiveInverseMass(){if(!this._requireNotRemoved("effectiveInverseMass"))return;return this._rigidBody?this._rigidBody.effectiveInvMass():void 0}get effectiveWorldInversePrincipalAngularInertiaSqrt(){if(!this._requireNotRemoved("effectiveWorldInversePrincipalAngularInertiaSqrt"))return;return this._rigidBody?this._rigidBody.effectiveWorldInvInertiaSqrt():void 0}get enabledRotations(){if(!this._requireNotRemoved("enabledRotations"))return{x:!0,y:!0,z:!0};return this._enabledRotations}get enabledPositions(){if(!this._requireNotRemoved("enabledPositions"))return{x:!0,y:!0,z:!0};return this._enabledPositions}get gravityScale(){if(!this._requireNotRemoved("gravityScale"))return 0;return this._rigidBody?this._rigidBody.gravityScale():this._rigidBodyDesc.gravityScale}get inverseMass(){if(!this._requireNotRemoved("inverseMass"))return;return this._rigidBody?this._rigidBody.invMass():void 0}get inversePrincipalAngularInertiaSqrt(){if(!this._requireNotRemoved("inversePrincipalAngularInertiaSqrt"))return;return this._rigidBody?this._rigidBody.invPrincipalInertiaSqrt():void 0}get isCcdEnabled(){if(!this._requireNotRemoved("isCcdEnabled"))return!1;return this._rigidBody?this._rigidBody.isCcdEnabled():this._rigidBodyDesc.ccdEnabled}get isDynamic(){if(!this._requireNotRemoved("isDynamic"))return!1;return this._rigidBodyType==="dynamic"}get isEnabled(){if(!this._requireNotRemoved("isEnabled"))return!1;return this._rigidBody?this._rigidBody.isEnabled():this._rigidBodyDesc.enabled}get isFixed(){if(!this._requireNotRemoved("isFixed"))return!1;return this._rigidBodyType==="fixed"}get isKinematic(){if(!this._requireNotRemoved("isKinematic"))return!1;return["kinematic_position","kinematic_velocity"].includes(this._rigidBodyType)}get isKinematicPositionBased(){if(!this._requireNotRemoved("isKinematicPositionBased"))return!1;return this._rigidBodyType==="kinematic_position"}get isKinematicVelocityBased(){if(!this._requireNotRemoved("isKinematicVelocityBased"))return!1;return this._rigidBodyType==="kinematic_velocity"}get isMoving(){if(!this._requireNotRemoved("isMoving"))return!1;return this._rigidBody?this._rigidBody.isMoving():!1}get isRemoved(){return!this._rigidBody&&!this._rigidBodyDesc}get isSimulated(){if(!this._requireNotRemoved("isSimulated"))return!1;return this._rigidBody?!0:!1}get isSleeping(){if(!this._requireNotRemoved("isSleeping"))return!1;return this._rigidBody?this._rigidBody.isSleeping():this._rigidBodyDesc.sleeping}get linearDamping(){if(!this._requireNotRemoved("linearDamping"))return 0;return this._rigidBody?this._rigidBody.linearDamping():this._rigidBodyDesc.linearDamping}get linearVelocity(){if(!this._requireNotRemoved("linearVelocity"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.linvel():this._rigidBodyDesc.linvel}get localCenterOfMass(){if(!this._requireNotRemoved("localCenterOfMass"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.localCom():this._rigidBodyDesc.centerOfMass}get mass(){if(!this._requireNotRemoved("mass"))return 0;return this._rigidBody?this._rigidBody.mass():this._rigidBodyDesc.mass}get nextKinematicRotation(){if(!this._requireNotRemoved("nextKinematicRotation"))return{x:0,y:0,z:0,w:1};return this._rigidBody?this._rigidBody.nextRotation():this._rigidBodyDesc.rotation}get nextKinematicPosition(){if(!this._requireNotRemoved("nextKinematicPosition"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.nextTranslation():this._rigidBodyDesc.translation}get numColliders(){return this._colliders.size}get principalAngularInertia(){if(!this._requireNotRemoved("principalAngularInertia"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.principalInertia():this._rigidBodyDesc.principalAngularInertia}get principalAngularInertiaLocalFrame(){if(!this._requireNotRemoved("principalAngularInertiaLocalFrame"))return;return this._rigidBody?this._rigidBody.principalInertiaLocalFrame():void 0}get position(){if(!this._requireNotRemoved("position"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.translation():this._rigidBodyDesc.translation}get rawRigidBody(){if(!this._requireNotRemoved("rawRigidBody"))return;return this._rigidBody}get rotation(){if(!this._requireNotRemoved("rotation"))return{x:0,y:0,z:0,w:1};return this._rigidBody?this._rigidBody.rotation():this._rigidBodyDesc.rotation}get softCcdPrediction(){if(!this._requireNotRemoved("softCcdPrediction"))return 0;return this._rigidBody?this._rigidBody.softCcdPrediction():this._rigidBodyDesc.softCcdPrediction}get type(){if(!this._requireNotRemoved("type"))return"dynamic";return this._rigidBodyType}get worldCenterOfMass(){if(!this._requireNotRemoved("worldCenterOfMass"))return;return this._rigidBody?this._rigidBody.worldCom():void 0}setAdditionalMass(Z){if(!this._requireDynamic("setAdditionalMass"))return;if(!this._requireNotRemoved("setAdditionalMass"))return;this._rigidBody?this._rigidBody.setAdditionalMass(Z,!this._explicitSleep):this._rigidBodyDesc.setAdditionalMass(Z)}setAdditionalMassProperties(Z){if(!this._requireDynamic("setAdditionalMassProperties"))return;if(!this._requireNotRemoved("setAdditionalMassProperties"))return;let{additionalMass:J,centerOfMass:X,principalAngularInertia:$,principalAngularInertiaLocalFrame:Y}=Z;this._rigidBody?this._rigidBody.setAdditionalMassProperties(J,X,$,Y,!this._explicitSleep):this._rigidBodyDesc.setAdditionalMassProperties(J,X,$,Y)}setAdditionalSolverIterations(Z){if(!this._requireDynamic("setAdditionalSolverIterations"))return;if(!this._requireNotRemoved("setAdditionalSolverIterations"))return;this._rigidBody?this._rigidBody.setAdditionalSolverIterations(Z):this._rigidBodyDesc.setAdditionalSolverIterations(Z)}setAngularDamping(Z){if(!this._requireDynamic("setAngularDamping"))return;if(!this._requireNotRemoved("setAngularDamping"))return;this._rigidBody?this._rigidBody.setAngularDamping(Z):this._rigidBodyDesc.setAngularDamping(Z)}setAngularVelocity(Z){if(!this._requireNotKinematicPositionBased("setAngularVelocity"))return;if(!this._requireNotRemoved("setAngularVelocity"))return;this._rigidBody?this._rigidBody.setAngvel(Z,!this._explicitSleep):this._rigidBodyDesc.setAngvel(Z)}setCcdEnabled(Z){if(!this._requireDynamic("setCcdEnabled"))return;if(!this._requireNotRemoved("setCcdEnabled"))return;this._rigidBody?this._rigidBody.enableCcd(Z):this._rigidBodyDesc.setCcdEnabled(Z)}setDominanceGroup(Z){if(!this._requireDynamic("setDominanceGroup"))return;if(!this._requireNotRemoved("setDominanceGroup"))return;this._rigidBody?this._rigidBody.setDominanceGroup(Z):this._rigidBodyDesc.setDominanceGroup(Z)}setEnabled(Z){if(!this._requireNotRemoved("setEnabled"))return;this._rigidBody?this._rigidBody.setEnabled(Z):this._rigidBodyDesc.setEnabled(Z)}setEnabledPositions(Z){if(!this._requireDynamic("setEnabledPositions"))return;if(!this._requireNotRemoved("setEnabledPositions"))return;this._rigidBody?this._rigidBody.setEnabledTranslations(Z.x,Z.y,Z.z,!this._explicitSleep):this._rigidBodyDesc.enabledTranslations(Z.x,Z.y,Z.z),this._enabledPositions=Z}setEnabledRotations(Z){if(!this._requireDynamic("setEnabledRotations"))return;if(!this._requireNotRemoved("setEnabledRotations"))return;this._rigidBody?this._rigidBody.setEnabledRotations(Z.x,Z.y,Z.z,!this._explicitSleep):this._rigidBodyDesc.enabledRotations(Z.x,Z.y,Z.z),this._enabledRotations=Z}setGravityScale(Z){if(!this._requireDynamic("setGravityScale"))return;if(!this._requireNotRemoved("setGravityScale"))return;this._rigidBody?this._rigidBody.setGravityScale(Z,!this._explicitSleep):this._rigidBodyDesc.setGravityScale(Z)}setLinearDamping(Z){if(!this._requireDynamic("setLinearDamping"))return;if(!this._requireNotRemoved("setLinearDamping"))return;this._rigidBody?this._rigidBody.setLinearDamping(Z):this._rigidBodyDesc.setLinearDamping(Z)}setLinearVelocity(Z){if(!this._requireNotKinematicPositionBased("setLinearVelocity"))return;if(!this._requireNotRemoved("setLinearVelocity"))return;this._rigidBody?this._rigidBody.setLinvel(Z,!this._explicitSleep):this._rigidBodyDesc.setLinvel(Z.x,Z.y,Z.z)}setNextKinematicRotation(Z){if(!this._requireKinematic("setNextKinematicRotation"))return;if(!this._requireNotRemoved("setNextKinematicRotation"))return;this._rigidBody?this._rigidBody.setNextKinematicRotation(Z):this._rigidBodyDesc.setRotation(Z)}setNextKinematicPosition(Z){if(!this._requireKinematic("setNextKinematicPosition"))return;if(!this._requireNotRemoved("setNextKinematicPosition"))return;this._rigidBody?this._rigidBody.setNextKinematicTranslation(Z):this._rigidBodyDesc.setTranslation(Z.x,Z.y,Z.z)}setPosition(Z){if(!this._requireNotRemoved("setPosition"))return;this._rigidBody?this._rigidBody.setTranslation(Z,!this._explicitSleep):this._rigidBodyDesc.setTranslation(Z.x,Z.y,Z.z)}setRotation(Z){if(!this._requireNotRemoved("setRotation"))return;this._rigidBody?this._rigidBody.setRotation(Z,!this._explicitSleep):this._rigidBodyDesc.setRotation(Z)}setSleeping(Z){if(!this._requireDynamic("setSleeping"))return;if(!this._requireNotRemoved("setSleeping"))return;this._rigidBody?Z?this._rigidBody.sleep():this._rigidBody.wakeUp():this._rigidBodyDesc.sleeping=Z,this._explicitSleep=Z}setSoftCcdPrediction(Z){if(!this._requireDynamic("setSoftCcdPrediction"))return;if(!this._requireNotRemoved("setSoftCcdPrediction"))return;this._rigidBody?this._rigidBody.setSoftCcdPrediction(Z):this._rigidBodyDesc.setSoftCcdPrediction(Z)}setCollisionGroupsForSolidColliders(Z){if(!this._requireNotRemoved("setCollisionGroupsForSolidColliders"))return;this._colliders.forEach((J)=>{if(J.isSensor)return;J.setCollisionGroups(Z)})}setCollisionGroupsForSensorColliders(Z){if(!this._requireNotRemoved("setCollisionGroupsForSensorColliders"))return;this._colliders.forEach((J)=>{if(!J.isSensor)return;J.setCollisionGroups(Z)})}setType(Z){if(!this._requireNotRemoved("setType"))return;let X={["dynamic"]:$5.RigidBodyType.Dynamic,["fixed"]:$5.RigidBodyType.Fixed,["kinematic_position"]:$5.RigidBodyType.KinematicPositionBased,["kinematic_velocity"]:$5.RigidBodyType.KinematicVelocityBased}[Z];if(X===void 0)return u.error(`Invalid RigidBodyType: ${Z}`);this._rigidBody?this._rigidBody.setBodyType(X,!this._explicitSleep):this._rigidBodyDesc.status=X,this._rigidBodyType=Z}addForce(Z){if(!this._requireNotRemoved("addForce"))return;if(!this._requireCreated("addForce"))return;if(!this._requireDynamic("addForce"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.addForce(Z,!this._explicitSleep)}addTorque(Z){if(!this._requireNotRemoved("addTorque"))return;if(!this._requireCreated("addTorque"))return;if(!this._requireDynamic("addTorque"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.addTorque(Z,!this._explicitSleep)}addChildColliderToSimulation(Z){if(!this._requireNotRemoved("addChildColliderToSimulation"))return;if(!this._requireCreated("addChildColliderToSimulation"))return;Z.addToSimulation(this._simulation,this)}addToSimulation(Z){if(!this._requireNotRemoved("addToSimulation"))return;if(this._rigidBody)return u.error("RigidBody.addToSimulation(): Rigid body already exists in the simulation!");this._simulation=Z,this._rigidBody=this._simulation.createRawRigidBody(this._rigidBodyDesc),this._colliders.forEach((J)=>{if(!J.isSimulated)J.addToSimulation(Z,this)})}applyImpulse(Z){if(!this._requireNotRemoved("applyImpulse"))return;if(!this._requireCreated("applyImpulse"))return;if(!this._requireDynamic("applyImpulse"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.applyImpulse(Z,!this._explicitSleep)}applyImpulseAtPoint(Z,J){if(!this._requireNotRemoved("applyImpulseAtPoint"))return;if(!this._requireCreated("applyImpulseAtPoint"))return;if(!this._requireDynamic("applyImpulseAtPoint"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.applyImpulseAtPoint(Z,J,!this._explicitSleep)}applyTorqueImpulse(Z){if(!this._requireNotRemoved("applyTorqueImpulse"))return;if(!this._requireCreated("applyTorqueImpulse"))return;if(!this._requireDynamic("applyTorqueImpulse"))return;this._rigidBody.applyTorqueImpulse(Z,!this._explicitSleep)}createAndAddChildCollider(Z){if(!this._requireNotRemoved("createAndAddChildCollider"))return null;return this._simulation?new f7({...Z,parentRigidBody:this,simulation:this._simulation}):this._createAndAddPendingChildCollider(Z)}createAndAddChildColliders(Z){let J=[];return Z.forEach((X)=>{let $=this.createAndAddChildCollider(X);if($)J.push($)}),J}getCollidersByTag(Z){let J=[];for(let X of this._colliders)if(X.tag===Z)J.push(X);return J}linkCollider(Z){if(!this._requireNotRemoved("linkCollider"))return;if(Z.parentRigidBody!==this)return u.error("RigidBody.linkCollider(): Collider cannot be linked because it is not a child of this rigid body!");this._colliders.add(Z)}lockAllRotations(){if(!this._requireNotRemoved("lockAllRotations"))return;this.setEnabledRotations({x:!1,y:!1,z:!1})}lockAllPositions(){if(!this._requireNotRemoved("lockAllPositions"))return;this.setEnabledPositions({x:!1,y:!1,z:!1})}removeFromSimulation(){if(!this._requireNotRemoved("removeFromSimulation"))return;if(!this._rigidBody)return u.error("RigidBody.removeFromSimulation(): Rigid body does not exist in the simulation!");this._colliders.forEach((Z)=>{Z.removeFromSimulation()}),this._simulation.removeRawRigidBody(this._rigidBody),this._simulation=void 0,this._rigidBody=void 0}unlinkCollider(Z){if(!this._requireNotRemoved("unlinkCollider"))return;if(!Z.isRemoved)return u.error("RigidBody.unlinkCollider(): Collider is still simulated and therefore cannot be unlinked from this rigid body!");this._colliders.delete(Z)}resetAngularVelocity(){if(!this._requireNotRemoved("resetAngularVelocity"))return;if(!this._requireCreated("resetAngularVelocity"))return;this.setAngularVelocity({x:0,y:0,z:0})}resetForces(){if(!this._requireNotRemoved("resetForces"))return;if(!this._requireCreated("resetForces"))return;this._rigidBody.resetForces(!this._explicitSleep)}resetLinearVelocity(){if(!this._requireNotRemoved("resetLinearVelocity"))return;if(!this._requireCreated("resetLinearVelocity"))return;this.setLinearVelocity({x:0,y:0,z:0})}resetTorques(){if(!this._requireNotRemoved("resetTorques"))return;if(!this._requireCreated("resetTorques"))return;this._rigidBody.resetTorques(!this._explicitSleep)}sleep(){if(!this._requireNotRemoved("sleep"))return;this.setSleeping(!0)}wakeUp(){if(!this._requireNotRemoved("wakeUp"))return;this.setSleeping(!1)}_applyRigidBodyOptions(Z){[["additionalMass",this.setAdditionalMass.bind(this)],["additionalMassProperties",this.setAdditionalMassProperties.bind(this)],["additionalSolverIterations",this.setAdditionalSolverIterations.bind(this)],["angularDamping",this.setAngularDamping.bind(this)],["angularVelocity",this.setAngularVelocity.bind(this)],["dominanceGroup",this.setDominanceGroup.bind(this)],["ccdEnabled",this.setCcdEnabled.bind(this)],["enabled",this.setEnabled.bind(this)],["enabledPositions",this.setEnabledPositions.bind(this)],["enabledRotations",this.setEnabledRotations.bind(this)],["gravityScale",this.setGravityScale.bind(this)],["linearDamping",this.setLinearDamping.bind(this)],["linearVelocity",this.setLinearVelocity.bind(this)],["position",this.setPosition.bind(this)],["rotation",this.setRotation.bind(this)],["sleeping",this.setSleeping.bind(this)],["softCcdPrediction",this.setSoftCcdPrediction.bind(this)]].forEach(([X,$])=>{if(X in Z)$(Z[X])})}_autoAddToSimulation(Z){if(Z.colliders)this._createAndAddPendingChildColliders(Z.colliders);if(Z.simulation)this.addToSimulation(Z.simulation)}_createAndAddPendingChildCollider(Z){if(!this._requireNotRemoved("createAndAddPendingChildCollider"))return null;if(!this._requireNotSimulated("createAndAddPendingChildCollider"))return null;let J=new f7(Z);return this._colliders.add(J),J}_createAndAddPendingChildColliders(Z){let J=[];return Z.forEach((X)=>{let $=this._createAndAddPendingChildCollider(X);if($)J.push($)}),J}_createRigidBodyDesc(Z){let J=Z.type??Sn;return{["dynamic"]:()=>$5.RigidBodyDesc.dynamic(),["fixed"]:()=>$5.RigidBodyDesc.fixed(),["kinematic_position"]:()=>$5.RigidBodyDesc.kinematicPositionBased(),["kinematic_velocity"]:()=>$5.RigidBodyDesc.kinematicVelocityBased()}[J]()}_requireCreated(Z){if(!this._rigidBody||!this._simulation)u.error(`RigidBody._requireCreated(): Rigid body has not been created and therefore does not support the invoked method: ${Z}()`);return!!this._rigidBody&&!!this._simulation}_requireDynamic(Z){if(!this.isDynamic)u.error(`RigidBody._requireDynamic(): Rigid body is not dynamic and therefore does not support the invoked method: ${Z}()`);return this.isDynamic}_requireKinematic(Z){if(!this.isKinematic)u.error(`RigidBody._requireKinematic(): Rigid body is not kinematic and therefore does not support the invoked method: ${Z}()`);return this.isKinematic}_requireNotKinematicPositionBased(Z){if(this.isKinematicPositionBased)u.error(`RigidBody._requireNotKinematicPositionBased(): Rigid body is kinematic position based and therefore does not support the invoked method: ${Z}()`);return!this.isKinematicPositionBased}_requireNotRemoved(Z){if(!this._rigidBody&&!this._rigidBodyDesc)u.error(`RigidBody._requireNotRemoved(): Rigid body has been removed and therefore does not support the invoked method: ${Z}()`);return!!this._rigidBody||!!this._rigidBodyDesc}_requireNotSimulated(Z){if(this.isSimulated)u.error(`RigidBody._requireNotSimulated(): Rigid body is simulated and therefore does not support the invoked method: ${Z}()`);return!this.isSimulated}_isNegligibleVector(Z){return Math.abs(Z.x)<iP&&Math.abs(Z.y)<iP&&Math.abs(Z.z)<iP}}var nP;((Y)=>{Y[Y.Average=0]="Average";Y[Y.Min=1]="Min";Y[Y.Multiply=2]="Multiply";Y[Y.Max=3]="Max"})(nP||={});var QV;((H)=>{H.NONE="none";H.BALL="ball";H.BLOCK="block";H.CAPSULE="capsule";H.CONE="cone";H.CYLINDER="cylinder";H.ROUND_CYLINDER="round-cylinder";H.TRIMESH="trimesh";H.VOXELS="voxels";H.WEDGE="wedge"})(QV||={});class f7 extends D0{_collider;_colliderDesc;_onCollision;_parentRigidBody;_relativePosition={x:0,y:0,z:0};_relativeRotation={x:0,y:0,z:0,w:1};_shape;_simulation;_tag;constructor(Z){super();this._colliderDesc=this._createColliderDesc(Z),this._shape=Z.shape,this._applyColliderOptions(Z),this._autoAddToSimulation(Z)}static optionsFromBlockHalfExtents(Z){return{shape:"block",halfExtents:Z}}static optionsFromModelUri(Z,J=1,X){let $=V7.instance.getBoundingBox(Z),Y=$.max.x-$.min.x,Q=$.max.y-$.min.y,W=$.max.z-$.min.z,K=Math.max(Y,W),G=Math.min(Y,W),V=K/G,H=K/Q,q=K*J/2,z=(O)=>Math.max(0.01,O),F=()=>({shape:"block",halfExtents:{x:z(Y*J/2),y:z(Q*J/2),z:z(W*J/2)}}),U=()=>({shape:"round-cylinder",radius:z(q),halfHeight:z(Q*J/2),borderRadius:z(q*0.1)}),L=()=>{let O=V7.instance.getTrimesh(Z,J);if(!O)return;return{shape:"trimesh",vertices:O.vertices,indices:O.indices}},B=()=>({shape:"wedge",extents:{x:Y*J,y:Q*J,z:W*J}}),w=()=>({shape:"capsule",radius:z(q),halfHeight:z(Q*J/2-q)});if(X)switch(X){case"block":return F();case"capsule":return w();case"round-cylinder":return U();case"trimesh":{let O=L();if(!O){u.error(`Collider.optionsFromModelUri(): Failed to create trimesh options for model ${Z}, falling back to generic shape!`);break}return O}case"wedge":return B();default:u.warning(`Collider.optionsFromModelUri(): Preferred shape ${X} is not yet supported with Collider.optionsFromModelUri(), defaulting to generic shape!`)}if(V>2)return F();if(H>1.5)return U();return w()}get bounciness(){if(!this._requireNotRemoved("bounciness"))return 0;return this._collider?this._collider.restitution():this._colliderDesc.restitution}get bouncinessCombineRule(){if(!this._requireNotRemoved("bouncinessCombineRule"))return 0;return this._collider?this._collider.restitutionCombineRule():this._colliderDesc.restitutionCombineRule}get collisionGroups(){if(!this._requireNotRemoved("collisionGroups"))return{belongsTo:[],collidesWith:[]};return this._collider?e9.decodeRawCollisionGroups(this._collider.collisionGroups()):e9.decodeRawCollisionGroups(this._colliderDesc.collisionGroups)}get friction(){if(!this._requireNotRemoved("friction"))return 0;return this._collider?this._collider.friction():this._colliderDesc.friction}get frictionCombineRule(){if(!this._requireNotRemoved("frictionCombineRule"))return 0;return this._collider?this._collider.frictionCombineRule():this._colliderDesc.frictionCombineRule}get isEnabled(){if(!this._requireNotRemoved("isEnabled"))return!1;return this._collider?this._collider.isEnabled():this._colliderDesc.enabled}get isRemoved(){return!this._collider&&!this._colliderDesc}get isSensor(){if(!this._requireNotRemoved("isSensor"))return!1;return this._collider?this._collider.isSensor():this._colliderDesc.isSensor}get isSimulated(){if(!this._requireNotRemoved("isSimulated"))return!1;return!!this._collider}get parentRigidBody(){if(!this._requireNotRemoved("parentRigidBody"))return;return this._parentRigidBody}get rawCollider(){if(!this._requireNotRemoved("rawCollider"))return;return this._collider}get rawShape(){if(!this._requireNotRemoved("rawShape"))return;return this._collider?this._collider.shape:this._colliderDesc.shape}get relativePosition(){if(!this._requireNotRemoved("relativePosition"))return{x:0,y:0,z:0};return this._relativePosition}get relativeRotation(){if(!this._requireNotRemoved("relativeRotation"))return{x:0,y:0,z:0,w:1};return this._relativeRotation}get shape(){if(!this._requireNotRemoved("shape"))return"none";return this._shape}get tag(){if(!this._requireNotRemoved("tag"))return;return this._tag}setBounciness(Z){if(!this._requireNotRemoved("setBounciness"))return;this._collider?this._collider.setRestitution(Z):this._colliderDesc.setRestitution(Z)}setBouncinessCombineRule(Z){if(!this._requireNotRemoved("setBouncinessCombineRule"))return;this._collider?this._collider.setRestitutionCombineRule(Z):this._colliderDesc.setRestitutionCombineRule(Z)}setCollisionGroups(Z){if(!this._requireNotRemoved("setCollisionGroups"))return;let J=e9.buildRawCollisionGroups(Z);this._collider?this._collider.setCollisionGroups(J):this._colliderDesc.setCollisionGroups(J)}setEnabled(Z){if(!this._requireNotRemoved("setEnabled"))return;this._collider?this._collider.setEnabled(Z):this._colliderDesc.setEnabled(Z)}setFriction(Z){if(!this._requireNotRemoved("setFriction"))return;this._collider?this._collider.setFriction(Z):this._colliderDesc.setFriction(Z)}setFrictionCombineRule(Z){if(!this._requireNotRemoved("setFrictionCombineRule"))return;this._collider?this._collider.setFrictionCombineRule(Z):this._colliderDesc.setFrictionCombineRule(Z)}setMass(Z){if(!this._requireNotRemoved("setMass"))return;this._collider?this._collider.setMass(Z):this._colliderDesc.setMass(Z)}setOnCollision(Z){if(!this._requireNotRemoved("setOnCollision"))return;if(this._onCollision=Z,this.isSimulated)if(this.enableCollisionEvents(!!Z),Z)this._simulation.colliderMap.setColliderCollisionCallback(this,Z);else this._simulation.colliderMap.removeColliderCollisionCallback(this)}setRelativeRotation(Z){if(!this._requireNotRemoved("setRelativeRotation"))return;this._relativeRotation=Z,this._collider?this._collider.parent()?this._collider.setRotationWrtParent(Z):this._collider.setRotation(Z):this._colliderDesc.setRotation(Z)}setRelativePosition(Z){if(!this._requireNotRemoved("setRelativePosition"))return;this._relativePosition=Z,this._collider?this._collider.parent()?this._collider.setTranslationWrtParent(Z):this._collider.setTranslation(Z):this._colliderDesc.setTranslation(Z.x,Z.y,Z.z)}setSensor(Z){if(!this._requireNotRemoved("setSensor"))return;this._collider?this._collider.setSensor(Z):this._colliderDesc.setSensor(Z)}setTag(Z){if(!this._requireNotRemoved("setTag"))return;this._tag=Z}setVoxel(Z,J){if(!this._requireNotRemoved("setVoxel"))return;if(!this._requireSimulated("setVoxel"))return;if(this.shape!=="voxels")return u.error("Collider.setVoxel(): Collider is not a voxels collider!");this._collider.setVoxel(Z.x,Z.y,Z.z,J)}addToSimulation(Z,J){if(!this._requireNotRemoved("addToSimulation"))return;if(!this._requireUnsimulated("addToSimulation"))return;if(J){if(!J.isSimulated)return u.error("Collider.addToSimulation(): Rigid body must be simulated before adding a collider to it!");if(J.type==="dynamic"&&this.shape==="trimesh")u.warning("Collider.addToSimulation(): Trimesh colliders are strongly discouraged to be used with dynamic rigid bodies, they will not contribute any mass!")}if(this._simulation=Z,this._parentRigidBody=J,this._collider=this._simulation.createRawCollider(this._colliderDesc,J?.rawRigidBody),this._colliderDesc=void 0,J)J.linkCollider(this);if(this._onCollision)this.setOnCollision(this._onCollision)}combineVoxelStates(Z){if(!this._requireNotRemoved("combineVoxelStates"))return;if(!this._requireSimulated("combineVoxelStates"))return;if(!Z.isSimulated)return u.error("Collider.combineVoxelStates(): Other collider is not simulated!");if(this.shape!=="voxels")return u.error("Collider.combineVoxelStates(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return u.error("Collider.combineVoxelStates(): Other collider is not a voxels collider!");this._collider.combineVoxelStates(Z.rawCollider,0,0,0)}enableCollisionEvents(Z){if(!this._requireNotRemoved("enableCollisionEvents"))return;let J=this._collider?this._collider.activeEvents():this._colliderDesc.activeEvents,X=Z?J|$5.ActiveEvents.COLLISION_EVENTS:J&~$5.ActiveEvents.COLLISION_EVENTS;(this._collider??this._colliderDesc).setActiveEvents(X),this._setActiveCollisionTypes()}enableContactForceEvents(Z){if(!this._requireNotRemoved("enableContactForceEvents"))return;let J=this._collider?this._collider.activeEvents():this._colliderDesc.activeEvents,X=Z?J|$5.ActiveEvents.CONTACT_FORCE_EVENTS:J&~$5.ActiveEvents.CONTACT_FORCE_EVENTS;(this._collider??this._colliderDesc).setActiveEvents(X),this._setActiveCollisionTypes()}propagateVoxelChange(Z,J){if(!this._requireNotRemoved("propagateVoxelChange"))return;if(!this._requireSimulated("propagateVoxelChange"))return;if(!Z.isSimulated)return u.error("Collider.propagateVoxelChange(): Other collider is not simulated!");if(this.shape!=="voxels")return u.error("Collider.propagateVoxelChange(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return u.error("Collider.propagateVoxelChange(): Other collider is not a voxels collider!");this._collider.propagateVoxelChange(Z.rawCollider,J.x,J.y,J.z,0,0,0)}removeFromSimulation(){if(!this._requireNotRemoved("removeFromSimulation"))return;if(!this._requireSimulated("removeFromSimulation"))return;if(this._simulation.removeRawCollider(this._collider),this._simulation=void 0,this._collider=void 0,this._parentRigidBody)this._parentRigidBody.unlinkCollider(this);this._parentRigidBody=void 0}scale(Z){if(!this._requireNotRemoved("scale"))return;switch(this.setRelativePosition({x:this.relativePosition.x*Z,y:this.relativePosition.y*Z,z:this.relativePosition.z*Z}),this._shape){case"ball":{if(this._collider)this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.radius*=Z;return}case"block":{if(this._collider){let J=this._collider.halfExtents();this._collider.setHalfExtents({x:J.x*Z,y:J.y*Z,z:J.z*Z})}else this._colliderDesc.shape.halfExtents.x*=Z,this._colliderDesc.shape.halfExtents.y*=Z,this._colliderDesc.shape.halfExtents.z*=Z;return}case"capsule":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"cone":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"cylinder":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"round-cylinder":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRoundRadius(this._collider.roundRadius()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight=this._colliderDesc.shape.halfHeight*Z,this._colliderDesc.shape.borderRadius=this._colliderDesc.shape.borderRadius*Z,this._colliderDesc.shape.radius=this._colliderDesc.shape.radius*Z;return}case"trimesh":{u.error("Collider.setScale(): Trimesh colliders cannot be scaled!");return}case"voxels":{u.error("Collider.setScale(): Voxels colliders cannot be scaled!");return}case"wedge":{u.error("Collider.setScale(): Wedge colliders cannot be scaled!");return}default:u.fatalError(`Collider.setScale(): ${this._shape} is not a valid collider shape!`)}}_applyColliderOptions(Z){[["bounciness",this.setBounciness.bind(this)],["bouncinessCombineRule",this.setBouncinessCombineRule.bind(this)],["collisionGroups",this.setCollisionGroups.bind(this)],["enabled",this.setEnabled.bind(this)],["friction",this.setFriction.bind(this)],["frictionCombineRule",this.setFrictionCombineRule.bind(this)],["isSensor",this.setSensor.bind(this)],["mass",this.setMass.bind(this)],["onCollision",this.setOnCollision.bind(this)],["relativePosition",this.setRelativePosition.bind(this)],["relativeRotation",this.setRelativeRotation.bind(this)],["tag",this.setTag.bind(this)]].forEach(([X,$])=>{if(Z[X]!==void 0)$.call(this,Z[X])})}_autoAddToSimulation(Z){if(Z.simulation)this.addToSimulation(Z.simulation,Z.parentRigidBody)}_buildWedgeConvexHullVertices(Z){let{x:J,y:X,z:$}=Z,Y=J/2,Q=$/2,W=X/2;return new Float32Array([-Y,0-W,-Q,Y,0-W,-Q,Y,0-W,Q,-Y,0-W,Q,-Y,X-W,-Q,Y,X-W,-Q])}_createColliderDesc(Z){let{shape:J,flags:X}=Z;switch(J){case"ball":{if(!Z.radius)u.fatalError("Ball collider must have a radius!");return $5.ColliderDesc.ball(Z.radius)}case"block":{if(!Z.halfExtents)u.fatalError("Block collider must have halfExtents!");return $5.ColliderDesc.cuboid(Z.halfExtents.x,Z.halfExtents.y,Z.halfExtents.z)}case"capsule":{if(!Z.halfHeight||!Z.radius)u.fatalError("Capsule collider must have halfHeight and radius!");return $5.ColliderDesc.capsule(Z.halfHeight,Z.radius)}case"cone":{if(!Z.radius||!Z.halfHeight)u.fatalError("Cone collider must have radius and halfHeight!");return $5.ColliderDesc.cone(Z.halfHeight,Z.radius)}case"cylinder":{if(!Z.radius||!Z.halfHeight)u.fatalError("Cylinder collider must have radius and halfHeight!");return $5.ColliderDesc.cylinder(Z.halfHeight,Z.radius)}case"round-cylinder":{if(!Z.radius||!Z.halfHeight||!Z.borderRadius)u.fatalError("Round cylinder collider must have radius, halfHeight, and borderRadius!");return $5.ColliderDesc.roundCylinder(Z.halfHeight,Z.radius,Z.borderRadius)}case"trimesh":{if(!Z.indices||!Z.vertices)u.fatalError("Trimesh collider must have vertices and indices!");return $5.ColliderDesc.trimesh(Z.vertices,Z.indices,X)}case"voxels":{if(!Z.coordinates||!Z.size)u.fatalError("Voxels collider must have coordinates and size!");return $5.ColliderDesc.voxels(this._coordinatesToInt32Array(Z.coordinates),Z.size)}case"wedge":{if(!Z.extents)u.fatalError("Wedge collider must have extents!");let $=this._buildWedgeConvexHullVertices(Z.extents),Y=$5.ColliderDesc.convexHull($);if(!Y)throw u.fatalError("Failed to create convex hull for wedge collider!"),new Error("Convex hull creation failed");return Y}default:u.fatalError(`Collider._createColliderDesc(): ${J} is not a valid collider shape!`)}}_requireSimulated(Z){if(!this.isSimulated)u.error(`Collider._requireSimulated(): Collider is not simulated, invoked method: ${Z}()`);return this.isSimulated}_requireUnsimulated(Z){if(this.isSimulated)u.error(`Collider._requireUnsimulated(): Collider is already simulated, invoked method: ${Z}()`);return!this.isSimulated}_requireNotRemoved(Z){if(this.isRemoved)u.error(`Collider._requireNotRemoved(): Collider is removed, invoked method: ${Z}()`);return!this.isRemoved}_setActiveCollisionTypes(){(this._collider??this._colliderDesc).setActiveCollisionTypes($5.ActiveCollisionTypes.DYNAMIC_DYNAMIC|$5.ActiveCollisionTypes.DYNAMIC_KINEMATIC|$5.ActiveCollisionTypes.DYNAMIC_FIXED|$5.ActiveCollisionTypes.KINEMATIC_KINEMATIC|$5.ActiveCollisionTypes.KINEMATIC_FIXED)}_coordinatesToInt32Array(Z){let J=new Int32Array(Z.length*3);for(let X=0;X<Z.length;X++){let $=Z[X],Y=X*3;J[Y]=Math.floor($.x),J[Y+1]=Math.floor($.y),J[Y+2]=Math.floor($.z)}return J}}var yL5={shape:"voxels"},sP;((X)=>{X.ENTITY_COLLISION="BLOCK_TYPE.ENTITY_COLLISION";X.ENTITY_CONTACT_FORCE="BLOCK_TYPE.ENTITY_CONTACT_FORCE"})(sP||={});class h7 extends D0{_id;_customColliderOptions;_halfExtents;_isLiquid;_lightLevel;_name;_textureUri;constructor(Z={id:-1,textureUri:"textures/missing.png",name:"Unknown"}){if(Z.id<0)u.fatalError("BlockType.constructor(): BlockType id not set.");super();this._id=Z.id,this._customColliderOptions=Z.customColliderOptions,this._halfExtents=Z.halfExtents??{x:0.5,y:0.5,z:0.5},this._isLiquid=Z.isLiquid??!1,this._name=Z.name,this._textureUri=Z.textureUri,this._lightLevel=Math.min(Z.lightLevel??0,15)}get id(){return this._id}get colliderOptions(){return{...this._customColliderOptions,...yL5}}get halfExtents(){return this._halfExtents}get isLiquid(){return this._isLiquid}get isMeshable(){return!this._customColliderOptions}get lightLevel(){return this._lightLevel}get name(){return this._name}get size(){return{x:this._halfExtents.x*2,y:this._halfExtents.y*2,z:this._halfExtents.z*2}}get textureUri(){return this._textureUri}createCollider(Z){let J=new f7({...this.colliderOptions,coordinates:Z,size:this.size});if(this.isLiquid)J.setSensor(!0);if(this.hasListeners("BLOCK_TYPE.ENTITY_COLLISION")||this.isLiquid)J.enableCollisionEvents(!0);if(this.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))J.enableContactForceEvents(!0);if(e9.isDefaultCollisionGroups(J.collisionGroups))J.setCollisionGroups({belongsTo:[1],collidesWith:[65535&~1]});return J}serialize(){return E0.serializeBlockType(this)}}var aP;((J)=>J.REGISTER_BLOCK_TYPE="BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE")(aP||={});class WV extends D0{_blockTypes=new Map;_world;constructor(Z){super();this._world=Z}get world(){return this._world}getAllBlockTypes(){return Array.from(this._blockTypes.values())}getBlockType(Z){let J=this._blockTypes.get(Z);if(!J)u.fatalError(`BlockTypeRegistry.getBlockType(): BlockType with id ${Z} not found.`);return J}registerGenericBlockType(Z){let X=new class extends h7{constructor($=Z){super($)}};return this.registerBlockType(X),X}registerBlockType(Z){this._blockTypes.set(Z.id,Z),this.emitWithWorld(this._world,"BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",{blockTypeRegistry:this,id:Z.id,blockType:Z})}serialize(){return E0.serializeBlockTypeRegistry(this)}}var TT={};bZ(TT,{worldSchema:()=>CT,worldPacketDefinition:()=>Tt,vectorSchema:()=>G5,vectorBooleanSchema:()=>hD5,uiSchema:()=>DT,uiPacketDefinition:()=>Pt,uiDatasSchema:()=>PT,uiDatasPacketDefinition:()=>Ct,uiDataSendPacketDefinition:()=>Vt,uiDataSchema:()=>vV,syncResponseSchema:()=>RT,syncResponsePacketDefinition:()=>Dt,syncRequestSchema:()=>rC,syncRequestPacketDefinition:()=>Gt,stateRequestSchema:()=>aC,stateRequestPacketDefinition:()=>Kt,sceneUIsSchema:()=>MT,sceneUIsPacketDefinition:()=>Rt,sceneUISchema:()=>jT,rgbColorSchema:()=>O6,registeredPackets:()=>vB,quaternionSchema:()=>GT,playersSchema:()=>NT,playersPacketDefinition:()=>Mt,playerSchema:()=>OT,physicsDebugRenderSchema:()=>wT,physicsDebugRenderPacketDefinition:()=>Nt,physicsDebugRaycastsSchema:()=>LT,physicsDebugRaycastsPacketDefinition:()=>jt,physicsDebugRaycastSchema:()=>BT,particleEmittersSchema:()=>UT,particleEmittersPacketDefinition:()=>Ot,particleEmitterSchema:()=>FT,outboundPackets:()=>IB,modelNodeOverrideSchema:()=>KT,lightsSchema:()=>zT,lightsPacketDefinition:()=>wt,lightSchema:()=>qT,isValidPacket:()=>yD5,inputSchema:()=>sC,inputPacketDefinition:()=>Wt,inboundPackets:()=>EB,hexColorSchema:()=>iC,heartbeatSchema:()=>pC,heartbeatPacketDefinition:()=>$t,entitySchema:()=>VT,entitiesSchema:()=>HT,entitiesPacketDefinition:()=>Lt,definePacket:()=>S0,debugConfigSchema:()=>nC,debugConfigPacketDefinition:()=>Qt,createPacket:()=>TD5,connectionSchema:()=>lC,connectionPacketDefinition:()=>Xt,chunksSchema:()=>WT,chunksPacketDefinition:()=>Bt,chunkSchema:()=>QT,chatMessagesSchema:()=>YT,chatMessagesPacketDefinition:()=>Ut,chatMessageSendPacketDefinition:()=>Yt,chatMessageSchema:()=>IV,cameraSchema:()=>$T,cameraPacketDefinition:()=>Ft,blocksSchema:()=>ZT,blocksPacketDefinition:()=>qt,blockTypesSchema:()=>XT,blockTypesPacketDefinition:()=>zt,blockTypeSchema:()=>JT,blockSchema:()=>eC,bidirectionalPackets:()=>kB,audiosSchema:()=>tC,audiosPacketDefinition:()=>Ht,audioSchema:()=>oC,PacketId:()=>T5});var kB={};bZ(kB,{heartbeatPacketDefinition:()=>$t,connectionPacketDefinition:()=>Xt});var uC=e(Zt(),1);class cC extends uC.default{static instance=new uC.default}var T5;((k)=>{k[k.SYNC_REQUEST=0]="SYNC_REQUEST";k[k.INPUT=1]="INPUT";k[k.STATE_REQUEST=2]="STATE_REQUEST";k[k.CHAT_MESSAGE_SEND=3]="CHAT_MESSAGE_SEND";k[k.UI_DATA_SEND=4]="UI_DATA_SEND";k[k.SYNC_RESPONSE=32]="SYNC_RESPONSE";k[k.AUDIOS=33]="AUDIOS";k[k.BLOCKS=34]="BLOCKS";k[k.BLOCK_TYPES=35]="BLOCK_TYPES";k[k.CHAT_MESSAGES=36]="CHAT_MESSAGES";k[k.CHUNKS=37]="CHUNKS";k[k.ENTITIES=38]="ENTITIES";k[k.WORLD=39]="WORLD";k[k.CAMERA=40]="CAMERA";k[k.UI=41]="UI";k[k.UI_DATAS=42]="UI_DATAS";k[k.SCENE_UIS=43]="SCENE_UIS";k[k.LIGHTS=44]="LIGHTS";k[k.PLAYERS=45]="PLAYERS";k[k.PARTICLE_EMITTERS=46]="PARTICLE_EMITTERS";k[k.CONNECTION=116]="CONNECTION";k[k.HEARTBEAT=117]="HEARTBEAT";k[k.DEBUG_CONFIG=128]="DEBUG_CONFIG";k[k.PHYSICS_DEBUG_RENDER=192]="PHYSICS_DEBUG_RENDER";k[k.PHYSICS_DEBUG_RAYCASTS=193]="PHYSICS_DEBUG_RAYCASTS"})(T5||={});function TD5(Z,J,X){if(!Z.validate(J))throw new Error(`Invalid payload for packet with id ${Z.id}. Error: ${cC.instance.errorsText(Z.validate.errors)}`);let $=[Z.id,J];if(typeof X==="number")$.push(X);return $}function S0(Z,J){return{id:Z,schema:J,validate:cC.instance.compile(J)}}var kD5={type:"object",properties:{i:{type:"string"}},required:["i"],additionalProperties:!1},Jt={type:"object",properties:{role:{type:"string",enum:["auto","client","server"],nullable:!0},fingerprints:{type:"array",items:{type:"object",properties:{algorithm:{type:"string",enum:["sha-1","sha-224","sha-256","sha-384","sha-512"]},value:{type:"string"}},required:["algorithm","value"]}}},required:["fingerprints"],additionalProperties:!1},ED5={type:"object",properties:{foundation:{type:"string"},priority:{type:"number"},ip:{type:"string"},address:{type:"string"},protocol:{type:"string",enum:["udp","tcp"]},port:{type:"number"},type:{type:"string",enum:["host"]},tcpType:{type:"string",enum:["passive"],nullable:!0}},required:["foundation","priority","ip","address","protocol","port","type"],additionalProperties:!1},ID5={type:"object",properties:{usernameFragment:{type:"string"},password:{type:"string"},iceLite:{type:"boolean",nullable:!0}},required:["usernameFragment","password"],additionalProperties:!1},vD5={type:"object",properties:{i:{type:"string"},l:{type:"string"}},required:["i","l"],additionalProperties:!1},SD5={type:"object",properties:{port:{type:"number"},OS:{type:"number"},MIS:{type:"number"},maxMessageSize:{type:"number"}},required:["port","OS","MIS","maxMessageSize"],additionalProperties:!0},_D5={type:"object",properties:{streamId:{type:"number"},ordered:{type:"boolean",nullable:!0},maxPacketLifeTime:{type:"number",nullable:!0},maxRetransmits:{type:"number",nullable:!0}},required:["streamId"],additionalProperties:!1},AD5={type:"object",properties:{i:{type:"string"},f:{type:"string",enum:["cs","sc"]},ip:ID5,ic:{type:"array",items:ED5},d:Jt,s:SD5},required:["i","f","ip","ic","d","s"],additionalProperties:!1},xD5={type:"object",properties:{i:{type:"string"},d:Jt},required:["i","d"],additionalProperties:!1},fD5={type:"object",properties:{i:{type:"string",nullable:!0},pi:{type:"string",nullable:!0},l:{type:"string"},s:_D5},required:["l","s"],additionalProperties:!1},lC={type:"object",properties:{i:{type:"string",nullable:!0},k:{type:"boolean",nullable:!0},c:{...xD5,nullable:!0},ca:{...kD5,nullable:!0},d:{type:"array",items:{...fD5},nullable:!0},pa:{...vD5,nullable:!0},t:{type:"array",items:{...AD5},nullable:!0}},additionalProperties:!1};var Xt=S0(116,lC);var pC={type:"null",nullable:!0};var $t=S0(117,pC);var EB={};bZ(EB,{uiDataSendPacketDefinition:()=>Vt,syncRequestPacketDefinition:()=>Gt,stateRequestPacketDefinition:()=>Kt,inputPacketDefinition:()=>Wt,debugConfigPacketDefinition:()=>Qt,chatMessageSendPacketDefinition:()=>Yt});var iC={type:"string",pattern:"^[0-9A-Fa-f]{6}$"};var IV={type:"object",properties:{m:{type:"string"},c:{...iC,nullable:!0},p:{type:"string",nullable:!0}},required:["m"],additionalProperties:!1};var Yt=S0(3,IV);var nC={type:"object",properties:{pdr:{type:"boolean",nullable:!0}},additionalProperties:!1};var Qt=S0(128,nC);var sC={type:"object",properties:{"1":{type:"boolean",nullable:!0},"2":{type:"boolean",nullable:!0},"3":{type:"boolean",nullable:!0},"4":{type:"boolean",nullable:!0},"5":{type:"boolean",nullable:!0},"6":{type:"boolean",nullable:!0},"7":{type:"boolean",nullable:!0},"8":{type:"boolean",nullable:!0},"9":{type:"boolean",nullable:!0},"0":{type:"boolean",nullable:!0},w:{type:"boolean",nullable:!0},a:{type:"boolean",nullable:!0},s:{type:"boolean",nullable:!0},d:{type:"boolean",nullable:!0},q:{type:"boolean",nullable:!0},e:{type:"boolean",nullable:!0},r:{type:"boolean",nullable:!0},f:{type:"boolean",nullable:!0},z:{type:"boolean",nullable:!0},x:{type:"boolean",nullable:!0},c:{type:"boolean",nullable:!0},v:{type:"boolean",nullable:!0},u:{type:"boolean",nullable:!0},i:{type:"boolean",nullable:!0},o:{type:"boolean",nullable:!0},j:{type:"boolean",nullable:!0},k:{type:"boolean",nullable:!0},l:{type:"boolean",nullable:!0},n:{type:"boolean",nullable:!0},m:{type:"boolean",nullable:!0},sp:{type:"boolean",nullable:!0},sh:{type:"boolean",nullable:!0},tb:{type:"boolean",nullable:!0},ml:{type:"boolean",nullable:!0},mr:{type:"boolean",nullable:!0},cp:{type:"number",nullable:!0},cy:{type:"number",nullable:!0},sq:{type:"number",nullable:!0}},additionalProperties:!1};var Wt=S0(1,sC);var aC={type:"object",properties:{},additionalProperties:!1};var Kt=S0(2,aC);var rC={type:"null",nullable:!0};var Gt=S0(0,rC);var vV={type:"object",properties:{},additionalProperties:!0};var Vt=S0(4,vV);var IB={};bZ(IB,{worldPacketDefinition:()=>Tt,uiPacketDefinition:()=>Pt,uiDatasPacketDefinition:()=>Ct,syncResponsePacketDefinition:()=>Dt,sceneUIsPacketDefinition:()=>Rt,playersPacketDefinition:()=>Mt,physicsDebugRenderPacketDefinition:()=>Nt,physicsDebugRaycastsPacketDefinition:()=>jt,particleEmittersPacketDefinition:()=>Ot,lightsPacketDefinition:()=>wt,entitiesPacketDefinition:()=>Lt,chunksPacketDefinition:()=>Bt,chatMessagesPacketDefinition:()=>Ut,cameraPacketDefinition:()=>Ft,blocksPacketDefinition:()=>qt,blockTypesPacketDefinition:()=>zt,audiosPacketDefinition:()=>Ht});var G5={type:"array",items:[{type:"number"},{type:"number"},{type:"number"}],minItems:3,maxItems:3};var oC={type:"object",properties:{i:{type:"number"},a:{type:"string",nullable:!0},cd:{type:"number",nullable:!0},d:{type:"number",nullable:!0},de:{type:"number",nullable:!0},di:{type:"number",minimum:0,nullable:!0},e:{type:"number",nullable:!0},l:{type:"boolean",nullable:!0},o:{type:"number",nullable:!0},p:{...G5,nullable:!0},pa:{type:"boolean",nullable:!0},pl:{type:"boolean",nullable:!0},pr:{type:"number",minimum:0,nullable:!0},r:{type:"boolean",nullable:!0},rd:{type:"number",nullable:!0},s:{type:"number",nullable:!0},v:{type:"number",minimum:0,maximum:1,nullable:!0}},required:["i"],additionalProperties:!1};var tC={type:"array",items:{...oC}};var Ht=S0(33,tC);var eC={type:"object",properties:{i:{type:"number"},c:G5},required:["i","c"],additionalProperties:!1};var ZT={type:"array",items:{...eC}};var qt=S0(34,ZT);var JT={type:"object",properties:{i:{type:"number"},l:{type:"boolean",nullable:!0},ll:{type:"number",nullable:!0},n:{type:"string",nullable:!0},t:{type:"string",nullable:!0}},required:["i"],additionalProperties:!1};var XT={type:"array",items:{...JT}};var zt=S0(35,XT);var $T={type:"object",properties:{m:{type:"number",nullable:!0},e:{type:"number",nullable:!0},et:{type:"number",nullable:!0},fo:{type:"number",nullable:!0},ffo:{type:"number",nullable:!0},fv:{type:"number",nullable:!0},h:{type:"array",items:{type:"string"},nullable:!0},o:{...G5,nullable:!0},p:{...G5,nullable:!0},pt:{...G5,nullable:!0},pl:{...G5,nullable:!0},s:{type:"array",items:{type:"string"},nullable:!0},sa:{type:"number",nullable:!0},z:{type:"number",nullable:!0}},additionalProperties:!1};var YT={type:"array",items:{...IV}};var QT={type:"object",properties:{c:G5,b:{type:"array",items:{type:"number",minimum:0,maximum:255},minItems:4096,maxItems:4096,nullable:!0},rm:{type:"boolean",nullable:!0}},required:["c"],additionalProperties:!1};var WT={type:"array",items:{...QT}};var O6={type:"array",items:[{type:"number",minimum:0,maximum:255},{type:"number",minimum:0,maximum:255},{type:"number",minimum:0,maximum:255}],minItems:3,maxItems:3};var KT={type:"object",properties:{n:{type:"string"},h:{type:"boolean",nullable:!0},o:{type:"number",minimum:0,maximum:1,nullable:!0},r:{type:"boolean",nullable:!0},s:{type:"number",nullable:!0},t:{...O6,nullable:!0}},required:["n"],additionalProperties:!1};var GT={type:"array",items:[{type:"number"},{type:"number"},{type:"number"},{type:"number"}],minItems:4,maxItems:4};var VT={type:"object",properties:{i:{type:"number"},al:{type:"array",items:{type:"string"},nullable:!0},ao:{type:"array",items:{type:"string"},nullable:!0},ap:{type:"number",nullable:!0},as:{type:"array",items:{type:"string"},nullable:!0},bh:{...G5,nullable:!0},bt:{type:"string",nullable:!0},h:{type:"array",items:{type:"string"},nullable:!0},m:{type:"string",nullable:!0},mo:{type:"array",items:{...KT},nullable:!0},mt:{type:"string",nullable:!0},n:{type:"string",nullable:!0},o:{type:"number",nullable:!0},p:{...G5,nullable:!0},pe:{type:"number",nullable:!0},pn:{type:"string",nullable:!0},r:{...GT,nullable:!0},rm:{type:"boolean",nullable:!0},s:{type:"number",nullable:!0},sn:{type:"array",items:{type:"string"},nullable:!0},t:{...O6,nullable:!0}},required:["i"],additionalProperties:!1};var HT={type:"array",items:{...VT}};var qT={type:"object",properties:{i:{type:"number"},a:{type:"number",nullable:!0},e:{type:"number",nullable:!0},c:{...O6,nullable:!0},d:{type:"number",nullable:!0},n:{type:"number",nullable:!0},o:{...G5,nullable:!0},p:{...G5,nullable:!0},pe:{type:"number",minimum:0,maximum:1,nullable:!0},rm:{type:"boolean",nullable:!0},t:{type:"number",nullable:!0},te:{type:"number",nullable:!0},tp:{...G5,nullable:!0}},required:["i"],additionalProperties:!1};var zT={type:"array",items:{...qT}};var FT={type:"object",properties:{i:{type:"number"},at:{type:"number",nullable:!0},b:{type:"number",nullable:!0},ce:{...O6,nullable:!0},cev:{...O6,nullable:!0},cs:{...O6,nullable:!0},csv:{...O6,nullable:!0},e:{type:"number",nullable:!0},en:{type:"string",nullable:!0},g:{...G5,nullable:!0},l:{type:"number",nullable:!0},lv:{type:"number",nullable:!0},mp:{type:"number",nullable:!0},o:{...G5,nullable:!0},oe:{type:"number",nullable:!0},oev:{type:"number",nullable:!0},os:{type:"number",nullable:!0},osv:{type:"number",nullable:!0},p:{...G5,nullable:!0},pa:{type:"boolean",nullable:!0},pv:{...G5,nullable:!0},r:{type:"number",nullable:!0},rv:{type:"number",nullable:!0},rm:{type:"boolean",nullable:!0},se:{type:"number",nullable:!0},sev:{type:"number",nullable:!0},ss:{type:"number",nullable:!0},ssv:{type:"number",nullable:!0},t:{type:"boolean",nullable:!0},tu:{type:"string",nullable:!0},v:{...G5,nullable:!0},vv:{...G5,nullable:!0}},required:["i"],additionalProperties:!1};var UT={type:"array",items:{...FT}};var BT={type:"object",properties:{o:{...G5},d:{...G5},l:{type:"number"},h:{type:"boolean"}},required:["o","d","l","h"],additionalProperties:!1};var LT={type:"array",items:{...BT}};var wT={type:"object",properties:{v:{type:"array",items:{type:"number"}},c:{type:"array",items:{type:"number"}}},required:["v","c"],additionalProperties:!1};var OT={type:"object",properties:{i:{type:"string"},p:{type:"string",nullable:!0},rm:{type:"boolean",nullable:!0},u:{type:"string",nullable:!0}},required:["i"],additionalProperties:!1};var NT={type:"array",items:{...OT}};var jT={type:"object",properties:{i:{type:"number"},e:{type:"number",nullable:!0},o:{...G5,nullable:!0},p:{...G5,nullable:!0},rm:{type:"boolean",nullable:!0},s:{type:"object",nullable:!0},t:{type:"string",nullable:!0},v:{type:"number",nullable:!0}},required:["i"],additionalProperties:!1};var MT={type:"array",items:{...jT}};var RT={type:"object",properties:{r:{type:"number"},s:{type:"number"},p:{type:"number"},n:{type:"number"}},required:["r","s","p","n"],additionalProperties:!1};var DT={type:"object",properties:{p:{type:"boolean",nullable:!0},u:{type:"string",nullable:!0}},additionalProperties:!1};var PT={type:"array",items:{...vV}};var hD5={type:"array",items:[{type:"boolean"},{type:"boolean"},{type:"boolean"}],minItems:3,maxItems:3};var CT={type:"object",properties:{i:{type:"number"},ac:{...O6,nullable:!0},ai:{type:"number",nullable:!0},dc:{...O6,nullable:!0},di:{type:"number",nullable:!0},dp:{...G5,nullable:!0},fc:{...O6,nullable:!0},ff:{type:"number",nullable:!0},fn:{type:"number",nullable:!0},n:{type:"string",nullable:!0},s:{type:"string",nullable:!0},si:{type:"number",nullable:!0},t:{type:"number",nullable:!0}},required:["i"],additionalProperties:!1};var Ft=S0(40,$T);var Ut=S0(36,YT);var Bt=S0(37,WT);var Lt=S0(38,HT);var wt=S0(44,zT);var Ot=S0(46,UT);var Nt=S0(192,wT);var jt=S0(193,LT);var Mt=S0(45,NT);var Rt=S0(43,MT);var Dt=S0(32,RT);var Pt=S0(41,DT);var Ct=S0(42,PT);var Tt=S0(39,CT);var vB=new Map,bD5={...kB,...EB,...IB};for(let Z of Object.values(bD5))if("id"in Z&&"schema"in Z){let J=Z;if(vB.has(J.id))throw new Error(`Packet with id ${J.id} is already registered.`);vB.set(J.id,J)}function yD5(Z){if(typeof Z!=="object"||Z===null||typeof Z[0]!=="number"||Z[0]<0||Z[1]===void 0||Z[2]!==void 0&&(typeof Z[2]!=="number"||Z[2]<0))return!1;let J=vB.get(Z[0]);return!!J&&J.validate(Z[1])}var $0=TT;var ot=e(at(),1);import EY from"fs";import rt from"path";var _V="./dev/persistence";class QJ{static instance=new QJ;gameId=process.env.HYTOPIA_GAME_ID;lobbyId=process.env.HYTOPIA_LOBBY_ID;_creativeGateway;constructor(){try{this._creativeGateway=new ot.CreativeGateway}catch{console.warn(["━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","\uD83D\uDEA8 HYTOPIA PLATFORM GATEWAY IS NOT INITIALIZED \uD83D\uDEA8","","\uD83D\uDD27 Local development is still possible, but these features will be disabled:"," • \uD83D\uDC64 Player Accounts"," • \uD83C\uDFAD Player Cosmetics"," • \uD83D\uDC1B Crash Analytics & Debug Logs","","\uD83D\uDCA1 These features will be enabled but modified:"," • \uD83D\uDCBE Player & Global Persisted Data - Data will be persisted"," locally in the ./dev/persistence directory of your project."," Player ids for data persistence will begin at 1 for the first "," player to join your local server, and increments for each"," additional player. This means that if you restart your"," server, the first player id will be 1 again. This is to ensure"," that data persistence across server restarts can be easily"," tested and debugged in local development.","","To enable the HYTOPIA Platform Gateway locally:"," 1. Set these environment variables:"," HYTOPIA_API_KEY, HYTOPIA_GAME_ID, HYTOPIA_LOBBY_ID"," 2. You can find these values at: https://create.hytopia.com","","Note: In production, these environment variables will be auto-populated ","& the HYTOPIA Platform Gateway will automatically be initialized \uD83D\uDE80","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",""].join(`
92
92
  `))}}get isGatewayAvailable(){return!!this._creativeGateway}async getData(Z){if(!this._creativeGateway&&process.env.NODE_ENV==="production")return u.warning("PlatformGateway.getData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be returned.");return this._creativeGateway?await this._creativeGateway.kv.get(Z):this._readDevDataLocally(Z)}async getPlayerLoadout(Z){if(!this._creativeGateway)return;return await this._creativeGateway.getLoadout(Z)}async getPlayerSession(Z){if(!this._creativeGateway)return;return await this._creativeGateway.getSession(Z)}async setData(Z,J){if(J.error)return u.warning("PlatformGateway.setData(): Cannot set data with an error property.");if(!this._creativeGateway&&process.env.NODE_ENV==="production")return u.warning("PlatformGateway.setData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be set.");return this._creativeGateway?await this._creativeGateway.kv.set(Z,J):this._writeDevDataLocally(Z,J)}_readDevDataLocally(Z){try{if(!EY.existsSync(_V))return;let J=rt.join(_V,`${Z}.json`);return JSON.parse(EY.readFileSync(J,"utf8"))}catch(J){u.warning(`PlatformGateway._readDevDataLocally(): Failed to read data for key "${Z}": ${J}`)}}_writeDevDataLocally(Z,J){try{if(!EY.existsSync(_V))EY.mkdirSync(_V,{recursive:!0});let X=rt.join(_V,`${Z}.json`),$={};if(EY.existsSync(X))$=JSON.parse(EY.readFileSync(X,"utf8"));let Y={...$,...J};EY.writeFileSync(X,JSON.stringify(Y,null,2),"utf8")}catch(X){u.warning(`PlatformGateway._writeDevDataLocally(): Failed to write data for key "${Z}": ${X}`)}}}class IY{static instance=new IY;constructor(){}async getGlobalData(Z){let J=await QJ.instance.getData(Z);if(!J||J.error){if(J?.error)u.warning(`PersistenceManager.getGlobalData(): ${J.error.message}`);return}return J}async getPlayerData(Z){let J=await QJ.instance.getData(this._getPlayerKey(Z));if(!J||J.error){if(J?.error)u.warning(`PersistenceManager.getPlayerData(): ${J.error.message}`);return}return J}async setGlobalData(Z,J){let X=await QJ.instance.setData(Z,J);if(!X||X.error){if(X?.error)u.warning(`PersistenceManager.setGlobalData(): ${X.error.message}`);return}return X}async setPlayerData(Z,J){let X=await QJ.instance.setData(this._getPlayerKey(Z),J);if(!X||X.error){if(X?.error)u.warning(`PersistenceManager.setPlayerData(): ${X.error.message}`);return}return X}_getPlayerKey(Z){return`player-${Z.id}`}}var tt;(($)=>{$[$.FIRST_PERSON=0]="FIRST_PERSON";$[$.THIRD_PERSON=1]="THIRD_PERSON";$[$.SPECTATOR=2]="SPECTATOR"})(tt||={});var ET;((L)=>{L.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";L.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";L.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";L.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";L.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";L.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";L.SET_FOV="PLAYER_CAMERA.SET_FOV";L.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";L.SET_MODEL_SHOWN_NODES="PLAYER_CAMERA.SET_MODEL_SHOWN_NODES";L.SET_MODE="PLAYER_CAMERA.SET_MODE";L.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";L.SET_SHOULDER_ANGLE="PLAYER_CAMERA.SET_SHOULDER_ANGLE";L.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";L.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";L.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(ET||={});class AV extends D0{player;_attachedToEntity;_attachedToPosition;_filmOffset=0;_forwardOffset=0;_fov=75;_modelHiddenNodes=new Set;_modelShownNodes=new Set;_mode=1;_offset={x:0,y:0,z:0};_orientation={pitch:0,yaw:0};_shoulderAngle=0;_trackedEntity;_trackedPosition;_zoom=1;constructor(Z){super();this.player=Z}get attachedToEntity(){return this._attachedToEntity}get attachedToPosition(){return this._attachedToPosition}get facingDirection(){return{x:-Math.sin(this._orientation.yaw)*Math.cos(this._orientation.pitch),y:Math.sin(this._orientation.pitch),z:-Math.cos(this._orientation.yaw)*Math.cos(this._orientation.pitch)}}get facingQuaternion(){let Z=this._orientation.pitch*0.5,J=this._orientation.yaw*0.5,X=Math.cos(Z),$=Math.sin(Z),Y=Math.cos(J),Q=Math.sin(J);return{x:$*Y,y:X*Q,z:-$*Q,w:X*Y}}get filmOffset(){return this._filmOffset}get forwardOffset(){return this._forwardOffset}get fov(){return this._fov}get modelHiddenNodes(){return this._modelHiddenNodes}get modelShownNodes(){return this._modelShownNodes}get mode(){return this._mode}get offset(){return this._offset}get orientation(){return this._orientation}get shoulderAngle(){return this._shoulderAngle}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get zoom(){return this._zoom}lookAtEntity(Z){if(!this._requirePlayerWorld("lookAtEntity"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_ENTITY",{playerCamera:this,entity:Z})}lookAtPosition(Z){if(!this._requirePlayerWorld("lookAtPosition"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_POSITION",{playerCamera:this,position:Z})}reset(){this._attachedToEntity=void 0,this._attachedToPosition=void 0,this._orientation={pitch:0,yaw:0},this._trackedEntity=void 0,this._trackedPosition=void 0}setAttachedToEntity(Z){if(!this._requirePlayerWorld("setAttachedToEntity"))return;if(!Z.isSpawned)return u.error(`PlayerCamera.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);this._attachedToEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",{playerCamera:this,entity:Z})}setAttachedToPosition(Z){if(!this._requirePlayerWorld("setAttachedToPosition"))return;this._attachedToPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",{playerCamera:this,position:Z})}setFilmOffset(Z){if(!this._requirePlayerWorld("setFilmOffset"))return;this._filmOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FILM_OFFSET",{playerCamera:this,filmOffset:Z})}setForwardOffset(Z){if(!this._requirePlayerWorld("setForwardOffset"))return;this._forwardOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FORWARD_OFFSET",{playerCamera:this,forwardOffset:Z})}setFov(Z){if(!this._requirePlayerWorld("setFov"))return;this._fov=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FOV",{playerCamera:this,fov:Z})}setModelHiddenNodes(Z){if(!this._requirePlayerWorld("setModelHiddenNodes"))return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",{playerCamera:this,modelHiddenNodes:this._modelHiddenNodes})}setModelShownNodes(Z){if(!this._requirePlayerWorld("setModelShownNodes"))return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",{playerCamera:this,modelShownNodes:this._modelShownNodes})}setMode(Z){if(!this._requirePlayerWorld("setMode"))return;this._mode=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODE",{playerCamera:this,mode:Z})}setOffset(Z){if(!this._requirePlayerWorld("setOffset"))return;this._offset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_OFFSET",{playerCamera:this,offset:Z})}setOrientationPitch(Z){this._orientation.pitch=Z}setOrientationYaw(Z){this._orientation.yaw=Z}setShoulderAngle(Z){if(!this._requirePlayerWorld("setShoulderAngle"))return;this._shoulderAngle=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_SHOULDER_ANGLE",{playerCamera:this,shoulderAngle:Z})}setTrackedEntity(Z){if(!this._requirePlayerWorld("setTrackedEntity"))return;this._trackedEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_ENTITY",{playerCamera:this,entity:Z})}setTrackedPosition(Z){if(!this._requirePlayerWorld("setTrackedPosition"))return;this._trackedPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_POSITION",{playerCamera:this,position:Z})}setZoom(Z){if(!this._requirePlayerWorld("setZoom"))return;this._zoom=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ZOOM",{playerCamera:this,zoom:Z})}serialize(){return E0.serializePlayerCamera(this)}_requirePlayerWorld(Z){if(!this.player.world)u.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world, invoked method: ${Z}()`);return!!this.player.world}}var _B;((Y)=>{Y.DATA="PLAYER_UI.DATA";Y.LOAD="PLAYER_UI.LOAD";Y.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";Y.SEND_DATA="PLAYER_UI.SEND_DATA"})(_B||={});class xV extends D0{player;constructor(Z){super();this.player=Z}load(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOAD",{playerUI:this,htmlUri:Z})}lockPointer(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOCK_POINTER",{playerUI:this,lock:Z})}sendData(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.SEND_DATA",{playerUI:this,data:Z})}}var et=["w","a","s","d","sp","sh","tb","ml","mr","q","e","r","f","z","x","c","v","u","i","o","j","k","l","n","m","1","2","3","4","5","6","7","8","9","0"],fV;((Q)=>{Q.CHAT_MESSAGE_SEND="PLAYER.CHAT_MESSAGE_SEND";Q.JOINED_WORLD="PLAYER.JOINED_WORLD";Q.LEFT_WORLD="PLAYER.LEFT_WORLD";Q.RECONNECTED_WORLD="PLAYER.RECONNECTED_WORLD";Q.REQUEST_SYNC="PLAYER.REQUEST_SYNC"})(fV||={});class YK extends D0{static _devNextPlayerId=1;id;username;profilePictureUrl;camera;connection;ui;_input={};_lastUnreliableInputSequenceNumber=0;_persistedData;_world;_worldSwitched=!1;constructor(Z,J){super();this.id=J?.user.id??`player-${YK._devNextPlayerId++}`,this.username=J?.user.username??this.id,this.profilePictureUrl=J?.user.profilePictureURL??void 0,this.camera=new AV(this),this.connection=Z,this.ui=new xV(this),Z.onPacket($0.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),Z.onPacket($0.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),Z.onPacket($0.PacketId.INPUT,this._onInputPacket),Z.onPacket($0.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),Z.onPacket($0.PacketId.UI_DATA_SEND,this._onUIDataSendPacket)}get input(){return this._input}get world(){return this._world}disconnect(){this._leaveWorld(),this.connection.disconnect()}getPersistedData(){return this._persistedData}joinWorld(Z){if(this._world===Z)return;if(!this._world)this._world=Z,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world});else{for(let J of this._world.entityManager.getPlayerEntitiesByPlayer(this))if(J.isSpawned)J.despawn();this.disconnect(),this._world=Z,this._worldSwitched=!0}}async loadInitialPersistedData(){if(this._persistedData)return;this._persistedData=await IY.instance.getPlayerData(this)??void 0}reconnected(){if(!this._world)return;if(this._lastUnreliableInputSequenceNumber=0,!this._worldSwitched)this.emitWithWorld(this._world,"PLAYER.RECONNECTED_WORLD",{player:this,world:this._world});else this._worldSwitched=!1,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world})}resetInputs(){this._input={}}setPersistedData(Z){return this._persistedData={...this._persistedData,...Z},IY.instance.setPlayerData(this,Z).catch((J)=>{}),this._persistedData}serialize(){return E0.serializePlayer(this)}_leaveWorld(){if(!this._world)return;this.emitWithWorld(this._world,"PLAYER.LEFT_WORLD",{player:this,world:this._world}),this._world=void 0}_onChatMessageSendPacket=(Z)=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.CHAT_MESSAGE_SEND",{player:this,message:Z[1].m})};_onDebugConfigPacket=(Z)=>{console.log(Z)};_onInputPacket=(Z)=>{let J=Z[1];if(J.sq!==void 0){if(J.sq<this._lastUnreliableInputSequenceNumber)return;this._lastUnreliableInputSequenceNumber=J.sq}if(et.forEach((X)=>{let $=X;if(J[$]!==void 0)this._input[$]=Boolean(J[$])}),J.cp!==void 0)this.camera.setOrientationPitch(J.cp);if(J.cy!==void 0)this.camera.setOrientationYaw(J.cy)};_onSyncRequestPacket=()=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.REQUEST_SYNC",{player:this,receivedAt:Date.now(),receivedAtMs:performance.now()})};_onUIDataSendPacket=(Z)=>{this.ui.emit("PLAYER_UI.DATA",{playerUI:this.ui,data:Z[1]})}}var IT;((X)=>{X.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";X.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(IT||={});class hV extends D0{_commandCallbacks={};_world;constructor(Z){super();this._world=Z,this._subscribeToPlayerEvents()}registerCommand(Z,J){this._commandCallbacks[Z]=J}unregisterCommand(Z){delete this._commandCallbacks[Z]}sendBroadcastMessage(Z,J){this._sendBroadcastMessage(void 0,Z,J)}sendPlayerMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.PLAYER_MESSAGE",{player:Z,message:J,color:X})}_subscribeToPlayerEvents(){this._world.on("PLAYER.CHAT_MESSAGE_SEND",(Z)=>{let{player:J,message:X}=Z,[$,...Y]=X.split(" "),Q=this._commandCallbacks[$];if(Q){Q(J,Y,X);return}this._sendBroadcastMessage(J,X)})}_sendBroadcastMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.BROADCAST_MESSAGE",{player:Z,message:J,color:X})}}var b7=16,vT=b7-1,VP5=b7**3;class y7{_blocks;_originCoordinate;constructor(Z){this._blocks=new Uint8Array(VP5),this._originCoordinate=Z}get blocks(){return this._blocks}get originCoordinate(){return this._originCoordinate}static blockIndexToLocalCoordinate(Z){return{x:Z%b7,y:(Z/b7|0)%b7,z:Z/(b7*b7)|0}}static globalCoordinateToLocalCoordinate(Z){return{x:Z.x&b7-1,y:Z.y&b7-1,z:Z.z&b7-1}}static globalCoordinateToOriginCoordinate(Z){return{x:Z.x&~(b7-1),y:Z.y&~(b7-1),z:Z.z&~(b7-1)}}getBlockId(Z){return this._blocks[this._getIndex(Z)]}hasBlock(Z){return this._blocks[this._getIndex(Z)]!==0}setBlock(Z,J){if(!this._isValidLocalCoordinate(Z))return u.error("Chunk.setBlock(): Block local coordinate is out of bounds");let X=this._getIndex(Z);this._blocks[X]=J}serialize(){return E0.serializeChunk(this)}_getIndex(Z){return Z.x+(Z.y<<4)+(Z.z<<8)}_isValidLocalCoordinate(Z){return Z.x>=0&&Z.x<=vT&&Z.y>=0&&Z.y<=vT&&Z.z>=0&&Z.z<=vT}}var ST;(($)=>{$.ADD_CHUNK="CHUNK_LATTICE.ADD_CHUNK";$.REMOVE_CHUNK="CHUNK_LATTICE.REMOVE_CHUNK";$.SET_BLOCK="CHUNK_LATTICE.SET_BLOCK"})(ST||={});class bV extends D0{_blockTypeColliders=new Map;_blockTypeCounts=new Map;_chunks=new Map;_rigidBody;_world;constructor(Z){super();this._world=Z}get chunkCount(){return this._chunks.size}clear(){for(let Z of this._blockTypeColliders.values())this._world.simulation.colliderMap.removeColliderBlockType(Z),Z.removeFromSimulation();this._chunks.forEach((Z)=>{this.emitWithWorld(this._world,"CHUNK_LATTICE.REMOVE_CHUNK",{chunkLattice:this,chunk:Z})}),this._blockTypeColliders.clear(),this._blockTypeCounts.clear(),this._chunks.clear()}getBlockId(Z){let J=this.getChunk(y7.globalCoordinateToOriginCoordinate(Z));if(!J)return 0;return J.getBlockId(y7.globalCoordinateToLocalCoordinate(Z))}getBlockTypeCollider(Z){return this._blockTypeColliders.get(Z)}getBlockType(Z){let J=this.getBlockId(Z);return J?this._world.blockTypeRegistry.getBlockType(J):null}getBlockTypeCount(Z){return this._blockTypeCounts.get(Z)??0}getChunk(Z){return this._chunks.get(this._getChunkKey(y7.globalCoordinateToOriginCoordinate(Z)))}getOrCreateBlockTypeCollider(Z,J){let X=this._blockTypeColliders.get(Z);if(X)return X;let Y=this._world.blockTypeRegistry.getBlockType(Z).createCollider(J);return this._blockTypeColliders.set(Z,Y),Y}getOrCreateChunk(Z){let J=y7.globalCoordinateToOriginCoordinate(Z),X=this._chunks.get(this._getChunkKey(J));if(X)return X;return X=new y7(J),this._chunks.set(this._getChunkKey(J),X),this.emitWithWorld(this._world,"CHUNK_LATTICE.ADD_CHUNK",{chunkLattice:this,chunk:X}),X}getAllChunks(){return Array.from(this._chunks.values())}hasBlock(Z){let J=this.getChunk(y7.globalCoordinateToOriginCoordinate(Z));if(!J)return!1;return J.hasBlock(y7.globalCoordinateToLocalCoordinate(Z))}hasChunk(Z){let J=y7.globalCoordinateToOriginCoordinate(Z);return this._chunks.has(this._getChunkKey(J))}setBlock(Z,J){let X=y7.globalCoordinateToLocalCoordinate(Z),$=this.getOrCreateChunk(Z),Y=$.getBlockId(X);if(Y===J)return;if($.setBlock(X,J),!this._rigidBody)this._rigidBody=new MY({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);if(Y!==0){let Q=Math.max(0,(this._blockTypeCounts.get(Y)??0)-1),W=this.getBlockTypeCollider(Y);if(W)if(Q===0)this._world.simulation.colliderMap.removeColliderBlockType(W),W.removeFromSimulation(),this._blockTypeColliders.delete(Y);else W.setVoxel(Z,!1),this._propagateVoxelChange(W,Z);this._blockTypeCounts.set(Y,Q)}if(J!==0){let Q=(this._blockTypeCounts.get(J)??0)+1,W=this.getOrCreateBlockTypeCollider(J,[Z]);if(Q===1){let K=this._world.blockTypeRegistry.getBlockType(J);W.addToSimulation(this._world.simulation,this._rigidBody),this._world.simulation.colliderMap.setColliderBlockType(W,K),this._combineVoxelStates(W)}else W.setVoxel(Z,!0),this._propagateVoxelChange(W,Z);this._blockTypeCounts.set(J,Q)}this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:$,globalCoordinate:Z,localCoordinate:X,blockTypeId:J})}_combineVoxelStates(Z){if(Z.isSensor)return;for(let J of this._blockTypeColliders.values()){if(J===Z||J.isSensor)continue;Z.combineVoxelStates(J)}}_getChunkKey(Z){return`${Z.x},${Z.y},${Z.z}`}_propagateVoxelChange(Z,J){if(Z.isSensor)return;for(let X of this._blockTypeColliders.values()){if(X===Z||X.isSensor)continue;Z.propagateVoxelChange(X,J)}}}class yV{_colliderHandleBlockTypeMap=new Map;_colliderHandleCollisionCallbackMap=new Map;_colliderHandleEntityMap=new Map;_cleanupBlockTypeColliderHandles=new Set;_pendingCleanupBlockTypeColliderHandles=new Set;_cleanupCollisionCallbackColliderHandles=new Set;_pendingCleanupCollisionCallbackColliderHandles=new Set;_cleanupEntityColliderHandles=new Set;_pendingCleanupEntityColliderHandles=new Set;getColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleBlockTypeMap.get(Z.rawCollider.handle)}getColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleCollisionCallbackMap.get(Z.rawCollider.handle)}getColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleEntityMap.get(Z.rawCollider.handle)}getColliderHandleBlockType(Z){return this._colliderHandleBlockTypeMap.get(Z)}getColliderHandleCollisionCallback(Z){return this._colliderHandleCollisionCallbackMap.get(Z)}getColliderHandleEntity(Z){return this._colliderHandleEntityMap.get(Z)}removeColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleBlockType(Z.rawCollider.handle)}removeColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleCollisionCallback(Z.rawCollider.handle)}removeColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleEntity(Z.rawCollider.handle)}removeColliderHandleBlockType(Z){this._colliderHandleBlockTypeMap.delete(Z)}removeColliderHandleCollisionCallback(Z){this._colliderHandleCollisionCallbackMap.delete(Z)}removeColliderHandleEntity(Z){this._colliderHandleEntityMap.delete(Z)}setColliderBlockType(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleBlockType(Z.rawCollider.handle,J)}setColliderCollisionCallback(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleCollisionCallback(Z.rawCollider.handle,J)}setColliderEntity(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleEntity(Z.rawCollider.handle,J)}setColliderHandleBlockType(Z,J){this._colliderHandleBlockTypeMap.set(Z,J),this._cleanupBlockTypeColliderHandles.delete(Z),this._pendingCleanupBlockTypeColliderHandles.delete(Z)}setColliderHandleCollisionCallback(Z,J){this._colliderHandleCollisionCallbackMap.set(Z,J),this._cleanupCollisionCallbackColliderHandles.delete(Z),this._pendingCleanupCollisionCallbackColliderHandles.delete(Z)}setColliderHandleEntity(Z,J){this._colliderHandleEntityMap.set(Z,J),this._cleanupEntityColliderHandles.delete(Z),this._pendingCleanupEntityColliderHandles.delete(Z)}queueColliderHandleForCleanup(Z){if(this._colliderHandleBlockTypeMap.has(Z))this._pendingCleanupBlockTypeColliderHandles.add(Z);if(this._colliderHandleCollisionCallbackMap.has(Z))this._pendingCleanupCollisionCallbackColliderHandles.add(Z);if(this._colliderHandleEntityMap.has(Z))this._pendingCleanupEntityColliderHandles.add(Z)}cleanup(){for(let Z of this._cleanupBlockTypeColliderHandles)this._colliderHandleBlockTypeMap.delete(Z);if(this._cleanupBlockTypeColliderHandles.size>0)this._cleanupBlockTypeColliderHandles.clear();for(let Z of this._cleanupCollisionCallbackColliderHandles)this._colliderHandleCollisionCallbackMap.delete(Z);if(this._cleanupCollisionCallbackColliderHandles.size>0)this._cleanupCollisionCallbackColliderHandles.clear();for(let Z of this._cleanupEntityColliderHandles)this._colliderHandleEntityMap.delete(Z);if(this._cleanupEntityColliderHandles.size>0)this._cleanupEntityColliderHandles.clear();for(let Z of this._pendingCleanupBlockTypeColliderHandles)this._cleanupBlockTypeColliderHandles.add(Z);if(this._pendingCleanupBlockTypeColliderHandles.size>0)this._pendingCleanupBlockTypeColliderHandles.clear();for(let Z of this._pendingCleanupCollisionCallbackColliderHandles)this._cleanupCollisionCallbackColliderHandles.add(Z);if(this._pendingCleanupCollisionCallbackColliderHandles.size>0)this._pendingCleanupCollisionCallbackColliderHandles.clear();for(let Z of this._pendingCleanupEntityColliderHandles)this._cleanupEntityColliderHandles.add(Z);if(this._pendingCleanupEntityColliderHandles.size>0)this._pendingCleanupEntityColliderHandles.clear()}_requireSimulatedCollider(Z){if(!Z.rawCollider)u.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!Z.rawCollider}}var Ze={type:"dynamic",softCcdPrediction:1},Je=0.015625,Xe=Math.cos(0.026),gV;((N)=>{N.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";N.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";N.DESPAWN="ENTITY.DESPAWN";N.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";N.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";N.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";N.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";N.SET_MODEL_SCALE="ENTITY.SET_MODEL_SCALE";N.SET_MODEL_SHOWN_NODES="ENTITY.SET_MODEL_SHOWN_NODES";N.SET_MODEL_TEXTURE_URI="ENTITY.SET_MODEL_TEXTURE_URI";N.SET_OPACITY="ENTITY.SET_OPACITY";N.SET_PARENT="ENTITY.SET_PARENT";N.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";N.SPAWN="ENTITY.SPAWN";N.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";N.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";N.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";N.TICK="ENTITY.TICK";N.UPDATE_POSITION="ENTITY.UPDATE_POSITION";N.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})(gV||={});class h8 extends MY{_id;_blockHalfExtents;_blockTextureUri;_controller;_isEnvironmental=!1;_modelAnimationsPlaybackRate=1;_modelHiddenNodes=new Set;_modelLoopedAnimations=new Set;_modelOneshotAnimations=new Set;_modelPreferredShape;_modelScale=1;_modelShownNodes=new Set;_modelTextureUri;_modelUri;_name;_opacity;_parent;_parentNodeName;_tag;_tintColor;_lastUpdatedPosition={x:0,y:0,z:0};_lastUpdatedRotation={x:0,y:0,z:0,w:1};_lastParentlessType="dynamic";_world;_positionUpdateThresholdSq;_rotationUpdateThreshold;constructor(Z){let J="blockTextureUri"in Z,X="modelUri"in Z;if(!J===!X)u.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(J&&!Z.blockHalfExtents)u.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(Z.parent&&!Z.parent.isSpawned)u.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(Z.parent?.modelUri&&Z.parentNodeName&&!V7.instance.modelHasNode(Z.parent.modelUri,Z.parentNodeName))u.fatalError(`Entity.constructor(): Parent node name ${Z.parentNodeName} not found in parent model ${Z.parent.modelUri}!`);super(Z.rigidBodyOptions??Ze);if(J)this._blockHalfExtents=Z.blockHalfExtents,this._blockTextureUri=Z.blockTextureUri;if(X)this._modelAnimationsPlaybackRate=Z.modelAnimationsPlaybackRate??1,this._modelPreferredShape=Z.modelPreferredShape,this._modelScale=Z.modelScale??1,this._modelTextureUri=Z.modelTextureUri,this._modelUri=Z.modelUri,Z.modelHiddenNodes?.forEach(($)=>this._modelHiddenNodes.add($.toLowerCase())),Z.modelLoopedAnimations?.forEach(($)=>this._modelLoopedAnimations.add($)),Z.modelShownNodes?.forEach(($)=>this._modelShownNodes.add($.toLowerCase()));if(this._isEnvironmental=Z.isEnvironmental??!1,this._name=Z.name??"Nameless",this._opacity=Z.opacity??1,this._parent=Z.parent,this._parentNodeName=Z.parentNodeName,this._tag=Z.tag,this._tintColor=Z.tintColor,this._positionUpdateThresholdSq=Je,this._rotationUpdateThreshold=Xe,Z.controller)this.setController(Z.controller)}get id(){return this._id}get blockHalfExtents(){return this._blockHalfExtents}get blockTextureUri(){return this._blockTextureUri}get controller(){return this._controller}get depth(){return this.isModelEntity?V7.instance.getDepth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.z*2}get height(){return this.isModelEntity?V7.instance.getHeight(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.y*2}get modelAnimationsPlaybackRate(){return this._modelAnimationsPlaybackRate}get modelHiddenNodes(){return this._modelHiddenNodes}get modelLoopedAnimations(){return this._modelLoopedAnimations}get modelPreferredShape(){return this._modelPreferredShape}get modelScale(){return this._modelScale}get modelShownNodes(){return this._modelShownNodes}get modelTextureUri(){return this._modelTextureUri}get modelUri(){return this._modelUri}get name(){return this._name}get opacity(){return this._opacity}get parent(){return this._parent}get parentNodeName(){return this._parentNodeName}get tag(){return this._tag}get tintColor(){return this._tintColor}get isBlockEntity(){return!!this._blockTextureUri}get isEnvironmental(){return this._isEnvironmental}get isModelEntity(){return!!this._modelUri}get isSpawned(){return!!this._world}get width(){return this.isModelEntity?V7.instance.getWidth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.x*2}get world(){return this._world}spawn(Z,J,X){if(this.isSpawned)return u.error(`Entity.spawn(): Entity ${this._name} is already spawned with id ${this._id}!`);if(!this.isSimulated)this.addToSimulation(Z.simulation);if(this._blockTextureUri&&this._blockHalfExtents&&this.numColliders===0)this.addChildColliderToSimulation(new f7(f7.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new f7(f7.optionsFromModelUri(this._modelUri,this._modelScale,this._modelPreferredShape)));if(this.colliders.forEach(($)=>{if(this.hasListeners("ENTITY.BLOCK_COLLISION")||this.hasListeners("ENTITY.ENTITY_COLLISION"))$.enableCollisionEvents(!0);if(this.hasListeners("ENTITY.BLOCK_CONTACT_FORCE")||this.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))$.enableContactForceEvents(!0);if(e9.isDefaultCollisionGroups($.collisionGroups)){let Y=this.isEnvironmental?[8]:[$.isSensor?4:2],Q=this.isEnvironmental?[65535&~8&~1]:[65535];$.setCollisionGroups({belongsTo:Y,collidesWith:Q})}}),this.setPosition(J),X)this.setRotation(X);if(this._id=Z.entityManager.registerEntity(this),this._world=Z,this._controller)this._controller.spawn(this);if(this._parent)this.setParent(this._parent,this._parentNodeName,J,X);this.colliders.forEach(($)=>{Z.simulation.colliderMap.setColliderEntity($,this)}),this.emitWithWorld(Z,"ENTITY.SPAWN",{entity:this})}despawn(){if(!this._requireSpawned("despawn"))return;if(this._world.entityManager.getEntityChildren(this).forEach((Z)=>{Z.despawn()}),this._controller)this._controller.detach(this),this._controller.despawn(this);if(this.emitWithWorld(this._world,"ENTITY.DESPAWN",{entity:this}),this.isSimulated)this.removeFromSimulation();this._world.entityManager.unregisterEntity(this),this._world.audioManager.unregisterEntityAttachedAudios(this),this._world.lightManager.despawnEntityAttachedLights(this),this._world.particleEmitterManager.despawnEntityAttachedParticleEmitters(this),this._world.sceneUIManager.unloadEntityAttachedSceneUIs(this),this._id=void 0,this._world=void 0}setController(Z){if(this._controller===Z)return;if(this._controller)this._controller.detach(this);if(this._controller=Z,this._controller)this._controller.attach(this)}setModelAnimationsPlaybackRate(Z){if(!this._requireSpawned("setModelAnimationsPlaybackRate"))return;if(!this.isModelEntity||this._modelAnimationsPlaybackRate===Z)return;this._modelAnimationsPlaybackRate=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",{entity:this,playbackRate:Z})}setModelHiddenNodes(Z){if(!this._requireSpawned("setModelHiddenNodes"))return;if(!this.isModelEntity)return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_HIDDEN_NODES",{entity:this,modelHiddenNodes:this._modelHiddenNodes})}setModelScale(Z){if(!this._requireSpawned("setModelScale"))return;if(!this.isModelEntity||this._modelScale===Z)return;let J=Z/this._modelScale;this._modelScale=Z,this.colliders.forEach((X)=>X.scale(J)),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SCALE",{entity:this,modelScale:Z})}setModelShownNodes(Z){if(!this._requireSpawned("setModelShownNodes"))return;if(!this.isModelEntity)return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SHOWN_NODES",{entity:this,modelShownNodes:this._modelShownNodes})}setModelTextureUri(Z){if(!this._requireSpawned("setModelTextureUri"))return;if(!this.isModelEntity||this._modelTextureUri===Z)return;this._modelTextureUri=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_TEXTURE_URI",{entity:this,modelTextureUri:Z})}setOpacity(Z){if(!this._requireSpawned("setOpacity"))return;if(this._opacity===Z)return;this._opacity=Z,this.emitWithWorld(this._world,"ENTITY.SET_OPACITY",{entity:this,opacity:Z})}setParent(Z,J,X,$){if(!this._requireSpawned("setParent"))return;if(Z&&!Z.isSpawned)return u.error("Entity.setParent(): Parent entity is not spawned, cannot set parent!");if(!this._parent&&Z)this._lastParentlessType=this.type;if(this._parent=Z,this._parentNodeName=J,this.colliders.forEach((Y)=>Y.setEnabled(!Z)),this.setType(!Z?this._lastParentlessType:"kinematic_velocity"),this.setPosition(X??{x:0,y:0,z:0}),this.setRotation($??{x:0,y:0,z:0,w:1}),!this.isKinematicPositionBased)this.resetAngularVelocity(),this.resetForces(),this.resetLinearVelocity(),this.resetTorques();this.emitWithWorld(this._world,"ENTITY.SET_PARENT",{entity:this,parent:Z,parentNodeName:J})}setTintColor(Z){if(!this._requireSpawned("setTintColor"))return;if(!Z&&!this._tintColor||Z&&this._tintColor&&Z.r===this._tintColor.r&&Z.g===this._tintColor.g&&Z.b===this._tintColor.b)return;this._tintColor=Z,this.emitWithWorld(this._world,"ENTITY.SET_TINT_COLOR",{entity:this,tintColor:Z})}startModelLoopedAnimations(Z){if(!this._requireSpawned("startModelLoopedAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>!this._modelLoopedAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_LOOPED_ANIMATIONS",{entity:this,animations:new Set(Z)})}startModelOneshotAnimations(Z){if(!this._requireSpawned("startModelOneshotAnimations"))return;if(!this.isModelEntity||!Z.length)return;Z.forEach((J)=>{this._modelOneshotAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_ONESHOT_ANIMATIONS",{entity:this,animations:new Set(Z)})}stopAllModelAnimations(Z=[]){if(!this._requireSpawned("stopAllModelAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations,this._modelOneshotAnimations],Z)}stopAllModelLoopedAnimations(Z=[]){if(!this._requireSpawned("stopAllModelLoopedAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations],Z)}stopAllModelOneshotAnimations(Z=[]){if(!this._requireSpawned("stopAllModelOneshotAnimations"))return;this._stopAnimationsFromSets([this._modelOneshotAnimations],Z)}stopModelAnimations(Z){if(!this._requireSpawned("stopModelAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>this._modelLoopedAnimations.has(J))&&!Z.some((J)=>this._modelOneshotAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.delete(J),this._modelOneshotAnimations.delete(J)}),this.emitWithWorld(this._world,"ENTITY.STOP_MODEL_ANIMATIONS",{entity:this,animations:new Set(Z)})}serialize(){return E0.serializeEntity(this)}tick(Z){if(this.emit("ENTITY.TICK",{entity:this,tickDeltaMs:Z}),this._controller)this._controller.tick(this,Z)}checkAndEmitUpdates(){if(!this._requireSpawned("checkAndEmitUpdates"))return;let Z=this.position,J=this.rotation;if(this._rotationExceedsThreshold(J,this._lastUpdatedRotation))this._lastUpdatedRotation=J,this.emitWithWorld(this._world,"ENTITY.UPDATE_ROTATION",{entity:this,rotation:J});if(this._positionExceedsThreshold(Z,this._lastUpdatedPosition))this._lastUpdatedPosition=Z,this.emitWithWorld(this._world,"ENTITY.UPDATE_POSITION",{entity:this,position:Z})}_positionExceedsThreshold(Z,J){let X=Z.x-J.x,$=Z.y-J.y,Y=Z.z-J.z;return X*X+$*$+Y*Y>this._positionUpdateThresholdSq}_requireSpawned(Z){if(!this.isSpawned)u.error(`Entity._requireSpawned(): Entity ${this._name} is not spawned, cannot invoke ${Z}()!`);return this.isSpawned}_rotationExceedsThreshold(Z,J){return Math.abs(Z.x*J.x+Z.y*J.y+Z.z*J.z+Z.w*J.w)<this._rotationUpdateThreshold}_stopAnimationsFromSets(Z,J=[]){if(!this.isModelEntity)return;let X=new Set(J),$=[];for(let Y of Z)for(let Q of Y)if(!X.has(Q))$.push(Q);if($.length>0)this.stopModelAnimations($)}}class A5 extends f${static BASE_ENTITY_HEIGHT=1.5;static GROUND_SENSOR_HEIGHT_SCALE=0.125;static GROUND_SENSOR_RADIUS_SCALE=0.23;static JUMP_LAND_HEAVY_VELOCITY_THRESHOLD=-12;static WALL_COLLIDER_HEIGHT_SCALE=0.33;static WALL_COLLIDER_RADIUS_SCALE=0.4;static MOVEMENT_ROTATIONS={wa:Math.PI/4,wd:-Math.PI/4,sa:Math.PI-Math.PI/4,sd:Math.PI+Math.PI/4,s:Math.PI,asd:Math.PI,a:Math.PI/2,d:-Math.PI/2};static EXTERNAL_IMPULSE_DECAY_RATE=0.253;static SWIM_UPWARD_COOLDOWN_MS=600;static SWIMMING_DRAG_FACTOR=0.05;static WATER_ENTRY_SINKING_FACTOR=0.8;static WATER_ENTRY_SINKING_MS=250;applyDirectionalMovementRotations=!0;autoCancelMouseLeftClick=!0;canJump=()=>!0;canRun=()=>!0;canSwim=()=>!0;canWalk=()=>!0;faceForwardOnStop=!0;idleLoopedAnimations=["idle-upper","idle-lower"];interactOneshotAnimations=["simple-interact"];jumpLandHeavyOneshotAnimations=["jump-post-heavy"];jumpLandLightOneshotAnimations=["jump-post-light"];jumpOneshotAnimations=["jump-loop"];jumpVelocity=10;runLoopedAnimations=["run-upper","run-lower"];runVelocity=8;sticksToPlatforms=!0;swimFastVelocity=5;swimGravity=0;swimIdleLoopedAnimations=["swim-idle"];swimLoopedAnimations=["swim-forward"];swimMaxGravityVelocity=-1;swimSlowVelocity=3;swimUpwardVelocity=2;walkLoopedAnimations=["walk-upper","walk-lower"];walkVelocity=4;_externalVelocity={x:0,y:0,z:0};_magnitudeYTracker=0;_groundContactCount=0;_internalApplyImpulse=()=>{};_isActivelyMoving=!1;_isFullySubmerged=!1;_justSubmergedUntil=0;_liquidContactCount=0;_platform;_reusableImpulse={x:0,y:0,z:0};_reusablePlatformVelocity={x:0,y:0,z:0};_reusableTargetVelocities={x:0,y:0,z:0};_reusableVelocityClamp={x:0,y:0,z:0};_stepAudio;_swimUpwardCooldownAt=0;constructor(Z={}){super();this.applyDirectionalMovementRotations=Z.applyDirectionalMovementRotations??this.applyDirectionalMovementRotations,this.autoCancelMouseLeftClick=Z.autoCancelMouseLeftClick??this.autoCancelMouseLeftClick,this.faceForwardOnStop=Z.faceForwardOnStop??this.faceForwardOnStop,this.sticksToPlatforms=Z.sticksToPlatforms??this.sticksToPlatforms,this.canJump=Z.canJump??this.canJump,this.canRun=Z.canRun??this.canRun,this.canSwim=Z.canSwim??this.canSwim,this.canWalk=Z.canWalk??this.canWalk,this.jumpVelocity=Z.jumpVelocity??this.jumpVelocity,this.runVelocity=Z.runVelocity??this.runVelocity,this.walkVelocity=Z.walkVelocity??this.walkVelocity,this.swimFastVelocity=Z.swimFastVelocity??this.swimFastVelocity,this.swimSlowVelocity=Z.swimSlowVelocity??this.swimSlowVelocity,this.swimUpwardVelocity=Z.swimUpwardVelocity??this.swimUpwardVelocity,this.swimGravity=Z.swimGravity??this.swimGravity,this.swimMaxGravityVelocity=Z.swimMaxGravityVelocity??this.swimMaxGravityVelocity,this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.interactOneshotAnimations=Z.interactOneshotAnimations??this.interactOneshotAnimations,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.jumpLandHeavyOneshotAnimations=Z.jumpLandHeavyOneshotAnimations??this.jumpLandHeavyOneshotAnimations,this.jumpLandLightOneshotAnimations=Z.jumpLandLightOneshotAnimations??this.jumpLandLightOneshotAnimations,this.runLoopedAnimations=Z.runLoopedAnimations??this.runLoopedAnimations,this.swimLoopedAnimations=Z.swimLoopedAnimations??this.swimLoopedAnimations,this.swimIdleLoopedAnimations=Z.swimIdleLoopedAnimations??this.swimIdleLoopedAnimations,this.walkLoopedAnimations=Z.walkLoopedAnimations??this.walkLoopedAnimations}get isActivelyMoving(){return this._isActivelyMoving}get isGrounded(){return this._groundContactCount>0}get isOnPlatform(){return!!this._platform}get isSwimming(){return this._liquidContactCount>0}get platform(){return this._platform}attach(Z){super.attach(Z),this._internalApplyImpulse=Z.applyImpulse.bind(Z),Z.applyImpulse=(J)=>{let X=Z.mass||1;this._externalVelocity.x+=J.x/X,this._externalVelocity.y+=J.y/X,this._externalVelocity.z+=J.z/X},this._stepAudio=new I4({uri:"audio/sfx/step/stone/stone-step-04.mp3",loop:!0,volume:0.1,referenceDistance:2,cutoffDistance:15,attachedToEntity:Z}),Z.setCcdEnabled(!0),Z.lockAllRotations(),Z.on("ENTITY.BLOCK_COLLISION",({blockType:J,started:X})=>{if(!J.isLiquid||!this.canSwim(this))return;if(this._liquidContactCount<=0&&X){let $=Z.linearVelocity;Z.setLinearVelocity({x:$.x*this.swimGravity,y:$.y*this.swimGravity,z:$.z*this.swimGravity})}if(this._liquidContactCount+=X?1:-1,this._liquidContactCount>0)Z.setGravityScale(this.swimGravity),Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),this._swimUpwardCooldownAt=performance.now()+A5.SWIM_UPWARD_COOLDOWN_MS;else Z.setGravityScale(1),Z.stopModelAnimations(this.swimLoopedAnimations)})}spawn(Z){if(!Z.isSpawned)return u.error("DefaultPlayerEntityController.spawn(): Entity is not spawned!");Z.createAndAddChildCollider({shape:"cylinder",radius:A5.GROUND_SENSOR_RADIUS_SCALE*(Z.height/A5.BASE_ENTITY_HEIGHT),halfHeight:A5.GROUND_SENSOR_HEIGHT_SCALE*(Z.height/A5.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},isSensor:!0,relativePosition:{x:0,y:-Z.height/2,z:0},tag:"groundSensor",onCollision:(J,X)=>{if(!Z.isSpawned)return;if(!(J instanceof h7)||!J.isLiquid){if(X&&this._groundContactCount===0&&Z.linearVelocity.y<-1)if(Z.linearVelocity.y<A5.JUMP_LAND_HEAVY_VELOCITY_THRESHOLD)Z.startModelOneshotAnimations(this.jumpLandHeavyOneshotAnimations);else Z.startModelOneshotAnimations(this.jumpLandLightOneshotAnimations);this._groundContactCount+=X?1:-1}if(!this._groundContactCount&&!this.isSwimming)Z.startModelOneshotAnimations(this.jumpOneshotAnimations);else Z.stopModelAnimations(this.jumpOneshotAnimations);if(!(J instanceof h8))return;if(X&&this.sticksToPlatforms)this._platform=J;else if(J===this._platform&&!X)this._platform=void 0}}),Z.createAndAddChildCollider({shape:"capsule",halfHeight:A5.WALL_COLLIDER_HEIGHT_SCALE*(Z.height/A5.BASE_ENTITY_HEIGHT),radius:A5.WALL_COLLIDER_RADIUS_SCALE*(Z.height/A5.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},friction:0,frictionCombineRule:1,tag:"wallCollider"})}tickWithPlayerInput(Z,J,X,$){if(!Z.isSpawned||!Z.world)return;if(super.tickWithPlayerInput(Z,J,X,$),Z.parent)return;let{w:Y,a:Q,s:W,d:K,c:G,sp:V,sh:H,ml:q}=J,{yaw:z}=X,F=Z.linearVelocity;this._reusableTargetVelocities.x=0,this._reusableTargetVelocities.y=0,this._reusableTargetVelocities.z=0,this._isActivelyMoving=!!(Y||Q||W||K);let U=H,L=Q&&K&&!Y&&!W||Y&&W&&!Q&&!K,B=U&&this.canRun(this)||!U&&this.canWalk(this);if(this.isSwimming&&!this._isFullySubmerged)this._isFullySubmerged=!0,this._justSubmergedUntil=performance.now()+A5.WATER_ENTRY_SINKING_MS;else if(!this.isSwimming)this._isFullySubmerged=!1,this._justSubmergedUntil=0;if(this.isGrounded&&!this.isSwimming&&this._isActivelyMoving&&!L&&B){let D=U?this.runLoopedAnimations:this.walkLoopedAnimations;Z.stopAllModelLoopedAnimations(D),Z.startModelLoopedAnimations(D),this._stepAudio?.setPlaybackRate(U?0.75:0.51),this._stepAudio?.play(Z.world,!this._stepAudio?.isPlaying)}else if(this._isFullySubmerged&&this.canSwim(this))if(this._stepAudio?.pause(),this._isActivelyMoving)Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),Z.startModelLoopedAnimations(this.swimLoopedAnimations);else Z.stopAllModelLoopedAnimations(this.swimIdleLoopedAnimations),Z.startModelLoopedAnimations(this.swimIdleLoopedAnimations);else this._stepAudio?.pause(),Z.stopAllModelLoopedAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations);let w;if(this.applyDirectionalMovementRotations&&B){if(Y&&Q&&!K&&!W)w=A5.MOVEMENT_ROTATIONS.wa;else if(Y&&K&&!Q&&!W)w=A5.MOVEMENT_ROTATIONS.wd;else if(W&&Q&&!Y&&!K)w=A5.MOVEMENT_ROTATIONS.sa;else if(W&&K&&!Y&&!Q)w=A5.MOVEMENT_ROTATIONS.sd;else if(W&&!Y&&!Q&&!K||Q&&W&&K&&!Y)w=A5.MOVEMENT_ROTATIONS.s;else if(Q&&!Y&&!W&&!K)w=A5.MOVEMENT_ROTATIONS.a;else if(K&&!Y&&!Q&&!W)w=A5.MOVEMENT_ROTATIONS.d}if(q)Z.startModelOneshotAnimations(this.interactOneshotAnimations),J.ml=!this.autoCancelMouseLeftClick;if(B){let D=!this.isSwimming?U?this.runVelocity:this.walkVelocity:U?this.swimFastVelocity:this.swimSlowVelocity,C=Math.sin(z),T=Math.cos(z);if(Y)this._reusableTargetVelocities.x-=D*C,this._reusableTargetVelocities.z-=D*T;if(W)this._reusableTargetVelocities.x+=D*C,this._reusableTargetVelocities.z+=D*T;if(Q)this._reusableTargetVelocities.x-=D*T,this._reusableTargetVelocities.z+=D*C;if(K)this._reusableTargetVelocities.x+=D*T,this._reusableTargetVelocities.z-=D*C;let k=Math.sqrt(this._reusableTargetVelocities.x*this._reusableTargetVelocities.x+this._reusableTargetVelocities.z*this._reusableTargetVelocities.z);if(k>D){let A=D/k;this._reusableTargetVelocities.x*=A,this._reusableTargetVelocities.z*=A}}if(this.isSwimming){if(F.y<this.swimMaxGravityVelocity)this._reusableVelocityClamp.x=F.x,this._reusableVelocityClamp.y=this.swimMaxGravityVelocity,this._reusableVelocityClamp.z=F.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(F.y>this.swimUpwardVelocity*2)this._reusableVelocityClamp.x=F.x,this._reusableVelocityClamp.y=this.swimUpwardVelocity*2,this._reusableVelocityClamp.z=F.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(G)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*A5.WATER_ENTRY_SINKING_FACTOR;else if(!V)this._reusableTargetVelocities.y=-F.y*A5.SWIMMING_DRAG_FACTOR}if(V&&this.canJump(this)){if(this.isGrounded&&!this.isSwimming&&F.y>-0.001&&F.y<=3)this._reusableTargetVelocities.y=this.jumpVelocity;else if(this.isSwimming&&performance.now()>this._swimUpwardCooldownAt)this._reusableTargetVelocities.y=this.swimUpwardVelocity}let O=this._platform?.linearVelocity??this._reusablePlatformVelocity;if(this._externalVelocity.y!==0)this._magnitudeYTracker+=this._externalVelocity.y;if(this._externalVelocity.x!==0||this._externalVelocity.y!==0||this._externalVelocity.z!==0){if(this.isGrounded){let D=Math.sqrt(this._externalVelocity.x*this._externalVelocity.x+this._magnitudeYTracker*this._magnitudeYTracker+this._externalVelocity.z*this._externalVelocity.z);if(D>0.01){let T=Math.max(0,D-A5.EXTERNAL_IMPULSE_DECAY_RATE)/D;this._externalVelocity.x*=T,this._magnitudeYTracker*=T,this._externalVelocity.z*=T}else this._externalVelocity.x=0,this._externalVelocity.y=0,this._magnitudeYTracker=0,this._externalVelocity.z=0}}let M=this._reusableTargetVelocities.x+this._externalVelocity.x-F.x+O.x,N=this._reusableTargetVelocities.y+this._externalVelocity.y+O.y,P=this._reusableTargetVelocities.z+this._externalVelocity.z-F.z+O.z;if(this._externalVelocity.y=0,M!==0||N!==0||P!==0){let D=Z.mass;this._reusableImpulse.x=M*D,this._reusableImpulse.y=N*D,this._reusableImpulse.z=P*D,this._internalApplyImpulse(this._reusableImpulse)}if(z!==void 0&&(this.faceForwardOnStop||this.isActivelyMoving)){let C=(w!==void 0?z+w:z)*0.5;Z.setRotation({x:0,y:Math.sin(C),z:0,w:Math.cos(C)})}}}var _T;((K)=>{K.LOAD="SCENE_UI.LOAD";K.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";K.SET_OFFSET="SCENE_UI.SET_OFFSET";K.SET_POSITION="SCENE_UI.SET_POSITION";K.SET_STATE="SCENE_UI.SET_STATE";K.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";K.UNLOAD="SCENE_UI.UNLOAD"})(_T||={});class mV extends D0{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)u.fatalError("Either attachedToEntity or position must be set, but not both");super();this._attachedToEntity=Z.attachedToEntity,this._offset=Z.offset,this._position=Z.position,this._state=Z.state??{},this._templateId=Z.templateId,this._viewDistance=Z.viewDistance}get id(){return this._id}get attachedToEntity(){return this._attachedToEntity}get isLoaded(){return this._id!==void 0}get offset(){return this._offset}get position(){return this._position}get state(){return this._state}get templateId(){return this._templateId}get viewDistance(){return this._viewDistance}get world(){return this._world}load(Z){if(this.isLoaded)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return u.error(`SceneUI.load(): Attached entity ${this._attachedToEntity.id} must be spawned before loading SceneUI!`);this._id=Z.sceneUIManager.registerSceneUI(this),this._world=Z,this.emitWithWorld(Z,"SCENE_UI.LOAD",{sceneUI:this})}setAttachedToEntity(Z){if(!Z.isSpawned)return u.error(`SceneUI.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_ATTACHED_TO_ENTITY",{sceneUI:this,entity:Z})}setOffset(Z){if(this._offset===Z)return;if(this._offset=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_OFFSET",{sceneUI:this,offset:Z})}setPosition(Z){if(this._position===Z)return;if(this._attachedToEntity=void 0,this._position=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_POSITION",{sceneUI:this,position:Z})}setState(Z){if(this._state={...this._state,...Z},this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_STATE",{sceneUI:this,state:this._state})}setViewDistance(Z){if(this._viewDistance=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_VIEW_DISTANCE",{sceneUI:this,viewDistance:Z})}unload(){if(!this.isLoaded||!this._world)return;this._world.sceneUIManager.unregisterSceneUI(this),this.emitWithWorld(this._world,"SCENE_UI.UNLOAD",{sceneUI:this}),this._id=void 0,this._world=void 0}serialize(){return E0.serializeSceneUI(this)}}var $e=0.010000000000000002,Ye=Math.cos(0.026);class WJ extends h8{player;nametagSceneUI;constructor(Z){super(Z);this._positionUpdateThresholdSq=$e,this._rotationUpdateThreshold=Ye,this.player=Z.player,this.nametagSceneUI=new mV({templateId:"hytopia:nametag",attachedToEntity:this,offset:{x:0,y:1,z:0},viewDistance:15,state:{username:this.player.username,profilePictureUrl:this.player.profilePictureUrl}})}spawn(Z,J,X){super.spawn(Z,J,X),this.nametagSceneUI.load(Z),this.player.on("PLAYER.CHAT_MESSAGE_SEND",({message:$})=>{this.nametagSceneUI.setState({chat:$})})}tick(Z){if(!this.isSpawned||!this.world)return;if(!this.controller)return u.error(`PlayerEntity.tick(): PlayerEntity "${this.name}" must have a controller.`);let{input:J,camera:X}=this.player;this.controller.tickWithPlayerInput(this,J,X.orientation,Z),super.tick(Z)}}class AT extends WJ{constructor(Z){super({modelUri:"models/players/player.gltf",modelLoopedAnimations:["idle_lower","idle_upper"],modelHiddenNodes:["hair-"],modelShownNodes:["hair-0003"],...Z});if(!Z.controller)this.setController(new A5)}}class dV{_activeEntities=new Set;_entities=new Map;_nextEntityId=1;_world;constructor(Z){this._world=Z}get entityCount(){return this._entities.size}get world(){return this._world}registerEntity(Z){if(Z.id!==void 0)u.fatalError(`EntityManager.registerEntity(): Entity ${Z.name} is already assigned the id ${Z.id}!`);let J=this._nextEntityId;if(this._entities.set(J,Z),this._nextEntityId++,!Z.isEnvironmental)this._activeEntities.add(Z);return J}unregisterEntity(Z){if(Z.id===void 0)return u.error(`EntityManager.unregisterEntity(): Entity ${Z.name} is not assigned an id!`);if(this._entities.delete(Z.id),!Z.isEnvironmental)this._activeEntities.delete(Z)}getAllEntities(){return Array.from(this._entities.values())}getAllPlayerEntities(){let Z=[];return this._entities.forEach((J)=>{if(J instanceof WJ)Z.push(J)}),Z}getPlayerEntitiesByPlayer(Z){let J=[];return this._entities.forEach((X)=>{if(X instanceof WJ&&X.player===Z)J.push(X)}),J}getEntity(Z){return this._entities.get(Z)}getEntitiesByTag(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getEntitiesByTagSubstring(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag?.includes(Z))J.push(X)}),J}getEntityChildren(Z){let J=[];return this._entities.forEach((X)=>{if(X.parent===Z)J.push(X)}),J}tickEntities(Z){for(let J of this._activeEntities)J.tick(Z)}checkAndEmitUpdates(){for(let Z of this._activeEntities)Z.checkAndEmitUpdates()}}import{gzipSync as Rp8}from"zlib";var d6=e(G00(),1),kw6=d6.default.v1,Ew6=d6.default.v1ToV6,Iw6=d6.default.v3,V00=d6.default.v4,vw6=d6.default.v5,Sw6=d6.default.v6,_w6=d6.default.v6ToV1,Aw6=d6.default.v7,xw6=d6.default.NIL,fw6=d6.default.MAX,hw6=d6.default.version,bw6=d6.default.validate,yw6=d6.default.stringify,gw6=d6.default.parse;var dT;try{dT=new TextDecoder}catch(Z){}var J0,m7,b=0;var pT=[],SY=pT,lV=0,k5={},Q5,Q1,g7=0,w9=0,b8,W1,B7=[],Z5,H00={useRecords:!1,mapsAsObjects:!0};class mB{}var iT=new mB;iT.name="MessagePack 0xC1";var DX=!1,O00=2,uT,cT,lT;try{new Function("")}catch(Z){O00=1/0}class K1{constructor(Z){if(Z){if(Z.useRecords===!1&&Z.mapsAsObjects===void 0)Z.mapsAsObjects=!0;if(Z.sequential&&Z.trusted!==!1){if(Z.trusted=!0,!Z.structures&&Z.useRecords!=!1){if(Z.structures=[],!Z.maxSharedStructures)Z.maxSharedStructures=0}}if(Z.structures)Z.structures.sharedLength=Z.structures.length;else if(Z.getStructures)(Z.structures=[]).uninitialized=!0,Z.structures.sharedLength=0;if(Z.int64AsNumber)Z.int64AsType="number"}Object.assign(this,Z)}unpack(Z,J){if(J0)return I00(()=>{return gB(),this?this.unpack(Z,J):K1.prototype.unpack.call(H00,Z,J)});if(!Z.buffer&&Z.constructor===ArrayBuffer)Z=typeof Buffer!=="undefined"?Buffer.from(Z):new Uint8Array(Z);if(typeof J==="object")m7=J.end||Z.length,b=J.start||0;else b=0,m7=J>-1?J:Z.length;lV=0,w9=0,Q1=null,SY=pT,b8=null,J0=Z;try{Z5=Z.dataView||(Z.dataView=new DataView(Z.buffer,Z.byteOffset,Z.byteLength))}catch(X){if(J0=null,Z instanceof Uint8Array)throw X;throw new Error("Source must be a Uint8Array or Buffer but was a "+(Z&&typeof Z=="object"?Z.constructor.name:typeof Z))}if(this instanceof K1){if(k5=this,this.structures)return Q5=this.structures,bB(J);else if(!Q5||Q5.length>0)Q5=[]}else if(k5=H00,!Q5||Q5.length>0)Q5=[];return bB(J)}unpackMultiple(Z,J){let X,$=0;try{DX=!0;let Y=Z.length,Q=this?this.unpack(Z,Y):dB.unpack(Z,Y);if(J){if(J(Q,$,b)===!1)return;while(b<Y)if($=b,J(bB(),$,b)===!1)return}else{X=[Q];while(b<Y)$=b,X.push(bB());return X}}catch(Y){throw Y.lastPosition=$,Y.values=X,Y}finally{DX=!1,gB()}}_mergeStructures(Z,J){if(cT)Z=cT.call(this,Z);if(Z=Z||[],Object.isFrozen(Z))Z=Z.map((X)=>X.slice(0));for(let X=0,$=Z.length;X<$;X++){let Y=Z[X];if(Y){if(Y.isShared=!0,X>=32)Y.highByte=X-32>>5}}Z.sharedLength=Z.length;for(let X in J||[])if(X>=0){let $=Z[X],Y=J[X];if(Y){if($)(Z.restoreStructures||(Z.restoreStructures=[]))[X]=$;Z[X]=Y}}return this.structures=Z}decode(Z,J){return this.unpack(Z,J)}}function bB(Z){try{if(!k5.trusted&&!DX){let X=Q5.sharedLength||0;if(X<Q5.length)Q5.length=X}let J;if(k5.randomAccessStructure&&J0[b]<64&&J0[b]>=32&&uT){if(J=uT(J0,b,m7,k5),J0=null,!(Z&&Z.lazy)&&J)J=J.toJSON();b=m7}else J=R8();if(b8)b=b8.postBundlePosition,b8=null;if(DX)Q5.restoreStructures=null;if(b==m7){if(Q5&&Q5.restoreStructures)q00();if(Q5=null,J0=null,W1)W1=null}else if(b>m7)throw new Error("Unexpected end of MessagePack data");else if(!DX){let X;try{X=JSON.stringify(J,($,Y)=>typeof Y==="bigint"?`${Y}n`:Y).slice(0,100)}catch($){X="(JSON view not available "+$+")"}throw new Error("Data read, but end of buffer not reached "+X)}return J}catch(J){if(Q5&&Q5.restoreStructures)q00();if(gB(),J instanceof RangeError||J.message.startsWith("Unexpected end of buffer")||b>m7)J.incomplete=!0;throw J}}function q00(){for(let Z in Q5.restoreStructures)Q5[Z]=Q5.restoreStructures[Z];Q5.restoreStructures=null}function R8(){let Z=J0[b++];if(Z<160)if(Z<128)if(Z<64)return Z;else{let J=Q5[Z&63]||k5.getStructures&&N00()[Z&63];if(J){if(!J.read)J.read=nT(J,Z&63);return J.read()}else return Z}else if(Z<144)if(Z-=128,k5.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let $=k00();if($==="__proto__")$="__proto_";J[$]=R8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(R8(),R8());return J}else{Z-=144;let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=R8();if(k5.freezeData)return Object.freeze(J);return J}else if(Z<192){let J=Z-160;if(w9>=b)return Q1.slice(b-g7,(b+=J)-g7);if(w9==0&&m7<140){let X=J<16?sT(J):T00(J);if(X!=null)return X}return yB(J)}else{let J;switch(Z){case 192:return null;case 193:if(b8)if(J=R8(),J>0)return b8[1].slice(b8.position1,b8.position1+=J);else return b8[0].slice(b8.position0,b8.position0-=J);return iT;case 194:return!1;case 195:return!0;case 196:if(J=J0[b++],J===void 0)throw new Error("Unexpected end of buffer");return mT(J);case 197:return J=Z5.getUint16(b),b+=2,mT(J);case 198:return J=Z5.getUint32(b),b+=4,mT(J);case 199:return vY(J0[b++]);case 200:return J=Z5.getUint16(b),b+=2,vY(J);case 201:return J=Z5.getUint32(b),b+=4,vY(J);case 202:if(J=Z5.getFloat32(b),k5.useFloat32>2){let X=AY[(J0[b]&127)<<1|J0[b+1]>>7];return b+=4,(X*J+(J>0?0.5:-0.5)>>0)/X}return b+=4,J;case 203:return J=Z5.getFloat64(b),b+=8,J;case 204:return J0[b++];case 205:return J=Z5.getUint16(b),b+=2,J;case 206:return J=Z5.getUint32(b),b+=4,J;case 207:if(k5.int64AsType==="number")J=Z5.getUint32(b)*4294967296,J+=Z5.getUint32(b+4);else if(k5.int64AsType==="string")J=Z5.getBigUint64(b).toString();else if(k5.int64AsType==="auto"){if(J=Z5.getBigUint64(b),J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=Z5.getBigUint64(b);return b+=8,J;case 208:return Z5.getInt8(b++);case 209:return J=Z5.getInt16(b),b+=2,J;case 210:return J=Z5.getInt32(b),b+=4,J;case 211:if(k5.int64AsType==="number")J=Z5.getInt32(b)*4294967296,J+=Z5.getUint32(b+4);else if(k5.int64AsType==="string")J=Z5.getBigInt64(b).toString();else if(k5.int64AsType==="auto"){if(J=Z5.getBigInt64(b),J>=BigInt(-2)<<BigInt(52)&&J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=Z5.getBigInt64(b);return b+=8,J;case 212:if(J=J0[b++],J==114)return w00(J0[b++]&63);else{let X=B7[J];if(X)if(X.read)return b++,X.read(R8());else if(X.noBuffer)return b++,X();else return X(J0.subarray(b,++b));else throw new Error("Unknown extension "+J)}case 213:if(J=J0[b],J==114)return b++,w00(J0[b++]&63,J0[b++]);else return vY(2);case 214:return vY(4);case 215:return vY(8);case 216:return vY(16);case 217:if(J=J0[b++],w9>=b)return Q1.slice(b-g7,(b+=J)-g7);return j00(J);case 218:if(J=Z5.getUint16(b),b+=2,w9>=b)return Q1.slice(b-g7,(b+=J)-g7);return M00(J);case 219:if(J=Z5.getUint32(b),b+=4,w9>=b)return Q1.slice(b-g7,(b+=J)-g7);return R00(J);case 220:return J=Z5.getUint16(b),b+=2,F00(J);case 221:return J=Z5.getUint32(b),b+=4,F00(J);case 222:return J=Z5.getUint16(b),b+=2,U00(J);case 223:return J=Z5.getUint32(b),b+=4,U00(J);default:if(Z>=224)return Z-256;if(Z===void 0){let X=new Error("Unexpected end of MessagePack data");throw X.incomplete=!0,X}throw new Error("Unknown MessagePack token "+Z)}}}var yC5=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function nT(Z,J){function X(){if(X.count++>O00){let Y=Z.read=new Function("r","return function(){return "+(k5.freezeData?"Object.freeze":"")+"({"+Z.map((Q)=>Q==="__proto__"?"__proto_:r()":yC5.test(Q)?Q+":r()":"["+JSON.stringify(Q)+"]:r()").join(",")+"})}")(R8);if(Z.highByte===0)Z.read=z00(J,Z.read);return Y()}let $={};for(let Y=0,Q=Z.length;Y<Q;Y++){let W=Z[Y];if(W==="__proto__")W="__proto_";$[W]=R8()}if(k5.freezeData)return Object.freeze($);return $}if(X.count=0,Z.highByte===0)return z00(J,X);return X}var z00=(Z,J)=>{return function(){let X=J0[b++];if(X===0)return J();let $=Z<32?-(Z+(X<<5)):Z+(X<<5),Y=Q5[$]||N00()[$];if(!Y)throw new Error("Record id is not defined for "+$);if(!Y.read)Y.read=nT(Y,Z);return Y.read()}};function N00(){let Z=I00(()=>{return J0=null,k5.getStructures()});return Q5=k5._mergeStructures(Z,Q5)}var yB=_Y,j00=_Y,M00=_Y,R00=_Y,D00=!1;function P00(Z){D00=!0,yB=J(1),j00=J(2),M00=J(3),R00=J(5);function J(X){return function $(Y){let Q=SY[lV++];if(Q==null){if(b8)return _Y(Y);let K=J0.byteOffset,G=Z(b-X+K,m7+K,J0.buffer);if(typeof G=="string")Q=G,SY=pT;else if(SY=G,lV=1,w9=1,Q=SY[0],Q===void 0)throw new Error("Unexpected end of buffer")}let W=Q.length;if(W<=Y)return b+=Y,Q;return Q1=Q,g7=b,w9=b+W,b+=Y,Q.slice(0,Y)}}}function _Y(Z){let J;if(Z<16){if(J=sT(Z))return J}if(Z>64&&dT)return dT.decode(J0.subarray(b,b+=Z));let X=b+Z,$=[];J="";while(b<X){let Y=J0[b++];if((Y&128)===0)$.push(Y);else if((Y&224)===192){let Q=J0[b++]&63;$.push((Y&31)<<6|Q)}else if((Y&240)===224){let Q=J0[b++]&63,W=J0[b++]&63;$.push((Y&31)<<12|Q<<6|W)}else if((Y&248)===240){let Q=J0[b++]&63,W=J0[b++]&63,K=J0[b++]&63,G=(Y&7)<<18|Q<<12|W<<6|K;if(G>65535)G-=65536,$.push(G>>>10&1023|55296),G=56320|G&1023;$.push(G)}else $.push(Y);if($.length>=4096)J+=p8.apply(String,$),$.length=0}if($.length>0)J+=p8.apply(String,$);return J}function C00(Z,J,X){let $=J0;J0=Z,b=J;try{return _Y(X)}finally{J0=$}}function F00(Z){let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=R8();if(k5.freezeData)return Object.freeze(J);return J}function U00(Z){if(k5.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let $=k00();if($==="__proto__")$="__proto_";J[$]=R8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(R8(),R8());return J}}var p8=String.fromCharCode;function T00(Z){let J=b,X=new Array(Z);for(let $=0;$<Z;$++){let Y=J0[b++];if((Y&128)>0){b=J;return}X[$]=Y}return p8.apply(String,X)}function sT(Z){if(Z<4)if(Z<2)if(Z===0)return"";else{let J=J0[b++];if((J&128)>1){b-=1;return}return p8(J)}else{let J=J0[b++],X=J0[b++];if((J&128)>0||(X&128)>0){b-=2;return}if(Z<3)return p8(J,X);let $=J0[b++];if(($&128)>0){b-=3;return}return p8(J,X,$)}else{let J=J0[b++],X=J0[b++],$=J0[b++],Y=J0[b++];if((J&128)>0||(X&128)>0||($&128)>0||(Y&128)>0){b-=4;return}if(Z<6)if(Z===4)return p8(J,X,$,Y);else{let Q=J0[b++];if((Q&128)>0){b-=5;return}return p8(J,X,$,Y,Q)}else if(Z<8){let Q=J0[b++],W=J0[b++];if((Q&128)>0||(W&128)>0){b-=6;return}if(Z<7)return p8(J,X,$,Y,Q,W);let K=J0[b++];if((K&128)>0){b-=7;return}return p8(J,X,$,Y,Q,W,K)}else{let Q=J0[b++],W=J0[b++],K=J0[b++],G=J0[b++];if((Q&128)>0||(W&128)>0||(K&128)>0||(G&128)>0){b-=8;return}if(Z<10)if(Z===8)return p8(J,X,$,Y,Q,W,K,G);else{let V=J0[b++];if((V&128)>0){b-=9;return}return p8(J,X,$,Y,Q,W,K,G,V)}else if(Z<12){let V=J0[b++],H=J0[b++];if((V&128)>0||(H&128)>0){b-=10;return}if(Z<11)return p8(J,X,$,Y,Q,W,K,G,V,H);let q=J0[b++];if((q&128)>0){b-=11;return}return p8(J,X,$,Y,Q,W,K,G,V,H,q)}else{let V=J0[b++],H=J0[b++],q=J0[b++],z=J0[b++];if((V&128)>0||(H&128)>0||(q&128)>0||(z&128)>0){b-=12;return}if(Z<14)if(Z===12)return p8(J,X,$,Y,Q,W,K,G,V,H,q,z);else{let F=J0[b++];if((F&128)>0){b-=13;return}return p8(J,X,$,Y,Q,W,K,G,V,H,q,z,F)}else{let F=J0[b++],U=J0[b++];if((F&128)>0||(U&128)>0){b-=14;return}if(Z<15)return p8(J,X,$,Y,Q,W,K,G,V,H,q,z,F,U);let L=J0[b++];if((L&128)>0){b-=15;return}return p8(J,X,$,Y,Q,W,K,G,V,H,q,z,F,U,L)}}}}}function B00(){let Z=J0[b++],J;if(Z<192)J=Z-160;else switch(Z){case 217:J=J0[b++];break;case 218:J=Z5.getUint16(b),b+=2;break;case 219:J=Z5.getUint32(b),b+=4;break;default:throw new Error("Expected string")}return _Y(J)}function mT(Z){return k5.copyBuffers?Uint8Array.prototype.slice.call(J0,b,b+=Z):J0.subarray(b,b+=Z)}function vY(Z){let J=J0[b++];if(B7[J]){let X;return B7[J](J0.subarray(b,X=b+=Z),($)=>{b=$;try{return R8()}finally{b=X}})}else throw new Error("Unknown extension type "+J)}var L00=new Array(4096);function k00(){let Z=J0[b++];if(Z>=160&&Z<192){if(Z=Z-160,w9>=b)return Q1.slice(b-g7,(b+=Z)-g7);else if(!(w9==0&&m7<180))return yB(Z)}else return b--,E00(R8());let J=(Z<<5^(Z>1?Z5.getUint16(b):Z>0?J0[b]:0))&4095,X=L00[J],$=b,Y=b+Z-3,Q,W=0;if(X&&X.bytes==Z){while($<Y){if(Q=Z5.getUint32($),Q!=X[W++]){$=1879048192;break}$+=4}Y+=3;while($<Y)if(Q=J0[$++],Q!=X[W++]){$=1879048192;break}if($===Y)return b=$,X.string;Y-=3,$=b}X=[],L00[J]=X,X.bytes=Z;while($<Y)Q=Z5.getUint32($),X.push(Q),$+=4;Y+=3;while($<Y)Q=J0[$++],X.push(Q);let K=Z<16?sT(Z):T00(Z);if(K!=null)return X.string=K;return X.string=yB(Z)}function E00(Z){if(typeof Z==="string")return Z;if(typeof Z==="number"||typeof Z==="boolean"||typeof Z==="bigint")return Z.toString();if(Z==null)return Z+"";if(k5.allowArraysInMapKeys&&Array.isArray(Z)&&Z.flat().every((J)=>["string","number","boolean","bigint"].includes(typeof J)))return Z.flat().toString();throw new Error(`Invalid property type for record: ${typeof Z}`)}var w00=(Z,J)=>{let X=R8().map(E00),$=Z;if(J!==void 0)Z=Z<32?-((J<<5)+Z):(J<<5)+Z,X.highByte=J;let Y=Q5[Z];if(Y&&(Y.isShared||DX))(Q5.restoreStructures||(Q5.restoreStructures=[]))[Z]=Y;return Q5[Z]=X,X.read=nT(X,$),X.read()};B7[0]=()=>{};B7[0].noBuffer=!0;B7[66]=(Z)=>{let J=Z.length,X=BigInt(Z[0]&128?Z[0]-256:Z[0]);for(let $=1;$<J;$++)X<<=BigInt(8),X+=BigInt(Z[$]);return X};var gC5={Error,TypeError,ReferenceError};B7[101]=()=>{let Z=R8();return(gC5[Z[0]]||Error)(Z[1],{cause:Z[2]})};B7[105]=(Z)=>{if(k5.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=Z5.getUint32(b-4);if(!W1)W1=new Map;let X=J0[b],$;if(X>=144&&X<160||X==220||X==221)$=[];else if(X>=128&&X<144||X==222||X==223)$=new Map;else if((X>=199&&X<=201||X>=212&&X<=216)&&J0[b+1]===115)$=new Set;else $={};let Y={target:$};W1.set(J,Y);let Q=R8();if(!Y.used)return Y.target=Q;else Object.assign($,Q);if($ instanceof Map)for(let[W,K]of Q.entries())$.set(W,K);if($ instanceof Set)for(let W of Array.from(Q))$.add(W);return $};B7[112]=(Z)=>{if(k5.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=Z5.getUint32(b-4),X=W1.get(J);return X.used=!0,X.target};B7[115]=()=>new Set(R8());var aT=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((Z)=>Z+"Array"),mC5=typeof globalThis==="object"?globalThis:window;B7[116]=(Z)=>{let J=Z[0],X=Uint8Array.prototype.slice.call(Z,1).buffer,$=aT[J];if(!$){if(J===16)return X;if(J===17)return new DataView(X);throw new Error("Could not find typed array for code "+J)}return new mC5[$](X)};B7[120]=()=>{let Z=R8();return new RegExp(Z[0],Z[1])};var dC5=[];B7[98]=(Z)=>{let J=(Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3],X=b;return b+=J-Z.length,b8=dC5,b8=[B00(),B00()],b8.position0=0,b8.position1=0,b8.postBundlePosition=b,b=X,R8()};B7[255]=(Z)=>{if(Z.length==4)return new Date((Z[0]*16777216+(Z[1]<<16)+(Z[2]<<8)+Z[3])*1000);else if(Z.length==8)return new Date(((Z[0]<<22)+(Z[1]<<14)+(Z[2]<<6)+(Z[3]>>2))/1e6+((Z[3]&3)*4294967296+Z[4]*16777216+(Z[5]<<16)+(Z[6]<<8)+Z[7])*1000);else if(Z.length==12)return new Date(((Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3])/1e6+((Z[4]&128?-281474976710656:0)+Z[6]*1099511627776+Z[7]*4294967296+Z[8]*16777216+(Z[9]<<16)+(Z[10]<<8)+Z[11])*1000);else return new Date("invalid")};function I00(Z){if(lT)lT();let J=m7,X=b,$=lV,Y=g7,Q=w9,W=Q1,K=SY,G=W1,V=b8,H=new Uint8Array(J0.slice(0,m7)),q=Q5,z=Q5.slice(0,Q5.length),F=k5,U=DX,L=Z();return m7=J,b=X,lV=$,g7=Y,w9=Q,Q1=W,SY=K,W1=G,b8=V,J0=H,DX=U,Q5=q,Q5.splice(0,Q5.length,...z),k5=F,Z5=new DataView(J0.buffer,J0.byteOffset,J0.byteLength),L}function gB(){J0=null,W1=null,Q5=null}var AY=new Array(147);for(let Z=0;Z<256;Z++)AY[Z]=+("1e"+Math.floor(45.15-Z*0.30103));var dB=new K1({useRecords:!1}),uC5=dB.unpack,cC5=dB.unpackMultiple,lC5=dB.unpack,pV={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},pC5=new Float32Array(1),dw6=new Uint8Array(pC5.buffer,0,4);function v00(Z,J,X){uT=Z,cT=J,lT=X}var cB;try{cB=new TextEncoder}catch(Z){}var tT,A00,nV=typeof Buffer!=="undefined",uB=nV?function(Z){return Buffer.allocUnsafeSlow(Z)}:Uint8Array,x00=nV?Buffer:Uint8Array,S00=nV?4294967296:2144337920,l,iV,x5,d=0,u6,o5=null,f00,iC5=21760,nC5=/[\u0080-\uFFFF]/,KJ=Symbol("record-id");class xY extends K1{constructor(Z){super(Z);this.offset=0;let J,X,$,Y,Q,W=x00.prototype.utf8Write?function(I,S){return l.utf8Write(I,S,l.byteLength-S)}:cB&&cB.encodeInto?function(I,S){return cB.encodeInto(I,l.subarray(S)).written}:!1,K=this;if(!Z)Z={};let G=Z&&Z.sequential,V=Z.structures||Z.saveStructures,H=Z.maxSharedStructures;if(H==null)H=V?32:0;if(H>8160)throw new Error("Maximum maxSharedStructure is 8160");if(Z.structuredClone&&Z.moreTypes==null)this.moreTypes=!0;let q=Z.maxOwnStructures;if(q==null)q=V?32:64;if(!this.structures&&Z.useRecords!=!1)this.structures=[];let z=H>32||q+H>64,F=H+64,U=H+q+64;if(U>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let L=[],B=0,w=0;this.pack=this.encode=function(I,S){if(!l)l=new uB(8192),x5=l.dataView||(l.dataView=new DataView(l.buffer,0,8192)),d=0;if(u6=l.length-10,u6-d<2048)l=new uB(l.length),x5=l.dataView||(l.dataView=new DataView(l.buffer,0,l.length)),u6=l.length-10,d=0;else d=d+7&2147483640;if(X=d,S&ZT5)d+=S&255;if(Q=K.structuredClone?new Map:null,K.bundleStrings&&typeof I!=="string")o5=[],o5.size=1/0;else o5=null;if(Y=K.structures,Y){if(Y.uninitialized)Y=K._mergeStructures(K.getStructures());let m=Y.sharedLength||0;if(m>H)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+Y.sharedLength);if(!Y.transitions){Y.transitions=Object.create(null);for(let i=0;i<m;i++){let r=Y[i];if(!r)continue;let Q0,F0=Y.transitions;for(let _0=0,A0=r.length;_0<A0;_0++){let o0=r[_0];if(Q0=F0[o0],!Q0)Q0=F0[o0]=Object.create(null);F0=Q0}F0[KJ]=i+64}this.lastNamedStructuresLength=m}if(!G)Y.nextId=m+64}if($)$=!1;let g;try{if(K.randomAccessStructure&&I&&I.constructor&&I.constructor===Object)x(I);else N(I);let m=o5;if(o5)_00(X,N,0);if(Q&&Q.idsToInsert){let i=Q.idsToInsert.sort((_0,A0)=>_0.offset>A0.offset?1:-1),r=i.length,Q0=-1;while(m&&r>0){let _0=i[--r].offset+X;if(_0<m.stringsPosition+X&&Q0===-1)Q0=0;if(_0>m.position+X){if(Q0>=0)Q0+=6}else{if(Q0>=0)x5.setUint32(m.position+X,x5.getUint32(m.position+X)+Q0),Q0=-1;m=m.previous,r++}}if(Q0>=0&&m)x5.setUint32(m.position+X,x5.getUint32(m.position+X)+Q0);if(d+=i.length*6,d>u6)k(d);K.offset=d;let F0=aC5(l.subarray(X,d),i);return Q=null,F0}if(K.offset=d,S&tC5)return l.start=X,l.end=d,l;return l.subarray(X,d)}catch(m){throw g=m,m}finally{if(Y){if(O(),$&&K.saveStructures){let m=Y.sharedLength||0,i=l.subarray(X,d),r=h00(Y,K);if(!g){if(K.saveStructures(r,r.isCompatible)===!1)return K.pack(I,S);if(K.lastNamedStructuresLength=m,l.length>1073741824)l=null;return i}}}if(l.length>1073741824)l=null;if(S&eC5)d=X}};let O=()=>{if(w<10)w++;let I=Y.sharedLength||0;if(Y.length>I&&!G)Y.length=I;if(B>1e4){if(Y.transitions=null,w=0,B=0,L.length>0)L=[]}else if(L.length>0&&!G){for(let S=0,g=L.length;S<g;S++)L[S][KJ]=0;L=[]}},M=(I)=>{var S=I.length;if(S<16)l[d++]=144|S;else if(S<65536)l[d++]=220,l[d++]=S>>8,l[d++]=S&255;else l[d++]=221,x5.setUint32(d,S),d+=4;for(let g=0;g<S;g++)N(I[g])},N=(I)=>{if(d>u6)l=k(d);var S=typeof I,g;if(S==="string"){let m=I.length;if(o5&&m>=4&&m<4096){if((o5.size+=m)>iC5){let F0,_0=(o5[0]?o5[0].length*3+o5[1].length:0)+10;if(d+_0>u6)l=k(d+_0);let A0;if(o5.position)A0=o5,l[d]=200,d+=3,l[d++]=98,F0=d-X,d+=4,_00(X,N,0),x5.setUint16(F0+X-3,d-X-F0);else l[d++]=214,l[d++]=98,F0=d-X,d+=4;o5=["",""],o5.previous=A0,o5.size=0,o5.position=F0}let Q0=nC5.test(I);o5[Q0?0:1]+=I,l[d++]=193,N(Q0?-m:m);return}let i;if(m<32)i=1;else if(m<256)i=2;else if(m<65536)i=3;else i=5;let r=m*3;if(d+r>u6)l=k(d+r);if(m<64||!W){let Q0,F0,_0,A0=d+i;for(Q0=0;Q0<m;Q0++)if(F0=I.charCodeAt(Q0),F0<128)l[A0++]=F0;else if(F0<2048)l[A0++]=F0>>6|192,l[A0++]=F0&63|128;else if((F0&64512)===55296&&((_0=I.charCodeAt(Q0+1))&64512)===56320)F0=65536+((F0&1023)<<10)+(_0&1023),Q0++,l[A0++]=F0>>18|240,l[A0++]=F0>>12&63|128,l[A0++]=F0>>6&63|128,l[A0++]=F0&63|128;else l[A0++]=F0>>12|224,l[A0++]=F0>>6&63|128,l[A0++]=F0&63|128;g=A0-d-i}else g=W(I,d+i);if(g<32)l[d++]=160|g;else if(g<256){if(i<2)l.copyWithin(d+2,d+1,d+1+g);l[d++]=217,l[d++]=g}else if(g<65536){if(i<3)l.copyWithin(d+3,d+2,d+2+g);l[d++]=218,l[d++]=g>>8,l[d++]=g&255}else{if(i<5)l.copyWithin(d+5,d+3,d+3+g);l[d++]=219,x5.setUint32(d,g),d+=4}d+=g}else if(S==="number")if(I>>>0===I)if(I<32||I<128&&this.useRecords===!1||I<64&&!this.randomAccessStructure)l[d++]=I;else if(I<256)l[d++]=204,l[d++]=I;else if(I<65536)l[d++]=205,l[d++]=I>>8,l[d++]=I&255;else l[d++]=206,x5.setUint32(d,I),d+=4;else if(I>>0===I)if(I>=-32)l[d++]=256+I;else if(I>=-128)l[d++]=208,l[d++]=I+256;else if(I>=-32768)l[d++]=209,x5.setInt16(d,I),d+=2;else l[d++]=210,x5.setInt32(d,I),d+=4;else{let m;if((m=this.useFloat32)>0&&I<4294967296&&I>=-2147483648){l[d++]=202,x5.setFloat32(d,I);let i;if(m<4||(i=I*AY[(l[d]&127)<<1|l[d+1]>>7])>>0===i){d+=4;return}else d--}l[d++]=203,x5.setFloat64(d,I),d+=8}else if(S==="object"||S==="function")if(!I)l[d++]=192;else{if(Q){let i=Q.get(I);if(i){if(!i.id){let r=Q.idsToInsert||(Q.idsToInsert=[]);i.id=r.push(i)}l[d++]=214,l[d++]=112,x5.setUint32(d,i.id),d+=4;return}else Q.set(I,{offset:d-X})}let m=I.constructor;if(m===Object)T(I);else if(m===Array)M(I);else if(m===Map)if(this.mapAsEmptyObject)l[d++]=128;else{if(g=I.size,g<16)l[d++]=128|g;else if(g<65536)l[d++]=222,l[d++]=g>>8,l[d++]=g&255;else l[d++]=223,x5.setUint32(d,g),d+=4;for(let[i,r]of I)N(i),N(r)}else{for(let i=0,r=tT.length;i<r;i++){let Q0=A00[i];if(I instanceof Q0){let F0=tT[i];if(F0.write){if(F0.type)l[d++]=212,l[d++]=F0.type,l[d++]=0;let n5=F0.write.call(this,I);if(n5===I)if(Array.isArray(I))M(I);else T(I);else N(n5);return}let _0=l,A0=x5,o0=d;l=null;let T8;try{T8=F0.pack.call(this,I,(n5)=>{if(l=_0,_0=null,d+=n5,d>u6)k(d);return{target:l,targetView:x5,position:d-n5}},N)}finally{if(_0)l=_0,x5=A0,d=o0,u6=l.length-10}if(T8){if(T8.length+d>u6)k(T8.length+d);d=sC5(T8,l,d,F0.type)}return}}if(Array.isArray(I))M(I);else{if(I.toJSON){let i=I.toJSON();if(i!==I)return N(i)}if(S==="function")return N(this.writeFunction&&this.writeFunction(I));T(I)}}}else if(S==="boolean")l[d++]=I?195:194;else if(S==="bigint"){if(I<9223372036854776000&&I>=-9223372036854776000)l[d++]=211,x5.setBigInt64(d,I);else if(I<18446744073709552000&&I>0)l[d++]=207,x5.setBigUint64(d,I);else if(this.largeBigIntToFloat)l[d++]=203,x5.setFloat64(d,Number(I));else if(this.largeBigIntToString)return N(I.toString());else if((this.useBigIntExtension||this.moreTypes)&&I<BigInt(2)**BigInt(1023)&&I>-(BigInt(2)**BigInt(1023))){l[d++]=199,d++,l[d++]=66;let m=[],i;do{let r=I&BigInt(255);i=(r&BigInt(128))===(I<BigInt(0)?BigInt(128):BigInt(0)),m.push(r),I>>=BigInt(8)}while(!((I===BigInt(0)||I===BigInt(-1))&&i));l[d-2]=m.length;for(let r=m.length;r>0;)l[d++]=Number(m[--r]);return}else throw new RangeError(I+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string");d+=8}else if(S==="undefined")if(this.encodeUndefinedAsNil)l[d++]=192;else l[d++]=212,l[d++]=0,l[d++]=0;else throw new Error("Unknown type: "+S)},P=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(I)=>{let S;if(this.skipValues){S=[];for(let i in I)if((typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(i))&&!this.skipValues.includes(I[i]))S.push(i)}else S=Object.keys(I);let g=S.length;if(g<16)l[d++]=128|g;else if(g<65536)l[d++]=222,l[d++]=g>>8,l[d++]=g&255;else l[d++]=223,x5.setUint32(d,g),d+=4;let m;if(this.coercibleKeyAsNumber)for(let i=0;i<g;i++){m=S[i];let r=Number(m);N(isNaN(r)?m:r),N(I[m])}else for(let i=0;i<g;i++)N(m=S[i]),N(I[m])}:(I)=>{l[d++]=222;let S=d-X;d+=2;let g=0;for(let m in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(m))N(m),N(I[m]),g++;if(g>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');l[S+++X]=g>>8,l[S+X]=g&255},D=this.useRecords===!1?P:Z.progressiveRecords&&!z?(I)=>{let S,g=Y.transitions||(Y.transitions=Object.create(null)),m=d++-X,i;for(let r in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(r)){if(S=g[r],S)g=S;else{let Q0=Object.keys(I),F0=g;g=Y.transitions;let _0=0;for(let A0=0,o0=Q0.length;A0<o0;A0++){let T8=Q0[A0];if(S=g[T8],!S)S=g[T8]=Object.create(null),_0++;g=S}if(m+X+1==d)d--,A(g,Q0,_0);else v(g,Q0,m,_0);i=!0,g=F0[r]}N(I[r])}if(!i){let r=g[KJ];if(r)l[m+X]=r;else v(g,Object.keys(I),m,0)}}:(I)=>{let S,g=Y.transitions||(Y.transitions=Object.create(null)),m=0;for(let r in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(r)){if(S=g[r],!S)S=g[r]=Object.create(null),m++;g=S}let i=g[KJ];if(i)if(i>=96&&z)l[d++]=((i-=96)&31)+96,l[d++]=i>>5;else l[d++]=i;else A(g,g.__keys__||Object.keys(I),m);for(let r in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(r))N(I[r])},C=typeof this.useRecords=="function"&&this.useRecords,T=C?(I)=>{C(I)?D(I):P(I)}:D,k=(I)=>{let S;if(I>16777216){if(I-X>S00)throw new Error("Packed buffer would be larger than maximum buffer size");S=Math.min(S00,Math.round(Math.max((I-X)*(I>67108864?1.25:2),4194304)/4096)*4096)}else S=(Math.max(I-X<<2,l.length-1)>>12)+1<<12;let g=new uB(S);if(x5=g.dataView||(g.dataView=new DataView(g.buffer,0,S)),I=Math.min(I,l.length),l.copy)l.copy(g,0,X,I);else g.set(l.slice(X,I));return d-=X,X=0,u6=g.length-10,l=g},A=(I,S,g)=>{let m=Y.nextId;if(!m)m=64;if(m<F&&this.shouldShareStructure&&!this.shouldShareStructure(S)){if(m=Y.nextOwnId,!(m<U))m=F;Y.nextOwnId=m+1}else{if(m>=U)m=F;Y.nextId=m+1}let i=S.highByte=m>=96&&z?m-96>>5:-1;if(I[KJ]=m,I.__keys__=S,Y[m-64]=S,m<F)if(S.isShared=!0,Y.sharedLength=m-63,$=!0,i>=0)l[d++]=(m&31)+96,l[d++]=i;else l[d++]=m;else{if(i>=0)l[d++]=213,l[d++]=114,l[d++]=(m&31)+96,l[d++]=i;else l[d++]=212,l[d++]=114,l[d++]=m;if(g)B+=w*g;if(L.length>=q)L.shift()[KJ]=0;L.push(I),N(S)}},v=(I,S,g,m)=>{let i=l,r=d,Q0=u6,F0=X;if(l=iV,d=0,X=0,!l)iV=l=new uB(8192);u6=l.length-10,A(I,S,m),iV=l;let _0=d;if(l=i,d=r,u6=Q0,X=F0,_0>1){let A0=d+_0-1;if(A0>u6)k(A0);let o0=g+X;l.copyWithin(o0+_0,o0+1,d),l.set(iV.slice(0,_0),o0),d=A0}else l[g+X]=iV[0]},x=(I)=>{let S=f00(I,l,X,d,Y,k,(g,m,i)=>{if(i)return $=!0;d=m;let r=l;if(N(g),O(),r!==l)return{position:d,targetView:x5,target:l};return d},this);if(S===0)return T(I);d=S}}useBuffer(Z){l=Z,l.dataView||(l.dataView=new DataView(l.buffer,l.byteOffset,l.byteLength)),d=0}set position(Z){d=Z}get position(){return d}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}A00=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,mB];tT=[{pack(Z,J,X){let $=Z.getTime()/1000;if((this.useTimestamp32||Z.getMilliseconds()===0)&&$>=0&&$<4294967296){let{target:Y,targetView:Q,position:W}=J(6);Y[W++]=214,Y[W++]=255,Q.setUint32(W,$)}else if($>0&&$<4294967296){let{target:Y,targetView:Q,position:W}=J(10);Y[W++]=215,Y[W++]=255,Q.setUint32(W,Z.getMilliseconds()*4000000+($/1000/4294967296>>0)),Q.setUint32(W+4,$)}else if(isNaN($)){if(this.onInvalidDate)return J(0),X(this.onInvalidDate());let{target:Y,targetView:Q,position:W}=J(3);Y[W++]=212,Y[W++]=255,Y[W++]=255}else{let{target:Y,targetView:Q,position:W}=J(15);Y[W++]=199,Y[W++]=12,Y[W++]=255,Q.setUint32(W,Z.getMilliseconds()*1e6),Q.setBigInt64(W+4,BigInt(Math.floor($)))}}},{pack(Z,J,X){if(this.setAsEmptyObject)return J(0),X({});let $=Array.from(Z),{target:Y,position:Q}=J(this.moreTypes?3:0);if(this.moreTypes)Y[Q++]=212,Y[Q++]=115,Y[Q++]=0;X($)}},{pack(Z,J,X){let{target:$,position:Y}=J(this.moreTypes?3:0);if(this.moreTypes)$[Y++]=212,$[Y++]=101,$[Y++]=0;X([Z.name,Z.message,Z.cause])}},{pack(Z,J,X){let{target:$,position:Y}=J(this.moreTypes?3:0);if(this.moreTypes)$[Y++]=212,$[Y++]=120,$[Y++]=0;X([Z.source,Z.flags])}},{pack(Z,J){if(this.moreTypes)rT(Z,16,J);else oT(nV?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let X=Z.constructor;if(X!==x00&&this.moreTypes)rT(Z,aT.indexOf(X.name),J);else oT(Z,J)}},{pack(Z,J){if(this.moreTypes)rT(Z,17,J);else oT(nV?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let{target:X,position:$}=J(1);X[$]=193}}];function rT(Z,J,X,$){let Y=Z.byteLength;if(Y+1<256){var{target:Q,position:W}=X(4+Y);Q[W++]=199,Q[W++]=Y+1}else if(Y+1<65536){var{target:Q,position:W}=X(5+Y);Q[W++]=200,Q[W++]=Y+1>>8,Q[W++]=Y+1&255}else{var{target:Q,position:W,targetView:K}=X(7+Y);Q[W++]=201,K.setUint32(W,Y+1),W+=4}if(Q[W++]=116,Q[W++]=J,!Z.buffer)Z=new Uint8Array(Z);Q.set(new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength),W)}function oT(Z,J){let X=Z.byteLength;var $,Y;if(X<256){var{target:$,position:Y}=J(X+2);$[Y++]=196,$[Y++]=X}else if(X<65536){var{target:$,position:Y}=J(X+3);$[Y++]=197,$[Y++]=X>>8,$[Y++]=X&255}else{var{target:$,position:Y,targetView:Q}=J(X+5);$[Y++]=198,Q.setUint32(Y,X),Y+=4}$.set(Z,Y)}function sC5(Z,J,X,$){let Y=Z.length;switch(Y){case 1:J[X++]=212;break;case 2:J[X++]=213;break;case 4:J[X++]=214;break;case 8:J[X++]=215;break;case 16:J[X++]=216;break;default:if(Y<256)J[X++]=199,J[X++]=Y;else if(Y<65536)J[X++]=200,J[X++]=Y>>8,J[X++]=Y&255;else J[X++]=201,J[X++]=Y>>24,J[X++]=Y>>16&255,J[X++]=Y>>8&255,J[X++]=Y&255}return J[X++]=$,J.set(Z,X),X+=Y,X}function aC5(Z,J){let X,$=J.length*6,Y=Z.length-$;while(X=J.pop()){let{offset:Q,id:W}=X;Z.copyWithin(Q+$,Q,Y),$-=6;let K=Q+$;Z[K++]=214,Z[K++]=105,Z[K++]=W>>24,Z[K++]=W>>16&255,Z[K++]=W>>8&255,Z[K++]=W&255,Y=Q}return Z}function _00(Z,J,X){if(o5.length>0){x5.setUint32(o5.position+Z,d+X-o5.position-Z),o5.stringsPosition=d-Z;let $=o5;o5=null,J($[0]),J($[1])}}function h00(Z,J){return Z.isCompatible=(X)=>{let $=!X||(J.lastNamedStructuresLength||0)===X.length;if(!$)J._mergeStructures(X);return $},Z}function b00(Z,J){f00=Z,h00=J}var y00=new xY({useRecords:!1}),rC5=y00.pack,oC5=y00.pack;var tC5=512,eC5=1024,ZT5=2048;var eT=3,WK=0,sV=2,lB=1,Jk=16,m00=["num","object","string","ascii"];m00[Jk]="date";var XT5=[!1,!0,!0,!1,!1,!0,!0,!1],d00;try{new Function(""),d00=!0}catch(Z){}var fY,$T5=typeof Buffer!=="undefined",pB,GJ;try{pB=new TextEncoder}catch(Z){}var YT5=$T5?function(Z,J,X){return Z.utf8Write(J,X,Z.byteLength-X)}:pB&&pB.encodeInto?function(Z,J,X){return pB.encodeInto(J,Z.subarray(X)).written}:!1,rw6=Symbol("type"),ow6=Symbol("parent");b00(u00,VT5);function u00(Z,J,X,$,Y,Q,W,K){let G=K.typedStructs||(K.typedStructs=[]),V=J.dataView,H=(G.lastStringStart||100)+$,q=J.length-10,z=$;if($>q)J=Q($),V=J.dataView,$-=X,z-=X,H-=X,X=0,q=J.length-10;let F,U=H,L=G.transitions||(G.transitions=Object.create(null)),B=G.nextId||G.length,w=B<15?1:B<240?2:B<61440?3:B<15728640?4:0;if(w===0)return 0;$+=w;let O=[],M,N=0;for(let D in Z){let C=Z[D],T=L[D];if(!T)L[D]=T={key:D,parent:L,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};if($>q)J=Q($),V=J.dataView,$-=X,z-=X,H-=X,U-=X,X=0,q=J.length-10;switch(typeof C){case"number":let k=C;if(B<200||!T.num64){if(k>>0===k&&k<536870912&&k>-520093696){if(k<246&&k>=0&&(T.num8&&!(B>200&&T.num32)||k<32&&!T.num32))L=T.num8||L7(T,WK,1),J[$++]=k;else L=T.num32||L7(T,WK,4),V.setUint32($,k,!0),$+=4;break}else if(k<4294967296&&k>=-2147483648){if(V.setFloat32($,k,!0),XT5[J[$+3]>>>5]){let I;if((I=k*AY[(J[$+3]&127)<<1|J[$+2]>>7])>>0===I){L=T.num32||L7(T,WK,4),$+=4;break}}}}L=T.num64||L7(T,WK,8),V.setFloat64($,k,!0),$+=8;break;case"string":let A=C.length;if(F=U-H,(A<<2)+U>q)J=Q((A<<2)+U),V=J.dataView,$-=X,z-=X,H-=X,U-=X,X=0,q=J.length-10;if(A>65280+F>>2){O.push(D,C,$-z);break}let v,x=U;if(A<64){let I,S,g;for(I=0;I<A;I++)if(S=C.charCodeAt(I),S<128)J[U++]=S;else if(S<2048)v=!0,J[U++]=S>>6|192,J[U++]=S&63|128;else if((S&64512)===55296&&((g=C.charCodeAt(I+1))&64512)===56320)v=!0,S=65536+((S&1023)<<10)+(g&1023),I++,J[U++]=S>>18|240,J[U++]=S>>12&63|128,J[U++]=S>>6&63|128,J[U++]=S&63|128;else v=!0,J[U++]=S>>12|224,J[U++]=S>>6&63|128,J[U++]=S&63|128}else U+=YT5(J,C,U),v=U-x>A;if(F<160||F<246&&(T.ascii8||T.string8)){if(v){if(!(L=T.string8))if(G.length>10&&(L=T.ascii8))L.__type=sV,T.ascii8=null,T.string8=L,W(null,0,!0);else L=L7(T,sV,1)}else if(F===0&&!M){M=!0,L=T.ascii0||L7(T,eT,0);break}else if(!(L=T.ascii8)&&!(G.length>10&&(L=T.string8)))L=L7(T,eT,1);J[$++]=F}else L=T.string16||L7(T,sV,2),V.setUint16($,F,!0),$+=2;break;case"object":if(C){if(C.constructor===Date)L=T.date64||L7(T,Jk,8),V.setFloat64($,C.getTime(),!0),$+=8;else O.push(D,C,N);break}else if(T=g00(T,$,V,-10),T)L=T,$=fY;else O.push(D,C,N);break;case"boolean":L=T.num8||T.ascii8||L7(T,WK,1),J[$++]=C?249:248;break;case"undefined":if(T=g00(T,$,V,-9),T)L=T,$=fY;else O.push(D,C,N);break;default:O.push(D,C,N)}N++}for(let D=0,C=O.length;D<C;){let T=O[D++],k=O[D++],A=O[D++],v=L[T];if(!v)L[T]=v={key:T,parent:L,enumerationOffset:A-N,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null};let x;if(k){let I;if(F=U-H,F<65280)if(L=v.object16,L)I=2;else if(L=v.object32)I=4;else L=L7(v,lB,2),I=2;else L=v.object32||L7(v,lB,4),I=4;if(x=W(k,U),typeof x==="object")U=x.position,V=x.targetView,J=x.target,H-=X,$-=X,z-=X,X=0;else U=x;if(I===2)V.setUint16($,F,!0),$+=2;else V.setUint32($,F,!0),$+=4}else L=v.object16||L7(v,lB,2),V.setInt16($,k===null?-10:-9,!0),$+=2;N++}let P=L[KJ];if(P==null){P=K.typedStructs.length;let D=[],C=L,T,k;while((k=C.__type)!==void 0){let A=C.__size;C=C.__parent,T=C.key;let v=[k,A,T];if(C.enumerationOffset)v.push(C.enumerationOffset);D.push(v),C=C.parent}D.reverse(),L[KJ]=P,K.typedStructs[P]=D,W(null,0,!0)}switch(w){case 1:if(P>=16)return 0;J[z]=P+32;break;case 2:if(P>=256)return 0;J[z]=56,J[z+1]=P;break;case 3:if(P>=65536)return 0;J[z]=57,V.setUint16(z+1,P,!0);break;case 4:if(P>=16777216)return 0;V.setUint32(z,(P<<8)+58,!0);break}if($<H){if(H===U)return $;J.copyWithin($,H,U),U+=$-H,G.lastStringStart=$-z}else if($>H){if(H===U)return $;return G.lastStringStart=$-z,u00(Z,J,X,z,Y,Q,W,K)}return U}function g00(Z,J,X,$){let Y;if(Y=Z.ascii8||Z.num8)return X.setInt8(J,$,!0),fY=J+1,Y;if(Y=Z.string16||Z.object16)return X.setInt16(J,$,!0),fY=J+2,Y;if(Y=Z.num32)return X.setUint32(J,3758096640+$,!0),fY=J+4,Y;if(Y=Z.num64)return X.setFloat64(J,NaN,!0),X.setInt8(J,$),fY=J+8,Y;fY=J;return}function L7(Z,J,X){let $=m00[J]+(X<<3),Y=Z[$]||(Z[$]=Object.create(null));return Y.__type=J,Y.__size=X,Y.__parent=Z,Y}function QT5(Z){if(!(Z instanceof Map))return Z;let J=Z.get("typed")||[];if(Object.isFrozen(J))J=J.map((Y)=>Y.slice(0));let X=Z.get("named"),$=Object.create(null);for(let Y=0,Q=J.length;Y<Q;Y++){let W=J[Y],K=$;for(let[G,V,H]of W){let q=K[H];if(!q)K[H]=q={key:H,parent:K,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};K=L7(q,G,V)}K[KJ]=Y}return J.transitions=$,this.typedStructs=J,this.lastTypedStructuresLength=J.length,X}var Zk=Symbol.for("source");function WT5(Z,J,X,$){let Y=Z[J++]-32;if(Y>=24)switch(Y){case 24:Y=Z[J++];break;case 25:Y=Z[J++]+(Z[J++]<<8);break;case 26:Y=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16);break;case 27:Y=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16)+(Z[J++]<<24);break}let Q=$.typedStructs&&$.typedStructs[Y];if(!Q){if(Z=Uint8Array.prototype.slice.call(Z,J,X),X-=J,J=0,!$.getStructures)throw new Error(`Reference to shared structure ${Y} without getStructures method`);if($._mergeStructures($.getStructures()),!$.typedStructs)throw new Error("Could not find any shared typed structures");if($.lastTypedStructuresLength=$.typedStructs.length,Q=$.typedStructs[Y],!Q)throw new Error("Could not find typed structure "+Y)}var{construct:W,fullConstruct:K}=Q;if(!W){W=Q.construct=function F(){},K=Q.fullConstruct=function F(){},K.prototype=$.structPrototype??{};var G=W.prototype=$.structPrototype?Object.create($.structPrototype):{};let H=[],q=0,z;for(let F=0,U=Q.length;F<U;F++){let L=Q[F],[B,w,O,M]=L;if(O==="__proto__")O="__proto_";let N={key:O,offset:q};if(M)H.splice(F+M,0,N);else H.push(N);let P;switch(w){case 0:P=()=>0;break;case 1:P=(C,T)=>{let k=C.bytes[T+N.offset];return k>=246?QK(k):k};break;case 2:P=(C,T)=>{let k=C.bytes,v=(k.dataView||(k.dataView=new DataView(k.buffer,k.byteOffset,k.byteLength))).getUint16(T+N.offset,!0);return v>=65280?QK(v&255):v};break;case 4:P=(C,T)=>{let k=C.bytes,v=(k.dataView||(k.dataView=new DataView(k.buffer,k.byteOffset,k.byteLength))).getUint32(T+N.offset,!0);return v>=4294967040?QK(v&255):v};break}N.getRef=P,q+=w;let D;switch(B){case eT:if(z&&!z.next)z.next=N;z=N,N.multiGetCount=0,D=function(C){let{bytes:T,position:k}=C,A=q+k,v=P(C,k);if(typeof v!=="number")return v;let x,I=N.next;while(I){if(x=I.getRef(C,k),typeof x==="number")break;else x=null;I=I.next}if(x==null)x=C.bytesEnd-A;if(C.srcString)return C.srcString.slice(v,x);return C00(T,v+A,x-v)};break;case sV:case lB:if(z&&!z.next)z.next=N;z=N,D=function(C){let T=C.position,k=q+T,A=P(C,T);if(typeof A!=="number")return A;let v=C.bytes,x,I=N.next;while(I){if(x=I.getRef(C,T),typeof x==="number")break;else x=null;I=I.next}if(x==null)x=C.bytesEnd-k;if(B===sV)return v.toString("utf8",A+k,x+k);else{GJ=C;try{return $.unpack(v,{start:A+k,end:x+k})}finally{GJ=null}}};break;case WK:switch(w){case 4:D=function(C){let T=C.bytes,k=T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength)),A=C.position+N.offset,v=k.getInt32(A,!0);if(v<536870912){if(v>-520093696)return v;if(v>-536870912)return QK(v&255)}let x=k.getFloat32(A,!0),I=AY[(T[A+3]&127)<<1|T[A+2]>>7];return(I*x+(x>0?0.5:-0.5)>>0)/I};break;case 8:D=function(C){let T=C.bytes,A=(T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength))).getFloat64(C.position+N.offset,!0);if(isNaN(A)){let v=T[C.position+N.offset];if(v>=246)return QK(v)}return A};break;case 1:D=function(C){let k=C.bytes[C.position+N.offset];return k<246?k:QK(k)};break}break;case Jk:D=function(C){let T=C.bytes,k=T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength));return new Date(k.getFloat64(C.position+N.offset,!0))};break}N.get=D}if(d00){let F=[],U=[],L=0,B;for(let O of H){if($.alwaysLazyProperty&&$.alwaysLazyProperty(O.key)){B=!0;continue}Object.defineProperty(G,O.key,{get:KT5(O.get),enumerable:!0});let M="v"+L++;U.push(M),F.push("o["+JSON.stringify(O.key)+"]="+M+"(s)")}if(B)F.push("__proto__:this");let w=new Function(...U,"var c=this;return function(s){var o=new c();"+F.join(";")+";return o;}").apply(K,H.map((O)=>O.get));Object.defineProperty(G,"toJSON",{value(O){return w.call(this,this[Zk])}})}else Object.defineProperty(G,"toJSON",{value(F){let U={};for(let L=0,B=H.length;L<B;L++){let w=H[L].key;U[w]=this[w]}return U}})}var V=new W;return V[Zk]={bytes:Z,position:J,srcString:"",bytesEnd:X},V}function QK(Z){switch(Z){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw new Error("Unknown constant")}function KT5(Z){return function(){return Z(this[Zk])}}function GT5(){if(GJ)GJ.bytes=Uint8Array.prototype.slice.call(GJ.bytes,GJ.position,GJ.bytesEnd),GJ.position=0,GJ.bytesEnd=GJ.bytes.length}function VT5(Z,J){if(J.typedStructs){let $=new Map;$.set("named",Z),$.set("typed",J.typedStructs),Z=$}let X=J.lastTypedStructuresLength||0;return Z.isCompatible=($)=>{let Y=!0;if($ instanceof Map){if(($.get("named")||[]).length!==(J.lastNamedStructuresLength||0))Y=!1;if(($.get("typed")||[]).length!==X)Y=!1}else if($ instanceof Array||Array.isArray($)){if($.length!==(J.lastNamedStructuresLength||0))Y=!1}if(!Y)J._mergeStructures($);return Y},J.lastTypedStructuresLength=J.typedStructs&&J.typedStructs.length,Z}v00(WT5,QT5,GT5);var zT5=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!zT5){let Z;try{if(Z=a("msgpackr-extract"),Z)P00(Z.extractStrings)}catch(J){}}globalThis.addEventListener("unhandledrejection",(Z)=>{let J=Z,X=J?.reason?.code??J?.reason?.cause?.code;if(console.error(Z),["EPIPE","ECONNRESET"].includes(X))Z.preventDefault()});class O9{static instance=new O9;_connectionIdConnections=new Map;_userIdConnections=new Map;_wrtcMinPort=process.env.WRTC_MIN_PORT?parseInt(process.env.WRTC_MIN_PORT):40000;_wrtcMaxPort=process.env.WRTC_MAX_PORT?parseInt(process.env.WRTC_MAX_PORT):41023;_wrtcPublicIpv4=process.env.NODE_ENV==="production"?process.env.WRTC_PUBLIC_IPV4:"127.0.0.1";_wrtcPublicIpv6=process.env.NODE_ENV==="production"?process.env.WRTC_PUBLIC_IPV6:"::";_wrtcRouter=null;_wrtcWorker=null;constructor(){this._initWrtc().catch((Z)=>{u.warning(`Socket._constructor(): Failed to initialize WebRTC, falling back to Websockets. This can be ignored for local development. Error: ${Z.message}`)})}get isWrtcEnabled(){return this._wrtcWorker&&!this._wrtcWorker.died&&this._wrtcRouter}get wrtcRouter(){return this._wrtcRouter}async createWrtcTransports(){if(!this.isWrtcEnabled)u.fatalError("Socket.createWrtcTransports(): WebRTC not enabled, unable to create transports.");let Z={listenIps:[{ip:"::",announcedIp:this._wrtcPublicIpv6},{ip:"0.0.0.0",announcedIp:this._wrtcPublicIpv4}],preferUdp:!0,enableSctp:!0,enableTcp:!1},J=await this._wrtcRouter.createDirectTransport(),X=await this._wrtcRouter.createWebRtcTransport(Z),$=await this._wrtcRouter.createWebRtcTransport(Z);return{directTransport:J,clientServerTransport:X,serverClientTransport:$}}handleConnection(Z,J,X){let $=J?.user.id,Y=(X&&this._connectionIdConnections.get(X))??($&&this._userIdConnections.get($));if(Y)Y.bindWs(Z);else{let Q=new BZ(Z,J);if(Q.on("CONNECTION.CLOSED",()=>{if(this._connectionIdConnections.delete(Q.id),$)this._userIdConnections.delete($)}),this._connectionIdConnections.set(Q.id,Q),$)this._userIdConnections.set($,Q)}}isValidConnectionId(Z){return this._connectionIdConnections.has(Z)}async _initWrtc(){if(!this._wrtcPublicIpv4||!this._wrtcPublicIpv6)throw new Error("Socket._initWrtc(): WebRTC disabled, falling back to Websockets. Env variables WRTC_PUBLIC_IPV4 and WRTC_PUBLIC_IPV6 must be set in production");let Z=await import("mediasoup");this._wrtcWorker=await Z.createWorker({rtcMinPort:this._wrtcMinPort,rtcMaxPort:this._wrtcMaxPort}),this._wrtcWorker.on("died",this._onWrtcWorkerDied),this._wrtcRouter=await this._wrtcWorker.createRouter({mediaCodecs:[]}),console.log("Socket._initWrtc(): WebRTC enabled and ready!")}_onWrtcWorkerDied=(Z)=>{u.warning(`Socket._onWrtcWorkerDied(): WebRTC worker unexpectedly died, falling back to Websockets for all players. Internal error: ${Z}`),d7.instance.getConnectedPlayers().forEach((J)=>{J.connection.closeWrtc()}),this._wrtcRouter?.close(),this._wrtcRouter=null,this._wrtcWorker?.close(),this._wrtcWorker=null}}var Dx={};bZ(Dx,{zodErrorsIntegration:()=>DE,wrapMcpServerWithSentry:()=>EE,withScope:()=>p7,withMonitor:()=>HJ,withIsolationScope:()=>z1,withActiveSpan:()=>fX,vercelAIIntegration:()=>OO,validateOpenTelemetrySetup:()=>Rx,updateSpanName:()=>wk,trpcMiddleware:()=>CE,tediousIntegration:()=>zO,suppressTracing:()=>HH,supabaseIntegration:()=>RE,startSpanManual:()=>VH,startSpan:()=>P9,startSession:()=>wH,startNewTrace:()=>bk,startInactiveSpan:()=>fk,spotlightIntegration:()=>KO,spanToTraceHeader:()=>ZH,spanToJSON:()=>O0,spanToBaggageHeader:()=>Ck,setupKoaErrorHandler:()=>Q55,setupHapiErrorHandler:()=>A05,setupFastifyErrorHandler:()=>ia0,setupExpressErrorHandler:()=>Za0,setupConnectErrorHandler:()=>E55,setUser:()=>nk,setTags:()=>pk,setTag:()=>ik,setNodeAsyncContextStrategy:()=>ow,setMeasurement:()=>Ak,setHttpStatus:()=>UK,setExtras:()=>ck,setExtra:()=>lk,setCurrentClient:()=>KE,setContext:()=>uk,rewriteFramesIntegration:()=>ME,requestDataIntegration:()=>MH,redisIntegration:()=>p2,profiler:()=>PE,prismaIntegration:()=>o2,preloadOpenTelemetry:()=>y65,postgresIntegration:()=>a2,parameterize:()=>OL,onUnhandledRejectionIntegration:()=>B2,onUncaughtExceptionIntegration:()=>U2,nodeContextIntegration:()=>G2,nativeNodeFetchIntegration:()=>Q2,mysqlIntegration:()=>d2,mysql2Integration:()=>c2,mongooseIntegration:()=>g2,mongoIntegration:()=>b2,modulesIntegration:()=>F2,makeNodeTransport:()=>CO,lruMemoizerIntegration:()=>h2,logger:()=>_E,localVariablesIntegration:()=>z2,linkedErrorsIntegration:()=>jH,lastEventId:()=>sk,koaIntegration:()=>YO,knexIntegration:()=>o55,kafkaIntegration:()=>f2,isInitialized:()=>BH,instrumentSupabaseClient:()=>PL,initWithoutDefaultIntegrations:()=>m65,initOpenTelemetry:()=>vO,init:()=>SO,inboundFiltersIntegration:()=>NH,httpIntegration:()=>J2,hapiIntegration:()=>JO,graphqlIntegration:()=>x2,getTraceMetaTags:()=>qE,getTraceData:()=>B1,getSpanStatusFromHttpCode:()=>FK,getSpanDescendants:()=>JH,getSentryRelease:()=>EO,getRootSpan:()=>y5,getIsolationScope:()=>x0,getGlobalScope:()=>q1,getDefaultIntegrationsWithoutPerformance:()=>jx,getDefaultIntegrations:()=>Mx,getCurrentScope:()=>l0,getClient:()=>Y0,getAutoPerformanceIntegrations:()=>RO,getActiveSpan:()=>MZ,genericPoolIntegration:()=>FO,generateInstrumentOnce:()=>C0,functionToStringIntegration:()=>OH,fsIntegration:()=>Zs0,flush:()=>ak,fastifyIntegration:()=>v2,extraErrorDataIntegration:()=>LE,expressIntegration:()=>M2,expressErrorHandler:()=>l_,eventFiltersIntegration:()=>jL,endSession:()=>sY,disableAnrDetectionForCallback:()=>Ns0,defaultStackParser:()=>IO,dedupeIntegration:()=>BE,dataloaderIntegration:()=>u85,cron:()=>i65,createTransport:()=>MK,createSentryWinstonTransport:()=>F65,createGetModuleFromFilename:()=>kO,continueTrace:()=>hk,contextLinesIntegration:()=>V2,consoleLoggingIntegration:()=>vE,consoleIntegration:()=>RH,connectIntegration:()=>WO,close:()=>rk,childProcessIntegration:()=>NO,captureSession:()=>tk,captureMessage:()=>jK,captureFeedback:()=>IE,captureException:()=>F5,captureEvent:()=>UH,captureConsoleIntegration:()=>UE,captureCheckIn:()=>FH,anrIntegration:()=>Os0,amqplibIntegration:()=>LO,addIntegration:()=>XE,addEventProcessor:()=>ok,addBreadcrumb:()=>l6,SentryContextManager:()=>MO,Scope:()=>Q6,SEMANTIC_ATTRIBUTE_SENTRY_SOURCE:()=>E5,SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE:()=>D9,SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN:()=>v0,SEMANTIC_ATTRIBUTE_SENTRY_OP:()=>j0,SDK_VERSION:()=>Q8,NodeClient:()=>lq});var _E={};bZ(_E,{warn:()=>sE5,trace:()=>pE5,info:()=>nE5,fmt:()=>VE,fatal:()=>rE5,error:()=>aE5,debug:()=>iE5});import{format as lE5}from"node:util";var t=typeof __SENTRY_DEBUG__==="undefined"||__SENTRY_DEBUG__;var Q8="9.22.0";var N0=globalThis;function j6(){return PX(N0),N0}function PX(Z){let J=Z.__SENTRY__=Z.__SENTRY__||{};return J.version=J.version||Q8,J[Q8]=J[Q8]||{}}function hY(Z,J,X=N0){let $=X.__SENTRY__=X.__SENTRY__||{},Y=$[Q8]=$[Q8]||{};return Y[Z]||(Y[Z]=J())}var c00=Object.prototype.toString;function LZ(Z){switch(c00.call(Z)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return G1(Z,Error)}}function iB(Z,J){return c00.call(Z)===`[object ${J}]`}function l00(Z){return iB(Z,"ErrorEvent")}function bY(Z){return iB(Z,"String")}function yY(Z){return typeof Z==="object"&&Z!==null&&"__sentry_template_string__"in Z&&"__sentry_template_values__"in Z}function aV(Z){return Z===null||yY(Z)||typeof Z!=="object"&&typeof Z!=="function"}function N9(Z){return iB(Z,"Object")}function p00(Z){return typeof Event!=="undefined"&&G1(Z,Event)}function i00(Z){return typeof Element!=="undefined"&&G1(Z,Element)}function n00(Z){return iB(Z,"RegExp")}function j9(Z){return Boolean(Z?.then&&typeof Z.then==="function")}function s00(Z){return N9(Z)&&"nativeEvent"in Z&&"preventDefault"in Z&&"stopPropagation"in Z}function G1(Z,J){try{return Z instanceof J}catch(X){return!1}}function nB(Z){return!!(typeof Z==="object"&&Z!==null&&(Z.__isVue||Z._isVue))}var UT5=N0,BT5=80;function a00(Z,J={}){if(!Z)return"<unknown>";try{let X=Z,$=5,Y=[],Q=0,W=0,K=" > ",G=K.length,V,H=Array.isArray(J)?J:J.keyAttrs,q=!Array.isArray(J)&&J.maxStringLength||BT5;while(X&&Q++<$){if(V=LT5(X,H),V==="html"||Q>1&&W+Y.length*G+V.length>=q)break;Y.push(V),W+=V.length,X=X.parentNode}return Y.reverse().join(K)}catch(X){return"<unknown>"}}function LT5(Z,J){let X=Z,$=[];if(!X?.tagName)return"";if(UT5.HTMLElement){if(X instanceof HTMLElement&&X.dataset){if(X.dataset.sentryComponent)return X.dataset.sentryComponent;if(X.dataset.sentryElement)return X.dataset.sentryElement}}$.push(X.tagName.toLowerCase());let Y=J?.length?J.filter((W)=>X.getAttribute(W)).map((W)=>[W,X.getAttribute(W)]):null;if(Y?.length)Y.forEach((W)=>{$.push(`[${W[0]}="${W[1]}"]`)});else{if(X.id)$.push(`#${X.id}`);let W=X.className;if(W&&bY(W)){let K=W.split(/\s+/);for(let G of K)$.push(`.${G}`)}}let Q=["aria-label","type","name","title","alt"];for(let W of Q){let K=X.getAttribute(W);if(K)$.push(`[${W}="${K}"]`)}return $.join("")}var wT5="Sentry Logger ",wZ=["debug","info","warn","error","log","assert","trace"],KK={};function t5(Z){if(!("console"in N0))return Z();let J=N0.console,X={},$=Object.keys(KK);$.forEach((Y)=>{let Q=KK[Y];X[Y]=J[Y],J[Y]=Q});try{return Z()}finally{$.forEach((Y)=>{J[Y]=X[Y]})}}function OT5(){let Z=!1,J={enable:()=>{Z=!0},disable:()=>{Z=!1},isEnabled:()=>Z};if(t)wZ.forEach((X)=>{J[X]=(...$)=>{if(Z)t5(()=>{N0.console[X](`${wT5}[${X}]:`,...$)})}});else wZ.forEach((X)=>{J[X]=()=>{return}});return J}var y=hY("logger",OT5);function w7(Z,J=0){if(typeof Z!=="string"||J===0)return Z;return Z.length<=J?Z:`${Z.slice(0,J)}...`}function Xk(Z,J){let X=Z,$=X.length;if($<=150)return X;if(J>$)J=$;let Y=Math.max(J-60,0);if(Y<5)Y=0;let Q=Math.min(Y+140,$);if(Q>$-5)Q=$;if(Q===$)Y=Math.max(Q-140,0);if(X=X.slice(Y,Q),Y>0)X=`'{snip} ${X}`;if(Q<$)X+=" {snip}";return X}function CX(Z,J){if(!Array.isArray(Z))return"";let X=[];for(let $=0;$<Z.length;$++){let Y=Z[$];try{if(nB(Y))X.push("[VueViewModel]");else X.push(String(Y))}catch(Q){X.push("[value cannot be serialized]")}}return X.join(J)}function r00(Z,J,X=!1){if(!bY(Z))return!1;if(n00(J))return J.test(Z);if(bY(J))return X?Z===J:Z.includes(J);return!1}function TX(Z,J=[],X=!1){return J.some(($)=>r00(Z,$,X))}function $k(Z,J,X){if(!(J in Z))return;let $=Z[J];if(typeof $!=="function")return;let Y=X($);if(typeof Y==="function")e00(Y,$);try{Z[J]=Y}catch{t&&y.log(`Failed to replace method "${J}" in object`,Z)}}function W8(Z,J,X){try{Object.defineProperty(Z,J,{value:X,writable:!0,configurable:!0})}catch($){t&&y.log(`Failed to add non-enumerable property "${J}" to object`,Z)}}function e00(Z,J){try{let X=J.prototype||{};Z.prototype=J.prototype=X,W8(Z,"__sentry_original__",J)}catch(X){}}function Yk(Z){return Z.__sentry_original__}function sB(Z){if(LZ(Z))return{message:Z.message,name:Z.name,stack:Z.stack,...t00(Z)};else if(p00(Z)){let J={type:Z.type,target:o00(Z.target),currentTarget:o00(Z.currentTarget),...t00(Z)};if(typeof CustomEvent!=="undefined"&&G1(Z,CustomEvent))J.detail=Z.detail;return J}else return Z}function o00(Z){try{return i00(Z)?a00(Z):Object.prototype.toString.call(Z)}catch(J){return"<unknown>"}}function t00(Z){if(typeof Z==="object"&&Z!==null){let J={};for(let X in Z)if(Object.prototype.hasOwnProperty.call(Z,X))J[X]=Z[X];return J}else return{}}function Qk(Z,J=40){let X=Object.keys(sB(Z));X.sort();let $=X[0];if(!$)return"[object has no keys]";if($.length>=J)return w7($,J);for(let Y=X.length;Y>0;Y--){let Q=X.slice(0,Y).join(", ");if(Q.length>J)continue;if(Y===X.length)return Q;return w7(Q,J)}return""}function NT5(){let Z=N0;return Z.crypto||Z.msCrypto}function D8(Z=NT5()){let J=()=>Math.random()*16;try{if(Z?.randomUUID)return Z.randomUUID().replace(/-/g,"");if(Z?.getRandomValues)J=()=>{let X=new Uint8Array(1);return Z.getRandomValues(X),X[0]}}catch(X){}return([1e7]+1000+4000+8000+100000000000).replace(/[018]/g,(X)=>(X^(J()&15)>>X/4).toString(16))}function Z50(Z){return Z.exception?.values?.[0]}function kX(Z){let{message:J,event_id:X}=Z;if(J)return J;let $=Z50(Z);if($){if($.type&&$.value)return`${$.type}: ${$.value}`;return $.type||$.value||X||"<unknown>"}return X||"<unknown>"}function Kk(Z,J,X){let $=Z.exception=Z.exception||{},Y=$.values=$.values||[],Q=Y[0]=Y[0]||{};if(!Q.value)Q.value=J||"";if(!Q.type)Q.type=X||"Error"}function EX(Z,J){let X=Z50(Z);if(!X)return;let $={type:"generic",handled:!0},Y=X.mechanism;if(X.mechanism={...$,...Y,...J},J&&"data"in J){let Q={...Y?.data,...J.data};X.mechanism.data=Q}}var jT5=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function Wk(Z){return parseInt(Z||"",10)}function Gk(Z){let J=Z.match(jT5)||[],X=Wk(J[1]),$=Wk(J[2]),Y=Wk(J[3]);return{buildmetadata:J[5],major:isNaN(X)?void 0:X,minor:isNaN($)?void 0:$,patch:isNaN(Y)?void 0:Y,prerelease:J[4]}}function aB(Z){if(MT5(Z))return!0;try{W8(Z,"__sentry_captured__",!0)}catch(J){}return!1}function MT5(Z){try{return Z.__sentry_captured__}catch{}}var J50=1000;function V1(){return Date.now()/J50}function RT5(){let{performance:Z}=N0;if(!Z?.now)return V1;let J=Date.now()-Z.now(),X=Z.timeOrigin==null?J:Z.timeOrigin;return()=>{return(X+Z.now())/J50}}var u7=RT5();function X50(Z){let J=u7(),X={sid:D8(),init:!0,timestamp:J,started:J,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>DT5(X)};if(Z)H1(X,Z);return X}function H1(Z,J={}){if(J.user){if(!Z.ipAddress&&J.user.ip_address)Z.ipAddress=J.user.ip_address;if(!Z.did&&!J.did)Z.did=J.user.id||J.user.email||J.user.username}if(Z.timestamp=J.timestamp||u7(),J.abnormal_mechanism)Z.abnormal_mechanism=J.abnormal_mechanism;if(J.ignoreDuration)Z.ignoreDuration=J.ignoreDuration;if(J.sid)Z.sid=J.sid.length===32?J.sid:D8();if(J.init!==void 0)Z.init=J.init;if(!Z.did&&J.did)Z.did=`${J.did}`;if(typeof J.started==="number")Z.started=J.started;if(Z.ignoreDuration)Z.duration=void 0;else if(typeof J.duration==="number")Z.duration=J.duration;else{let X=Z.timestamp-Z.started;Z.duration=X>=0?X:0}if(J.release)Z.release=J.release;if(J.environment)Z.environment=J.environment;if(!Z.ipAddress&&J.ipAddress)Z.ipAddress=J.ipAddress;if(!Z.userAgent&&J.userAgent)Z.userAgent=J.userAgent;if(typeof J.errors==="number")Z.errors=J.errors;if(J.status)Z.status=J.status}function $50(Z,J){let X={};if(J)X={status:J};else if(Z.status==="ok")X={status:"exited"};H1(Z,X)}function DT5(Z){return{sid:`${Z.sid}`,init:Z.init,started:new Date(Z.started*1000).toISOString(),timestamp:new Date(Z.timestamp*1000).toISOString(),status:Z.status,errors:Z.errors,did:typeof Z.did==="number"||typeof Z.did==="string"?`${Z.did}`:void 0,duration:Z.duration,abnormal_mechanism:Z.abnormal_mechanism,attrs:{release:Z.release,environment:Z.environment,ip_address:Z.ipAddress,user_agent:Z.userAgent}}}function IX(Z,J,X=2){if(!J||typeof J!=="object"||X<=0)return J;if(Z&&Object.keys(J).length===0)return Z;let $={...Z};for(let Y in J)if(Object.prototype.hasOwnProperty.call(J,Y))$[Y]=IX($[Y],J[Y],X-1);return $}var Vk="_sentrySpan";function gY(Z,J){if(J)W8(Z,Vk,J);else delete Z[Vk]}function OZ(Z){return Z[Vk]}function c7(){return D8()}function l7(){return D8().substring(16)}var PT5=100;class Q6{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:c7(),sampleRand:Math.random()}}clone(){let Z=new Q6;if(Z._breadcrumbs=[...this._breadcrumbs],Z._tags={...this._tags},Z._extra={...this._extra},Z._contexts={...this._contexts},this._contexts.flags)Z._contexts.flags={values:[...this._contexts.flags.values]};return Z._user=this._user,Z._level=this._level,Z._session=this._session,Z._transactionName=this._transactionName,Z._fingerprint=this._fingerprint,Z._eventProcessors=[...this._eventProcessors],Z._attachments=[...this._attachments],Z._sdkProcessingMetadata={...this._sdkProcessingMetadata},Z._propagationContext={...this._propagationContext},Z._client=this._client,Z._lastEventId=this._lastEventId,gY(Z,OZ(this)),Z}setClient(Z){this._client=Z}setLastEventId(Z){this._lastEventId=Z}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(Z){this._scopeListeners.push(Z)}addEventProcessor(Z){return this._eventProcessors.push(Z),this}setUser(Z){if(this._user=Z||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session)H1(this._session,{user:Z});return this._notifyScopeListeners(),this}getUser(){return this._user}setTags(Z){return this._tags={...this._tags,...Z},this._notifyScopeListeners(),this}setTag(Z,J){return this._tags={...this._tags,[Z]:J},this._notifyScopeListeners(),this}setExtras(Z){return this._extra={...this._extra,...Z},this._notifyScopeListeners(),this}setExtra(Z,J){return this._extra={...this._extra,[Z]:J},this._notifyScopeListeners(),this}setFingerprint(Z){return this._fingerprint=Z,this._notifyScopeListeners(),this}setLevel(Z){return this._level=Z,this._notifyScopeListeners(),this}setTransactionName(Z){return this._transactionName=Z,this._notifyScopeListeners(),this}setContext(Z,J){if(J===null)delete this._contexts[Z];else this._contexts[Z]=J;return this._notifyScopeListeners(),this}setSession(Z){if(!Z)delete this._session;else this._session=Z;return this._notifyScopeListeners(),this}getSession(){return this._session}update(Z){if(!Z)return this;let J=typeof Z==="function"?Z(this):Z,X=J instanceof Q6?J.getScopeData():N9(J)?Z:void 0,{tags:$,extra:Y,user:Q,contexts:W,level:K,fingerprint:G=[],propagationContext:V}=X||{};if(this._tags={...this._tags,...$},this._extra={...this._extra,...Y},this._contexts={...this._contexts,...W},Q&&Object.keys(Q).length)this._user=Q;if(K)this._level=K;if(G.length)this._fingerprint=G;if(V)this._propagationContext=V;return this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,gY(this,void 0),this._attachments=[],this.setPropagationContext({traceId:c7(),sampleRand:Math.random()}),this._notifyScopeListeners(),this}addBreadcrumb(Z,J){let X=typeof J==="number"?J:PT5;if(X<=0)return this;let $={timestamp:V1(),...Z,message:Z.message?w7(Z.message,2048):Z.message};if(this._breadcrumbs.push($),this._breadcrumbs.length>X)this._breadcrumbs=this._breadcrumbs.slice(-X),this._client?.recordDroppedEvent("buffer_overflow","log_item");return this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(Z){return this._attachments.push(Z),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:OZ(this)}}setSDKProcessingMetadata(Z){return this._sdkProcessingMetadata=IX(this._sdkProcessingMetadata,Z,2),this}setPropagationContext(Z){return this._propagationContext=Z,this}getPropagationContext(){return this._propagationContext}captureException(Z,J){let X=J?.event_id||D8();if(!this._client)return y.warn("No client configured on scope - will not capture exception!"),X;let $=new Error("Sentry syntheticException");return this._client.captureException(Z,{originalException:Z,syntheticException:$,...J,event_id:X},this),X}captureMessage(Z,J,X){let $=X?.event_id||D8();if(!this._client)return y.warn("No client configured on scope - will not capture message!"),$;let Y=new Error(Z);return this._client.captureMessage(Z,J,{originalException:Z,syntheticException:Y,...X,event_id:$},this),$}captureEvent(Z,J){let X=J?.event_id||D8();if(!this._client)return y.warn("No client configured on scope - will not capture event!"),X;return this._client.captureEvent(Z,{...J,event_id:X},this),X}_notifyScopeListeners(){if(!this._notifyingListeners)this._notifyingListeners=!0,this._scopeListeners.forEach((Z)=>{Z(this)}),this._notifyingListeners=!1}}function GK(){return hY("defaultCurrentScope",()=>new Q6)}function M9(){return hY("defaultIsolationScope",()=>new Q6)}class Q50{constructor(Z,J){let X;if(!Z)X=new Q6;else X=Z;let $;if(!J)$=new Q6;else $=J;this._stack=[{scope:X}],this._isolationScope=$}withScope(Z){let J=this._pushScope(),X;try{X=Z(J)}catch($){throw this._popScope(),$}if(j9(X))return X.then(($)=>{return this._popScope(),$},($)=>{throw this._popScope(),$});return this._popScope(),X}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let Z=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:Z}),Z}_popScope(){if(this._stack.length<=1)return!1;return!!this._stack.pop()}}function VK(){let Z=j6(),J=PX(Z);return J.stack=J.stack||new Q50(GK(),M9())}function CT5(Z){return VK().withScope(Z)}function TT5(Z,J){let X=VK();return X.withScope(()=>{return X.getStackTop().scope=Z,J(Z)})}function Y50(Z){return VK().withScope(()=>{return Z(VK().getIsolationScope())})}function W50(){return{withIsolationScope:Y50,withScope:CT5,withSetScope:TT5,withSetIsolationScope:(Z,J)=>{return Y50(J)},getCurrentScope:()=>VK().getScope(),getIsolationScope:()=>VK().getIsolationScope()}}function Hk(Z){let J=j6(),X=PX(J);X.acs=Z}function R9(Z){let J=PX(Z);if(J.acs)return J.acs;return W50()}function l0(){let Z=j6();return R9(Z).getCurrentScope()}function x0(){let Z=j6();return R9(Z).getIsolationScope()}function q1(){return hY("globalScope",()=>new Q6)}function p7(...Z){let J=j6(),X=R9(J);if(Z.length===2){let[$,Y]=Z;if(!$)return X.withScope(Y);return X.withSetScope($,Y)}return X.withScope(Z[0])}function z1(...Z){let J=j6(),X=R9(J);if(Z.length===2){let[$,Y]=Z;if(!$)return X.withIsolationScope(Y);return X.withSetIsolationScope($,Y)}return X.withIsolationScope(Z[0])}function Y0(){return l0().getClient()}function HK(Z){let J=Z.getPropagationContext(),{traceId:X,parentSpanId:$,propagationSpanId:Y}=J,Q={trace_id:X,span_id:Y||l7()};if($)Q.parent_span_id=$;return Q}var E5="sentry.source",D9="sentry.sample_rate",qk="sentry.previous_trace_sample_rate",j0="sentry.op",v0="sentry.origin";var rB="sentry.measurement_unit",oB="sentry.measurement_value",NZ="sentry.custom_span_name",qK="sentry.profile_id",zK="sentry.exclusive_time",zk="cache.hit",Fk="cache.key",Uk="cache.item_size";var Bk=0,vX=1,O7=2;function FK(Z){if(Z<400&&Z>=100)return{code:1};if(Z>=400&&Z<500)switch(Z){case 401:return{code:2,message:"unauthenticated"};case 403:return{code:2,message:"permission_denied"};case 404:return{code:2,message:"not_found"};case 409:return{code:2,message:"already_exists"};case 413:return{code:2,message:"failed_precondition"};case 429:return{code:2,message:"resource_exhausted"};case 499:return{code:2,message:"cancelled"};default:return{code:2,message:"invalid_argument"}}if(Z>=500&&Z<600)switch(Z){case 501:return{code:2,message:"unimplemented"};case 503:return{code:2,message:"unavailable"};case 504:return{code:2,message:"deadline_exceeded"};default:return{code:2,message:"internal_error"}}return{code:2,message:"unknown_error"}}function UK(Z,J){Z.setAttribute("http.response.status_code",J);let X=FK(J);if(X.message!=="unknown_error")Z.setStatus(X)}var K50="_sentryScope",G50="_sentryIsolationScope";function rV(Z,J,X){if(Z)W8(Z,G50,X),W8(Z,K50,J)}function jZ(Z){return{scope:Z[K50],isolationScope:Z[G50]}}function i7(Z){if(typeof Z==="boolean")return Number(Z);let J=typeof Z==="string"?parseFloat(Z):Z;if(typeof J!=="number"||isNaN(J)||J<0||J>1)return;return J}var oV="sentry-",H50=/^sentry-/,q50=8192;function SX(Z){let J=mY(Z);if(!J)return;let X=Object.entries(J).reduce(($,[Y,Q])=>{if(Y.match(H50)){let W=Y.slice(oV.length);$[W]=Q}return $},{});if(Object.keys(X).length>0)return X;else return}function _X(Z){if(!Z)return;let J=Object.entries(Z).reduce((X,[$,Y])=>{if(Y)X[`${oV}${$}`]=Y;return X},{});return tB(J)}function mY(Z){if(!Z||!bY(Z)&&!Array.isArray(Z))return;if(Array.isArray(Z))return Z.reduce((J,X)=>{let $=V50(X);return Object.entries($).forEach(([Y,Q])=>{J[Y]=Q}),J},{});return V50(Z)}function V50(Z){return Z.split(",").map((J)=>J.split("=").map((X)=>{try{return decodeURIComponent(X.trim())}catch{return}})).reduce((J,[X,$])=>{if(X&&$)J[X]=$;return J},{})}function tB(Z){if(Object.keys(Z).length===0)return;return Object.entries(Z).reduce((J,[X,$],Y)=>{let Q=`${encodeURIComponent(X)}=${encodeURIComponent($)}`,W=Y===0?Q:`${J},${Q}`;if(W.length>q50)return t&&y.warn(`Not adding key: ${X} with val: ${$} to baggage header due to exceeding baggage size limits.`),J;else return W},"")}var tV=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function z50(Z){if(!Z)return;let J=Z.match(tV);if(!J)return;let X;if(J[3]==="1")X=!0;else if(J[3]==="0")X=!1;return{traceId:J[1],parentSampled:X,parentSpanId:J[2]}}function dY(Z,J){let X=z50(Z),$=SX(J);if(!X?.traceId)return{traceId:c7(),sampleRand:Math.random()};let Y=kT5(X,$);if($)$.sample_rand=Y.toString();let{traceId:Q,parentSpanId:W,parentSampled:K}=X;return{traceId:Q,parentSpanId:W,sampled:K,dsc:$||{},sampleRand:Y}}function AX(Z=c7(),J=l7(),X){let $="";if(X!==void 0)$=X?"-1":"-0";return`${Z}-${J}${$}`}function kT5(Z,J){let X=i7(J?.sample_rand);if(X!==void 0)return X;let $=i7(J?.sample_rate);if($&&Z?.parentSampled!==void 0)return Z.parentSampled?Math.random()*$:$+Math.random()*(1-$);else return Math.random()}var eB=0,ZL=1,F50=!1;function B50(Z){let{spanId:J,traceId:X}=Z.spanContext(),{data:$,op:Y,parent_span_id:Q,status:W,origin:K,links:G}=O0(Z);return{parent_span_id:Q,span_id:J,trace_id:X,data:$,op:Y,status:W,origin:K,links:G}}function xX(Z){let{spanId:J,traceId:X,isRemote:$}=Z.spanContext(),Y=$?J:O0(Z).parent_span_id,Q=jZ(Z).scope,W=$?Q?.getPropagationContext().propagationSpanId||l7():J;return{parent_span_id:Y,span_id:W,trace_id:X}}function ZH(Z){let{traceId:J,spanId:X}=Z.spanContext(),$=VJ(Z);return AX(J,X,$)}function uY(Z){if(Z&&Z.length>0)return Z.map(({context:{spanId:J,traceId:X,traceFlags:$,...Y},attributes:Q})=>({span_id:J,trace_id:X,sampled:$===ZL,attributes:Q,...Y}));else return}function N7(Z){if(typeof Z==="number")return U50(Z);if(Array.isArray(Z))return Z[0]+Z[1]/1e9;if(Z instanceof Date)return U50(Z.getTime());return u7()}function U50(Z){return Z>9999999999?Z/1000:Z}function O0(Z){if(IT5(Z))return Z.getSpanJSON();let{spanId:J,traceId:X}=Z.spanContext();if(ET5(Z)){let{attributes:$,startTime:Y,name:Q,endTime:W,status:K,links:G}=Z,V="parentSpanId"in Z?Z.parentSpanId:("parentSpanContext"in Z)?Z.parentSpanContext?.spanId:void 0;return{span_id:J,trace_id:X,data:$,description:Q,parent_span_id:V,start_timestamp:N7(Y),timestamp:N7(W)||void 0,status:cY(K),op:$[j0],origin:$[v0],links:uY(G)}}return{span_id:J,trace_id:X,start_timestamp:0,data:{}}}function ET5(Z){let J=Z;return!!J.attributes&&!!J.startTime&&!!J.name&&!!J.endTime&&!!J.status}function IT5(Z){return typeof Z.getSpanJSON==="function"}function VJ(Z){let{traceFlags:J}=Z.spanContext();return J===ZL}function cY(Z){if(!Z||Z.code===Bk)return;if(Z.code===vX)return"ok";return Z.message||"unknown_error"}var eV="_sentryChildSpans",Lk="_sentryRootSpan";function BK(Z,J){let X=Z[Lk]||Z;if(W8(J,Lk,X),Z[eV])Z[eV].add(J);else W8(Z,eV,new Set([J]))}function JH(Z){let J=new Set;function X($){if(J.has($))return;else if(VJ($)){J.add($);let Y=$[eV]?Array.from($[eV]):[];for(let Q of Y)X(Q)}}return X(Z),Array.from(J)}function y5(Z){return Z[Lk]||Z}function MZ(){let Z=j6(),J=R9(Z);if(J.getActiveSpan)return J.getActiveSpan();return OZ(l0())}function XH(){if(!F50)t5(()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly.")}),F50=!0}function wk(Z,J){Z.updateName(J),Z.setAttributes({[E5]:"custom",[NZ]:J})}var Nk="?",L50=/\(error: (.*)\)/,w50=/captureMessage|captureException/;function XL(...Z){let J=Z.sort((X,$)=>X[0]-$[0]).map((X)=>X[1]);return(X,$=0,Y=0)=>{let Q=[],W=X.split(`
93
93
  `);for(let K=$;K<W.length;K++){let G=W[K];if(G.length>1024)continue;let V=L50.test(G)?G.replace(L50,"$1"):G;if(V.match(/\S*Error: /))continue;for(let H of J){let q=H(V);if(q){Q.push(q);break}}if(Q.length>=50+Y)break}return O50(Q.slice(Y))}}function jk(Z){if(Array.isArray(Z))return XL(...Z);return Z}function O50(Z){if(!Z.length)return[];let J=Array.from(Z);if(/sentryWrapped/.test(JL(J).function||""))J.pop();if(J.reverse(),w50.test(JL(J).function||"")){if(J.pop(),w50.test(JL(J).function||""))J.pop()}return J.slice(0,50).map((X)=>({...X,filename:X.filename||JL(J).filename,function:X.function||"?"}))}function JL(Z){return Z[Z.length-1]||{}}var Ok="<anonymous>";function $H(Z){try{if(!Z||typeof Z!=="function")return Ok;return Z.name||Ok}catch(J){return Ok}}function $L(Z){let J=Z.exception;if(J){let X=[];try{return J.values.forEach(($)=>{if($.stacktrace.frames)X.push(...$.stacktrace.frames)}),X}catch($){return}}return}var YL={},N50={};function LK(Z,J){YL[Z]=YL[Z]||[],YL[Z].push(J)}function wK(Z,J){if(!N50[Z]){N50[Z]=!0;try{J()}catch(X){t&&y.error(`Error while instrumenting ${Z}`,X)}}}function OK(Z,J){let X=Z&&YL[Z];if(!X)return;for(let $ of X)try{$(J)}catch(Y){t&&y.error(`Error while triggering instrumentation handler.
94
94
  Type: ${Z}
@@ -362,4 +362,4 @@ qYGMwU/HBVHkLAn5XvT2a9xM0mzZ558d+ahbw8qAgRxg7BZ+2PW/bf7F2WRBUk1f
362
362
  xauhAoGBALEspoxQozwohGQnP7EMF0/0JoKNpdNv0b0qCVvNiMo0+N297lI2mFQp
363
363
  6xYlW/1l9afLokklF/J2IsyBrTCZoY7SaEk/lMMrQSyra+y0z71ogZ8A4ny9fxsj
364
364
  0dDYJZGllL+3E/MQfd7k+KnOM/+A+cPoAnci76+L3vdkUb2P8SJk
365
- -----END RSA PRIVATE KEY-----`;var Uf=parseInt(process.env.PORT??"8080"),Bf="0.9.2",KZ5;((J)=>J.READY="WEBSERVER.READY")(KZ5||={});class P4 extends D0{static instance=new P4;_webserver=new qN;start(){this._webserver.use(async(J,X)=>{J.response.headers.set("Access-Control-Allow-Origin","*"),await X()});let Z=new Gz;Z.get("/",(J)=>{if(J.isUpgradable)this._authorizeAndUpgradeWebsocket(J);else J.response.body=JSON.stringify({status:"OK",version:Bf,runtime:"deno"})}),this._webserver.use(Z.routes()),this._webserver.use(Z.allowedMethods()),this._webserver.use(this._serveStatic("assets")),this._webserver.use(this._serveStatic("node_modules/@hytopia.com/assets")),this._webserver.listen({port:Uf,cert:process.env.NODE_ENV!=="production"?QZ5:void 0,key:process.env.NODE_ENV!=="production"?WZ5:void 0}),this.emitWithGlobal("WEBSERVER.READY",{}),console.info(`WebServer.start(): Server running on port ${Uf}.`)}async _authorizeAndUpgradeWebsocket(Z){let J=Z.request.url.searchParams.get("connectionId")??"",X=Z.request.url.searchParams.get("sessionToken")??"",$;if(!J||!O9.instance.isValidConnectionId(J)){let Q=await QJ.instance.getPlayerSession(X);if(Q?.error)return new Response(`${Q.error.code}: ${Q.error.message}`,{status:401});$=Q}let Y=Z.upgrade();if(Y.readyState!==WebSocket.OPEN)Y.addEventListener("open",()=>{O9.instance.handleConnection(Y,$,J)},{once:!0});else O9.instance.handleConnection(Y,$,J);return}_serveStatic(Z){return async(J,X)=>{let $=J.request.url.pathname;try{await Qz(J,$,{root:Z,hidden:!0})}catch{await X()}}}}var pQ;((L)=>{L.BUILD_PACKETS="build_packets";L.ENTITIES_EMIT_UPDATES="entities_emit_updates";L.ENTITIES_TICK="entities_tick";L.NETWORK_SYNCHRONIZE="network_synchronize";L.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";L.PHYSICS_CLEANUP="physics_cleanup";L.PHYSICS_STEP="physics_step";L.SEND_ALL_PACKETS="send_all_packets";L.SEND_PACKETS="send_packets";L.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";L.SERIALIZE_PACKETS="serialize_packets";L.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";L.SIMULATION_STEP="simulation_step";L.TICKER_TICK="ticker_tick";L.WORLD_TICK="world_tick"})(pQ||={});class q8{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([$,Y])=>[$,Y.value]))}static initializeSentry(Z,J=50){SO({dsn:Z,release:Bf,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=q8.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let Y=X?.start_timestamp,Q=X?.timestamp;if(!Y||!Q)return null;if((Q-Y)*1000>J)return X.measurements=q8.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(BH())return P9({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return Dx}}var GZ5=new xY({useFloat32:pV.ALWAYS}),Dp8=5000;class BZ extends D0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=V00(),this.onPacket($0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket($0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),D0.globalInstance.emit("CONNECTION.OPENED",{connection:this,session:J})}static clearCachedPacketsSerializedBuffers(){if(BZ._cachedPacketsSerializedBuffer.size>0)BZ._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!$0.isValidPacket(X))return u.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=BZ._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return q8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let $=GZ5.pack(Z);if($.byteLength>65536)$=Rp8($,{level:1});return X?.setAttribute("serializedBytes",$.byteLength),BZ._cachedPacketsSerializedBuffer.set(Z,$),$})}bindWs(Z){let J=!!this._ws;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this.send([$0.createPacket($0.bidirectionalPackets.connectionPacketDefinition,{k:!0})]);if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([$0.createPacket($0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(O9.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){if(this._ws.readyState!==WebSocket.OPEN)return;try{this._ws.close()}catch(Z){u.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==WebSocket.OPEN)return;if(!J&&this._ws.bufferedAmount>4096)return;q8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let $=BZ.serializePackets(Z);if(!$)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&$.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send($)}catch{this._ws.send($)}else this._ws.send($);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch($){u.error(`Connection.send(): Packet send failed. Error: ${$}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,$=J.d;if(X){let{i:Y,d:Q}=X,W=!1;if(Y==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),W=!0;if(Y==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),W=!0;if(W)this.send([$0.createPacket($0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:Y}})])}if($)for(let Y of $){let{s:Q,l:W}=Y,K=await this._wrtcClientServerTransport.produceData({label:W,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:K.id});this._wrtcClientServerDataProducers.push(K),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([$0.createPacket($0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:K.id,l:W}})])}};_onHeartbeatPacket=()=>{this.send([$0.createPacket($0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){u.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},Dp8)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await O9.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:$}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(W)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,W)}),this._wrtcServerClientTransport=$,this._wrtcServerClientTransport.on("icestatechange",(W)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,W)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let Y=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push(Y,Q),this.send([$0.createPacket($0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:Y.id,pi:Y.dataProducerId,l:"scr",s:Y.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=GZ5.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return u.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!$0.isValidPacket(J))return u.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class Vz{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class r8{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,$)=>{Z.call(J,X,$,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var VZ5;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(VZ5||={});var Lf;((z)=>{z.DESPAWN="LIGHT.DESPAWN";z.SET_ANGLE="LIGHT.SET_ANGLE";z.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";z.SET_COLOR="LIGHT.SET_COLOR";z.SET_DISTANCE="LIGHT.SET_DISTANCE";z.SET_INTENSITY="LIGHT.SET_INTENSITY";z.SET_OFFSET="LIGHT.SET_OFFSET";z.SET_PENUMBRA="LIGHT.SET_PENUMBRA";z.SET_POSITION="LIGHT.SET_POSITION";z.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";z.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";z.SPAWN="LIGHT.SPAWN"})(Lf||={});class wf extends D0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)u.fatalError("Either attachedToEntity or position must be set, but not both.");super();u.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return u.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return u.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return u.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){return E0.serializeLight(this)}}var Of;((m)=>{m.BURST="PARTICLE_EMITTER.BURST";m.DESPAWN="PARTICLE_EMITTER.DESPAWN";m.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";m.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";m.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";m.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";m.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";m.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";m.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";m.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";m.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";m.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";m.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";m.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";m.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";m.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";m.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";m.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";m.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";m.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";m.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";m.SET_RATE="PARTICLE_EMITTER.SET_RATE";m.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";m.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";m.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";m.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";m.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";m.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";m.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";m.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";m.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";m.SPAWN="PARTICLE_EMITTER.SPAWN"})(Of||={});class Nf extends D0{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)u.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)u.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=Z.alphaTest??0.05,this._attachedToEntity=Z.attachedToEntity,this._attachedToEntityNodeName=Z.attachedToEntityNodeName,this._colorEnd=Z.colorEnd,this._colorEndVariance=Z.colorEndVariance,this._colorStart=Z.colorStart,this._colorStartVariance=Z.colorStartVariance,this._gravity=Z.gravity,this._lifetime=Z.lifetime,this._lifetimeVariance=Z.lifetimeVariance,this._maxParticles=Z.maxParticles,this._offset=Z.offset,this._opacityEnd=Z.opacityEnd,this._opacityEndVariance=Z.opacityEndVariance,this._opacityStart=Z.opacityStart,this._opacityStartVariance=Z.opacityStartVariance,this._paused=!1,this._position=Z.position,this._positionVariance=Z.positionVariance,this._rate=Z.rate,this._rateVariance=Z.rateVariance,this._sizeEnd=Z.sizeEnd,this._sizeEndVariance=Z.sizeEndVariance,this._sizeStart=Z.sizeStart,this._sizeStartVariance=Z.sizeStartVariance,this._textureUri=Z.textureUri,this._transparent=Z.transparent,this._velocity=Z.velocity,this._velocityVariance=Z.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(Z){if(this._alphaTest===Z)return;if(this._alphaTest=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return u.error(`ParticleEmitter.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:Z})}setAttachedToEntityNodeName(Z){if(this._attachedToEntityNodeName===Z)return;if(this._attachedToEntityNodeName=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:Z})}setColorEnd(Z){if(this._colorEnd&&this._colorEnd.r===Z.r&&this._colorEnd.g===Z.g&&this._colorEnd.b===Z.b)return;if(this._colorEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:Z})}setColorEndVariance(Z){if(this._colorEndVariance&&this._colorEndVariance.r===Z.r&&this._colorEndVariance.g===Z.g&&this._colorEndVariance.b===Z.b)return;if(this._colorEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:Z})}setColorStart(Z){if(this._colorStart&&this._colorStart.r===Z.r&&this._colorStart.g===Z.g&&this._colorStart.b===Z.b)return;if(this._colorStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:Z})}setColorStartVariance(Z){if(this._colorStartVariance&&this._colorStartVariance.r===Z.r&&this._colorStartVariance.g===Z.g&&this._colorStartVariance.b===Z.b)return;if(this._colorStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:Z})}setGravity(Z){if(this._gravity&&this._gravity.x===Z.x&&this._gravity.y===Z.y&&this._gravity.z===Z.z)return;if(this._gravity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:Z})}setLifetime(Z){if(this._lifetime===Z)return;if(this._lifetime=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:Z})}setLifetimeVariance(Z){if(this._lifetimeVariance===Z)return;if(this._lifetimeVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:Z})}setMaxParticles(Z){if(this._maxParticles===Z)return;if(this._maxParticles=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:Z})}setOpacityEnd(Z){if(this._opacityEnd===Z)return;if(this._opacityEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:Z})}setOpacityEndVariance(Z){if(this._opacityEndVariance===Z)return;if(this._opacityEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:Z})}setOpacityStart(Z){if(this._opacityStart===Z)return;if(this._opacityStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:Z})}setOpacityStartVariance(Z){if(this._opacityStartVariance===Z)return;if(this._opacityStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:Z})}setPositionVariance(Z){if(this._positionVariance&&this._positionVariance.x===Z.x&&this._positionVariance.y===Z.y&&this._positionVariance.z===Z.z)return;if(this._positionVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:Z})}setRate(Z){if(this._rate===Z)return;if(this._rate=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:Z})}setRateVariance(Z){if(this._rateVariance===Z)return;if(this._rateVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:Z})}setSizeEnd(Z){if(this._sizeEnd===Z)return;if(this._sizeEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:Z})}setSizeEndVariance(Z){if(this._sizeEndVariance===Z)return;if(this._sizeEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:Z})}setSizeStart(Z){if(this._sizeStart===Z)return;if(this._sizeStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:Z})}setSizeStartVariance(Z){if(this._sizeStartVariance===Z)return;if(this._sizeStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:Z})}setTextureUri(Z){if(this._textureUri===Z)return;if(this._textureUri=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:Z})}setTransparent(Z){if(this._transparent===Z)return;if(this._transparent=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:Z})}setVelocity(Z){if(this._velocity&&this._velocity.x===Z.x&&this._velocity.y===Z.y&&this._velocity.z===Z.z)return;if(this._velocity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:Z})}setVelocityVariance(Z){if(this._velocityVariance&&this._velocityVariance.x===Z.x&&this._velocityVariance.y===Z.y&&this._velocityVariance.z===Z.z)return;if(this._velocityVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:Z})}burst(Z){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return u.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=Z.particleEmitterManager.registerParticleEmitter(this),this._world=Z,this.emitWithWorld(Z,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return E0.serializeParticleEmitter(this)}}var Pp8={x:0,y:-32,z:0},jf=60,Mf;((Y)=>{Y.STEP_START="SIMULATION.STEP_START";Y.STEP_END="SIMULATION.STEP_END";Y.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";Y.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Mf||={});class Hz extends D0{_colliderMap=new yV;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=jf,X=Pp8){super();this._rapierEventQueue=new $5.EventQueue(!0),this._rapierSimulation=new $5.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=$5.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,($,Y)=>{if($.numContacts()===0)return;let Q=$.normal(),W=[];for(let K=0;K<$.numSolverContacts();K++)W.push($.solverContactPoint(K));X.push({contactPoints:W,localNormalA:!Y?$.localNormal1():$.localNormal2(),localNormalB:!Y?$.localNormal2():$.localNormal1(),normal:!Y?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,$={}){let Y=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(W)=>{let K=this._colliderMap.getColliderHandleBlockType(W.handle);if(K&&!Y.has(K))return Y.add(K),Q.push({intersectedBlockType:K}),!0;let G=this._colliderMap.getColliderHandleEntity(W.handle);if(G&&!Y.has(G))return Y.add(G),Q.push({intersectedEntity:G}),!0;return!0},$.filterFlags,$.filterGroups,$.filterExcludeCollider,$.filterExcludeRigidBody,$.filterPredicate),Q}raycast(Z,J,X,$={}){let Y=new $5.Ray(Z,J),Q=this._rapierSimulation.castRay(Y,X,$.solidMode??!0,$.filterFlags,$.filterGroups,$.filterExcludeCollider,$.filterExcludeRigidBody,$.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let W=Y.pointAt(Q.timeOfImpact),K=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:eQ.fromGlobalCoordinate({x:Math.floor(W.x-(Y.dir.x<0?0.0001:-0.0001)),y:Math.floor(W.y-(Y.dir.y<0?0.0001:-0.0001)),z:Math.floor(W.z-(Y.dir.z<0?0.0001:-0.0001))},V),hitPoint:W,hitDistance:K};let H=this._colliderMap.getColliderHandleEntity(G.handle);if(H)return{hitEntity:H,hitPoint:W,hitDistance:K};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(q8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),q8.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[$,Y]=this._getCollisionObjects(Z,J);if(!$||!Y)return;let Q=(W,K)=>{if(W instanceof h7&&K instanceof h8&&W.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))W.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:W,entity:K,started:X,colliderHandleA:Z,colliderHandleB:J});else if(W instanceof h8&&K instanceof h7&&W.hasListeners("ENTITY.BLOCK_COLLISION"))W.emit("ENTITY.BLOCK_COLLISION",{entity:W,blockType:K,started:X,colliderHandleA:Z,colliderHandleB:J});else if(W instanceof h8&&K instanceof h8&&W.hasListeners("ENTITY.ENTITY_COLLISION"))W.emit("ENTITY.ENTITY_COLLISION",{entity:W,otherEntity:K,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof W==="function"&&(K instanceof h8||K instanceof h7))W(K,X,Z,J)};Q($,Y),Q(Y,$)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let $={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},Y=(Q,W)=>{if(Q instanceof h7&&W instanceof h8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:W,contactForceData:$});else if(Q instanceof h8&&W instanceof h7&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:W,contactForceData:$});else if(Q instanceof h8&&W instanceof h8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:W,contactForceData:$})};Y(J,X),Y(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),$=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,$]}}class zN{_synchronizedPlayerReliablePackets=new r8;_queuedBroadcasts=[];_queuedAudioSynchronizations=new r8;_queuedBlockSynchronizations=new r8;_queuedBlockTypeSynchronizations=new r8;_queuedChunkSynchronizations=new r8;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new r8;_queuedLightSynchronizations=new r8;_queuedParticleEmitterSynchronizations=new r8;_queuedPerPlayerSynchronizations=new r8;_queuedPerPlayerCameraSynchronizations=new r8;_queuedPerPlayerUISynchronizations=new r8;_queuedPerPlayerUIDatasSynchronizations=new r8;_queuedPlayerSynchronizations=new r8;_queuedSceneUISynchronizations=new r8;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=[],J=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(...Y);if(this._queuedEntitySynchronizations.size>0){let $=[],Y=[];for(let Q of this._queuedEntitySynchronizations.valuesArray){let W=!1;for(let K in Q)if(K!=="i"&&K!=="p"&&K!=="r"){W=!0;break}if(W)$.push(Q);else Y.push(Q)}if(Y.length>0){let Q=$0.createPacket($0.outboundPackets.entitiesPacketDefinition,Y,X);J.push(Q)}if($.length>0){let Q=$0.createPacket($0.outboundPackets.entitiesPacketDefinition,$,X);Z.push(Q);for(let W of this._synchronizedPlayerReliablePackets.valuesArray)W.push(Q)}}if(this._queuedAudioSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBlockTypeSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedChunkSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBlockSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedLightSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedParticleEmitterSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerUISynchronizations){let Q=$0.createPacket($0.outboundPackets.uiPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerUIDatasSynchronizations){let Q=$0.createPacket($0.outboundPackets.uiDatasPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedSceneUISynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedWorldSynchronization){let $=$0.createPacket($0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerCameraSynchronizations){let Q=$0.createPacket($0.outboundPackets.cameraPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedPlayerSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBroadcasts.length>0)for(let $ of this._queuedBroadcasts){Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedDebugRaycastSynchronizations.length>0){let $=$0.createPacket($0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}q8.startSpan({operation:"send_all_packets"},()=>{for(let $ of d7.instance.getConnectedPlayersByWorld(this._world)){let Y=this._synchronizedPlayerReliablePackets.get($)??Z;if(Y.length>0)$.connection.send(Y);if(J.length>0)$.connection.send(J,!1)}}),q8.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();BZ.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity)}_onAudioPause=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=Z.audio.serialize();J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?E0.serializeVector(Z.position):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let{player:J,message:X,color:$}=Z;this._queuedBroadcasts.push($0.createPacket($0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:$,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:$}=Z,Y=this._queuedPerPlayerSynchronizations.get(J)??[];Y.push($0.createPacket($0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:$}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,Y)};_onChunkLatticeAddChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=Array.from(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkLatticeRemoveChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkLatticeSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=Array.from(Z.modelHiddenNodes)};_onEntitySetModelScale=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.s=Z.modelScale};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=Array.from(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?E0.serializeRgbColor(Z.tintColor):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al=Array.from(new Set([...J.al??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.ao=Array.from(new Set([...J.ao??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al)J.al=J.al.filter((X)=>!Z.animations.has(X)).filter(Boolean);if(J.ao)J.ao=J.ao.filter((X)=>!Z.animations.has(X)).filter(Boolean);J.as=Array.from(new Set([...J.as??[],...Z.animations]))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=[Z.rotation.x,Z.rotation.y,Z.rotation.z,Z.rotation.w]};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=[Z.position.x,Z.position.y,Z.position.z]};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=E0.serializeRgbColor(Z.color)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?E0.serializeVector(Z.offset):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?E0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?E0.serializeVector(Z.position):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onParticleEmitterBurst=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.b=Z.count};_onParticleEmitterDespawn=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rm=!0};_onParticleEmitterSetAlphaTest=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.at=Z.alphaTest};_onParticleEmitterSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onParticleEmitterSetAttachedToEntityNodeName=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.en=Z.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ce=Z.colorEnd?E0.serializeRgbColor(Z.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?E0.serializeRgbColor(Z.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?E0.serializeRgbColor(Z.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?E0.serializeRgbColor(Z.colorStartVariance):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?E0.serializeVector(Z.gravity):void 0};_onParticleEmitterSetLifetime=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.l=Z.lifetime};_onParticleEmitterSetLifetimeVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.lv=Z.lifetimeVariance};_onParticleEmitterSetMaxParticles=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.mp=Z.maxParticles};_onParticleEmitterSetOffset=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.o=Z.offset?E0.serializeVector(Z.offset):void 0};_onParticleEmitterSetOpacityEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oe=Z.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oev=Z.opacityEndVariance};_onParticleEmitterSetOpacityStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.os=Z.opacityStart};_onParticleEmitterSetOpacityStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.osv=Z.opacityStartVariance};_onParticleEmitterSetPaused=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pa=Z.paused};_onParticleEmitterSetPosition=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.p=Z.position?E0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e,J.en=Z.position?void 0:J.en};_onParticleEmitterSetPositionVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pv=Z.positionVariance?E0.serializeVector(Z.positionVariance):void 0};_onParticleEmitterSetRate=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.r=Z.rate};_onParticleEmitterSetRateVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rv=Z.rateVariance};_onParticleEmitterSetSizeEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.se=Z.sizeEnd};_onParticleEmitterSetSizeEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.sev=Z.sizeEndVariance};_onParticleEmitterSetSizeStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ss=Z.sizeStart};_onParticleEmitterSetSizeStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ssv=Z.sizeStartVariance};_onParticleEmitterSetTextureUri=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.tu=Z.textureUri};_onParticleEmitterSetTransparent=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.t=Z.transparent};_onParticleEmitterSetVelocity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.v=Z.velocity?E0.serializeVector(Z.velocity):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?E0.serializeVector(Z.velocityVariance):void 0};_onParticleEmitterSpawn=(Z)=>{let J=Z.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=E0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?E0.serializeVector(Z.position):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?E0.serializeVector(Z.position):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=Array.from(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=Array.from(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?E0.serializeVector(Z.offset):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?E0.serializeVector(Z.position):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let{player:J}=Z,X=this._queuedPerPlayerSynchronizations.get(J)??[];X.push($0.createPacket($0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((Y)=>{if(J.camera.attachedToEntity===void 0&&Y instanceof WJ&&Y.player===J)J.camera.setAttachedToEntity(Y);return Y.serialize()}),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.playersPacketDefinition,d7.instance.getConnectedPlayers().map((Y)=>Y.serialize()),this._world.loop.currentTick));let $=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...$}),this._queuedPerPlayerSynchronizations.set(J,X),this._queuedPlayerSynchronizations.set(J.id,J.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{Z.player.connection.send([$0.createPacket($0.outboundPackets.syncResponsePacketDefinition,{r:Z.receivedAt,s:Date.now(),p:performance.now()-Z.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?E0.serializeVector(Z.offset):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?E0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(E0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push($0.createPacket($0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=E0.serializeRgbColor(Z.color)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=E0.serializeRgbColor(Z.color)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=E0.serializeVector(Z.position)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=E0.serializeRgbColor(Z.color)};_onWorldSetFogFar=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ff=Z.far};_onWorldSetFogNear=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fn=Z.near};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:$}=Z,Y=`${J},${X},${$}`,Q=this._queuedBlockSynchronizations.get(Y);if(!Q)Q={i:0,c:[J,X,$]},this._queuedBlockSynchronizations.set(Y,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)u.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:$}=Z.originCoordinate,Y=`${J},${X},${$}`,Q=this._queuedChunkSynchronizations.get(Y);if(!Q)Q={c:[J,X,$]},this._queuedChunkSynchronizations.set(Y,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedParticleEmitterSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let J=this._queuedParticleEmitterSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedParticleEmitterSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=[],this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)u.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:Z.id}}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=[...J],this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class qz{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedParticleEmitters(Z){this.getAllEntityAttachedParticleEmitters(Z).forEach((J)=>{J.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(Z){return this.getAllParticleEmitters().filter((J)=>J.attachedToEntity===Z)}registerParticleEmitter(Z){if(Z.id!==void 0)return Z.id;let J=this._nextParticleEmitterId;return this._particleEmitters.set(J,Z),this._nextParticleEmitterId++,J}unregisterParticleEmitter(Z){if(Z.id===void 0)return;this._particleEmitters.delete(Z.id)}}class zz{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}var Cp8=2,Tp8=3;class Fz{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*Tp8,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)q8.startSpan({operation:"ticker_tick"},()=>{let $=0;while(this._accumulatorMs>=this._fixedTimestepMs&&$<Cp8)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,$++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else u.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var HZ5;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(HZ5||={});class Uz extends D0{_currentTick=0;_ticker;_world;constructor(Z,J=jf){super();this._ticker=new Fz(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();q8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:d7.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{q8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),q8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),q8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),q8.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{u.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var Rf;((q)=>{q.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";q.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";q.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";q.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";q.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";q.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";q.SET_FOG_FAR="WORLD.SET_FOG_FAR";q.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";q.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";q.START="WORLD.START";q.STOP="WORLD.STOP"})(Rf||={});class Bz extends D0{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;constructor(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=Z.fogColor,this._fogFar=Z.fogFar??550,this._fogNear=Z.fogNear??500,this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new v4(this),this._blockTypeRegistry=new WV(this),this._chatManager=new hV(this),this._chunkLattice=new bV(this),this._entityManager=new dV(this),this._lightManager=new Vz(this),this._loop=new Uz(this,Z.tickRate),this._networkSynchronizer=new zN(this),this._particleEmitterManager=new qz(this),this._sceneUIManager=new zz(this),this._simulation=new Hz(this,Z.tickRate,Z.gravity),Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,lightLevel:J.lightLevel,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[$,Y,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:$,y:Y,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[$,Y,Q]=J.split(",").map(Number);new h8({isEnvironmental:!0,...X}).spawn(this,{x:$,y:Y,z:Q})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setFogColor(Z){this._fogColor=Z,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:Z})}setFogFar(Z){this._fogFar=Z,this.emit("WORLD.SET_FOG_FAR",{world:this,far:Z})}setFogNear(Z){this._fogNear=Z,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return E0.serializeWorld(this)}}var qZ5;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(qZ5||={});class _${static instance=new _$;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new Bz({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),D0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var zZ5;(($)=>{$.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";$.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";$.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(zZ5||={});class d7{static instance=new d7;worldSelectionHandler;_connectionPlayers=new Map;constructor(){D0.globalInstance.on("CONNECTION.OPENED",({connection:Z,session:J})=>{this._onConnectionOpened(Z,J)}),D0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),D0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),D0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}async _onConnectionOpened(Z,J){let X=new YK(Z,J);await X.loadInitialPersistedData(),D0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let $=await this.worldSelectionHandler?.(X);X.joinWorld($??_$.instance.getDefaultWorld()),this._connectionPlayers.set(Z,X)}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),D0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else u.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),D0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else u.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var FZ5;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(FZ5||={});function kp8(Z){$5.init().then(()=>{return iQ.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(iQ.instance.worldManager.getDefaultWorld());else Z();iQ.instance.start()}).catch((J)=>{u.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class iQ{static _instance;_modelRegistry=V7.instance;_playerManager=d7.instance;_socket=O9.instance;_worldManager=_$.instance;_webServer=P4.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new iQ;return this._instance}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){D0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var o8=e(aQ(),1);class rQ extends Float32Array{constructor(Z,J,X,$){super([Z,J,X,$])}get determinant(){return o8.mat2.determinant(this)}get frobeniusNorm(){return o8.mat2.frob(this)}static create(){let Z=new rQ(0,0,0,0);return o8.mat2.identity(Z),Z}static fromRotation(Z){let J=rQ.create();return o8.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=rQ.create();return o8.mat2.fromScaling(J,Z),J}add(Z){return o8.mat2.add(this,this,Z),this}adjoint(){return o8.mat2.adjoint(this,this),this}clone(){return new rQ(this[0],this[1],this[2],this[3])}copy(Z){return o8.mat2.copy(this,Z),this}equals(Z){return o8.mat2.equals(this,Z)}exactEquals(Z){return o8.mat2.exactEquals(this,Z)}identity(){return o8.mat2.identity(this),this}invert(){return o8.mat2.invert(this,this),this}multiply(Z){return o8.mat2.mul(this,this,Z),this}multiplyScalar(Z){return o8.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return o8.mat2.rotate(this,this,Z),this}subtract(Z){return o8.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return o8.mat2.transpose(this,this),this}}var z8=e(aQ(),1);class SJ extends Float32Array{constructor(Z,J,X,$,Y,Q,W,K,G){super([Z,J,X,$,Y,Q,W,K,G])}get determinant(){return z8.mat3.determinant(this)}get frobeniusNorm(){return z8.mat3.frob(this)}static create(){let Z=new SJ(0,0,0,0,0,0,0,0,0);return z8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=SJ.create();return z8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=SJ.create();return z8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=SJ.create();return z8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=SJ.create();return z8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=SJ.create();return z8.mat3.fromTranslation(J,Z),J}add(Z){return z8.mat3.add(this,this,Z),this}adjoint(){return z8.mat3.adjoint(this,this),this}clone(){return new SJ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return z8.mat3.copy(this,Z),this}equals(Z){return z8.mat3.equals(this,Z)}exactEquals(Z){return z8.mat3.exactEquals(this,Z)}identity(){return z8.mat3.identity(this),this}invert(){return z8.mat3.invert(this,this),this}multiply(Z){return z8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return z8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return z8.mat3.projection(this,Z,J),this}rotate(Z){return z8.mat3.rotate(this,this,Z),this}subtract(Z){return z8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return z8.mat3.transpose(this,this),this}}var J5=e(aQ(),1);class X7 extends Float32Array{constructor(Z,J,X,$,Y,Q,W,K,G,V,H,q,z,F,U,L){super([Z,J,X,$,Y,Q,W,K,G,V,H,q,z,F,U,L])}get determinant(){return J5.mat4.determinant(this)}get frobeniusNorm(){return J5.mat4.frob(this)}static create(){let Z=new X7(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return J5.mat4.identity(Z),Z}static fromQuaternion(Z){let J=X7.create();return J5.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=X7.create();return J5.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=X7.create();return J5.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let $=X7.create();return J5.mat4.fromRotationTranslationScale($,Z,J,X),$}static fromRotationTranslationScaleOrigin(Z,J,X,$){let Y=X7.create();return J5.mat4.fromRotationTranslationScaleOrigin(Y,Z,J,X,$),Y}static fromScaling(Z){let J=X7.create();return J5.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=X7.create();return J5.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=X7.create();return J5.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=X7.create();return J5.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=X7.create();return J5.mat4.fromZRotation(J,Z),J}add(Z){return J5.mat4.add(this,this,Z),this}adjoint(){return J5.mat4.adjoint(this,this),this}clone(){return new X7(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(Z){return J5.mat4.copy(this,Z),this}equals(Z){return J5.mat4.equals(this,Z)}exactEquals(Z){return J5.mat4.exactEquals(this,Z)}frustrum(Z,J,X,$,Y,Q){return J5.mat4.frustum(this,Z,J,X,$,Y,Q),this}identity(){return J5.mat4.identity(this),this}invert(){return J5.mat4.invert(this,this),this}lookAt(Z,J,X){return J5.mat4.lookAt(this,Z,J,X),this}multiply(Z){return J5.mat4.mul(this,this,Z),this}multiplyScalar(Z){return J5.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,$,Y,Q){return J5.mat4.ortho(this,Z,J,X,$,Y,Q),this}perspective(Z,J,X,$){return J5.mat4.perspective(this,Z,J,X,$),this}rotate(Z,J){return J5.mat4.rotate(this,this,Z,J),this}rotateX(Z){return J5.mat4.rotateX(this,this,Z),this}rotateY(Z){return J5.mat4.rotateY(this,this,Z),this}rotateZ(Z){return J5.mat4.rotateZ(this,this,Z),this}scale(Z){return J5.mat4.scale(this,this,Z),this}subtract(Z){return J5.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return J5.mat4.targetTo(this,Z,J,X),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(Z){return J5.mat4.translate(this,this,Z),this}transpose(){return J5.mat4.transpose(this,this),this}}var S5=e(aQ(),1);class C4 extends Float32Array{constructor(Z,J,X,$){super([Z,J,X,$])}get length(){return S5.quat.length(this)}get squaredLength(){return S5.quat.squaredLength(this)}get magnitude(){return S5.quat.length(this)}get squaredMagnitude(){return S5.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let $=S5.quat.fromEuler(new Float32Array(4),Z,J,X);return new C4($[0],$[1],$[2],$[3])}static fromQuaternionLike(Z){return new C4(Z.x,Z.y,Z.z,Z.w)}clone(){return new C4(this.x,this.y,this.z,this.w)}conjugate(){return S5.quat.conjugate(this,this),this}copy(Z){return S5.quat.copy(this,Z),this}dot(Z){return S5.quat.dot(this,Z)}exponential(){return S5.quat.exp(this,this),this}equals(Z){return S5.quat.equals(this,Z)}exactEquals(Z){return S5.quat.exactEquals(this,Z)}getAngle(Z){return S5.quat.getAngle(this,Z)}identity(){return S5.quat.identity(this),this}invert(){return S5.quat.invert(this,this),this}lerp(Z,J){return S5.quat.lerp(this,this,Z,J),this}logarithm(){return S5.quat.ln(this,this),this}multiply(Z){return S5.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return S5.quat.normalize(this,this),this}power(Z){return S5.quat.pow(this,this,Z),this}randomize(){return S5.quat.random(this),this}rotateX(Z){return S5.quat.rotateX(this,this,Z),this}rotateY(Z){return S5.quat.rotateY(this,this,Z),this}rotateZ(Z){return S5.quat.rotateZ(this,this,Z),this}scale(Z){return S5.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return S5.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return S5.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var U5=e(aQ(),1);class Lz extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return U5.vec2.length(this)}get squaredLength(){return U5.vec2.squaredLength(this)}get magnitude(){return U5.vec2.length(this)}get squaredMagnitude(){return U5.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new Lz(0,0)}add(Z){return U5.vec2.add(this,this,Z),this}angle(Z){return U5.vec2.angle(this,Z)}ceil(){return U5.vec2.ceil(this,this),this}clone(){return new Lz(this.x,this.y)}copy(Z){return U5.vec2.copy(this,Z),this}distance(Z){return U5.vec2.distance(this,Z)}divide(Z){return U5.vec2.divide(this,this,Z),this}dot(Z){return U5.vec2.dot(this,Z)}equals(Z){return U5.vec2.equals(this,Z)}exactEquals(Z){return U5.vec2.exactEquals(this,Z)}floor(){return U5.vec2.floor(this,this),this}invert(){return U5.vec2.inverse(this,this),this}lerp(Z,J){return U5.vec2.lerp(this,this,Z,J),this}max(Z){return U5.vec2.max(this,this,Z),this}min(Z){return U5.vec2.min(this,this,Z),this}multiply(Z){return U5.vec2.mul(this,this,Z),this}negate(){return U5.vec2.negate(this,this),this}normalize(){return U5.vec2.normalize(this,this),this}randomize(Z){return U5.vec2.random(this,Z),this}rotate(Z,J){return U5.vec2.rotate(this,this,Z,J),this}round(){return U5.vec2.round(this,this),this}scale(Z){return U5.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return U5.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return U5.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return U5.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return U5.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return U5.vec2.transformMat4(this,this,Z),this}zero(){return U5.vec2.zero(this),this}}var q5=e(aQ(),1);class T4 extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return q5.vec3.length(this)}get squaredLength(){return q5.vec3.squaredLength(this)}get magnitude(){return q5.vec3.length(this)}get squaredMagnitude(){return q5.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new T4(0,0,0)}static fromVector3Like(Z){return new T4(Z.x,Z.y,Z.z)}add(Z){return q5.vec3.add(this,this,Z),this}ceil(){return q5.vec3.ceil(this,this),this}clone(){return new T4(this.x,this.y,this.z)}copy(Z){return q5.vec3.copy(this,Z),this}cross(Z){return q5.vec3.cross(this,this,Z),this}distance(Z){return q5.vec3.distance(this,Z)}divide(Z){return q5.vec3.div(this,this,Z),this}dot(Z){return q5.vec3.dot(this,Z)}equals(Z){return q5.vec3.equals(this,Z)}exactEquals(Z){return q5.vec3.exactEquals(this,Z)}floor(){return q5.vec3.floor(this,this),this}invert(){return q5.vec3.inverse(this,this),this}lerp(Z,J){return q5.vec3.lerp(this,this,Z,J),this}max(Z){return q5.vec3.max(this,this,Z),this}min(Z){return q5.vec3.min(this,this,Z),this}multiply(Z){return q5.vec3.mul(this,this,Z),this}negate(){return q5.vec3.negate(this,this),this}normalize(){return q5.vec3.normalize(this,this),this}randomize(Z){return q5.vec3.random(this,Z),this}rotateX(Z,J){return q5.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return q5.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return q5.vec3.rotateZ(this,this,Z,J),this}round(){return q5.vec3.round(this,this),this}scale(Z){return q5.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return q5.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return q5.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return q5.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return q5.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return q5.vec3.transformQuat(this,this,Z),this}zero(){return q5.vec3.zero(this),this}}var J15=e(eJ5(),1);var Z15=0.099856;class wz extends f${faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=Z15;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:Z15,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,$=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let Y=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*Y*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let Y={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-$.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-$.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-$.z},Q=Y.x*Y.x+Y.y*Y.y+Y.z*Y.z,W=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let K=$.x-this._moveStuckLastPosition.x,G=$.y-this._moveStuckLastPosition.y,V=$.z-this._moveStuckLastPosition.z;W=Math.sqrt(K*K+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=$,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!W){let K=Math.sqrt(Q),G=this.moveSpeed*X,H=Math.min(K,G)/K,q={x:$.x+Y.x*H,y:$.y+Y.y*H,z:$.z+Y.z*H};if(Z.setPosition(q),this._onMove)this._onMove(q,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let K=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,K($)}}}if(this._faceTarget){let Y={x:this._faceTarget.x-$.x,z:this._faceTarget.z-$.z},Q=Math.atan2(-Y.x,-Y.z),W=Z.rotation,K=Math.atan2(2*(W.w*W.y),1-2*(W.y*W.y)),G=Q-K;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let V=this.faceSpeed*X,H=Math.abs(G)<V?G:Math.sign(G)*V,z=(K+H)/2,F={x:0,y:Math.fround(Math.sin(z)),z:0,w:Math.fround(Math.cos(z))};if(Z.setRotation(F),this._onFace)this._onFace(W,F)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class Sf extends wz{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(Z={}){super(Z)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return u.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)u.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},$=Math.abs(X.x-J.x),Y=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if($<=2&&Y<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let K=this._coordinateToKey(J),G=new Map,V=new Map([[K,0]]),H=new Map([[K,this._pathfindingHeuristic(J,X)]]),q=new Set,z=new J15.Heap((M,N)=>{let P=H.get(M[0])??1/0,D=H.get(N[0])??1/0;return P-D});z.push([K,J]);let F=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],U=[];for(let M=this._maxJump;M>=this._maxFall;M--){if(M===0)continue;let N=Math.abs(J.y+M-X.y);U.push({y:M,distanceToTargetY:N})}U.sort((M,N)=>M.distanceToTargetY-N.distanceToTargetY);let L=[...F,...U.flatMap(({y:M})=>F.map((N)=>({...N,y:M})))],B=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),O=Math.min(this._maxOpenSetIterations,w*20);while(!z.isEmpty()&&B<O){B++;let[M,N]=z.pop();if(N.x===X.x&&N.y===X.y&&N.z===X.z){let C=this._reconstructPath(G,N);if(this._waypoints=C.map((T)=>({x:T.x+0.5,y:T.y+Z/2,z:T.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${B} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}q.add(M);let P=V.get(M),D=new Map;for(let C of L){let T=`${C.x},${C.z}`,k=C.y<0;if(k&&D.has(T))continue;let A={x:N.x+C.x,y:N.y+C.y,z:N.z+C.z};if(Math.abs(X.x-A.x)+Math.abs(X.y-A.y)+Math.abs(X.z-A.z)>w*1.5)continue;let x=this._coordinateToKey(A);if(q.has(x))continue;let I=this._isNeighborCoordinateBlocked(N,A,this._entity.height);if(k&&I){D.set(T,!0);continue}if(I)continue;let S=Math.abs(C.x),g=Math.abs(C.y),m=Math.abs(C.z),i=g===0?0:this._verticalPenalty,r=(Math.max(S,g,m)===1&&S+g+m>1?1.4:1)+i,Q0=P+r,F0=V.get(x)??1/0;if(Q0>=F0)continue;G.set(x,N),V.set(x,Q0);let _0=Q0+this._pathfindingHeuristic(A,X);H.set(x,_0),z.push([x,A])}}if(B>=O){if(this._onPathfindAbort?.(),this._debug)u.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${O}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)u.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],$=J;while(Z.has(this._coordinateToKey($)))$=Z.get(this._coordinateToKey($)),X.unshift($);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let $=J.y-Z.y,Y=Math.min($,this._maxJump)+0.75;this.jump(Y);let Q=Math.abs(this._entity.world.simulation.gravity.y),W=Math.sqrt(2*Q*Y),K=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,H=J.z+0.5,q=V-K,z=H-G,F=Math.sqrt(q*q+z*z),U=W/Q,L=F/this._speed;X=Math.min(U*0.8,L)*1000}setTimeout(()=>{if(!this._entity)return;let $=Date.now();this.face(J,this._speed),this.move(J,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-$>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let $=this._entity.world,Y=Math.floor(J.x),Q=Math.floor(J.y),W=Math.floor(J.z),K=Math.floor(Z.x),G=Math.floor(Z.z);if(!$.chunkLattice.hasBlock({x:Y,y:Q-1,z:W}))return!0;for(let V=0;V<X;V++)if($.chunkLattice.hasBlock({x:Y,y:Q+V,z:W}))return!0;if(Y!==K&&W!==G)for(let V=0;V<X;V++){let H=$.chunkLattice.hasBlock({x:Y,y:Q+V,z:G}),q=$.chunkLattice.hasBlock({x:K,y:Q+V,z:W});if(H||q)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,$={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let Y=0;Y<=Math.abs(this._maxFall);Y++)if(this._entity.world.chunkLattice.hasBlock({...$,y:$.y-Y-1}))return{...$,y:$.y-Y};return}}export{kp8 as startServer,qZ5 as WorldManagerEvent,_$ as WorldManager,HZ5 as WorldLoopEvent,Uz as WorldLoop,Rf as WorldEvent,Bz as World,KZ5 as WebServerEvent,P4 as WebServer,T4 as Vector3,Lz as Vector2,Fz as Ticker,pQ as TelemetrySpanOperation,q8 as Telemetry,Mf as SimulationEvent,Hz as Simulation,wz as SimpleEntityController,zz as SceneUIManager,_T as SceneUIEvent,mV as SceneUI,et as SUPPORTED_INPUT_KEYS,YV as RigidBodyType,MY as RigidBody,C4 as Quaternion,_B as PlayerUIEvent,xV as PlayerUI,zZ5 as PlayerManagerEvent,d7 as PlayerManager,fV as PlayerEvent,WJ as PlayerEntity,tt as PlayerCameraMode,ET as PlayerCameraEvent,AV as PlayerCamera,YK as Player,IY as PersistenceManager,Sf as PathfindingEntityController,qz as ParticleEmitterManager,Of as ParticleEmitterEvent,Nf as ParticleEmitter,Uf as PORT,Ye as PLAYER_ROTATION_UPDATE_THRESHOLD,$e as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,V7 as ModelRegistry,X7 as Matrix4,SJ as Matrix3,rQ as Matrix2,VZ5 as LightType,Vz as LightManager,Lf as LightEvent,wf as Light,r8 as IterationMap,FZ5 as GameServerEvent,iQ as GameServer,D0 as EventRouter,u as ErrorHandler,dV as EntityManager,gV as EntityEvent,h8 as Entity,Xe as ENTITY_ROTATION_UPDATE_THRESHOLD,Je as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,A5 as DefaultPlayerEntityController,AT as DefaultPlayerEntity,Ze as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,e9 as CollisionGroupsBuilder,g$ as CollisionGroup,QV as ColliderShape,yV as ColliderMap,f7 as Collider,nP as CoefficientCombineRule,ST as ChunkLatticeEvent,bV as ChunkLattice,y7 as Chunk,hV as ChatManager,IT as ChatEvent,aP as BlockTypeRegistryEvent,WV as BlockTypeRegistry,sP as BlockTypeEvent,h7 as BlockType,eQ as Block,yf as BaseEntityControllerEvent,f$ as BaseEntityController,v4 as AudioManager,IN as AudioEvent,I4 as Audio};
365
+ -----END RSA PRIVATE KEY-----`;var Uf=parseInt(process.env.PORT??"8080"),Bf="0.9.4",KZ5;((J)=>J.READY="WEBSERVER.READY")(KZ5||={});class P4 extends D0{static instance=new P4;_webserver=new qN;start(){this._webserver.use(async(J,X)=>{J.response.headers.set("Access-Control-Allow-Origin","*"),await X()});let Z=new Gz;Z.get("/",async(J)=>{if(J.isUpgradable)try{await this._authorizeAndUpgradeWebsocket(J)}catch(X){return u.error(`Websocket upgrade failed: ${X instanceof Error?X.message:"Unknown error"}`)}else J.response.body=JSON.stringify({status:"OK",version:Bf,runtime:"deno"})}),this._webserver.use(Z.routes()),this._webserver.use(Z.allowedMethods()),this._webserver.use(this._serveStatic("assets")),this._webserver.use(this._serveStatic("node_modules/@hytopia.com/assets")),this._webserver.listen({port:Uf,cert:process.env.NODE_ENV!=="production"?QZ5:void 0,key:process.env.NODE_ENV!=="production"?WZ5:void 0}),this.emitWithGlobal("WEBSERVER.READY",{}),console.info(`WebServer.start(): Server running on port ${Uf}.`)}async _authorizeAndUpgradeWebsocket(Z){let J=Z.request.url.searchParams.get("connectionId")??"",X=Z.request.url.searchParams.get("sessionToken")??"",$;if(!J||!O9.instance.isValidConnectionId(J)){let Q=await QJ.instance.getPlayerSession(X);if(Q?.error)return new Response(`${Q.error.code}: ${Q.error.message}`,{status:401});$=Q}let Y=Z.upgrade();if(Y.readyState!==WebSocket.OPEN)Y.addEventListener("open",()=>{O9.instance.handleConnection(Y,$,J)},{once:!0});else O9.instance.handleConnection(Y,$,J);return}_serveStatic(Z){return async(J,X)=>{let $=J.request.url.pathname;try{await Qz(J,$,{root:Z,hidden:!0})}catch{await X()}}}}var pQ;((L)=>{L.BUILD_PACKETS="build_packets";L.ENTITIES_EMIT_UPDATES="entities_emit_updates";L.ENTITIES_TICK="entities_tick";L.NETWORK_SYNCHRONIZE="network_synchronize";L.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";L.PHYSICS_CLEANUP="physics_cleanup";L.PHYSICS_STEP="physics_step";L.SEND_ALL_PACKETS="send_all_packets";L.SEND_PACKETS="send_packets";L.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";L.SERIALIZE_PACKETS="serialize_packets";L.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";L.SIMULATION_STEP="simulation_step";L.TICKER_TICK="ticker_tick";L.WORLD_TICK="world_tick"})(pQ||={});class q8{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([$,Y])=>[$,Y.value]))}static initializeSentry(Z,J=50){SO({dsn:Z,release:Bf,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=q8.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let Y=X?.start_timestamp,Q=X?.timestamp;if(!Y||!Q)return null;if((Q-Y)*1000>J)return X.measurements=q8.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(BH())return P9({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return Dx}}var GZ5=new xY({useFloat32:pV.ALWAYS}),Dp8=5000;class BZ extends D0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=V00(),this.onPacket($0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket($0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),D0.globalInstance.emit("CONNECTION.OPENED",{connection:this,session:J})}static clearCachedPacketsSerializedBuffers(){if(BZ._cachedPacketsSerializedBuffer.size>0)BZ._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!$0.isValidPacket(X))return u.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=BZ._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return q8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let $=GZ5.pack(Z);if($.byteLength>65536)$=Rp8($,{level:1});return X?.setAttribute("serializedBytes",$.byteLength),BZ._cachedPacketsSerializedBuffer.set(Z,$),$})}bindWs(Z){let J=!!this._ws;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this.send([$0.createPacket($0.bidirectionalPackets.connectionPacketDefinition,{k:!0})]);if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([$0.createPacket($0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(O9.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){if(this._ws.readyState!==WebSocket.OPEN)return;try{this._ws.close()}catch(Z){u.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==WebSocket.OPEN)return;if(!J&&this._ws.bufferedAmount>4096)return;q8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let $=BZ.serializePackets(Z);if(!$)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&$.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send($)}catch{this._ws.send($)}else this._ws.send($);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch($){u.error(`Connection.send(): Packet send failed. Error: ${$}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,$=J.d;if(X){let{i:Y,d:Q}=X,W=!1;if(Y==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),W=!0;if(Y==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),W=!0;if(W)this.send([$0.createPacket($0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:Y}})])}if($)for(let Y of $){let{s:Q,l:W}=Y,K=await this._wrtcClientServerTransport.produceData({label:W,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:K.id});this._wrtcClientServerDataProducers.push(K),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([$0.createPacket($0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:K.id,l:W}})])}};_onHeartbeatPacket=()=>{this.send([$0.createPacket($0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){u.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},Dp8)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await O9.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:$}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(W)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,W)}),this._wrtcServerClientTransport=$,this._wrtcServerClientTransport.on("icestatechange",(W)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,W)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let Y=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push(Y,Q),this.send([$0.createPacket($0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:Y.id,pi:Y.dataProducerId,l:"scr",s:Y.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=GZ5.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return u.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!$0.isValidPacket(J))return u.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class Vz{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class r8{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,$)=>{Z.call(J,X,$,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var VZ5;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(VZ5||={});var Lf;((z)=>{z.DESPAWN="LIGHT.DESPAWN";z.SET_ANGLE="LIGHT.SET_ANGLE";z.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";z.SET_COLOR="LIGHT.SET_COLOR";z.SET_DISTANCE="LIGHT.SET_DISTANCE";z.SET_INTENSITY="LIGHT.SET_INTENSITY";z.SET_OFFSET="LIGHT.SET_OFFSET";z.SET_PENUMBRA="LIGHT.SET_PENUMBRA";z.SET_POSITION="LIGHT.SET_POSITION";z.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";z.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";z.SPAWN="LIGHT.SPAWN"})(Lf||={});class wf extends D0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)u.fatalError("Either attachedToEntity or position must be set, but not both.");super();u.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return u.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return u.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return u.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){return E0.serializeLight(this)}}var Of;((m)=>{m.BURST="PARTICLE_EMITTER.BURST";m.DESPAWN="PARTICLE_EMITTER.DESPAWN";m.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";m.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";m.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";m.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";m.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";m.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";m.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";m.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";m.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";m.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";m.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";m.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";m.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";m.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";m.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";m.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";m.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";m.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";m.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";m.SET_RATE="PARTICLE_EMITTER.SET_RATE";m.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";m.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";m.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";m.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";m.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";m.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";m.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";m.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";m.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";m.SPAWN="PARTICLE_EMITTER.SPAWN"})(Of||={});class Nf extends D0{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)u.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)u.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=Z.alphaTest??0.05,this._attachedToEntity=Z.attachedToEntity,this._attachedToEntityNodeName=Z.attachedToEntityNodeName,this._colorEnd=Z.colorEnd,this._colorEndVariance=Z.colorEndVariance,this._colorStart=Z.colorStart,this._colorStartVariance=Z.colorStartVariance,this._gravity=Z.gravity,this._lifetime=Z.lifetime,this._lifetimeVariance=Z.lifetimeVariance,this._maxParticles=Z.maxParticles,this._offset=Z.offset,this._opacityEnd=Z.opacityEnd,this._opacityEndVariance=Z.opacityEndVariance,this._opacityStart=Z.opacityStart,this._opacityStartVariance=Z.opacityStartVariance,this._paused=!1,this._position=Z.position,this._positionVariance=Z.positionVariance,this._rate=Z.rate,this._rateVariance=Z.rateVariance,this._sizeEnd=Z.sizeEnd,this._sizeEndVariance=Z.sizeEndVariance,this._sizeStart=Z.sizeStart,this._sizeStartVariance=Z.sizeStartVariance,this._textureUri=Z.textureUri,this._transparent=Z.transparent,this._velocity=Z.velocity,this._velocityVariance=Z.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(Z){if(this._alphaTest===Z)return;if(this._alphaTest=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return u.error(`ParticleEmitter.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:Z})}setAttachedToEntityNodeName(Z){if(this._attachedToEntityNodeName===Z)return;if(this._attachedToEntityNodeName=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:Z})}setColorEnd(Z){if(this._colorEnd&&this._colorEnd.r===Z.r&&this._colorEnd.g===Z.g&&this._colorEnd.b===Z.b)return;if(this._colorEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:Z})}setColorEndVariance(Z){if(this._colorEndVariance&&this._colorEndVariance.r===Z.r&&this._colorEndVariance.g===Z.g&&this._colorEndVariance.b===Z.b)return;if(this._colorEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:Z})}setColorStart(Z){if(this._colorStart&&this._colorStart.r===Z.r&&this._colorStart.g===Z.g&&this._colorStart.b===Z.b)return;if(this._colorStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:Z})}setColorStartVariance(Z){if(this._colorStartVariance&&this._colorStartVariance.r===Z.r&&this._colorStartVariance.g===Z.g&&this._colorStartVariance.b===Z.b)return;if(this._colorStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:Z})}setGravity(Z){if(this._gravity&&this._gravity.x===Z.x&&this._gravity.y===Z.y&&this._gravity.z===Z.z)return;if(this._gravity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:Z})}setLifetime(Z){if(this._lifetime===Z)return;if(this._lifetime=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:Z})}setLifetimeVariance(Z){if(this._lifetimeVariance===Z)return;if(this._lifetimeVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:Z})}setMaxParticles(Z){if(this._maxParticles===Z)return;if(this._maxParticles=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:Z})}setOpacityEnd(Z){if(this._opacityEnd===Z)return;if(this._opacityEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:Z})}setOpacityEndVariance(Z){if(this._opacityEndVariance===Z)return;if(this._opacityEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:Z})}setOpacityStart(Z){if(this._opacityStart===Z)return;if(this._opacityStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:Z})}setOpacityStartVariance(Z){if(this._opacityStartVariance===Z)return;if(this._opacityStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:Z})}setPositionVariance(Z){if(this._positionVariance&&this._positionVariance.x===Z.x&&this._positionVariance.y===Z.y&&this._positionVariance.z===Z.z)return;if(this._positionVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:Z})}setRate(Z){if(this._rate===Z)return;if(this._rate=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:Z})}setRateVariance(Z){if(this._rateVariance===Z)return;if(this._rateVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:Z})}setSizeEnd(Z){if(this._sizeEnd===Z)return;if(this._sizeEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:Z})}setSizeEndVariance(Z){if(this._sizeEndVariance===Z)return;if(this._sizeEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:Z})}setSizeStart(Z){if(this._sizeStart===Z)return;if(this._sizeStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:Z})}setSizeStartVariance(Z){if(this._sizeStartVariance===Z)return;if(this._sizeStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:Z})}setTextureUri(Z){if(this._textureUri===Z)return;if(this._textureUri=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:Z})}setTransparent(Z){if(this._transparent===Z)return;if(this._transparent=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:Z})}setVelocity(Z){if(this._velocity&&this._velocity.x===Z.x&&this._velocity.y===Z.y&&this._velocity.z===Z.z)return;if(this._velocity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:Z})}setVelocityVariance(Z){if(this._velocityVariance&&this._velocityVariance.x===Z.x&&this._velocityVariance.y===Z.y&&this._velocityVariance.z===Z.z)return;if(this._velocityVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:Z})}burst(Z){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return u.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=Z.particleEmitterManager.registerParticleEmitter(this),this._world=Z,this.emitWithWorld(Z,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return E0.serializeParticleEmitter(this)}}var Pp8={x:0,y:-32,z:0},jf=60,Mf;((Y)=>{Y.STEP_START="SIMULATION.STEP_START";Y.STEP_END="SIMULATION.STEP_END";Y.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";Y.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Mf||={});class Hz extends D0{_colliderMap=new yV;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=jf,X=Pp8){super();this._rapierEventQueue=new $5.EventQueue(!0),this._rapierSimulation=new $5.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=$5.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,($,Y)=>{if($.numContacts()===0)return;let Q=$.normal(),W=[];for(let K=0;K<$.numSolverContacts();K++)W.push($.solverContactPoint(K));X.push({contactPoints:W,localNormalA:!Y?$.localNormal1():$.localNormal2(),localNormalB:!Y?$.localNormal2():$.localNormal1(),normal:!Y?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,$={}){let Y=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(W)=>{let K=this._colliderMap.getColliderHandleBlockType(W.handle);if(K&&!Y.has(K))return Y.add(K),Q.push({intersectedBlockType:K}),!0;let G=this._colliderMap.getColliderHandleEntity(W.handle);if(G&&!Y.has(G))return Y.add(G),Q.push({intersectedEntity:G}),!0;return!0},$.filterFlags,$.filterGroups,$.filterExcludeCollider,$.filterExcludeRigidBody,$.filterPredicate),Q}raycast(Z,J,X,$={}){let Y=new $5.Ray(Z,J),Q=this._rapierSimulation.castRay(Y,X,$.solidMode??!0,$.filterFlags,$.filterGroups,$.filterExcludeCollider,$.filterExcludeRigidBody,$.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let W=Y.pointAt(Q.timeOfImpact),K=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:eQ.fromGlobalCoordinate({x:Math.floor(W.x-(Y.dir.x<0?0.0001:-0.0001)),y:Math.floor(W.y-(Y.dir.y<0?0.0001:-0.0001)),z:Math.floor(W.z-(Y.dir.z<0?0.0001:-0.0001))},V),hitPoint:W,hitDistance:K};let H=this._colliderMap.getColliderHandleEntity(G.handle);if(H)return{hitEntity:H,hitPoint:W,hitDistance:K};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(q8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),q8.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[$,Y]=this._getCollisionObjects(Z,J);if(!$||!Y)return;let Q=(W,K)=>{if(W instanceof h7&&K instanceof h8&&W.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))W.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:W,entity:K,started:X,colliderHandleA:Z,colliderHandleB:J});else if(W instanceof h8&&K instanceof h7&&W.hasListeners("ENTITY.BLOCK_COLLISION"))W.emit("ENTITY.BLOCK_COLLISION",{entity:W,blockType:K,started:X,colliderHandleA:Z,colliderHandleB:J});else if(W instanceof h8&&K instanceof h8&&W.hasListeners("ENTITY.ENTITY_COLLISION"))W.emit("ENTITY.ENTITY_COLLISION",{entity:W,otherEntity:K,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof W==="function"&&(K instanceof h8||K instanceof h7))W(K,X,Z,J)};Q($,Y),Q(Y,$)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let $={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},Y=(Q,W)=>{if(Q instanceof h7&&W instanceof h8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:W,contactForceData:$});else if(Q instanceof h8&&W instanceof h7&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:W,contactForceData:$});else if(Q instanceof h8&&W instanceof h8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:W,contactForceData:$})};Y(J,X),Y(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),$=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,$]}}class zN{_synchronizedPlayerReliablePackets=new r8;_queuedBroadcasts=[];_queuedAudioSynchronizations=new r8;_queuedBlockSynchronizations=new r8;_queuedBlockTypeSynchronizations=new r8;_queuedChunkSynchronizations=new r8;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new r8;_queuedLightSynchronizations=new r8;_queuedParticleEmitterSynchronizations=new r8;_queuedPerPlayerSynchronizations=new r8;_queuedPerPlayerCameraSynchronizations=new r8;_queuedPerPlayerUISynchronizations=new r8;_queuedPerPlayerUIDatasSynchronizations=new r8;_queuedPlayerSynchronizations=new r8;_queuedSceneUISynchronizations=new r8;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=[],J=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(...Y);if(this._queuedEntitySynchronizations.size>0){let $=[],Y=[];for(let Q of this._queuedEntitySynchronizations.valuesArray){let W=!1;for(let K in Q)if(K!=="i"&&K!=="p"&&K!=="r"){W=!0;break}if(W)$.push(Q);else Y.push(Q)}if(Y.length>0){let Q=$0.createPacket($0.outboundPackets.entitiesPacketDefinition,Y,X);J.push(Q)}if($.length>0){let Q=$0.createPacket($0.outboundPackets.entitiesPacketDefinition,$,X);Z.push(Q);for(let W of this._synchronizedPlayerReliablePackets.valuesArray)W.push(Q)}}if(this._queuedAudioSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBlockTypeSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedChunkSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBlockSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedLightSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedParticleEmitterSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerUISynchronizations){let Q=$0.createPacket($0.outboundPackets.uiPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerUIDatasSynchronizations){let Q=$0.createPacket($0.outboundPackets.uiDatasPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedSceneUISynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedWorldSynchronization){let $=$0.createPacket($0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerCameraSynchronizations){let Q=$0.createPacket($0.outboundPackets.cameraPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedPlayerSynchronizations.size>0){let $=$0.createPacket($0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBroadcasts.length>0)for(let $ of this._queuedBroadcasts){Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedDebugRaycastSynchronizations.length>0){let $=$0.createPacket($0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}q8.startSpan({operation:"send_all_packets"},()=>{for(let $ of d7.instance.getConnectedPlayersByWorld(this._world)){let Y=this._synchronizedPlayerReliablePackets.get($)??Z;if(Y.length>0)$.connection.send(Y);if(J.length>0)$.connection.send(J,!1)}}),q8.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();BZ.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity)}_onAudioPause=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=Z.audio.serialize();J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?E0.serializeVector(Z.position):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let{player:J,message:X,color:$}=Z;this._queuedBroadcasts.push($0.createPacket($0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:$,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:$}=Z,Y=this._queuedPerPlayerSynchronizations.get(J)??[];Y.push($0.createPacket($0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:$}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,Y)};_onChunkLatticeAddChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=Array.from(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkLatticeRemoveChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkLatticeSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=Array.from(Z.modelHiddenNodes)};_onEntitySetModelScale=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.s=Z.modelScale};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=Array.from(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?E0.serializeRgbColor(Z.tintColor):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al=Array.from(new Set([...J.al??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.ao=Array.from(new Set([...J.ao??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al)J.al=J.al.filter((X)=>!Z.animations.has(X)).filter(Boolean);if(J.ao)J.ao=J.ao.filter((X)=>!Z.animations.has(X)).filter(Boolean);J.as=Array.from(new Set([...J.as??[],...Z.animations]))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=[Z.rotation.x,Z.rotation.y,Z.rotation.z,Z.rotation.w]};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=[Z.position.x,Z.position.y,Z.position.z]};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=E0.serializeRgbColor(Z.color)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?E0.serializeVector(Z.offset):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?E0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?E0.serializeVector(Z.position):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onParticleEmitterBurst=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.b=Z.count};_onParticleEmitterDespawn=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rm=!0};_onParticleEmitterSetAlphaTest=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.at=Z.alphaTest};_onParticleEmitterSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onParticleEmitterSetAttachedToEntityNodeName=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.en=Z.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ce=Z.colorEnd?E0.serializeRgbColor(Z.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?E0.serializeRgbColor(Z.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?E0.serializeRgbColor(Z.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?E0.serializeRgbColor(Z.colorStartVariance):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?E0.serializeVector(Z.gravity):void 0};_onParticleEmitterSetLifetime=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.l=Z.lifetime};_onParticleEmitterSetLifetimeVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.lv=Z.lifetimeVariance};_onParticleEmitterSetMaxParticles=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.mp=Z.maxParticles};_onParticleEmitterSetOffset=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.o=Z.offset?E0.serializeVector(Z.offset):void 0};_onParticleEmitterSetOpacityEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oe=Z.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oev=Z.opacityEndVariance};_onParticleEmitterSetOpacityStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.os=Z.opacityStart};_onParticleEmitterSetOpacityStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.osv=Z.opacityStartVariance};_onParticleEmitterSetPaused=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pa=Z.paused};_onParticleEmitterSetPosition=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.p=Z.position?E0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e,J.en=Z.position?void 0:J.en};_onParticleEmitterSetPositionVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pv=Z.positionVariance?E0.serializeVector(Z.positionVariance):void 0};_onParticleEmitterSetRate=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.r=Z.rate};_onParticleEmitterSetRateVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rv=Z.rateVariance};_onParticleEmitterSetSizeEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.se=Z.sizeEnd};_onParticleEmitterSetSizeEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.sev=Z.sizeEndVariance};_onParticleEmitterSetSizeStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ss=Z.sizeStart};_onParticleEmitterSetSizeStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ssv=Z.sizeStartVariance};_onParticleEmitterSetTextureUri=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.tu=Z.textureUri};_onParticleEmitterSetTransparent=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.t=Z.transparent};_onParticleEmitterSetVelocity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.v=Z.velocity?E0.serializeVector(Z.velocity):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?E0.serializeVector(Z.velocityVariance):void 0};_onParticleEmitterSpawn=(Z)=>{let J=Z.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=E0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?E0.serializeVector(Z.position):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?E0.serializeVector(Z.position):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=Array.from(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=Array.from(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?E0.serializeVector(Z.offset):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?E0.serializeVector(Z.position):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let{player:J}=Z,X=this._queuedPerPlayerSynchronizations.get(J)??[];X.push($0.createPacket($0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((Y)=>{if(J.camera.attachedToEntity===void 0&&Y instanceof WJ&&Y.player===J)J.camera.setAttachedToEntity(Y);return Y.serialize()}),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push($0.createPacket($0.outboundPackets.playersPacketDefinition,d7.instance.getConnectedPlayers().map((Y)=>Y.serialize()),this._world.loop.currentTick));let $=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...$}),this._queuedPerPlayerSynchronizations.set(J,X),this._queuedPlayerSynchronizations.set(J.id,J.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{Z.player.connection.send([$0.createPacket($0.outboundPackets.syncResponsePacketDefinition,{r:Z.receivedAt,s:Date.now(),p:performance.now()-Z.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?E0.serializeVector(Z.offset):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?E0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(E0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push($0.createPacket($0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=E0.serializeRgbColor(Z.color)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=E0.serializeRgbColor(Z.color)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=E0.serializeVector(Z.position)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=E0.serializeRgbColor(Z.color)};_onWorldSetFogFar=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ff=Z.far};_onWorldSetFogNear=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fn=Z.near};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:$}=Z,Y=`${J},${X},${$}`,Q=this._queuedBlockSynchronizations.get(Y);if(!Q)Q={i:0,c:[J,X,$]},this._queuedBlockSynchronizations.set(Y,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)u.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:$}=Z.originCoordinate,Y=`${J},${X},${$}`,Q=this._queuedChunkSynchronizations.get(Y);if(!Q)Q={c:[J,X,$]},this._queuedChunkSynchronizations.set(Y,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedParticleEmitterSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let J=this._queuedParticleEmitterSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedParticleEmitterSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=[],this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)u.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:Z.id}}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=[...J],this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class qz{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedParticleEmitters(Z){this.getAllEntityAttachedParticleEmitters(Z).forEach((J)=>{J.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(Z){return this.getAllParticleEmitters().filter((J)=>J.attachedToEntity===Z)}registerParticleEmitter(Z){if(Z.id!==void 0)return Z.id;let J=this._nextParticleEmitterId;return this._particleEmitters.set(J,Z),this._nextParticleEmitterId++,J}unregisterParticleEmitter(Z){if(Z.id===void 0)return;this._particleEmitters.delete(Z.id)}}class zz{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}var Cp8=2,Tp8=3;class Fz{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*Tp8,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)q8.startSpan({operation:"ticker_tick"},()=>{let $=0;while(this._accumulatorMs>=this._fixedTimestepMs&&$<Cp8)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,$++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else u.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var HZ5;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(HZ5||={});class Uz extends D0{_currentTick=0;_ticker;_world;constructor(Z,J=jf){super();this._ticker=new Fz(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();q8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:d7.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{q8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),q8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),q8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),q8.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{u.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var Rf;((q)=>{q.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";q.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";q.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";q.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";q.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";q.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";q.SET_FOG_FAR="WORLD.SET_FOG_FAR";q.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";q.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";q.START="WORLD.START";q.STOP="WORLD.STOP"})(Rf||={});class Bz extends D0{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;constructor(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=Z.fogColor,this._fogFar=Z.fogFar??550,this._fogNear=Z.fogNear??500,this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new v4(this),this._blockTypeRegistry=new WV(this),this._chatManager=new hV(this),this._chunkLattice=new bV(this),this._entityManager=new dV(this),this._lightManager=new Vz(this),this._loop=new Uz(this,Z.tickRate),this._networkSynchronizer=new zN(this),this._particleEmitterManager=new qz(this),this._sceneUIManager=new zz(this),this._simulation=new Hz(this,Z.tickRate,Z.gravity),Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,lightLevel:J.lightLevel,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[$,Y,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:$,y:Y,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[$,Y,Q]=J.split(",").map(Number);new h8({isEnvironmental:!0,...X}).spawn(this,{x:$,y:Y,z:Q})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setFogColor(Z){this._fogColor=Z,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:Z})}setFogFar(Z){this._fogFar=Z,this.emit("WORLD.SET_FOG_FAR",{world:this,far:Z})}setFogNear(Z){this._fogNear=Z,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return E0.serializeWorld(this)}}var qZ5;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(qZ5||={});class _${static instance=new _$;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new Bz({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),D0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var zZ5;(($)=>{$.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";$.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";$.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(zZ5||={});class d7{static instance=new d7;worldSelectionHandler;_connectionPlayers=new Map;constructor(){D0.globalInstance.on("CONNECTION.OPENED",({connection:Z,session:J})=>{this._onConnectionOpened(Z,J)}),D0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),D0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),D0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}async _onConnectionOpened(Z,J){let X=new YK(Z,J);await X.loadInitialPersistedData(),D0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let $=await this.worldSelectionHandler?.(X);X.joinWorld($??_$.instance.getDefaultWorld()),this._connectionPlayers.set(Z,X)}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),D0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else u.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),D0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else u.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var FZ5;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(FZ5||={});function kp8(Z){$5.init().then(()=>{return iQ.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(iQ.instance.worldManager.getDefaultWorld());else Z();iQ.instance.start()}).catch((J)=>{u.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class iQ{static _instance;_modelRegistry=V7.instance;_playerManager=d7.instance;_socket=O9.instance;_worldManager=_$.instance;_webServer=P4.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new iQ;return this._instance}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){D0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var o8=e(aQ(),1);class rQ extends Float32Array{constructor(Z,J,X,$){super([Z,J,X,$])}get determinant(){return o8.mat2.determinant(this)}get frobeniusNorm(){return o8.mat2.frob(this)}static create(){let Z=new rQ(0,0,0,0);return o8.mat2.identity(Z),Z}static fromRotation(Z){let J=rQ.create();return o8.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=rQ.create();return o8.mat2.fromScaling(J,Z),J}add(Z){return o8.mat2.add(this,this,Z),this}adjoint(){return o8.mat2.adjoint(this,this),this}clone(){return new rQ(this[0],this[1],this[2],this[3])}copy(Z){return o8.mat2.copy(this,Z),this}equals(Z){return o8.mat2.equals(this,Z)}exactEquals(Z){return o8.mat2.exactEquals(this,Z)}identity(){return o8.mat2.identity(this),this}invert(){return o8.mat2.invert(this,this),this}multiply(Z){return o8.mat2.mul(this,this,Z),this}multiplyScalar(Z){return o8.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return o8.mat2.rotate(this,this,Z),this}subtract(Z){return o8.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return o8.mat2.transpose(this,this),this}}var z8=e(aQ(),1);class SJ extends Float32Array{constructor(Z,J,X,$,Y,Q,W,K,G){super([Z,J,X,$,Y,Q,W,K,G])}get determinant(){return z8.mat3.determinant(this)}get frobeniusNorm(){return z8.mat3.frob(this)}static create(){let Z=new SJ(0,0,0,0,0,0,0,0,0);return z8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=SJ.create();return z8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=SJ.create();return z8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=SJ.create();return z8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=SJ.create();return z8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=SJ.create();return z8.mat3.fromTranslation(J,Z),J}add(Z){return z8.mat3.add(this,this,Z),this}adjoint(){return z8.mat3.adjoint(this,this),this}clone(){return new SJ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return z8.mat3.copy(this,Z),this}equals(Z){return z8.mat3.equals(this,Z)}exactEquals(Z){return z8.mat3.exactEquals(this,Z)}identity(){return z8.mat3.identity(this),this}invert(){return z8.mat3.invert(this,this),this}multiply(Z){return z8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return z8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return z8.mat3.projection(this,Z,J),this}rotate(Z){return z8.mat3.rotate(this,this,Z),this}subtract(Z){return z8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return z8.mat3.transpose(this,this),this}}var J5=e(aQ(),1);class X7 extends Float32Array{constructor(Z,J,X,$,Y,Q,W,K,G,V,H,q,z,F,U,L){super([Z,J,X,$,Y,Q,W,K,G,V,H,q,z,F,U,L])}get determinant(){return J5.mat4.determinant(this)}get frobeniusNorm(){return J5.mat4.frob(this)}static create(){let Z=new X7(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return J5.mat4.identity(Z),Z}static fromQuaternion(Z){let J=X7.create();return J5.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=X7.create();return J5.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=X7.create();return J5.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let $=X7.create();return J5.mat4.fromRotationTranslationScale($,Z,J,X),$}static fromRotationTranslationScaleOrigin(Z,J,X,$){let Y=X7.create();return J5.mat4.fromRotationTranslationScaleOrigin(Y,Z,J,X,$),Y}static fromScaling(Z){let J=X7.create();return J5.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=X7.create();return J5.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=X7.create();return J5.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=X7.create();return J5.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=X7.create();return J5.mat4.fromZRotation(J,Z),J}add(Z){return J5.mat4.add(this,this,Z),this}adjoint(){return J5.mat4.adjoint(this,this),this}clone(){return new X7(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(Z){return J5.mat4.copy(this,Z),this}equals(Z){return J5.mat4.equals(this,Z)}exactEquals(Z){return J5.mat4.exactEquals(this,Z)}frustrum(Z,J,X,$,Y,Q){return J5.mat4.frustum(this,Z,J,X,$,Y,Q),this}identity(){return J5.mat4.identity(this),this}invert(){return J5.mat4.invert(this,this),this}lookAt(Z,J,X){return J5.mat4.lookAt(this,Z,J,X),this}multiply(Z){return J5.mat4.mul(this,this,Z),this}multiplyScalar(Z){return J5.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,$,Y,Q){return J5.mat4.ortho(this,Z,J,X,$,Y,Q),this}perspective(Z,J,X,$){return J5.mat4.perspective(this,Z,J,X,$),this}rotate(Z,J){return J5.mat4.rotate(this,this,Z,J),this}rotateX(Z){return J5.mat4.rotateX(this,this,Z),this}rotateY(Z){return J5.mat4.rotateY(this,this,Z),this}rotateZ(Z){return J5.mat4.rotateZ(this,this,Z),this}scale(Z){return J5.mat4.scale(this,this,Z),this}subtract(Z){return J5.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return J5.mat4.targetTo(this,Z,J,X),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(Z){return J5.mat4.translate(this,this,Z),this}transpose(){return J5.mat4.transpose(this,this),this}}var S5=e(aQ(),1);class C4 extends Float32Array{constructor(Z,J,X,$){super([Z,J,X,$])}get length(){return S5.quat.length(this)}get squaredLength(){return S5.quat.squaredLength(this)}get magnitude(){return S5.quat.length(this)}get squaredMagnitude(){return S5.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let $=S5.quat.fromEuler(new Float32Array(4),Z,J,X);return new C4($[0],$[1],$[2],$[3])}static fromQuaternionLike(Z){return new C4(Z.x,Z.y,Z.z,Z.w)}clone(){return new C4(this.x,this.y,this.z,this.w)}conjugate(){return S5.quat.conjugate(this,this),this}copy(Z){return S5.quat.copy(this,Z),this}dot(Z){return S5.quat.dot(this,Z)}exponential(){return S5.quat.exp(this,this),this}equals(Z){return S5.quat.equals(this,Z)}exactEquals(Z){return S5.quat.exactEquals(this,Z)}getAngle(Z){return S5.quat.getAngle(this,Z)}identity(){return S5.quat.identity(this),this}invert(){return S5.quat.invert(this,this),this}lerp(Z,J){return S5.quat.lerp(this,this,Z,J),this}logarithm(){return S5.quat.ln(this,this),this}multiply(Z){return S5.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return S5.quat.normalize(this,this),this}power(Z){return S5.quat.pow(this,this,Z),this}randomize(){return S5.quat.random(this),this}rotateX(Z){return S5.quat.rotateX(this,this,Z),this}rotateY(Z){return S5.quat.rotateY(this,this,Z),this}rotateZ(Z){return S5.quat.rotateZ(this,this,Z),this}scale(Z){return S5.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return S5.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return S5.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var U5=e(aQ(),1);class Lz extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return U5.vec2.length(this)}get squaredLength(){return U5.vec2.squaredLength(this)}get magnitude(){return U5.vec2.length(this)}get squaredMagnitude(){return U5.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new Lz(0,0)}add(Z){return U5.vec2.add(this,this,Z),this}angle(Z){return U5.vec2.angle(this,Z)}ceil(){return U5.vec2.ceil(this,this),this}clone(){return new Lz(this.x,this.y)}copy(Z){return U5.vec2.copy(this,Z),this}distance(Z){return U5.vec2.distance(this,Z)}divide(Z){return U5.vec2.divide(this,this,Z),this}dot(Z){return U5.vec2.dot(this,Z)}equals(Z){return U5.vec2.equals(this,Z)}exactEquals(Z){return U5.vec2.exactEquals(this,Z)}floor(){return U5.vec2.floor(this,this),this}invert(){return U5.vec2.inverse(this,this),this}lerp(Z,J){return U5.vec2.lerp(this,this,Z,J),this}max(Z){return U5.vec2.max(this,this,Z),this}min(Z){return U5.vec2.min(this,this,Z),this}multiply(Z){return U5.vec2.mul(this,this,Z),this}negate(){return U5.vec2.negate(this,this),this}normalize(){return U5.vec2.normalize(this,this),this}randomize(Z){return U5.vec2.random(this,Z),this}rotate(Z,J){return U5.vec2.rotate(this,this,Z,J),this}round(){return U5.vec2.round(this,this),this}scale(Z){return U5.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return U5.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return U5.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return U5.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return U5.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return U5.vec2.transformMat4(this,this,Z),this}zero(){return U5.vec2.zero(this),this}}var q5=e(aQ(),1);class T4 extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return q5.vec3.length(this)}get squaredLength(){return q5.vec3.squaredLength(this)}get magnitude(){return q5.vec3.length(this)}get squaredMagnitude(){return q5.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new T4(0,0,0)}static fromVector3Like(Z){return new T4(Z.x,Z.y,Z.z)}add(Z){return q5.vec3.add(this,this,Z),this}ceil(){return q5.vec3.ceil(this,this),this}clone(){return new T4(this.x,this.y,this.z)}copy(Z){return q5.vec3.copy(this,Z),this}cross(Z){return q5.vec3.cross(this,this,Z),this}distance(Z){return q5.vec3.distance(this,Z)}divide(Z){return q5.vec3.div(this,this,Z),this}dot(Z){return q5.vec3.dot(this,Z)}equals(Z){return q5.vec3.equals(this,Z)}exactEquals(Z){return q5.vec3.exactEquals(this,Z)}floor(){return q5.vec3.floor(this,this),this}invert(){return q5.vec3.inverse(this,this),this}lerp(Z,J){return q5.vec3.lerp(this,this,Z,J),this}max(Z){return q5.vec3.max(this,this,Z),this}min(Z){return q5.vec3.min(this,this,Z),this}multiply(Z){return q5.vec3.mul(this,this,Z),this}negate(){return q5.vec3.negate(this,this),this}normalize(){return q5.vec3.normalize(this,this),this}randomize(Z){return q5.vec3.random(this,Z),this}rotateX(Z,J){return q5.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return q5.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return q5.vec3.rotateZ(this,this,Z,J),this}round(){return q5.vec3.round(this,this),this}scale(Z){return q5.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return q5.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return q5.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return q5.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return q5.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return q5.vec3.transformQuat(this,this,Z),this}zero(){return q5.vec3.zero(this),this}}var J15=e(eJ5(),1);var Z15=0.099856;class wz extends f${faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=Z15;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:Z15,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,$=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let Y=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*Y*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let Y={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-$.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-$.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-$.z},Q=Y.x*Y.x+Y.y*Y.y+Y.z*Y.z,W=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let K=$.x-this._moveStuckLastPosition.x,G=$.y-this._moveStuckLastPosition.y,V=$.z-this._moveStuckLastPosition.z;W=Math.sqrt(K*K+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=$,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!W){let K=Math.sqrt(Q),G=this.moveSpeed*X,H=Math.min(K,G)/K,q={x:$.x+Y.x*H,y:$.y+Y.y*H,z:$.z+Y.z*H};if(Z.setPosition(q),this._onMove)this._onMove(q,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let K=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,K($)}}}if(this._faceTarget){let Y={x:this._faceTarget.x-$.x,z:this._faceTarget.z-$.z},Q=Math.atan2(-Y.x,-Y.z),W=Z.rotation,K=Math.atan2(2*(W.w*W.y),1-2*(W.y*W.y)),G=Q-K;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let V=this.faceSpeed*X,H=Math.abs(G)<V?G:Math.sign(G)*V,z=(K+H)/2,F={x:0,y:Math.fround(Math.sin(z)),z:0,w:Math.fround(Math.cos(z))};if(Z.setRotation(F),this._onFace)this._onFace(W,F)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class Sf extends wz{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(Z={}){super(Z)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return u.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)u.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},$=Math.abs(X.x-J.x),Y=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if($<=2&&Y<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let K=this._coordinateToKey(J),G=new Map,V=new Map([[K,0]]),H=new Map([[K,this._pathfindingHeuristic(J,X)]]),q=new Set,z=new J15.Heap((M,N)=>{let P=H.get(M[0])??1/0,D=H.get(N[0])??1/0;return P-D});z.push([K,J]);let F=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],U=[];for(let M=this._maxJump;M>=this._maxFall;M--){if(M===0)continue;let N=Math.abs(J.y+M-X.y);U.push({y:M,distanceToTargetY:N})}U.sort((M,N)=>M.distanceToTargetY-N.distanceToTargetY);let L=[...F,...U.flatMap(({y:M})=>F.map((N)=>({...N,y:M})))],B=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),O=Math.min(this._maxOpenSetIterations,w*20);while(!z.isEmpty()&&B<O){B++;let[M,N]=z.pop();if(N.x===X.x&&N.y===X.y&&N.z===X.z){let C=this._reconstructPath(G,N);if(this._waypoints=C.map((T)=>({x:T.x+0.5,y:T.y+Z/2,z:T.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${B} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}q.add(M);let P=V.get(M),D=new Map;for(let C of L){let T=`${C.x},${C.z}`,k=C.y<0;if(k&&D.has(T))continue;let A={x:N.x+C.x,y:N.y+C.y,z:N.z+C.z};if(Math.abs(X.x-A.x)+Math.abs(X.y-A.y)+Math.abs(X.z-A.z)>w*1.5)continue;let x=this._coordinateToKey(A);if(q.has(x))continue;let I=this._isNeighborCoordinateBlocked(N,A,this._entity.height);if(k&&I){D.set(T,!0);continue}if(I)continue;let S=Math.abs(C.x),g=Math.abs(C.y),m=Math.abs(C.z),i=g===0?0:this._verticalPenalty,r=(Math.max(S,g,m)===1&&S+g+m>1?1.4:1)+i,Q0=P+r,F0=V.get(x)??1/0;if(Q0>=F0)continue;G.set(x,N),V.set(x,Q0);let _0=Q0+this._pathfindingHeuristic(A,X);H.set(x,_0),z.push([x,A])}}if(B>=O){if(this._onPathfindAbort?.(),this._debug)u.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${O}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)u.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],$=J;while(Z.has(this._coordinateToKey($)))$=Z.get(this._coordinateToKey($)),X.unshift($);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let $=J.y-Z.y,Y=Math.min($,this._maxJump)+0.75;this.jump(Y);let Q=Math.abs(this._entity.world.simulation.gravity.y),W=Math.sqrt(2*Q*Y),K=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,H=J.z+0.5,q=V-K,z=H-G,F=Math.sqrt(q*q+z*z),U=W/Q,L=F/this._speed;X=Math.min(U*0.8,L)*1000}setTimeout(()=>{if(!this._entity)return;let $=Date.now();this.face(J,this._speed),this.move(J,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-$>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let $=this._entity.world,Y=Math.floor(J.x),Q=Math.floor(J.y),W=Math.floor(J.z),K=Math.floor(Z.x),G=Math.floor(Z.z);if(!$.chunkLattice.hasBlock({x:Y,y:Q-1,z:W}))return!0;for(let V=0;V<X;V++)if($.chunkLattice.hasBlock({x:Y,y:Q+V,z:W}))return!0;if(Y!==K&&W!==G)for(let V=0;V<X;V++){let H=$.chunkLattice.hasBlock({x:Y,y:Q+V,z:G}),q=$.chunkLattice.hasBlock({x:K,y:Q+V,z:W});if(H||q)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,$={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let Y=0;Y<=Math.abs(this._maxFall);Y++)if(this._entity.world.chunkLattice.hasBlock({...$,y:$.y-Y-1}))return{...$,y:$.y-Y};return}}export{kp8 as startServer,qZ5 as WorldManagerEvent,_$ as WorldManager,HZ5 as WorldLoopEvent,Uz as WorldLoop,Rf as WorldEvent,Bz as World,KZ5 as WebServerEvent,P4 as WebServer,T4 as Vector3,Lz as Vector2,Fz as Ticker,pQ as TelemetrySpanOperation,q8 as Telemetry,Mf as SimulationEvent,Hz as Simulation,wz as SimpleEntityController,zz as SceneUIManager,_T as SceneUIEvent,mV as SceneUI,et as SUPPORTED_INPUT_KEYS,YV as RigidBodyType,MY as RigidBody,C4 as Quaternion,_B as PlayerUIEvent,xV as PlayerUI,zZ5 as PlayerManagerEvent,d7 as PlayerManager,fV as PlayerEvent,WJ as PlayerEntity,tt as PlayerCameraMode,ET as PlayerCameraEvent,AV as PlayerCamera,YK as Player,IY as PersistenceManager,Sf as PathfindingEntityController,qz as ParticleEmitterManager,Of as ParticleEmitterEvent,Nf as ParticleEmitter,Uf as PORT,Ye as PLAYER_ROTATION_UPDATE_THRESHOLD,$e as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,V7 as ModelRegistry,X7 as Matrix4,SJ as Matrix3,rQ as Matrix2,VZ5 as LightType,Vz as LightManager,Lf as LightEvent,wf as Light,r8 as IterationMap,FZ5 as GameServerEvent,iQ as GameServer,D0 as EventRouter,u as ErrorHandler,dV as EntityManager,gV as EntityEvent,h8 as Entity,Xe as ENTITY_ROTATION_UPDATE_THRESHOLD,Je as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,A5 as DefaultPlayerEntityController,AT as DefaultPlayerEntity,Ze as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,e9 as CollisionGroupsBuilder,g$ as CollisionGroup,QV as ColliderShape,yV as ColliderMap,f7 as Collider,nP as CoefficientCombineRule,ST as ChunkLatticeEvent,bV as ChunkLattice,y7 as Chunk,hV as ChatManager,IT as ChatEvent,aP as BlockTypeRegistryEvent,WV as BlockTypeRegistry,sP as BlockTypeEvent,h7 as BlockType,eQ as Block,yf as BaseEntityControllerEvent,f$ as BaseEntityController,v4 as AudioManager,IN as AudioEvent,I4 as Audio};