hytopia 0.8.6-dev1 → 0.8.6-dev3

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/node-server.mjs CHANGED
@@ -409,7 +409,7 @@ For example, you can use the \`pathToFileURL()\` method of the \`url\` core modu
409
409
  Instead, \`yield\` should either be called with a value, or not be called at all. For example:
410
410
  if (condition) { yield value; }`)};import{Buffer as Jw1}from"node:buffer";import{StringDecoder as Xw1}from"node:string_decoder";var eB=(Z,J,X)=>{if(X)return;if(Z)return{transform:Yw1.bind(void 0,new TextEncoder)};let Y=new Xw1(J);return{transform:$w1.bind(void 0,Y),final:Qw1.bind(void 0,Y)}},Yw1=function*(Z,J){if(Jw1.isBuffer(J))yield xZ(J);else if(typeof J==="string")yield Z.encode(J);else yield J},$w1=function*(Z,J){yield l8(J)?Z.write(J):J},Qw1=function*(Z){let J=Z.end();if(J!=="")yield J};import{callbackify as Ji}from"node:util";var fC=Ji(async(Z,J,X,Y)=>{J.currentIterable=Z(...X);try{for await(let $ of J.currentIterable)Y.push($)}finally{delete J.currentIterable}}),ZL=async function*(Z,J,X){if(X===J.length){yield Z;return}let{transform:Y=Ww1}=J[X];for await(let $ of Y(Z))yield*ZL($,J,X+1)},Xi=async function*(Z){for(let[J,{final:X}]of Object.entries(Z))yield*Kw1(X,Number(J),Z)},Kw1=async function*(Z,J,X){if(Z===void 0)return;for await(let Y of Z())yield*ZL(Y,X,J+1)},Yi=Ji(async({currentIterable:Z},J)=>{if(Z!==void 0){await(J?Z.throw(J):Z.return());return}if(J)throw J}),Ww1=function*(Z){yield Z};var yC=(Z,J,X,Y)=>{try{for(let $ of Z(...J))X.push($);Y()}catch($){Y($)}},$i=(Z,J)=>[...J.flatMap((X)=>[...N$(X,Z,0)]),...gV(Z)],N$=function*(Z,J,X){if(X===J.length){yield Z;return}let{transform:Y=Vw1}=J[X];for(let $ of Y(Z))yield*N$($,J,X+1)},gV=function*(Z){for(let[J,{final:X}]of Object.entries(Z))yield*Gw1(X,Number(J),Z)},Gw1=function*(Z,J,X){if(Z===void 0)return;for(let Y of Z())yield*N$(Y,X,J+1)},Vw1=function*(Z){yield Z};var bC=({value:Z,value:{transform:J,final:X,writableObjectMode:Y,readableObjectMode:$},optionName:Q},{encoding:K})=>{let W={},G=Ki(Z,K,Q),V=M$(J),z=M$(X),F=V?fC.bind(void 0,ZL,W):yC.bind(void 0,N$),H=V||z?fC.bind(void 0,Xi,W):yC.bind(void 0,gV),q=V||z?Yi.bind(void 0,W):void 0;return{stream:new zw1({writableObjectMode:Y,writableHighWaterMark:Qi(Y),readableObjectMode:$,readableHighWaterMark:Qi($),transform(B,L,w){F([B,G,0],this,w)},flush(B){H([G],this,B)},destroy:q})}},JL=(Z,J,X,Y)=>{let $=J.filter(({type:K})=>K==="generator"),Q=Y?$.reverse():$;for(let{value:K,optionName:W}of Q){let G=Ki(K,X,W);Z=$i(G,Z)}return Z},Ki=({transform:Z,final:J,binary:X,writableObjectMode:Y,readableObjectMode:$,preserveNewlines:Q},K,W)=>{let G={};return[{transform:tp(Y,W)},eB(X,K,Y),tB(X,Q,Y,G),{transform:Z,final:J},{transform:ep($,W)},rp({binary:X,preserveNewlines:Q,readableObjectMode:$,state:G})].filter(Boolean)};var Wi=(Z,J)=>{for(let X of Hw1(Z))Fw1(Z,X,J)},Hw1=(Z)=>new Set(Object.entries(Z).filter(([,{direction:J}])=>J==="input").map(([J])=>Number(J))),Fw1=(Z,J,X)=>{let{stdioItems:Y}=Z[J],$=Y.filter(({contents:W})=>W!==void 0);if($.length===0)return;if(J!==0){let[{type:W,optionName:G}]=$;throw new TypeError(`Only the \`stdin\` option, not \`${G}\`, can be ${LX[W]} with synchronous methods.`)}let K=$.map(({contents:W})=>W).map((W)=>qw1(W,Y));X.input=vV(K)},qw1=(Z,J)=>{let X=JL(Z,J,"utf8",!0);return Uw1(X),vV(X)},Uw1=(Z)=>{let J=Z.find((X)=>typeof X!=="string"&&!l8(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 Ow1,appendFileSync as Mw1}from"node:fs";var XL=({stdioItems:Z,encoding:J,verboseInfo:X,fdNumber:Y})=>Y!=="all"&&cK(X,Y)&&!$9.has(J)&&Bw1(Y)&&(Z.some(({type:$,value:Q})=>$==="native"&&Lw1.has(Q))||Z.every(({type:$})=>m9.has($))),Bw1=(Z)=>Z===1||Z===2,Lw1=new Set(["pipe","overlapped"]),Gi=async(Z,J,X,Y)=>{for await(let $ of Z)if(!ww1(J))zi($,X,Y)},Vi=(Z,J,X)=>{for(let Y of Z)zi(Y,J,X)},ww1=(Z)=>Z._readableState.pipes.length>0,zi=(Z,J,X)=>{let Y=FB(Z);k7({type:"output",verboseMessage:Y,fdNumber:J,verboseInfo:X})};var Hi=({fileDescriptors:Z,syncResult:{output:J},options:X,isMaxBuffer:Y,verboseInfo:$})=>{if(J===null)return{output:Array.from({length:3})};let Q={},K=new Set([]);return{output:J.map((G,V)=>Nw1({result:G,fileDescriptors:Z,fdNumber:V,state:Q,outputFiles:K,isMaxBuffer:Y,verboseInfo:$},X)),...Q}},Nw1=({result:Z,fileDescriptors:J,fdNumber:X,state:Y,outputFiles:$,isMaxBuffer:Q,verboseInfo:K},{buffer:W,encoding:G,lines:V,stripFinalNewline:z,maxBuffer:F})=>{if(Z===null)return;let H=Fp(Z,Q,F),q=xZ(H),{stdioItems:U,objectMode:B}=J[X],L=Rw1([q],U,G,Y),{serializedResult:w,finalResult:M=w}=jw1({chunks:L,objectMode:B,encoding:G,lines:V,stripFinalNewline:z,fdNumber:X});Dw1({serializedResult:w,fdNumber:X,state:Y,verboseInfo:K,encoding:G,stdioItems:U,objectMode:B});let N=W[X]?M:void 0;try{if(Y.error===void 0)Pw1(w,U,$);return N}catch(R){return Y.error=R,N}},Rw1=(Z,J,X,Y)=>{try{return JL(Z,J,X,!1)}catch($){return Y.error=$,Z}},jw1=({chunks:Z,objectMode:J,encoding:X,lines:Y,stripFinalNewline:$,fdNumber:Q})=>{if(J)return{serializedResult:Z};if(X==="buffer")return{serializedResult:vV(Z)};let K=Td(Z,X);if(Y[Q])return{serializedResult:K,finalResult:hC(K,!$[Q],J)};return{serializedResult:K}},Dw1=({serializedResult:Z,fdNumber:J,state:X,verboseInfo:Y,encoding:$,stdioItems:Q,objectMode:K})=>{if(!XL({stdioItems:Q,encoding:$,verboseInfo:Y,fdNumber:J}))return;let W=hC(Z,!1,K);try{Vi(W,J,Y)}catch(G){X.error??=G}},Pw1=(Z,J,X)=>{for(let{path:Y,append:$}of J.filter(({type:Q})=>oB.has(Q))){let Q=typeof Y==="string"?Y:Y.toString();if($||X.has(Q))Mw1(Y,Z);else X.add(Q),Ow1(Y,Z)}};var Fi=([,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,bZ(J,X,"all")];if(Array.isArray(J))return[bZ(Z,X,"all"),...J];if(l8(Z)&&l8(J))return lP([Z,J]);return`${Z}${J}`};import{once as gC}from"node:events";var qi=async(Z,J)=>{let[X,Y]=await Cw1(Z);return J.isForcefullyTerminated??=!1,[X,Y]},Cw1=async(Z)=>{let[J,X]=await Promise.allSettled([gC(Z,"spawn"),gC(Z,"exit")]);if(J.status==="rejected")return[];return X.status==="rejected"?Ui(Z):X.value},Ui=async(Z)=>{try{return await gC(Z,"exit")}catch{return Ui(Z)}},Bi=async(Z)=>{let[J,X]=await Z;if(!Tw1(J,X)&&mC(J,X))throw new E7;return[J,X]},Tw1=(Z,J)=>Z===void 0&&J===void 0,mC=(Z,J)=>Z!==0||J!==null;var Li=({error:Z,status:J,signal:X,output:Y},{maxBuffer:$})=>{let Q=kw1(Z,J,X),K=Q?.code==="ETIMEDOUT",W=Hp(Q,Y,$);return{resultError:Q,exitCode:J,signal:X,timedOut:K,isMaxBuffer:W}},kw1=(Z,J,X)=>{if(Z!==void 0)return Z;return mC(J,X)?new E7:void 0};var wi=(Z,J,X)=>{let{file:Y,commandArguments:$,command:Q,escapedCommand:K,startTime:W,verboseInfo:G,options:V,fileDescriptors:z}=Iw1(Z,J,X),F=Sw1({file:Y,commandArguments:$,options:V,command:Q,escapedCommand:K,verboseInfo:G,fileDescriptors:z,startTime:W});return tK(F,G,V)},Iw1=(Z,J,X)=>{let{command:Y,escapedCommand:$,startTime:Q,verboseInfo:K}=UB(Z,J,X),W=_w1(X),{file:G,commandArguments:V,options:z}=yB(Z,J,W);vw1(z);let F=np(z,K);return{file:G,commandArguments:V,command:Y,escapedCommand:$,startTime:Q,verboseInfo:K,options:z,fileDescriptors:F}},_w1=(Z)=>Z.node&&!Z.ipc?{...Z,ipc:!1}:Z,vw1=({ipc:Z,ipcInput:J,detached:X,cancelSignal:Y})=>{if(J)YL("ipcInput");if(Z)YL("ipc: true");if(X)YL("detached: true");if(Y)YL("cancelSignal")},YL=(Z)=>{throw new TypeError(`The "${Z}" option cannot be used with synchronous methods.`)},Sw1=({file:Z,commandArguments:J,options:X,command:Y,escapedCommand:$,verboseInfo:Q,fileDescriptors:K,startTime:W})=>{let G=Aw1({file:Z,commandArguments:J,options:X,command:Y,escapedCommand:$,fileDescriptors:K,startTime:W});if(G.failed)return G;let{resultError:V,exitCode:z,signal:F,timedOut:H,isMaxBuffer:q}=Li(G,X),{output:U,error:B=V}=Hi({fileDescriptors:K,syncResult:G,options:X,isMaxBuffer:q,verboseInfo:Q}),L=U.map((M,N)=>bZ(M,X,N)),w=bZ(Fi(U,X),X,"all");return hw1({error:B,exitCode:z,signal:F,timedOut:H,isMaxBuffer:q,stdio:L,all:w,options:X,command:Y,escapedCommand:$,startTime:W})},Aw1=({file:Z,commandArguments:J,options:X,command:Y,escapedCommand:$,fileDescriptors:Q,startTime:K})=>{try{Wi(Q,X);let W=xw1(X);return Ew1(...bB(Z,J,W))}catch(W){return rK({error:W,command:Y,escapedCommand:$,fileDescriptors:Q,options:X,startTime:K,isSync:!0})}},xw1=({encoding:Z,maxBuffer:J,...X})=>({...X,encoding:"buffer",maxBuffer:iB(J)}),hw1=({error:Z,exitCode:J,signal:X,timedOut:Y,isMaxBuffer:$,stdio:Q,all:K,options:W,command:G,escapedCommand:V,startTime:z})=>Z===void 0?nB({command:G,escapedCommand:V,stdio:Q,all:K,ipcOutput:[],options:W,startTime:z}):bV({error:Z,command:G,escapedCommand:V,timedOut:Y,isCanceled:!1,isGracefullyCanceled:!1,isMaxBuffer:$,isForcefullyTerminated:!1,exitCode:J,signal:X,stdio:Q,all:K,ipcOutput:[],options:W,startTime:z,isSync:!0});import{setMaxListeners as jM1}from"node:events";import{spawn as DM1}from"node:child_process";import ji from"node:process";import{once as uC,on as fw1}from"node:events";var Oi=({anyProcess:Z,channel:J,isSubprocess:X,ipc:Y},{reference:$=!0,filter:Q}={})=>{return iK({methodName:"getOneMessage",isSubprocess:X,ipc:Y,isConnected:vB(Z)}),yw1({anyProcess:Z,channel:J,isSubprocess:X,filter:Q,reference:$})},yw1=async({anyProcess:Z,channel:J,isSubprocess:X,filter:Y,reference:$})=>{kB(J,$);let Q=BX(Z,J,X),K=new AbortController;try{return await Promise.race([bw1(Q,Y,K),gw1(Q,X,K),mw1(Q,X,K)])}catch(W){throw nK(Z),W}finally{K.abort(),EB(J,$)}},bw1=async(Z,J,{signal:X})=>{if(J===void 0){let[Y]=await uC(Z,"message",{signal:X});return Y}for await(let[Y]of fw1(Z,"message",{signal:X}))if(J(Y))return Y},gw1=async(Z,J,{signal:X})=>{await uC(Z,"disconnect",{signal:X}),Yl(J)},mw1=async(Z,J,{signal:X})=>{let[Y]=await uC(Z,"strict:error",{signal:X});throw PB(Y,J)};import{once as Ni,on as uw1}from"node:events";var Ri=({anyProcess:Z,channel:J,isSubprocess:X,ipc:Y},{reference:$=!0}={})=>dC({anyProcess:Z,channel:J,isSubprocess:X,ipc:Y,shouldAwait:!X,reference:$}),dC=({anyProcess:Z,channel:J,isSubprocess:X,ipc:Y,shouldAwait:$,reference:Q})=>{iK({methodName:"getEachMessage",isSubprocess:X,ipc:Y,isConnected:vB(Z)}),kB(J,Q);let K=BX(Z,J,X),W=new AbortController,G={};return dw1(Z,K,W),cw1({ipcEmitter:K,isSubprocess:X,controller:W,state:G}),lw1({anyProcess:Z,channel:J,ipcEmitter:K,isSubprocess:X,shouldAwait:$,controller:W,state:G,reference:Q})},dw1=async(Z,J,X)=>{try{await Ni(J,"disconnect",{signal:X.signal}),X.abort()}catch{}},cw1=async({ipcEmitter:Z,isSubprocess:J,controller:X,state:Y})=>{try{let[$]=await Ni(Z,"strict:error",{signal:X.signal});Y.error=PB($,J),X.abort()}catch{}},lw1=async function*({anyProcess:Z,channel:J,ipcEmitter:X,isSubprocess:Y,shouldAwait:$,controller:Q,state:K,reference:W}){try{for await(let[G]of uw1(X,"message",{signal:Q.signal}))Mi(K),yield G}catch{Mi(K)}finally{if(Q.abort(),EB(J,W),!Y)nK(Z);if($)await Z}},Mi=({error:Z})=>{if(Z)throw Z};var Di=(Z,{ipc:J})=>{Object.assign(Z,Ci(Z,!1,J))},Pi=()=>{let Z=ji,J=!0,X=ji.channel!==void 0;return{...Ci(Z,!0,X),getCancelSignal:_l.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:!0,ipc:X})}},Ci=(Z,J,X)=>({sendMessage:hB.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X}),getOneMessage:Oi.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X}),getEachMessage:Ri.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X})});import{ChildProcess as pw1}from"node:child_process";import{PassThrough as iw1,Readable as nw1,Writable as aw1,Duplex as sw1}from"node:stream";var Ti=({error:Z,command:J,escapedCommand:X,fileDescriptors:Y,options:$,startTime:Q,verboseInfo:K})=>{SC(Y);let W=new pw1;ow1(W,Y),Object.assign(W,{readable:rw1,writable:tw1,duplex:ew1});let G=rK({error:Z,command:J,escapedCommand:X,fileDescriptors:Y,options:$,startTime:Q,isSync:!1}),V=ZO1(G,K,$);return{subprocess:W,promise:V}},ow1=(Z,J)=>{let X=mV(),Y=mV(),$=mV(),Q=Array.from({length:J.length-3},mV),K=mV(),W=[X,Y,$,...Q];Object.assign(Z,{stdin:X,stdout:Y,stderr:$,all:K,stdio:W})},mV=()=>{let Z=new iw1;return Z.end(),Z},rw1=()=>new nw1({read(){}}),tw1=()=>new aw1({write(){}}),ew1=()=>new sw1({read(){},write(){}}),ZO1=async(Z,J,X)=>tK(Z,J,X);import{createReadStream as ki,createWriteStream as Ei}from"node:fs";import{Buffer as JO1}from"node:buffer";import{Readable as uV,Writable as XO1,Duplex as YO1}from"node:stream";var _i=(Z,J)=>rB($O1,Z,J,!1),dV=({type:Z,optionName:J})=>{throw new TypeError(`The \`${J}\` option cannot be ${LX[Z]}.`)},Ii={fileNumber:dV,generator:bC,asyncGenerator:bC,nodeStream:({value:Z})=>({stream:Z}),webTransform({value:{transform:Z,writableObjectMode:J,readableObjectMode:X}}){let Y=J||X;return{stream:YO1.fromWeb(Z,{objectMode:Y})}},duplex:({value:{transform:Z}})=>({stream:Z}),native(){}},$O1={input:{...Ii,fileUrl:({value:Z})=>({stream:ki(Z)}),filePath:({value:{file:Z}})=>({stream:ki(Z)}),webStream:({value:Z})=>({stream:uV.fromWeb(Z)}),iterable:({value:Z})=>({stream:uV.from(Z)}),asyncIterable:({value:Z})=>({stream:uV.from(Z)}),string:({value:Z})=>({stream:uV.from(Z)}),uint8Array:({value:Z})=>({stream:uV.from(JO1.from(Z))})},output:{...Ii,fileUrl:({value:Z})=>({stream:Ei(Z)}),filePath:({value:{file:Z,append:J}})=>({stream:Ei(Z,J?{flags:"a"}:{})}),webStream:({value:Z})=>({stream:XO1.fromWeb(Z)}),iterable:dV,asyncIterable:dV,string:dV,uint8Array:dV}};import{on as QO1,once as vi}from"node:events";import{PassThrough as KO1,getDefaultHighWaterMark as WO1}from"node:stream";import{finished as xi}from"node:stream/promises";function R$(Z){if(!Array.isArray(Z))throw new TypeError(`Expected an array, got \`${typeof Z}\`.`);for(let $ of Z)cC($);let J=Z.some(({readableObjectMode:$})=>$),X=GO1(Z,J),Y=new hi({objectMode:J,writableHighWaterMark:X,readableHighWaterMark:X});for(let $ of Z)Y.add($);return Y}var GO1=(Z,J)=>{if(Z.length===0)return WO1(J);let X=Z.filter(({readableObjectMode:Y})=>Y===J).map(({readableHighWaterMark:Y})=>Y);return Math.max(...X)};class hi extends KO1{#Z=new Set([]);#J=new Set([]);#Y=new Set([]);#X;#$=Symbol("unpipe");#z=new WeakMap;add(Z){if(cC(Z),this.#Z.has(Z))return;this.#Z.add(Z),this.#X??=VO1(this,this.#Z,this.#$);let J=FO1({passThroughStream:this,stream:Z,streams:this.#Z,ended:this.#J,aborted:this.#Y,onFinished:this.#X,unpipeEvent:this.#$});this.#z.set(Z,J),Z.pipe(this,{end:!1})}async remove(Z){if(cC(Z),!this.#Z.has(Z))return!1;let J=this.#z.get(Z);if(J===void 0)return!1;return this.#z.delete(Z),Z.unpipe(this),await J,!0}}var VO1=async(Z,J,X)=>{$L(Z,Si);let Y=new AbortController;try{await Promise.race([zO1(Z,Y),HO1(Z,J,X,Y)])}finally{Y.abort(),$L(Z,-Si)}},zO1=async(Z,{signal:J})=>{try{await xi(Z,{signal:J,cleanup:!0})}catch(X){throw fi(Z,X),X}},HO1=async(Z,J,X,{signal:Y})=>{for await(let[$]of QO1(Z,"unpipe",{signal:Y}))if(J.has($))$.emit(X)},cC=(Z)=>{if(typeof Z?.pipe!=="function")throw new TypeError(`Expected a readable stream, got: \`${typeof Z}\`.`)},FO1=async({passThroughStream:Z,stream:J,streams:X,ended:Y,aborted:$,onFinished:Q,unpipeEvent:K})=>{$L(Z,Ai);let W=new AbortController;try{await Promise.race([qO1(Q,J,W),UO1({passThroughStream:Z,stream:J,streams:X,ended:Y,aborted:$,controller:W}),BO1({stream:J,streams:X,ended:Y,aborted:$,unpipeEvent:K,controller:W})])}finally{W.abort(),$L(Z,-Ai)}if(X.size>0&&X.size===Y.size+$.size)if(Y.size===0&&$.size>0)lC(Z);else LO1(Z)},qO1=async(Z,J,{signal:X})=>{try{if(await Z,!X.aborted)lC(J)}catch(Y){if(!X.aborted)fi(J,Y)}},UO1=async({passThroughStream:Z,stream:J,streams:X,ended:Y,aborted:$,controller:{signal:Q}})=>{try{if(await xi(J,{signal:Q,cleanup:!0,readable:!0,writable:!1}),X.has(J))Y.add(J)}catch(K){if(Q.aborted||!X.has(J))return;if(yi(K))$.add(J);else bi(Z,K)}},BO1=async({stream:Z,streams:J,ended:X,aborted:Y,unpipeEvent:$,controller:{signal:Q}})=>{if(await vi(Z,$,{signal:Q}),!Z.readable)return vi(Q,"abort",{signal:Q});J.delete(Z),X.delete(Z),Y.delete(Z)},LO1=(Z)=>{if(Z.writable)Z.end()},fi=(Z,J)=>{if(yi(J))lC(Z);else bi(Z,J)},yi=(Z)=>Z?.code==="ERR_STREAM_PREMATURE_CLOSE",lC=(Z)=>{if(Z.readable||Z.writable)Z.destroy()},bi=(Z,J)=>{if(!Z.destroyed)Z.once("error",wO1),Z.destroy(J)},wO1=()=>{},$L=(Z,J)=>{let X=Z.getMaxListeners();if(X!==0&&X!==Number.POSITIVE_INFINITY)Z.setMaxListeners(X+J)},Si=2,Ai=1;import{finished as gi}from"node:stream/promises";var ZW=(Z,J)=>{Z.pipe(J),OO1(Z,J),MO1(Z,J)},OO1=async(Z,J)=>{if(m4(Z)||m4(J))return;try{await gi(Z,{cleanup:!0,readable:!0,writable:!1})}catch{}pC(J)},pC=(Z)=>{if(Z.writable)Z.end()},MO1=async(Z,J)=>{if(m4(Z)||m4(J))return;try{await gi(J,{cleanup:!0,readable:!1,writable:!0})}catch{}iC(Z)},iC=(Z)=>{if(Z.readable)Z.destroy()};var mi=(Z,J,X)=>{let Y=new Map;for(let[$,{stdioItems:Q,direction:K}]of Object.entries(J)){for(let{stream:W}of Q.filter(({type:G})=>m9.has(G)))NO1(Z,W,K,$);for(let{stream:W}of Q.filter(({type:G})=>!m9.has(G)))jO1({subprocess:Z,stream:W,direction:K,fdNumber:$,pipeGroups:Y,controller:X})}for(let[$,Q]of Y.entries()){let K=Q.length===1?Q[0]:R$(Q);ZW(K,$)}},NO1=(Z,J,X,Y)=>{if(X==="output")ZW(Z.stdio[Y],J);else ZW(J,Z.stdio[Y]);let $=RO1[Y];if($!==void 0)Z[$]=J;Z.stdio[Y]=J},RO1=["stdin","stdout","stderr"],jO1=({subprocess:Z,stream:J,direction:X,fdNumber:Y,pipeGroups:$,controller:Q})=>{if(J===void 0)return;DO1(J,Q);let[K,W]=X==="output"?[J,Z.stdio[Y]]:[Z.stdio[Y],J],G=$.get(K)??[];$.set(K,[...G,W])},DO1=(Z,{signal:J})=>{if(m4(Z))w$(Z,PO1,J)},PO1=2;import{addAbortListener as kO1}from"node:events";var j$=[];j$.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")j$.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")j$.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var QL=(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",nC=Symbol.for("signal-exit emitter"),aC=globalThis,CO1=Object.defineProperty.bind(Object);class ui{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(aC[nC])return aC[nC];CO1(aC,nC,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(Z,J){this.listeners[Z].push(J)}removeListener(Z,J){let X=this.listeners[Z],Y=X.indexOf(J);if(Y===-1)return;if(Y===0&&X.length===1)X.length=0;else X.splice(Y,1)}emit(Z,J,X){if(this.emitted[Z])return!1;this.emitted[Z]=!0;let Y=!1;for(let $ of this.listeners[Z])Y=$(J,X)===!0||Y;if(Z==="exit")Y=this.emit("afterExit",J,X)||Y;return Y}}class oC{}var TO1=(Z)=>{return{onExit(J,X){return Z.onExit(J,X)},load(){return Z.load()},unload(){return Z.unload()}}};class di extends oC{onExit(){return()=>{}}load(){}unload(){}}class ci extends oC{#Z=sC.platform==="win32"?"SIGINT":"SIGHUP";#J=new ui;#Y;#X;#$;#z={};#F=!1;constructor(Z){super();this.#Y=Z,this.#z={};for(let J of j$)this.#z[J]=()=>{let X=this.#Y.listeners(J),{count:Y}=this.#J,$=Z;if(typeof $.__signal_exit_emitter__==="object"&&typeof $.__signal_exit_emitter__.count==="number")Y+=$.__signal_exit_emitter__.count;if(X.length===Y){this.unload();let Q=this.#J.emit("exit",null,J),K=J==="SIGHUP"?this.#Z:J;if(!Q)Z.kill(Z.pid,K)}};this.#$=Z.reallyExit,this.#X=Z.emit}onExit(Z,J){if(!QL(this.#Y))return()=>{};if(this.#F===!1)this.load();let X=J?.alwaysLast?"afterExit":"exit";return this.#J.on(X,Z),()=>{if(this.#J.removeListener(X,Z),this.#J.listeners.exit.length===0&&this.#J.listeners.afterExit.length===0)this.unload()}}load(){if(this.#F)return;this.#F=!0,this.#J.count+=1;for(let Z of j$)try{let J=this.#z[Z];if(J)this.#Y.on(Z,J)}catch(J){}this.#Y.emit=(Z,...J)=>{return this.#G(Z,...J)},this.#Y.reallyExit=(Z)=>{return this.#W(Z)}}unload(){if(!this.#F)return;this.#F=!1,j$.forEach((Z)=>{let J=this.#z[Z];if(!J)throw new Error("Listener not defined for signal: "+Z);try{this.#Y.removeListener(Z,J)}catch(X){}}),this.#Y.emit=this.#X,this.#Y.reallyExit=this.#$,this.#J.count-=1}#W(Z){if(!QL(this.#Y))return 0;return this.#Y.exitCode=Z||0,this.#J.emit("exit",this.#Y.exitCode,null),this.#$.call(this.#Y,this.#Y.exitCode)}#G(Z,...J){let X=this.#X;if(Z==="exit"&&QL(this.#Y)){if(typeof J[0]==="number")this.#Y.exitCode=J[0];let Y=X.call(this.#Y,Z,...J);return this.#J.emit("exit",this.#Y.exitCode,null),Y}else return X.call(this.#Y,Z,...J)}}var sC=globalThis.process,{onExit:li,load:CI6,unload:TI6}=TO1(QL(sC)?new ci(sC):new di);var pi=(Z,{cleanup:J,detached:X},{signal:Y})=>{if(!J||X)return;let $=li(()=>{Z.kill()});kO1(Y,()=>{$()})};var ni=({source:Z,sourcePromise:J,boundOptions:X,createNested:Y},...$)=>{let Q=qB(),{destination:K,destinationStream:W,destinationError:G,from:V,unpipeSignal:z}=EO1(X,Y,$),{sourceStream:F,sourceError:H}=_O1(Z,V),{options:q,fileDescriptors:U}=_7.get(Z);return{sourcePromise:J,sourceStream:F,sourceOptions:q,sourceError:H,destination:K,destinationStream:W,destinationError:G,unpipeSignal:z,fileDescriptors:U,startTime:Q}},EO1=(Z,J,X)=>{try{let{destination:Y,pipeOptions:{from:$,to:Q,unpipeSignal:K}={}}=IO1(Z,J,...X),W=TB(Y,Q);return{destination:Y,destinationStream:W,from:$,unpipeSignal:K}}catch(Y){return{destinationError:Y}}},IO1=(Z,J,X,...Y)=>{if(Array.isArray(X))return{destination:J(ii,Z)(X,...Y),pipeOptions:Z};if(typeof X==="string"||X instanceof URL||dP(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[$,Q,K]=YB(X,...Y);return{destination:J(ii)($,Q,K),pipeOptions:K}}if(_7.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:Y[0]}}throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${X}`)},ii=({options:Z})=>({options:{...Z,stdin:"pipe",piped:!0}}),_O1=(Z,J)=>{try{return{sourceStream:aK(Z,J)}}catch(X){return{sourceError:X}}};var si=({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:Y,fileDescriptors:$,sourceOptions:Q,startTime:K})=>{let W=vO1({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:Y});if(W!==void 0)throw rC({error:W,fileDescriptors:$,sourceOptions:Q,startTime:K})},vO1=({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:Y})=>{if(J!==void 0&&Y!==void 0)return Y;if(Y!==void 0)return iC(Z),Y;if(J!==void 0)return pC(X),J},rC=({error:Z,fileDescriptors:J,sourceOptions:X,startTime:Y})=>rK({error:Z,command:ai,escapedCommand:ai,fileDescriptors:J,options:X,startTime:Y,isSync:!1}),ai="source.pipe(destination)";var oi=async(Z)=>{let[{status:J,reason:X,value:Y=X},{status:$,reason:Q,value:K=Q}]=await Z;if(!K.pipedFrom.includes(Y))K.pipedFrom.push(Y);if($==="rejected")throw K;if(J==="rejected")throw Y;return K};import{finished as SO1}from"node:stream/promises";var ri=(Z,J,X)=>{let Y=KL.has(J)?xO1(Z,J):AO1(Z,J);return w$(Z,fO1,X.signal),w$(J,yO1,X.signal),hO1(J),Y},AO1=(Z,J)=>{let X=R$([Z]);return ZW(X,J),KL.set(J,X),X},xO1=(Z,J)=>{let X=KL.get(J);return X.add(Z),X},hO1=async(Z)=>{try{await SO1(Z,{cleanup:!0,readable:!1,writable:!0})}catch{}KL.delete(Z)},KL=new WeakMap,fO1=2,yO1=1;import{aborted as bO1}from"node:util";var ti=(Z,J)=>Z===void 0?[]:[gO1(Z,J)],gO1=async(Z,{sourceStream:J,mergedStream:X,fileDescriptors:Y,sourceOptions:$,startTime:Q})=>{await bO1(Z,J),await X.remove(J);let K=new Error("Pipe canceled by `unpipeSignal` option.");throw rC({error:K,fileDescriptors:Y,sourceOptions:$,startTime:Q})};var WL=(Z,...J)=>{if(P8(J[0]))return WL.bind(void 0,{...Z,boundOptions:{...Z.boundOptions,...J[0]}});let{destination:X,...Y}=ni(Z,...J),$=mO1({...Y,destination:X});return $.pipe=WL.bind(void 0,{...Z,source:X,sourcePromise:$,boundOptions:{}}),$},mO1=async({sourcePromise:Z,sourceStream:J,sourceOptions:X,sourceError:Y,destination:$,destinationStream:Q,destinationError:K,unpipeSignal:W,fileDescriptors:G,startTime:V})=>{let z=uO1(Z,$);si({sourceStream:J,sourceError:Y,destinationStream:Q,destinationError:K,fileDescriptors:G,sourceOptions:X,startTime:V});let F=new AbortController;try{let H=ri(J,Q,F);return await Promise.race([oi(z),...ti(W,{sourceStream:J,mergedStream:H,sourceOptions:X,fileDescriptors:G,startTime:V})])}finally{F.abort()}},uO1=(Z,J)=>Promise.allSettled([Z,J]);import{setImmediate as aO1}from"node:timers/promises";import{on as dO1}from"node:events";import{getDefaultHighWaterMark as cO1}from"node:stream";var GL=({subprocessStdout:Z,subprocess:J,binary:X,shouldEncode:Y,encoding:$,preserveNewlines:Q})=>{let K=new AbortController;return lO1(J,K),Zn({stream:Z,controller:K,binary:X,shouldEncode:!Z.readableObjectMode&&Y,encoding:$,shouldSplit:!Z.readableObjectMode,preserveNewlines:Q})},lO1=async(Z,J)=>{try{await Z}catch{}finally{J.abort()}},tC=({stream:Z,onStreamEnd:J,lines:X,encoding:Y,stripFinalNewline:$,allMixed:Q})=>{let K=new AbortController;pO1(J,K,Z);let W=Z.readableObjectMode&&!Q;return Zn({stream:Z,controller:K,binary:Y==="buffer",shouldEncode:!W,encoding:Y,shouldSplit:!W&&X,preserveNewlines:!$})},pO1=async(Z,J,X)=>{try{await Z}catch{X.destroy()}finally{J.abort()}},Zn=({stream:Z,controller:J,binary:X,shouldEncode:Y,encoding:$,shouldSplit:Q,preserveNewlines:K})=>{let W=dO1(Z,"data",{signal:J.signal,highWaterMark:ei,highWatermark:ei});return iO1({onStdoutChunk:W,controller:J,binary:X,shouldEncode:Y,encoding:$,shouldSplit:Q,preserveNewlines:K})},eC=cO1(!0),ei=eC,iO1=async function*({onStdoutChunk:Z,controller:J,binary:X,shouldEncode:Y,encoding:$,shouldSplit:Q,preserveNewlines:K}){let W=nO1({binary:X,shouldEncode:Y,encoding:$,shouldSplit:Q,preserveNewlines:K});try{for await(let[G]of Z)yield*N$(G,W,0)}catch(G){if(!J.signal.aborted)throw G}finally{yield*gV(W)}},nO1=({binary:Z,shouldEncode:J,encoding:X,shouldSplit:Y,preserveNewlines:$})=>[eB(Z,X,!J),tB(Z,$,!Y,{})].filter(Boolean);var Jn=async({stream:Z,onStreamEnd:J,fdNumber:X,encoding:Y,buffer:$,maxBuffer:Q,lines:K,allMixed:W,stripFinalNewline:G,verboseInfo:V,streamInfo:z})=>{let F=sO1({stream:Z,onStreamEnd:J,fdNumber:X,encoding:Y,allMixed:W,verboseInfo:V,streamInfo:z});if(!$){await Promise.all([oO1(Z),F]);return}let H=AC(G,X),q=tC({stream:Z,onStreamEnd:J,lines:K,encoding:Y,stripFinalNewline:H,allMixed:W}),[U]=await Promise.all([rO1({stream:Z,iterable:q,fdNumber:X,encoding:Y,maxBuffer:Q,lines:K}),F]);return U},sO1=async({stream:Z,onStreamEnd:J,fdNumber:X,encoding:Y,allMixed:$,verboseInfo:Q,streamInfo:{fileDescriptors:K}})=>{if(!XL({stdioItems:K[X]?.stdioItems,encoding:Y,verboseInfo:Q,fdNumber:X}))return;let W=tC({stream:Z,onStreamEnd:J,lines:!0,encoding:Y,stripFinalNewline:!0,allMixed:$});await Gi(W,Z,X,Q)},oO1=async(Z)=>{if(await aO1(),Z.readableFlowing===null)Z.resume()},rO1=async({stream:Z,stream:{readableObjectMode:J},iterable:X,fdNumber:Y,encoding:$,maxBuffer:Q,lines:K})=>{try{if(J||K)return await dB(X,{maxBuffer:Q});if($==="buffer")return new Uint8Array(await cB(X,{maxBuffer:Q}));return await pB(X,{maxBuffer:Q})}catch(W){return Xn(Gp({error:W,stream:Z,readableObjectMode:J,lines:K,encoding:$,fdNumber:Y}))}},ZT=async(Z)=>{try{return await Z}catch(J){return Xn(J)}},Xn=({bufferedData:Z})=>Pd(Z)?new Uint8Array(Z):Z;import{finished as tO1}from"node:stream/promises";var cV=async(Z,J,X,{isSameDirection:Y,stopOnExit:$=!1}={})=>{let Q=eO1(Z,X),K=new AbortController;try{await Promise.race([...$?[X.exitPromise]:[],tO1(Z,{cleanup:!0,signal:K.signal})])}catch(W){if(!Q.stdinCleanedUp)XM1(W,J,X,Y)}finally{K.abort()}},eO1=(Z,{originalStreams:[J],subprocess:X})=>{let Y={stdinCleanedUp:!1};if(Z===J)ZM1(Z,X,Y);return Y},ZM1=(Z,J,X)=>{let{_destroy:Y}=Z;Z._destroy=(...$)=>{JM1(J,X),Y.call(Z,...$)}},JM1=({exitCode:Z,signalCode:J},X)=>{if(Z!==null||J!==null)X.stdinCleanedUp=!0},XM1=(Z,J,X,Y)=>{if(!YM1(Z,J,X,Y))throw Z},YM1=(Z,J,X,Y=!0)=>{if(X.propagating)return Yn(Z)||VL(Z);return X.propagating=!0,JT(X,J)===Y?Yn(Z):VL(Z)},JT=({fileDescriptors:Z},J)=>J!=="all"&&Z[J].direction==="input",VL=(Z)=>Z?.code==="ERR_STREAM_PREMATURE_CLOSE",Yn=(Z)=>Z?.code==="EPIPE";var $n=({subprocess:Z,encoding:J,buffer:X,maxBuffer:Y,lines:$,stripFinalNewline:Q,verboseInfo:K,streamInfo:W})=>Z.stdio.map((G,V)=>XT({stream:G,fdNumber:V,encoding:J,buffer:X[V],maxBuffer:Y[V],lines:$[V],allMixed:!1,stripFinalNewline:Q,verboseInfo:K,streamInfo:W})),XT=async({stream:Z,fdNumber:J,encoding:X,buffer:Y,maxBuffer:$,lines:Q,allMixed:K,stripFinalNewline:W,verboseInfo:G,streamInfo:V})=>{if(!Z)return;let z=cV(Z,J,V);if(JT(V,J)){await z;return}let[F]=await Promise.all([Jn({stream:Z,onStreamEnd:z,fdNumber:J,encoding:X,buffer:Y,maxBuffer:$,lines:Q,allMixed:K,stripFinalNewline:W,verboseInfo:G,streamInfo:V}),z]);return F};var Qn=({stdout:Z,stderr:J},{all:X})=>X&&(Z||J)?R$([Z,J].filter(Boolean)):void 0,Kn=({subprocess:Z,encoding:J,buffer:X,maxBuffer:Y,lines:$,stripFinalNewline:Q,verboseInfo:K,streamInfo:W})=>XT({...$M1(Z,X),fdNumber:"all",encoding:J,maxBuffer:Y[1]+Y[2],lines:$[1]||$[2],allMixed:QM1(Z),stripFinalNewline:Q,verboseInfo:K,streamInfo:W}),$M1=({stdout:Z,stderr:J,all:X},[,Y,$])=>{let Q=Y||$;if(!Q)return{stream:X,buffer:Q};if(!Y)return{stream:J,buffer:Q};if(!$)return{stream:Z,buffer:Q};return{stream:X,buffer:Q}},QM1=({all:Z,stdout:J,stderr:X})=>Z&&J&&X&&J.readableObjectMode!==X.readableObjectMode;import{once as KM1}from"node:events";var Wn=(Z)=>cK(Z,"ipc"),Gn=(Z,J)=>{let X=FB(Z);k7({type:"ipc",verboseMessage:X,fdNumber:"ipc",verboseInfo:J})};var Vn=async({subprocess:Z,buffer:J,maxBuffer:X,ipc:Y,ipcOutput:$,verboseInfo:Q})=>{if(!Y)return $;let K=Wn(Q),W=hZ(J,"ipc"),G=hZ(X,"ipc");for await(let V of dC({anyProcess:Z,channel:Z.channel,isSubprocess:!1,ipc:Y,shouldAwait:!1,reference:!0})){if(W)Vp(Z,$,G),$.push(V);if(K)Gn(V,Q)}return $},zn=async(Z,J)=>{return await Promise.allSettled([Z]),J};var Hn=async({subprocess:Z,options:{encoding:J,buffer:X,maxBuffer:Y,lines:$,timeoutDuration:Q,cancelSignal:K,gracefulCancel:W,forceKillAfterDelay:G,stripFinalNewline:V,ipc:z,ipcInput:F},context:H,verboseInfo:q,fileDescriptors:U,originalStreams:B,onInternalError:L,controller:w})=>{let M=qi(Z,H),N={originalStreams:B,fileDescriptors:U,subprocess:Z,exitPromise:M,propagating:!1},R=$n({subprocess:Z,encoding:J,buffer:X,maxBuffer:Y,lines:$,stripFinalNewline:V,verboseInfo:q,streamInfo:N}),P=Kn({subprocess:Z,encoding:J,buffer:X,maxBuffer:Y,lines:$,stripFinalNewline:V,verboseInfo:q,streamInfo:N}),D=[],C=Vn({subprocess:Z,buffer:X,maxBuffer:Y,ipc:z,ipcOutput:D,verboseInfo:q}),T=WM1(B,Z,N),k=GM1(U,N);try{return await Promise.race([Promise.all([{},Bi(M),Promise.all(R),P,C,ml(Z,F),...T,...k]),L,VM1(Z,w),...hl(Z,Q,H,w),...Xl({subprocess:Z,cancelSignal:K,gracefulCancel:W,context:H,controller:w}),...Al({subprocess:Z,cancelSignal:K,gracefulCancel:W,forceKillAfterDelay:G,context:H,controller:w})])}catch(A){return H.terminationReason??="other",Promise.all([{error:A},M,Promise.all(R.map((v)=>ZT(v))),ZT(P),zn(C,D),Promise.allSettled(T),Promise.allSettled(k)])}},WM1=(Z,J,X)=>Z.map((Y,$)=>Y===J.stdio[$]?void 0:cV(Y,$,X)),GM1=(Z,J)=>Z.flatMap(({stdioItems:X},Y)=>X.filter(({value:$,stream:Q=$})=>d4(Q,{checkOpen:!1})&&!m4(Q)).map(({type:$,value:Q,stream:K=Q})=>cV(K,Y,J,{isSameDirection:m9.has($),stopOnExit:$==="native"}))),VM1=async(Z,{signal:J})=>{let[X]=await KM1(Z,"error",{signal:J});throw X};var Fn=()=>({readableDestroy:new WeakMap,writableFinal:new WeakMap,writableDestroy:new WeakMap}),lV=(Z,J,X)=>{let Y=Z[X];if(!Y.has(J))Y.set(J,[]);let $=Y.get(J),Q=I7();return $.push(Q),{resolve:Q.resolve.bind(Q),promises:$}},JW=async({resolve:Z,promises:J},X)=>{Z();let[Y]=await Promise.race([Promise.allSettled([!0,X]),Promise.all([!1,...J])]);return!Y};import{Readable as zM1}from"node:stream";import{callbackify as HM1}from"node:util";import{finished as qn}from"node:stream/promises";var YT=async(Z)=>{if(Z===void 0)return;try{await $T(Z)}catch{}},Un=async(Z)=>{if(Z===void 0)return;try{await QT(Z)}catch{}},$T=async(Z)=>{await qn(Z,{cleanup:!0,readable:!1,writable:!0})},QT=async(Z)=>{await qn(Z,{cleanup:!0,readable:!0,writable:!1})},zL=async(Z,J)=>{if(await Z,J)throw J},HL=(Z,J,X)=>{if(X&&!VL(X))Z.destroy(X);else if(J)Z.destroy()};var Bn=({subprocess:Z,concurrentStreams:J,encoding:X},{from:Y,binary:$=!0,preserveNewlines:Q=!0}={})=>{let K=$||$9.has(X),{subprocessStdout:W,waitReadableDestroy:G}=KT(Z,Y,J),{readableEncoding:V,readableObjectMode:z,readableHighWaterMark:F}=WT(W,K),{read:H,onStdoutDataDone:q}=GT({subprocessStdout:W,subprocess:Z,binary:K,encoding:X,preserveNewlines:Q}),U=new zM1({read:H,destroy:HM1(zT.bind(void 0,{subprocessStdout:W,subprocess:Z,waitReadableDestroy:G})),highWaterMark:F,objectMode:z,encoding:V});return VT({subprocessStdout:W,onStdoutDataDone:q,readable:U,subprocess:Z}),U},KT=(Z,J,X)=>{let Y=aK(Z,J),$=lV(X,Y,"readableDestroy");return{subprocessStdout:Y,waitReadableDestroy:$}},WT=({readableEncoding:Z,readableObjectMode:J,readableHighWaterMark:X},Y)=>Y?{readableEncoding:Z,readableObjectMode:J,readableHighWaterMark:X}:{readableEncoding:Z,readableObjectMode:!0,readableHighWaterMark:eC},GT=({subprocessStdout:Z,subprocess:J,binary:X,encoding:Y,preserveNewlines:$})=>{let Q=I7(),K=GL({subprocessStdout:Z,subprocess:J,binary:X,shouldEncode:!X,encoding:Y,preserveNewlines:$});return{read(){FM1(this,K,Q)},onStdoutDataDone:Q}},FM1=async(Z,J,X)=>{try{let{value:Y,done:$}=await J.next();if($)X.resolve();else Z.push(Y)}catch{}},VT=async({subprocessStdout:Z,onStdoutDataDone:J,readable:X,subprocess:Y,subprocessStdin:$})=>{try{if(await QT(Z),await Y,await YT($),await J,X.readable)X.push(null)}catch(Q){await YT($),Ln(X,Q)}},zT=async({subprocessStdout:Z,subprocess:J,waitReadableDestroy:X},Y)=>{if(await JW(X,J))Ln(Z,Y),await zL(J,Y)},Ln=(Z,J)=>{HL(Z,Z.readable,J)};import{Writable as qM1}from"node:stream";import{callbackify as wn}from"node:util";var On=({subprocess:Z,concurrentStreams:J},{to:X}={})=>{let{subprocessStdin:Y,waitWritableFinal:$,waitWritableDestroy:Q}=HT(Z,X,J),K=new qM1({...FT(Y,Z,$),destroy:wn(UT.bind(void 0,{subprocessStdin:Y,subprocess:Z,waitWritableFinal:$,waitWritableDestroy:Q})),highWaterMark:Y.writableHighWaterMark,objectMode:Y.writableObjectMode});return qT(Y,K),K},HT=(Z,J,X)=>{let Y=TB(Z,J),$=lV(X,Y,"writableFinal"),Q=lV(X,Y,"writableDestroy");return{subprocessStdin:Y,waitWritableFinal:$,waitWritableDestroy:Q}},FT=(Z,J,X)=>({write:UM1.bind(void 0,Z),final:wn(BM1.bind(void 0,Z,J,X))}),UM1=(Z,J,X,Y)=>{if(Z.write(J,X))Y();else Z.once("drain",Y)},BM1=async(Z,J,X)=>{if(await JW(X,J)){if(Z.writable)Z.end();await J}},qT=async(Z,J,X)=>{try{if(await $T(Z),J.writable)J.end()}catch(Y){await Un(X),Mn(J,Y)}},UT=async({subprocessStdin:Z,subprocess:J,waitWritableFinal:X,waitWritableDestroy:Y},$)=>{if(await JW(X,J),await JW(Y,J))Mn(Z,$),await zL(J,$)},Mn=(Z,J)=>{HL(Z,Z.writable,J)};import{Duplex as LM1}from"node:stream";import{callbackify as wM1}from"node:util";var Nn=({subprocess:Z,concurrentStreams:J,encoding:X},{from:Y,to:$,binary:Q=!0,preserveNewlines:K=!0}={})=>{let W=Q||$9.has(X),{subprocessStdout:G,waitReadableDestroy:V}=KT(Z,Y,J),{subprocessStdin:z,waitWritableFinal:F,waitWritableDestroy:H}=HT(Z,$,J),{readableEncoding:q,readableObjectMode:U,readableHighWaterMark:B}=WT(G,W),{read:L,onStdoutDataDone:w}=GT({subprocessStdout:G,subprocess:Z,binary:W,encoding:X,preserveNewlines:K}),M=new LM1({read:L,...FT(z,Z,F),destroy:wM1(OM1.bind(void 0,{subprocessStdout:G,subprocessStdin:z,subprocess:Z,waitReadableDestroy:V,waitWritableFinal:F,waitWritableDestroy:H})),readableHighWaterMark:B,writableHighWaterMark:z.writableHighWaterMark,readableObjectMode:U,writableObjectMode:z.writableObjectMode,encoding:q});return VT({subprocessStdout:G,onStdoutDataDone:w,readable:M,subprocess:Z,subprocessStdin:z}),qT(z,M,G),M},OM1=async({subprocessStdout:Z,subprocessStdin:J,subprocess:X,waitReadableDestroy:Y,waitWritableFinal:$,waitWritableDestroy:Q},K)=>{await Promise.all([zT({subprocessStdout:Z,subprocess:X,waitReadableDestroy:Y},K),UT({subprocessStdin:J,subprocess:X,waitWritableFinal:$,waitWritableDestroy:Q},K)])};var BT=(Z,J,{from:X,binary:Y=!1,preserveNewlines:$=!1}={})=>{let Q=Y||$9.has(J),K=aK(Z,X),W=GL({subprocessStdout:K,subprocess:Z,binary:Q,shouldEncode:!0,encoding:J,preserveNewlines:$});return MM1(W,K,Z)},MM1=async function*(Z,J,X){try{yield*Z}finally{if(J.readable)J.destroy();await X}};var Rn=(Z,{encoding:J})=>{let X=Fn();Z.readable=Bn.bind(void 0,{subprocess:Z,concurrentStreams:X,encoding:J}),Z.writable=On.bind(void 0,{subprocess:Z,concurrentStreams:X}),Z.duplex=Nn.bind(void 0,{subprocess:Z,concurrentStreams:X,encoding:J}),Z.iterable=BT.bind(void 0,Z,J),Z[Symbol.asyncIterator]=BT.bind(void 0,Z,J,{})};var jn=(Z,J)=>{for(let[X,Y]of RM1){let $=Y.value.bind(J);Reflect.defineProperty(Z,X,{...Y,value:$})}},NM1=(async()=>{})().constructor.prototype,RM1=["then","catch","finally"].map((Z)=>[Z,Reflect.getOwnPropertyDescriptor(NM1,Z)]);var Dn=(Z,J,X,Y)=>{let{file:$,commandArguments:Q,command:K,escapedCommand:W,startTime:G,verboseInfo:V,options:z,fileDescriptors:F}=PM1(Z,J,X),{subprocess:H,promise:q}=TM1({file:$,commandArguments:Q,options:z,startTime:G,verboseInfo:V,command:K,escapedCommand:W,fileDescriptors:F});return H.pipe=WL.bind(void 0,{source:H,sourcePromise:q,boundOptions:{},createNested:Y}),jn(H,q),_7.set(H,{options:z,fileDescriptors:F}),H},PM1=(Z,J,X)=>{let{command:Y,escapedCommand:$,startTime:Q,verboseInfo:K}=UB(Z,J,X),{file:W,commandArguments:G,options:V}=yB(Z,J,X),z=CM1(V),F=_i(z,K);return{file:W,commandArguments:G,command:Y,escapedCommand:$,startTime:Q,verboseInfo:K,options:z,fileDescriptors:F}},CM1=({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}},TM1=({file:Z,commandArguments:J,options:X,startTime:Y,verboseInfo:$,command:Q,escapedCommand:K,fileDescriptors:W})=>{let G;try{G=DM1(...bB(Z,J,X))}catch(U){return Ti({error:U,command:Q,escapedCommand:K,fileDescriptors:W,options:X,startTime:Y,verboseInfo:$})}let V=new AbortController;jM1(Number.POSITIVE_INFINITY,V.signal);let z=[...G.stdio];mi(G,W,V),pi(G,X,V);let F={},H=I7();G.kill=Zl.bind(void 0,{kill:G.kill.bind(G),options:X,onInternalError:H,context:F,controller:V}),G.all=Qn(G,X),Rn(G,X),Di(G,X);let q=kM1({subprocess:G,options:X,startTime:Y,verboseInfo:$,fileDescriptors:W,originalStreams:z,command:Q,escapedCommand:K,context:F,onInternalError:H,controller:V});return{subprocess:G,promise:q}},kM1=async({subprocess:Z,options:J,startTime:X,verboseInfo:Y,fileDescriptors:$,originalStreams:Q,command:K,escapedCommand:W,context:G,onInternalError:V,controller:z})=>{let[F,[H,q],U,B,L]=await Hn({subprocess:Z,options:J,context:G,verboseInfo:Y,fileDescriptors:$,originalStreams:Q,onInternalError:V,controller:z});z.abort(),V.resolve();let w=U.map((R,P)=>bZ(R,J,P)),M=bZ(B,J,"all"),N=EM1({errorInfo:F,exitCode:H,signal:q,stdio:w,all:M,ipcOutput:L,context:G,options:J,command:K,escapedCommand:W,startTime:X});return tK(N,Y,J)},EM1=({errorInfo:Z,exitCode:J,signal:X,stdio:Y,all:$,ipcOutput:Q,context:K,options:W,command:G,escapedCommand:V,startTime:z})=>("error"in Z)?bV({error:Z.error,command:G,escapedCommand:V,timedOut:K.terminationReason==="timeout",isCanceled:K.terminationReason==="cancel"||K.terminationReason==="gracefulCancel",isGracefullyCanceled:K.terminationReason==="gracefulCancel",isMaxBuffer:Z.error instanceof fZ,isForcefullyTerminated:K.isForcefullyTerminated,exitCode:J,signal:X,stdio:Y,all:$,ipcOutput:Q,options:W,startTime:z,isSync:!1}):nB({command:G,escapedCommand:V,stdio:Y,all:$,ipcOutput:Q,options:W,startTime:z});var FL=(Z,J)=>{let X=Object.fromEntries(Object.entries(J).map(([Y,$])=>[Y,IM1(Y,Z[Y],$)]));return{...Z,...X}},IM1=(Z,J,X)=>{if(_M1.has(Z)&&P8(J)&&P8(X))return{...J,...X};return X},_M1=new Set(["env",...aP]);var wX=(Z,J,X,Y)=>{let $=(K,W,G)=>wX(K,W,X,G),Q=(...K)=>vM1({mapArguments:Z,deepOptions:X,boundOptions:J,setBoundExeca:Y,createNested:$},...K);if(Y!==void 0)Y(Q,$,J);return Q},vM1=({mapArguments:Z,deepOptions:J={},boundOptions:X={},setBoundExeca:Y,createNested:$},Q,...K)=>{if(P8(Q))return $(Z,FL(X,Q),Y);let{file:W,commandArguments:G,options:V,isSync:z}=SM1({mapArguments:Z,firstArgument:Q,nextArguments:K,deepOptions:J,boundOptions:X});return z?wi(W,G,V):Dn(W,G,V,$)},SM1=({mapArguments:Z,firstArgument:J,nextArguments:X,deepOptions:Y,boundOptions:$})=>{let Q=_d(J)?vd(J,X):[J,...X],[K,W,G]=YB(...Q),V=FL(FL(Y,$),G),{file:z=K,commandArguments:F=W,options:H=V,isSync:q=!1}=Z({file:K,commandArguments:W,options:V});return{file:z,commandArguments:F,options:H,isSync:q}};var Pn=({file:Z,commandArguments:J})=>Tn(Z,J),Cn=({file:Z,commandArguments:J})=>({...Tn(Z,J),isSync:!0}),Tn=(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,...Y]=AM1(Z);return{file:X,commandArguments:Y}},AM1=(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 Y of J.split(xM1)){let $=X.at(-1);if($&&$.endsWith("\\"))X[X.length-1]=`${$.slice(0,-1)} ${Y}`;else X.push(Y)}return X},xM1=/ +/g;var kn=(Z,J,X)=>{Z.sync=J(hM1,X),Z.s=Z.sync},En=({options:Z})=>In(Z),hM1=({options:Z})=>({...In(Z),isSync:!0}),In=(Z)=>({options:{...fM1(Z),...Z}}),fM1=({input:Z,inputFile:J,stdio:X})=>Z===void 0&&J===void 0&&X===void 0?{stdin:"inherit"}:{},_n={preferLocal:!0};var vn=wX(()=>({})),BS6=wX(()=>({isSync:!0})),LS6=wX(Pn),wS6=wX(Cn),OS6=wX(yl),MS6=wX(En,{},_n,kn),{sendMessage:NS6,getOneMessage:RS6,getEachMessage:jS6,getCancelSignal:DS6}=Pi();var LT=(Z,J,X)=>{let Y=Z instanceof RegExp?Sn(Z,X):Z,$=J instanceof RegExp?Sn(J,X):J,Q=Y!==null&&$!=null&&yM1(Y,$,X);return Q&&{start:Q[0],end:Q[1],pre:X.slice(0,Q[0]),body:X.slice(Q[0]+Y.length,Q[1]),post:X.slice(Q[1]+$.length)}},Sn=(Z,J)=>{let X=J.match(Z);return X?X[0]:null},yM1=(Z,J,X)=>{let Y,$,Q,K=void 0,W,G=X.indexOf(Z),V=X.indexOf(J,G+1),z=G;if(G>=0&&V>0){if(Z===J)return[G,V];Y=[],Q=X.length;while(z>=0&&!W){if(z===G)Y.push(z),G=X.indexOf(Z,z+1);else if(Y.length===1){let F=Y.pop();if(F!==void 0)W=[F,V]}else{if($=Y.pop(),$!==void 0&&$<Q)Q=$,K=V;V=X.indexOf(J,z+1)}z=G<V&&G>=0?G:V}if(Y.length&&K!==void 0)W=[Q,K]}return W};var An="\x00SLASH"+Math.random()+"\x00",xn="\x00OPEN"+Math.random()+"\x00",OT="\x00CLOSE"+Math.random()+"\x00",hn="\x00COMMA"+Math.random()+"\x00",fn="\x00PERIOD"+Math.random()+"\x00",bM1=new RegExp(An,"g"),gM1=new RegExp(xn,"g"),mM1=new RegExp(OT,"g"),uM1=new RegExp(hn,"g"),dM1=new RegExp(fn,"g"),cM1=/\\\\/g,lM1=/\\{/g,pM1=/\\}/g,iM1=/\\,/g,nM1=/\\./g;function wT(Z){return!isNaN(Z)?parseInt(Z,10):Z.charCodeAt(0)}function aM1(Z){return Z.replace(cM1,An).replace(lM1,xn).replace(pM1,OT).replace(iM1,hn).replace(nM1,fn)}function sM1(Z){return Z.replace(bM1,"\\").replace(gM1,"{").replace(mM1,"}").replace(uM1,",").replace(dM1,".")}function yn(Z){if(!Z)return[""];let J=[],X=LT("{","}",Z);if(!X)return Z.split(",");let{pre:Y,body:$,post:Q}=X,K=Y.split(",");K[K.length-1]+="{"+$+"}";let W=yn(Q);if(Q.length)K[K.length-1]+=W.shift(),K.push.apply(K,W);return J.push.apply(J,K),J}function bn(Z){if(!Z)return[];if(Z.slice(0,2)==="{}")Z="\\{\\}"+Z.slice(2);return pV(aM1(Z),!0).map(sM1)}function oM1(Z){return"{"+Z+"}"}function rM1(Z){return/^-?0\d/.test(Z)}function tM1(Z,J){return Z<=J}function eM1(Z,J){return Z>=J}function pV(Z,J){let X=[],Y=LT("{","}",Z);if(!Y)return[Z];let $=Y.pre,Q=Y.post.length?pV(Y.post,!1):[""];if(/\$$/.test(Y.pre))for(let K=0;K<Q.length;K++){let W=$+"{"+Y.body+"}"+Q[K];X.push(W)}else{let K=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(Y.body),W=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(Y.body),G=K||W,V=Y.body.indexOf(",")>=0;if(!G&&!V){if(Y.post.match(/,(?!,).*\}/))return Z=Y.pre+"{"+Y.body+OT+Y.post,pV(Z);return[Z]}let z;if(G)z=Y.body.split(/\.\./);else if(z=yn(Y.body),z.length===1&&z[0]!==void 0){if(z=pV(z[0],!1).map(oM1),z.length===1)return Q.map((H)=>Y.pre+z[0]+H)}let F;if(G&&z[0]!==void 0&&z[1]!==void 0){let H=wT(z[0]),q=wT(z[1]),U=Math.max(z[0].length,z[1].length),B=z.length===3&&z[2]!==void 0?Math.abs(wT(z[2])):1,L=tM1;if(q<H)B*=-1,L=eM1;let M=z.some(rM1);F=[];for(let N=H;L(N,q);N+=B){let R;if(W){if(R=String.fromCharCode(N),R==="\\")R=""}else if(R=String(N),M){let P=U-R.length;if(P>0){let D=new Array(P+1).join("0");if(N<0)R="-"+D+R.slice(1);else R=D+R}}F.push(R)}}else{F=[];for(let H=0;H<z.length;H++)F.push.apply(F,pV(z[H],!1))}for(let H=0;H<F.length;H++)for(let q=0;q<Q.length;q++){let U=$+F[H]+Q[q];if(!J||G||U)X.push(U)}}return X}var iV=(Z)=>{if(typeof Z!=="string")throw new TypeError("invalid pattern");if(Z.length>65536)throw new TypeError("pattern is too long")};var ZN1={"[: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]},nV=(Z)=>Z.replace(/[[\]\\-]/g,"\\$&"),JN1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),gn=(Z)=>Z.join(""),mn=(Z,J)=>{let X=J;if(Z.charAt(X)!=="[")throw new Error("not in a brace expression");let Y=[],$=[],Q=X+1,K=!1,W=!1,G=!1,V=!1,z=X,F="";Z:while(Q<Z.length){let B=Z.charAt(Q);if((B==="!"||B==="^")&&Q===X+1){V=!0,Q++;continue}if(B==="]"&&K&&!G){z=Q+1;break}if(K=!0,B==="\\"){if(!G){G=!0,Q++;continue}}if(B==="["&&!G){for(let[L,[w,M,N]]of Object.entries(ZN1))if(Z.startsWith(L,Q)){if(F)return["$.",!1,Z.length-X,!0];if(Q+=L.length,N)$.push(w);else Y.push(w);W=W||M;continue Z}}if(G=!1,F){if(B>F)Y.push(nV(F)+"-"+nV(B));else if(B===F)Y.push(nV(B));F="",Q++;continue}if(Z.startsWith("-]",Q+1)){Y.push(nV(B+"-")),Q+=2;continue}if(Z.startsWith("-",Q+1)){F=B,Q+=2;continue}Y.push(nV(B)),Q++}if(z<Q)return["",!1,0,!1];if(!Y.length&&!$.length)return["$.",!1,Z.length-X,!0];if($.length===0&&Y.length===1&&/^\\?.$/.test(Y[0])&&!V){let B=Y[0].length===2?Y[0].slice(-1):Y[0];return[JN1(B),!1,z-X,!1]}let H="["+(V?"^":"")+gn(Y)+"]",q="["+(V?"":"^")+gn($)+"]";return[Y.length&&$.length?"("+H+"|"+q+")":Y.length?H:q,W,z-X,!0]};var c4=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/\[([^\/\\])\]/g,"$1"):Z.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")};var XN1=new Set(["!","?","+","*","@"]),un=(Z)=>XN1.has(Z),YN1="(?!(?:^|/)\\.\\.?(?:$|/))",qL="(?!\\.)",$N1=new Set(["[","."]),QN1=new Set(["..","."]),KN1=new Set("().*{}+?[]^$\\!"),WN1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),MT="[^/]",dn=MT+"*?",cn=MT+"+?";class O6{type;#Z;#J;#Y=!1;#X=[];#$;#z;#F;#W=!1;#G;#V;#H=!1;constructor(Z,J,X={}){if(this.type=Z,Z)this.#J=!0;if(this.#$=J,this.#Z=this.#$?this.#$.#Z:this,this.#G=this.#Z===this?X:this.#Z.#G,this.#F=this.#Z===this?[]:this.#Z.#F,Z==="!"&&!this.#Z.#W)this.#F.push(this);this.#z=this.#$?this.#$.#X.length:0}get hasMagic(){if(this.#J!==void 0)return this.#J;for(let Z of this.#X){if(typeof Z==="string")continue;if(Z.type||Z.hasMagic)return this.#J=!0}return this.#J}toString(){if(this.#V!==void 0)return this.#V;if(!this.type)return this.#V=this.#X.map((Z)=>String(Z)).join("");else return this.#V=this.type+"("+this.#X.map((Z)=>String(Z)).join("|")+")"}#Q(){if(this!==this.#Z)throw new Error("should only call on root");if(this.#W)return this;this.toString(),this.#W=!0;let Z;while(Z=this.#F.pop()){if(Z.type!=="!")continue;let J=Z,X=J.#$;while(X){for(let Y=J.#z+1;!X.type&&Y<X.#X.length;Y++)for(let $ of Z.#X){if(typeof $==="string")throw new Error("string part in extglob AST??");$.copyIn(X.#X[Y])}J=X,X=J.#$}}return this}push(...Z){for(let J of Z){if(J==="")continue;if(typeof J!=="string"&&!(J instanceof O6&&J.#$===this))throw new Error("invalid part: "+J);this.#X.push(J)}}toJSON(){let Z=this.type===null?this.#X.slice().map((J)=>typeof J==="string"?J:J.toJSON()):[this.type,...this.#X.map((J)=>J.toJSON())];if(this.isStart()&&!this.type)Z.unshift([]);if(this.isEnd()&&(this===this.#Z||this.#Z.#W&&this.#$?.type==="!"))Z.push({});return Z}isStart(){if(this.#Z===this)return!0;if(!this.#$?.isStart())return!1;if(this.#z===0)return!0;let Z=this.#$;for(let J=0;J<this.#z;J++){let X=Z.#X[J];if(!(X instanceof O6&&X.type==="!"))return!1}return!0}isEnd(){if(this.#Z===this)return!0;if(this.#$?.type==="!")return!0;if(!this.#$?.isEnd())return!1;if(!this.type)return this.#$?.isEnd();let Z=this.#$?this.#$.#X.length:0;return this.#z===Z-1}copyIn(Z){if(typeof Z==="string")this.push(Z);else this.push(Z.clone(this))}clone(Z){let J=new O6(this.type,Z);for(let X of this.#X)J.copyIn(X);return J}static#U(Z,J,X,Y){let $=!1,Q=!1,K=-1,W=!1;if(J.type===null){let H=X,q="";while(H<Z.length){let U=Z.charAt(H++);if($||U==="\\"){$=!$,q+=U;continue}if(Q){if(H===K+1){if(U==="^"||U==="!")W=!0}else if(U==="]"&&!(H===K+2&&W))Q=!1;q+=U;continue}else if(U==="["){Q=!0,K=H,W=!1,q+=U;continue}if(!Y.noext&&un(U)&&Z.charAt(H)==="("){J.push(q),q="";let B=new O6(U,J);H=O6.#U(Z,B,H,Y),J.push(B);continue}q+=U}return J.push(q),H}let G=X+1,V=new O6(null,J),z=[],F="";while(G<Z.length){let H=Z.charAt(G++);if($||H==="\\"){$=!$,F+=H;continue}if(Q){if(G===K+1){if(H==="^"||H==="!")W=!0}else if(H==="]"&&!(G===K+2&&W))Q=!1;F+=H;continue}else if(H==="["){Q=!0,K=G,W=!1,F+=H;continue}if(un(H)&&Z.charAt(G)==="("){V.push(F),F="";let q=new O6(H,V);V.push(q),G=O6.#U(Z,q,G,Y);continue}if(H==="|"){V.push(F),F="",z.push(V),V=new O6(null,J);continue}if(H===")"){if(F===""&&J.#X.length===0)J.#H=!0;return V.push(F),F="",J.push(...z,V),G}F+=H}return J.type=null,J.#J=void 0,J.#X=[Z.substring(X-1)],G}static fromGlob(Z,J={}){let X=new O6(null,void 0,J);return O6.#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(!(Y||this.#J||this.#G.nocase&&!this.#G.nocaseMagicOnly&&Z.toUpperCase()!==Z.toLowerCase()))return X;let K=(this.#G.nocase?"i":"")+($?"u":"");return Object.assign(new RegExp(`^${J}$`,K),{_src:J,_glob:Z})}get options(){return this.#G}toRegExpSource(Z){let J=Z??!!this.#G.dot;if(this.#Z===this)this.#Q();if(!this.type){let W=this.isStart()&&this.isEnd(),G=this.#X.map((H)=>{let[q,U,B,L]=typeof H==="string"?O6.#B(H,this.#J,W):H.toRegExpSource(Z);return this.#J=this.#J||B,this.#Y=this.#Y||L,q}).join(""),V="";if(this.isStart()){if(typeof this.#X[0]==="string"){if(!(this.#X.length===1&&QN1.has(this.#X[0]))){let q=$N1,U=J&&q.has(G.charAt(0))||G.startsWith("\\.")&&q.has(G.charAt(2))||G.startsWith("\\.\\.")&&q.has(G.charAt(4)),B=!J&&!Z&&q.has(G.charAt(0));V=U?YN1:B?qL:""}}}let z="";if(this.isEnd()&&this.#Z.#W&&this.#$?.type==="!")z="(?:$|\\/)";return[V+G+z,c4(G),this.#J=!!this.#J,this.#Y]}let X=this.type==="*"||this.type==="+",Y=this.type==="!"?"(?:(?!(?:":"(?:",$=this.#L(J);if(this.isStart()&&this.isEnd()&&!$&&this.type!=="!"){let W=this.toString();return this.#X=[W],this.type=null,this.#J=void 0,[W,c4(this.toString()),!1,!1]}let Q=!X||Z||J||!qL?"":this.#L(!0);if(Q===$)Q="";if(Q)$=`(?:${$})(?:${Q})*?`;let K="";if(this.type==="!"&&this.#H)K=(this.isStart()&&!J?qL:"")+cn;else{let W=this.type==="!"?"))"+(this.isStart()&&!J&&!Z?qL:"")+dn+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&Q?")":this.type==="*"&&Q?")?":`)${this.type}`;K=Y+$+W}return[K,c4($),this.#J=!!this.#J,this.#Y]}#L(Z){return this.#X.map((J)=>{if(typeof J==="string")throw new Error("string type in extglob ast??");let[X,Y,$,Q]=J.toRegExpSource(Z);return this.#Y=this.#Y||Q,X}).filter((J)=>!(this.isStart()&&this.isEnd())||!!J).join("|")}static#B(Z,J,X=!1){let Y=!1,$="",Q=!1;for(let K=0;K<Z.length;K++){let W=Z.charAt(K);if(Y){Y=!1,$+=(KN1.has(W)?"\\":"")+W;continue}if(W==="\\"){if(K===Z.length-1)$+="\\\\";else Y=!0;continue}if(W==="["){let[G,V,z,F]=mn(Z,K);if(z){$+=G,Q=Q||V,K+=z-1,J=J||F;continue}}if(W==="*"){if(X&&Z==="*")$+=cn;else $+=dn;J=!0;continue}if(W==="?"){$+=MT,J=!0;continue}$+=WN1(W)}return[$,c4(Z),!!J,Q]}}var XW=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/[?*()[\]]/g,"[$&]"):Z.replace(/[?*()[\]\\]/g,"\\$&")};var Y5=(Z,J,X={})=>{if(iV(J),!X.nocomment&&J.charAt(0)==="#")return!1;return new d9(J,X).match(Z)},GN1=/^\*+([^+@!?\*\[\(]*)$/,VN1=(Z)=>(J)=>!J.startsWith(".")&&J.endsWith(Z),zN1=(Z)=>(J)=>J.endsWith(Z),HN1=(Z)=>{return Z=Z.toLowerCase(),(J)=>!J.startsWith(".")&&J.toLowerCase().endsWith(Z)},FN1=(Z)=>{return Z=Z.toLowerCase(),(J)=>J.toLowerCase().endsWith(Z)},qN1=/^\*+\.\*+$/,UN1=(Z)=>!Z.startsWith(".")&&Z.includes("."),BN1=(Z)=>Z!=="."&&Z!==".."&&Z.includes("."),LN1=/^\.\*+$/,wN1=(Z)=>Z!=="."&&Z!==".."&&Z.startsWith("."),ON1=/^\*+$/,MN1=(Z)=>Z.length!==0&&!Z.startsWith("."),NN1=(Z)=>Z.length!==0&&Z!=="."&&Z!=="..",RN1=/^\?+([^+@!?\*\[\(]*)?$/,jN1=([Z,J=""])=>{let X=nn([Z]);if(!J)return X;return J=J.toLowerCase(),(Y)=>X(Y)&&Y.toLowerCase().endsWith(J)},DN1=([Z,J=""])=>{let X=an([Z]);if(!J)return X;return J=J.toLowerCase(),(Y)=>X(Y)&&Y.toLowerCase().endsWith(J)},PN1=([Z,J=""])=>{let X=an([Z]);return!J?X:(Y)=>X(Y)&&Y.endsWith(J)},CN1=([Z,J=""])=>{let X=nn([Z]);return!J?X:(Y)=>X(Y)&&Y.endsWith(J)},nn=([Z])=>{let J=Z.length;return(X)=>X.length===J&&!X.startsWith(".")},an=([Z])=>{let J=Z.length;return(X)=>X.length===J&&X!=="."&&X!==".."},sn=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",ln={win32:{sep:"\\"},posix:{sep:"/"}},TN1=sn==="win32"?ln.win32.sep:ln.posix.sep;Y5.sep=TN1;var M6=Symbol("globstar **");Y5.GLOBSTAR=M6;var kN1="[^/]",EN1=kN1+"*?",IN1="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",_N1="(?:(?!(?:\\/|^)\\.).)*?",vN1=(Z,J={})=>(X)=>Y5(X,Z,J);Y5.filter=vN1;var u9=(Z,J={})=>Object.assign({},Z,J),SN1=(Z)=>{if(!Z||typeof Z!=="object"||!Object.keys(Z).length)return Y5;let J=Y5;return Object.assign((Y,$,Q={})=>J(Y,$,u9(Z,Q)),{Minimatch:class Y extends J.Minimatch{constructor($,Q={}){super($,u9(Z,Q))}static defaults($){return J.defaults(u9(Z,$)).Minimatch}},AST:class Y extends J.AST{constructor($,Q,K={}){super($,Q,u9(Z,K))}static fromGlob($,Q={}){return J.AST.fromGlob($,u9(Z,Q))}},unescape:(Y,$={})=>J.unescape(Y,u9(Z,$)),escape:(Y,$={})=>J.escape(Y,u9(Z,$)),filter:(Y,$={})=>J.filter(Y,u9(Z,$)),defaults:(Y)=>J.defaults(u9(Z,Y)),makeRe:(Y,$={})=>J.makeRe(Y,u9(Z,$)),braceExpand:(Y,$={})=>J.braceExpand(Y,u9(Z,$)),match:(Y,$,Q={})=>J.match(Y,$,u9(Z,Q)),sep:J.sep,GLOBSTAR:M6})};Y5.defaults=SN1;var on=(Z,J={})=>{if(iV(Z),J.nobrace||!/\{(?:(?!\{).)*\}/.test(Z))return[Z];return bn(Z)};Y5.braceExpand=on;var AN1=(Z,J={})=>new d9(Z,J).makeRe();Y5.makeRe=AN1;var xN1=(Z,J,X={})=>{let Y=new d9(J,X);if(Z=Z.filter(($)=>Y.match($)),Y.options.nonull&&!Z.length)Z.push(J);return Z};Y5.match=xN1;var pn=/[?*]|[+@!]\(.*?\)|\[|\]/,hN1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class d9{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(Z,J={}){if(iV(Z),J=J||{},this.options=J,this.pattern=Z,this.platform=J.platform||sn,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=(...$)=>console.error(...$);this.debug(this.pattern,this.globSet);let X=this.globSet.map(($)=>this.slashSplit($));this.globParts=this.preprocess(X),this.debug(this.pattern,this.globParts);let Y=this.globParts.map(($,Q,K)=>{if(this.isWindows&&this.windowsNoMagicRoot){let W=$[0]===""&&$[1]===""&&($[2]==="?"||!pn.test($[2]))&&!pn.test($[3]),G=/^[a-z]:/i.test($[0]);if(W)return[...$.slice(0,4),...$.slice(4).map((V)=>this.parse(V))];else if(G)return[$[0],...$.slice(1).map((V)=>this.parse(V))]}return $.map((W)=>this.parse(W))});if(this.debug(this.pattern,Y),this.set=Y.filter(($)=>$.indexOf(!1)===-1),this.isWindows)for(let $=0;$<this.set.length;$++){let Q=this.set[$];if(Q[0]===""&&Q[1]===""&&this.globParts[$][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 Y=0;Y<Z[X].length;Y++)if(Z[X][Y]==="**")Z[X][Y]="*"}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 Y=X;while(J[Y+1]==="**")Y++;if(Y!==X)J.splice(X,Y-X)}return J})}levelOneOptimize(Z){return Z.map((J)=>{return J=J.reduce((X,Y)=>{let $=X[X.length-1];if(Y==="**"&&$==="**")return X;if(Y===".."){if($&&$!==".."&&$!=="."&&$!=="**")return X.pop(),X}return X.push(Y),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 Y=1;Y<Z.length-1;Y++){let $=Z[Y];if(Y===1&&$===""&&Z[0]==="")continue;if($==="."||$==="")J=!0,Z.splice(Y,1),Y--}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 Y=Z[X-1];if(Y&&Y!=="."&&Y!==".."&&Y!=="**")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 Y=-1;while((Y=X.indexOf("**",Y+1))!==-1){let Q=Y;while(X[Q+1]==="**")Q++;if(Q>Y)X.splice(Y+1,Q-Y);let K=X[Y+1],W=X[Y+2],G=X[Y+3];if(K!=="..")continue;if(!W||W==="."||W===".."||!G||G==="."||G==="..")continue;J=!0,X.splice(Y,1);let V=X.slice(0);V[Y]="**",Z.push(V),Y--}if(!this.preserveMultipleSlashes){for(let Q=1;Q<X.length-1;Q++){let K=X[Q];if(Q===1&&K===""&&X[0]==="")continue;if(K==="."||K==="")J=!0,X.splice(Q,1),Q--}if(X[0]==="."&&X.length===2&&(X[1]==="."||X[1]===""))J=!0,X.pop()}let $=0;while(($=X.indexOf("..",$+1))!==-1){let Q=X[$-1];if(Q&&Q!=="."&&Q!==".."&&Q!=="**"){J=!0;let W=$===1&&X[$+1]==="**"?["."]:[];if(X.splice($-1,2,...W),X.length===0)X.push("");$-=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 Y=this.partsMatch(Z[J],Z[X],!this.preserveMultipleSlashes);if(Y){Z[J]=[],Z[X]=Y;break}}return Z.filter((J)=>J.length)}partsMatch(Z,J,X=!1){let Y=0,$=0,Q=[],K="";while(Y<Z.length&&$<J.length)if(Z[Y]===J[$])Q.push(K==="b"?J[$]:Z[Y]),Y++,$++;else if(X&&Z[Y]==="**"&&J[$]===Z[Y+1])Q.push(Z[Y]),Y++;else if(X&&J[$]==="**"&&Z[Y]===J[$+1])Q.push(J[$]),$++;else if(Z[Y]==="*"&&J[$]&&(this.options.dot||!J[$].startsWith("."))&&J[$]!=="**"){if(K==="b")return!1;K="a",Q.push(Z[Y]),Y++,$++}else if(J[$]==="*"&&Z[Y]&&(this.options.dot||!Z[Y].startsWith("."))&&Z[Y]!=="**"){if(K==="a")return!1;K="b",Q.push(J[$]),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 Y=0;Y<Z.length&&Z.charAt(Y)==="!";Y++)J=!J,X++;if(X)this.pattern=Z.slice(X);this.negate=J}matchOne(Z,J,X=!1){let Y=this.options;if(this.isWindows){let U=typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0]),B=!U&&Z[0]===""&&Z[1]===""&&Z[2]==="?"&&/^[a-z]:$/i.test(Z[3]),L=typeof J[0]==="string"&&/^[a-z]:$/i.test(J[0]),w=!L&&J[0]===""&&J[1]===""&&J[2]==="?"&&typeof J[3]==="string"&&/^[a-z]:$/i.test(J[3]),M=B?3:U?0:void 0,N=w?3:L?0:void 0;if(typeof M==="number"&&typeof N==="number"){let[R,P]=[Z[M],J[N]];if(R.toLowerCase()===P.toLowerCase()){if(J[N]=R,N>M)J=J.slice(N);else if(M>N)Z=Z.slice(M)}}}let{optimizationLevel:$=1}=this.options;if($>=2)Z=this.levelTwoFileOptimize(Z);this.debug("matchOne",this,{file:Z,pattern:J}),this.debug("matchOne",Z.length,J.length);for(var Q=0,K=0,W=Z.length,G=J.length;Q<W&&K<G;Q++,K++){this.debug("matchOne loop");var V=J[K],z=Z[Q];if(this.debug(J,V,z),V===!1)return!1;if(V===M6){this.debug("GLOBSTAR",[J,V,z]);var F=Q,H=K+1;if(H===G){this.debug("** at the end");for(;Q<W;Q++)if(Z[Q]==="."||Z[Q]===".."||!Y.dot&&Z[Q].charAt(0)===".")return!1;return!0}while(F<W){var q=Z[F];if(this.debug(`
411
411
  globstar while`,Z,F,J,H,q),this.matchOne(Z.slice(F),J.slice(H),X))return this.debug("globstar found match!",F,W,q),!0;else{if(q==="."||q===".."||!Y.dot&&q.charAt(0)==="."){this.debug("dot detected!",Z,F,J,H);break}this.debug("globstar swallow a segment, and continue"),F++}}if(X){if(this.debug(`
412
- >>> no match, partial?`,Z,F,J,H),F===W)return!0}return!1}let U;if(typeof V==="string")U=z===V,this.debug("string match",V,z,U);else U=V.test(z),this.debug("pattern match",V,z,U);if(!U)return!1}if(Q===W&&K===G)return!0;else if(Q===W)return X;else if(K===G)return Q===W-1&&Z[Q]==="";else throw new Error("wtf?")}braceExpand(){return on(this.pattern,this.options)}parse(Z){iV(Z);let J=this.options;if(Z==="**")return M6;if(Z==="")return"";let X,Y=null;if(X=Z.match(ON1))Y=J.dot?NN1:MN1;else if(X=Z.match(GN1))Y=(J.nocase?J.dot?FN1:HN1:J.dot?zN1:VN1)(X[1]);else if(X=Z.match(RN1))Y=(J.nocase?J.dot?DN1:jN1:J.dot?PN1:CN1)(X);else if(X=Z.match(qN1))Y=J.dot?BN1:UN1;else if(X=Z.match(LN1))Y=wN1;let $=O6.fromGlob(Z,this.options).toMMPattern();if(Y&&typeof $==="object")Reflect.defineProperty($,"test",{value:Y});return $}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?EN1:J.dot?IN1:_N1,Y=new Set(J.nocase?["i"]:[]),$=Z.map((W)=>{let G=W.map((V)=>{if(V instanceof RegExp)for(let z of V.flags.split(""))Y.add(z);return typeof V==="string"?hN1(V):V===M6?M6:V._src});return G.forEach((V,z)=>{let F=G[z+1],H=G[z-1];if(V!==M6||H===M6)return;if(H===void 0)if(F!==void 0&&F!==M6)G[z+1]="(?:\\/|"+X+"\\/)?"+F;else G[z]=X;else if(F===void 0)G[z-1]=H+"(?:\\/|"+X+")?";else if(F!==M6)G[z-1]=H+"(?:\\/|\\/"+X+"\\/)"+F,G[z+1]=M6}),G.filter((V)=>V!==M6).join("/")}).join("|"),[Q,K]=Z.length>1?["(?:",")"]:["",""];if($="^"+Q+$+K+"$",this.negate)$="^(?!"+$+").+$";try{this.regexp=new RegExp($,[...Y].join(""))}catch(W){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 Y=this.slashSplit(Z);this.debug(this.pattern,"split",Y);let $=this.set;this.debug(this.pattern,"set",$);let Q=Y[Y.length-1];if(!Q)for(let K=Y.length-2;!Q&&K>=0;K--)Q=Y[K];for(let K=0;K<$.length;K++){let W=$[K],G=Y;if(X.matchBase&&W.length===1)G=[Q];if(this.matchOne(G,W,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return Y5.defaults(Z).Minimatch}}Y5.AST=O6;Y5.Minimatch=d9;Y5.escape=XW;Y5.unescape=c4;import{fileURLToPath as qR1}from"node:url";var YW=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,tn=new Set,NT=typeof process==="object"&&!!process?process:{},en=(Z,J,X,Y)=>{typeof NT.emitWarning==="function"?NT.emitWarning(Z,J,X,Y):console.error(`[${X}] ${J}: ${Z}`)},UL=globalThis.AbortController,rn=globalThis.AbortSignal;if(typeof UL==="undefined"){rn=class X{onabort;_onabort=[];reason;aborted=!1;addEventListener(Y,$){this._onabort.push($)}},UL=class X{constructor(){J()}signal=new rn;abort(Y){if(this.signal.aborted)return;this.signal.reason=Y,this.signal.aborted=!0;for(let $ of this.signal._onabort)$(Y);this.signal.onabort?.(Y)}};let Z=NT.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",J=()=>{if(!Z)return;Z=!1,en("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 fN1=(Z)=>!tn.has(Z),lS6=Symbol("type"),OX=(Z)=>Z&&Z===Math.floor(Z)&&Z>0&&isFinite(Z),Za=(Z)=>!OX(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?aV:null;class aV extends Array{constructor(Z){super(Z);this.fill(0)}}class $W{heap;length;static#Z=!1;static create(Z){let J=Za(Z);if(!J)return[];$W.#Z=!0;let X=new $W(Z,J);return $W.#Z=!1,X}constructor(Z,J){if(!$W.#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 sV{#Z;#J;#Y;#X;#$;#z;#F;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#W;#G;#V;#H;#Q;#U;#L;#B;#O;#k;#M;#E;#j;#R;#N;#C;#w;#_;static unsafeExposeInternals(Z){return{starts:Z.#j,ttls:Z.#R,sizes:Z.#E,keyMap:Z.#V,keyList:Z.#H,valList:Z.#Q,next:Z.#U,prev:Z.#L,get head(){return Z.#B},get tail(){return Z.#O},free:Z.#k,isBackgroundFetch:(J)=>Z.#q(J),backgroundFetch:(J,X,Y,$)=>Z.#h(J,X,Y,$),moveToTail:(J)=>Z.#b(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.#J}get calculatedSize(){return this.#G}get size(){return this.#W}get fetchMethod(){return this.#z}get memoMethod(){return this.#F}get dispose(){return this.#Y}get onInsert(){return this.#X}get disposeAfter(){return this.#$}constructor(Z){let{max:J=0,ttl:X,ttlResolution:Y=1,ttlAutopurge:$,updateAgeOnGet:Q,updateAgeOnHas:K,allowStale:W,dispose:G,onInsert:V,disposeAfter:z,noDisposeOnSet:F,noUpdateTTL:H,maxSize:q=0,maxEntrySize:U=0,sizeCalculation:B,fetchMethod:L,memoMethod:w,noDeleteOnFetchRejection:M,noDeleteOnStaleGet:N,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:P,ignoreFetchAbort:D}=Z;if(J!==0&&!OX(J))throw new TypeError("max option must be a nonnegative integer");let C=J?Za(J):Array;if(!C)throw new Error("invalid max value: "+J);if(this.#Z=J,this.#J=q,this.maxEntrySize=U||this.#J,this.sizeCalculation=B,this.sizeCalculation){if(!this.#J&&!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.#F=w,L!==void 0&&typeof L!=="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#z=L,this.#C=!!L,this.#V=new Map,this.#H=new Array(J).fill(void 0),this.#Q=new Array(J).fill(void 0),this.#U=new C(J),this.#L=new C(J),this.#B=0,this.#O=0,this.#k=$W.create(J),this.#W=0,this.#G=0,typeof G==="function")this.#Y=G;if(typeof V==="function")this.#X=V;if(typeof z==="function")this.#$=z,this.#M=[];else this.#$=void 0,this.#M=void 0;if(this.#N=!!this.#Y,this.#_=!!this.#X,this.#w=!!this.#$,this.noDisposeOnSet=!!F,this.noUpdateTTL=!!H,this.noDeleteOnFetchRejection=!!M,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!P,this.ignoreFetchAbort=!!D,this.maxEntrySize!==0){if(this.#J!==0){if(!OX(this.#J))throw new TypeError("maxSize must be a positive integer if specified")}if(!OX(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#m()}if(this.allowStale=!!W,this.noDeleteOnStaleGet=!!N,this.updateAgeOnGet=!!Q,this.updateAgeOnHas=!!K,this.ttlResolution=OX(Y)||Y===0?Y:1,this.ttlAutopurge=!!$,this.ttl=X||0,this.ttl){if(!OX(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#K()}if(this.#Z===0&&this.ttl===0&&this.#J===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#Z&&!this.#J){if(fN1("LRU_CACHE_UNBOUNDED"))tn.add("LRU_CACHE_UNBOUNDED"),en("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",sV)}}getRemainingTTL(Z){return this.#V.has(Z)?1/0:0}#K(){let Z=new aV(this.#Z),J=new aV(this.#Z);this.#R=Z,this.#j=J,this.#v=($,Q,K=YW.now())=>{if(J[$]=Q!==0?K:0,Z[$]=Q,Q!==0&&this.ttlAutopurge){let W=setTimeout(()=>{if(this.#P($))this.#S(this.#H[$],"expire")},Q+1);if(W.unref)W.unref()}},this.#A=($)=>{J[$]=Z[$]!==0?YW.now():0},this.#D=($,Q)=>{if(Z[Q]){let K=Z[Q],W=J[Q];if(!K||!W)return;$.ttl=K,$.start=W,$.now=X||Y();let G=$.now-W;$.remainingTTL=K-G}};let X=0,Y=()=>{let $=YW.now();if(this.ttlResolution>0){X=$;let Q=setTimeout(()=>X=0,this.ttlResolution);if(Q.unref)Q.unref()}return $};this.getRemainingTTL=($)=>{let Q=this.#V.get($);if(Q===void 0)return 0;let K=Z[Q],W=J[Q];if(!K||!W)return 1/0;let G=(X||Y())-W;return K-G},this.#P=($)=>{let Q=J[$],K=Z[$];return!!K&&!!Q&&(X||Y())-Q>K}}#A=()=>{};#D=()=>{};#v=()=>{};#P=()=>!1;#m(){let Z=new aV(this.#Z);this.#G=0,this.#E=Z,this.#x=(J)=>{this.#G-=Z[J],Z[J]=0},this.#u=(J,X,Y,$)=>{if(this.#q(X))return 0;if(!OX(Y))if($){if(typeof $!=="function")throw new TypeError("sizeCalculation must be a function");if(Y=$(X,J),!OX(Y))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 Y},this.#f=(J,X,Y)=>{if(Z[J]=X,this.#J){let $=this.#J-Z[J];while(this.#G>$)this.#y(!0)}if(this.#G+=Z[J],Y)Y.entrySize=X,Y.totalCalculatedSize=this.#G}}#x=(Z)=>{};#f=(Z,J,X)=>{};#u=(Z,J,X,Y)=>{if(X||Y)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#T({allowStale:Z=this.allowStale}={}){if(this.#W)for(let J=this.#O;;){if(!this.#d(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.#W)for(let J=this.#B;;){if(!this.#d(J))break;if(Z||!this.#P(J))yield J;if(J===this.#O)break;else J=this.#U[J]}}#d(Z){return Z!==void 0&&this.#V.get(this.#H[Z])===Z}*entries(){for(let Z of this.#T())if(this.#Q[Z]!==void 0&&this.#H[Z]!==void 0&&!this.#q(this.#Q[Z]))yield[this.#H[Z],this.#Q[Z]]}*rentries(){for(let Z of this.#I())if(this.#Q[Z]!==void 0&&this.#H[Z]!==void 0&&!this.#q(this.#Q[Z]))yield[this.#H[Z],this.#Q[Z]]}*keys(){for(let Z of this.#T()){let J=this.#H[Z];if(J!==void 0&&!this.#q(this.#Q[Z]))yield J}}*rkeys(){for(let Z of this.#I()){let J=this.#H[Z];if(J!==void 0&&!this.#q(this.#Q[Z]))yield J}}*values(){for(let Z of this.#T())if(this.#Q[Z]!==void 0&&!this.#q(this.#Q[Z]))yield this.#Q[Z]}*rvalues(){for(let Z of this.#I())if(this.#Q[Z]!==void 0&&!this.#q(this.#Q[Z]))yield this.#Q[Z]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(Z,J={}){for(let X of this.#T()){let Y=this.#Q[X],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0)continue;if(Z($,this.#H[X],this))return this.get(this.#H[X],J)}}forEach(Z,J=this){for(let X of this.#T()){let Y=this.#Q[X],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0)continue;Z.call(J,$,this.#H[X],this)}}rforEach(Z,J=this){for(let X of this.#I()){let Y=this.#Q[X],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0)continue;Z.call(J,$,this.#H[X],this)}}purgeStale(){let Z=!1;for(let J of this.#I({allowStale:!0}))if(this.#P(J))this.#S(this.#H[J],"expire"),Z=!0;return Z}info(Z){let J=this.#V.get(Z);if(J===void 0)return;let X=this.#Q[J],Y=this.#q(X)?X.__staleWhileFetching:X;if(Y===void 0)return;let $={value:Y};if(this.#R&&this.#j){let Q=this.#R[J],K=this.#j[J];if(Q&&K){let W=Q-(YW.now()-K);$.ttl=W,$.start=Date.now()}}if(this.#E)$.size=this.#E[J];return $}dump(){let Z=[];for(let J of this.#T({allowStale:!0})){let X=this.#H[J],Y=this.#Q[J],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0||X===void 0)continue;let Q={value:$};if(this.#R&&this.#j){Q.ttl=this.#R[J];let K=YW.now()-this.#j[J];Q.start=Math.floor(Date.now()-K)}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 Y=Date.now()-X.start;X.start=YW.now()-Y}this.set(J,X.value,X)}}set(Z,J,X={}){if(J===void 0)return this.delete(Z),this;let{ttl:Y=this.ttl,start:$,noDisposeOnSet:Q=this.noDisposeOnSet,sizeCalculation:K=this.sizeCalculation,status:W}=X,{noUpdateTTL:G=this.noUpdateTTL}=X,V=this.#u(Z,J,X.size||0,K);if(this.maxEntrySize&&V>this.maxEntrySize){if(W)W.set="miss",W.maxEntrySizeExceeded=!0;return this.#S(Z,"set"),this}let z=this.#W===0?void 0:this.#V.get(Z);if(z===void 0){if(z=this.#W===0?this.#O:this.#k.length!==0?this.#k.pop():this.#W===this.#Z?this.#y(!1):this.#W,this.#H[z]=Z,this.#Q[z]=J,this.#V.set(Z,z),this.#U[this.#O]=z,this.#L[z]=this.#O,this.#O=z,this.#W++,this.#f(z,V,W),W)W.set="add";if(G=!1,this.#_)this.#X?.(J,Z,"add")}else{this.#b(z);let F=this.#Q[z];if(J!==F){if(this.#C&&this.#q(F)){F.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:H}=F;if(H!==void 0&&!Q){if(this.#N)this.#Y?.(H,Z,"set");if(this.#w)this.#M?.push([H,Z,"set"])}}else if(!Q){if(this.#N)this.#Y?.(F,Z,"set");if(this.#w)this.#M?.push([F,Z,"set"])}if(this.#x(z),this.#f(z,V,W),this.#Q[z]=J,W){W.set="replace";let H=F&&this.#q(F)?F.__staleWhileFetching:F;if(H!==void 0)W.oldValue=H}}else if(W)W.set="update";if(this.#_)this.onInsert?.(J,Z,J===F?"update":"replace")}if(Y!==0&&!this.#R)this.#K();if(this.#R){if(!G)this.#v(z,Y,$);if(W)this.#D(W,z)}if(!Q&&this.#w&&this.#M){let F=this.#M,H;while(H=F?.shift())this.#$?.(...H)}return this}pop(){try{while(this.#W){let Z=this.#Q[this.#B];if(this.#y(!0),this.#q(Z)){if(Z.__staleWhileFetching)return Z.__staleWhileFetching}else if(Z!==void 0)return Z}}finally{if(this.#w&&this.#M){let Z=this.#M,J;while(J=Z?.shift())this.#$?.(...J)}}}#y(Z){let J=this.#B,X=this.#H[J],Y=this.#Q[J];if(this.#C&&this.#q(Y))Y.__abortController.abort(new Error("evicted"));else if(this.#N||this.#w){if(this.#N)this.#Y?.(Y,X,"evict");if(this.#w)this.#M?.push([Y,X,"evict"])}if(this.#x(J),Z)this.#H[J]=void 0,this.#Q[J]=void 0,this.#k.push(J);if(this.#W===1)this.#B=this.#O=0,this.#k.length=0;else this.#B=this.#U[J];return this.#V.delete(X),this.#W--,J}has(Z,J={}){let{updateAgeOnHas:X=this.updateAgeOnHas,status:Y}=J,$=this.#V.get(Z);if($!==void 0){let Q=this.#Q[$];if(this.#q(Q)&&Q.__staleWhileFetching===void 0)return!1;if(!this.#P($)){if(X)this.#A($);if(Y)Y.has="hit",this.#D(Y,$);return!0}else if(Y)Y.has="stale",this.#D(Y,$)}else if(Y)Y.has="miss";return!1}peek(Z,J={}){let{allowStale:X=this.allowStale}=J,Y=this.#V.get(Z);if(Y===void 0||!X&&this.#P(Y))return;let $=this.#Q[Y];return this.#q($)?$.__staleWhileFetching:$}#h(Z,J,X,Y){let $=J===void 0?void 0:this.#Q[J];if(this.#q($))return $;let Q=new UL,{signal:K}=X;K?.addEventListener("abort",()=>Q.abort(K.reason),{signal:Q.signal});let W={signal:Q.signal,options:X,context:Y},G=(U,B=!1)=>{let{aborted:L}=Q.signal,w=X.ignoreFetchAbort&&U!==void 0;if(X.status)if(L&&!B){if(X.status.fetchAborted=!0,X.status.fetchError=Q.signal.reason,w)X.status.fetchAbortIgnored=!0}else X.status.fetchResolved=!0;if(L&&!w&&!B)return z(Q.signal.reason);let M=H;if(this.#Q[J]===H)if(U===void 0)if(M.__staleWhileFetching)this.#Q[J]=M.__staleWhileFetching;else this.#S(Z,"fetch");else{if(X.status)X.status.fetchUpdated=!0;this.set(Z,U,W.options)}return U},V=(U)=>{if(X.status)X.status.fetchRejected=!0,X.status.fetchError=U;return z(U)},z=(U)=>{let{aborted:B}=Q.signal,L=B&&X.allowStaleOnFetchAbort,w=L||X.allowStaleOnFetchRejection,M=w||X.noDeleteOnFetchRejection,N=H;if(this.#Q[J]===H){if(!M||N.__staleWhileFetching===void 0)this.#S(Z,"fetch");else if(!L)this.#Q[J]=N.__staleWhileFetching}if(w){if(X.status&&N.__staleWhileFetching!==void 0)X.status.returnedStale=!0;return N.__staleWhileFetching}else if(N.__returned===N)throw U},F=(U,B)=>{let L=this.#z?.(Z,$,W);if(L&&L instanceof Promise)L.then((w)=>U(w===void 0?void 0:w),B);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 H=new Promise(F).then(G,V),q=Object.assign(H,{__abortController:Q,__staleWhileFetching:$,__returned:void 0});if(J===void 0)this.set(Z,q,{...W.options,status:void 0}),J=this.#V.get(Z);else this.#Q[J]=q;return q}#q(Z){if(!this.#C)return!1;let J=Z;return!!J&&J instanceof Promise&&J.hasOwnProperty("__staleWhileFetching")&&J.__abortController instanceof UL}async fetch(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:Y=this.updateAgeOnGet,noDeleteOnStaleGet:$=this.noDeleteOnStaleGet,ttl:Q=this.ttl,noDisposeOnSet:K=this.noDisposeOnSet,size:W=0,sizeCalculation:G=this.sizeCalculation,noUpdateTTL:V=this.noUpdateTTL,noDeleteOnFetchRejection:z=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:F=this.allowStaleOnFetchRejection,ignoreFetchAbort:H=this.ignoreFetchAbort,allowStaleOnFetchAbort:q=this.allowStaleOnFetchAbort,context:U,forceRefresh:B=!1,status:L,signal:w}=J;if(!this.#C){if(L)L.fetch="get";return this.get(Z,{allowStale:X,updateAgeOnGet:Y,noDeleteOnStaleGet:$,status:L})}let M={allowStale:X,updateAgeOnGet:Y,noDeleteOnStaleGet:$,ttl:Q,noDisposeOnSet:K,size:W,sizeCalculation:G,noUpdateTTL:V,noDeleteOnFetchRejection:z,allowStaleOnFetchRejection:F,allowStaleOnFetchAbort:q,ignoreFetchAbort:H,status:L,signal:w},N=this.#V.get(Z);if(N===void 0){if(L)L.fetch="miss";let R=this.#h(Z,N,M,U);return R.__returned=R}else{let R=this.#Q[N];if(this.#q(R)){let k=X&&R.__staleWhileFetching!==void 0;if(L){if(L.fetch="inflight",k)L.returnedStale=!0}return k?R.__staleWhileFetching:R.__returned=R}let P=this.#P(N);if(!B&&!P){if(L)L.fetch="hit";if(this.#b(N),Y)this.#A(N);if(L)this.#D(L,N);return R}let D=this.#h(Z,N,M,U),T=D.__staleWhileFetching!==void 0&&X;if(L){if(L.fetch=P?"stale":"refresh",T&&P)L.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.#F;if(!X)throw new Error("no memoMethod provided to constructor");let{context:Y,forceRefresh:$,...Q}=J,K=this.get(Z,Q);if(!$&&K!==void 0)return K;let W=X(Z,K,{options:Q,context:Y});return this.set(Z,W,Q),W}get(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:Y=this.updateAgeOnGet,noDeleteOnStaleGet:$=this.noDeleteOnStaleGet,status:Q}=J,K=this.#V.get(Z);if(K!==void 0){let W=this.#Q[K],G=this.#q(W);if(Q)this.#D(Q,K);if(this.#P(K)){if(Q)Q.get="stale";if(!G){if(!$)this.#S(Z,"expire");if(Q&&X)Q.returnedStale=!0;return X?W:void 0}else{if(Q&&X&&W.__staleWhileFetching!==void 0)Q.returnedStale=!0;return X?W.__staleWhileFetching:void 0}}else{if(Q)Q.get="hit";if(G)return W.__staleWhileFetching;if(this.#b(K),Y)this.#A(K);return W}}else if(Q)Q.get="miss"}#c(Z,J){this.#L[J]=Z,this.#U[Z]=J}#b(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.#S(Z,"delete")}#S(Z,J){let X=!1;if(this.#W!==0){let Y=this.#V.get(Z);if(Y!==void 0)if(X=!0,this.#W===1)this.#g(J);else{this.#x(Y);let $=this.#Q[Y];if(this.#q($))$.__abortController.abort(new Error("deleted"));else if(this.#N||this.#w){if(this.#N)this.#Y?.($,Z,J);if(this.#w)this.#M?.push([$,Z,J])}if(this.#V.delete(Z),this.#H[Y]=void 0,this.#Q[Y]=void 0,Y===this.#O)this.#O=this.#L[Y];else if(Y===this.#B)this.#B=this.#U[Y];else{let Q=this.#L[Y];this.#U[Q]=this.#U[Y];let K=this.#U[Y];this.#L[K]=this.#L[Y]}this.#W--,this.#k.push(Y)}}if(this.#w&&this.#M?.length){let Y=this.#M,$;while($=Y?.shift())this.#$?.(...$)}return X}clear(){return this.#g("delete")}#g(Z){for(let J of this.#I({allowStale:!0})){let X=this.#Q[J];if(this.#q(X))X.__abortController.abort(new Error("deleted"));else{let Y=this.#H[J];if(this.#N)this.#Y?.(X,Y,Z);if(this.#w)this.#M?.push([X,Y,Z])}}if(this.#V.clear(),this.#Q.fill(void 0),this.#H.fill(void 0),this.#R&&this.#j)this.#R.fill(0),this.#j.fill(0);if(this.#E)this.#E.fill(0);if(this.#B=0,this.#O=0,this.#k.length=0,this.#G=0,this.#W=0,this.#w&&this.#M){let J=this.#M,X;while(X=J?.shift())this.#$?.(...X)}}}import{posix as nN1,win32 as _T}from"node:path";import{fileURLToPath as aN1}from"node:url";import{lstatSync as sN1,readdir as oN1,readdirSync as rN1,readlinkSync as tN1,realpathSync as eN1}from"fs";import*as ZR1 from"node:fs";import{lstat as XR1,readdir as YR1,readlink as $R1,realpath as QR1}from"node:fs/promises";import{EventEmitter as TT}from"node:events";import Qa from"node:stream";import{StringDecoder as yN1}from"node:string_decoder";var Ja=typeof process==="object"&&process?process:{stdout:null,stderr:null},bN1=(Z)=>!!Z&&typeof Z==="object"&&(Z instanceof P$||Z instanceof Qa||gN1(Z)||mN1(Z)),gN1=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof TT&&typeof Z.pipe==="function"&&Z.pipe!==Qa.Writable.prototype.pipe,mN1=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof TT&&typeof Z.write==="function"&&typeof Z.end==="function",gZ=Symbol("EOF"),mZ=Symbol("maybeEmitEnd"),MX=Symbol("emittedEnd"),BL=Symbol("emittingEnd"),oV=Symbol("emittedError"),LL=Symbol("closed"),Xa=Symbol("read"),wL=Symbol("flush"),Ya=Symbol("flushChunk"),l4=Symbol("encoding"),QW=Symbol("decoder"),Z6=Symbol("flowing"),rV=Symbol("paused"),KW=Symbol("resume"),J6=Symbol("buffer"),$5=Symbol("pipes"),X6=Symbol("bufferLength"),RT=Symbol("bufferPush"),OL=Symbol("bufferShift"),h6=Symbol("objectMode"),C8=Symbol("destroyed"),jT=Symbol("error"),DT=Symbol("emitData"),$a=Symbol("emitEnd"),PT=Symbol("emitEnd2"),S7=Symbol("async"),CT=Symbol("abort"),ML=Symbol("aborted"),tV=Symbol("signal"),D$=Symbol("dataListeners"),Q9=Symbol("discarded"),eV=(Z)=>Promise.resolve().then(Z),uN1=(Z)=>Z(),dN1=(Z)=>Z==="end"||Z==="finish"||Z==="prefinish",cN1=(Z)=>Z instanceof ArrayBuffer||!!Z&&typeof Z==="object"&&Z.constructor&&Z.constructor.name==="ArrayBuffer"&&Z.byteLength>=0,lN1=(Z)=>!Buffer.isBuffer(Z)&&ArrayBuffer.isView(Z);class kT{src;dest;opts;ondrain;constructor(Z,J,X){this.src=Z,this.dest=J,this.opts=X,this.ondrain=()=>Z[KW](),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 Ka extends kT{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(Z,J,X){super(Z,J,X);this.proxyErrors=(Y)=>J.emit("error",Y),Z.on("error",this.proxyErrors)}}var pN1=(Z)=>!!Z.objectMode,iN1=(Z)=>!Z.objectMode&&!!Z.encoding&&Z.encoding!=="buffer";class P$ extends TT{[Z6]=!1;[rV]=!1;[$5]=[];[J6]=[];[h6];[l4];[S7];[QW];[gZ]=!1;[MX]=!1;[BL]=!1;[LL]=!1;[oV]=null;[X6]=0;[C8]=!1;[tV];[ML]=!1;[D$]=0;[Q9]=!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(pN1(J))this[h6]=!0,this[l4]=null;else if(iN1(J))this[l4]=J.encoding,this[h6]=!1;else this[h6]=!1,this[l4]=null;if(this[S7]=!!J.async,this[QW]=this[l4]?new yN1(this[l4]):null,J&&J.debugExposeBuffer===!0)Object.defineProperty(this,"buffer",{get:()=>this[J6]});if(J&&J.debugExposePipes===!0)Object.defineProperty(this,"pipes",{get:()=>this[$5]});let{signal:X}=J;if(X)if(this[tV]=X,X.aborted)this[CT]();else X.addEventListener("abort",()=>this[CT]())}get bufferLength(){return this[X6]}get encoding(){return this[l4]}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[h6]}set objectMode(Z){throw new Error("objectMode must be set at instantiation time")}get["async"](){return this[S7]}set["async"](Z){this[S7]=this[S7]||!!Z}[CT](){this[ML]=!0,this.emit("abort",this[tV]?.reason),this.destroy(this[tV]?.reason)}get aborted(){return this[ML]}set aborted(Z){}write(Z,J,X){if(this[ML])return!1;if(this[gZ])throw new Error("write after end");if(this[C8])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 Y=this[S7]?eV:uN1;if(!this[h6]&&!Buffer.isBuffer(Z)){if(lN1(Z))Z=Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength);else if(cN1(Z))Z=Buffer.from(Z);else if(typeof Z!=="string")throw new Error("Non-contiguous data written to non-objectMode stream")}if(this[h6]){if(this[Z6]&&this[X6]!==0)this[wL](!0);if(this[Z6])this.emit("data",Z);else this[RT](Z);if(this[X6]!==0)this.emit("readable");if(X)Y(X);return this[Z6]}if(!Z.length){if(this[X6]!==0)this.emit("readable");if(X)Y(X);return this[Z6]}if(typeof Z==="string"&&!(J===this[l4]&&!this[QW]?.lastNeed))Z=Buffer.from(Z,J);if(Buffer.isBuffer(Z)&&this[l4])Z=this[QW].write(Z);if(this[Z6]&&this[X6]!==0)this[wL](!0);if(this[Z6])this.emit("data",Z);else this[RT](Z);if(this[X6]!==0)this.emit("readable");if(X)Y(X);return this[Z6]}read(Z){if(this[C8])return null;if(this[Q9]=!1,this[X6]===0||Z===0||Z&&Z>this[X6])return this[mZ](),null;if(this[h6])Z=null;if(this[J6].length>1&&!this[h6])this[J6]=[this[l4]?this[J6].join(""):Buffer.concat(this[J6],this[X6])];let J=this[Xa](Z||null,this[J6][0]);return this[mZ](),J}[Xa](Z,J){if(this[h6])this[OL]();else{let X=J;if(Z===X.length||Z===null)this[OL]();else if(typeof X==="string")this[J6][0]=X.slice(Z),J=X.slice(0,Z),this[X6]-=Z;else this[J6][0]=X.subarray(Z),J=X.subarray(0,Z),this[X6]-=Z}if(this.emit("data",J),!this[J6].length&&!this[gZ])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[gZ]=!0,this.writable=!1,this[Z6]||!this[rV])this[mZ]();return this}[KW](){if(this[C8])return;if(!this[D$]&&!this[$5].length)this[Q9]=!0;if(this[rV]=!1,this[Z6]=!0,this.emit("resume"),this[J6].length)this[wL]();else if(this[gZ])this[mZ]();else this.emit("drain")}resume(){return this[KW]()}pause(){this[Z6]=!1,this[rV]=!0,this[Q9]=!1}get destroyed(){return this[C8]}get flowing(){return this[Z6]}get paused(){return this[rV]}[RT](Z){if(this[h6])this[X6]+=1;else this[X6]+=Z.length;this[J6].push(Z)}[OL](){if(this[h6])this[X6]-=1;else this[X6]-=this[J6][0].length;return this[J6].shift()}[wL](Z=!1){do;while(this[Ya](this[OL]())&&this[J6].length);if(!Z&&!this[J6].length&&!this[gZ])this.emit("drain")}[Ya](Z){return this.emit("data",Z),this[Z6]}pipe(Z,J){if(this[C8])return Z;this[Q9]=!1;let X=this[MX];if(J=J||{},Z===Ja.stdout||Z===Ja.stderr)J.end=!1;else J.end=J.end!==!1;if(J.proxyErrors=!!J.proxyErrors,X){if(J.end)Z.end()}else if(this[$5].push(!J.proxyErrors?new kT(this,Z,J):new Ka(this,Z,J)),this[S7])eV(()=>this[KW]());else this[KW]();return Z}unpipe(Z){let J=this[$5].find((X)=>X.dest===Z);if(J){if(this[$5].length===1){if(this[Z6]&&this[D$]===0)this[Z6]=!1;this[$5]=[]}else this[$5].splice(this[$5].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[Q9]=!1,this[D$]++,!this[$5].length&&!this[Z6])this[KW]()}else if(Z==="readable"&&this[X6]!==0)super.emit("readable");else if(dN1(Z)&&this[MX])super.emit(Z),this.removeAllListeners(Z);else if(Z==="error"&&this[oV]){let Y=J;if(this[S7])eV(()=>Y.call(this,this[oV]));else Y.call(this,this[oV])}return X}removeListener(Z,J){return this.off(Z,J)}off(Z,J){let X=super.off(Z,J);if(Z==="data"){if(this[D$]=this.listeners("data").length,this[D$]===0&&!this[Q9]&&!this[$5].length)this[Z6]=!1}return X}removeAllListeners(Z){let J=super.removeAllListeners(Z);if(Z==="data"||Z===void 0){if(this[D$]=0,!this[Q9]&&!this[$5].length)this[Z6]=!1}return J}get emittedEnd(){return this[MX]}[mZ](){if(!this[BL]&&!this[MX]&&!this[C8]&&this[J6].length===0&&this[gZ]){if(this[BL]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[LL])this.emit("close");this[BL]=!1}}emit(Z,...J){let X=J[0];if(Z!=="error"&&Z!=="close"&&Z!==C8&&this[C8])return!1;else if(Z==="data")return!this[h6]&&!X?!1:this[S7]?(eV(()=>this[DT](X)),!0):this[DT](X);else if(Z==="end")return this[$a]();else if(Z==="close"){if(this[LL]=!0,!this[MX]&&!this[C8])return!1;let $=super.emit("close");return this.removeAllListeners("close"),$}else if(Z==="error"){this[oV]=X,super.emit(jT,X);let $=!this[tV]||this.listeners("error").length?super.emit("error",X):!1;return this[mZ](),$}else if(Z==="resume"){let $=super.emit("resume");return this[mZ](),$}else if(Z==="finish"||Z==="prefinish"){let $=super.emit(Z);return this.removeAllListeners(Z),$}let Y=super.emit(Z,...J);return this[mZ](),Y}[DT](Z){for(let X of this[$5])if(X.dest.write(Z)===!1)this.pause();let J=this[Q9]?!1:super.emit("data",Z);return this[mZ](),J}[$a](){if(this[MX])return!1;return this[MX]=!0,this.readable=!1,this[S7]?(eV(()=>this[PT]()),!0):this[PT]()}[PT](){if(this[QW]){let J=this[QW].end();if(J){for(let X of this[$5])X.dest.write(J);if(!this[Q9])super.emit("data",J)}}for(let J of this[$5])J.end();let Z=super.emit("end");return this.removeAllListeners("end"),Z}async collect(){let Z=Object.assign([],{dataLength:0});if(!this[h6])Z.dataLength=0;let J=this.promise();return this.on("data",(X)=>{if(Z.push(X),!this[h6])Z.dataLength+=X.length}),await J,Z}async concat(){if(this[h6])throw new Error("cannot concat in objectMode");let Z=await this.collect();return this[l4]?Z.join(""):Buffer.concat(Z,Z.dataLength)}async promise(){return new Promise((Z,J)=>{this.on(C8,()=>J(new Error("stream destroyed"))),this.on("error",(X)=>J(X)),this.on("end",()=>Z())})}[Symbol.asyncIterator](){this[Q9]=!1;let Z=!1,J=async()=>{return this.pause(),Z=!0,{value:void 0,done:!0}};return{next:()=>{if(Z)return J();let Y=this.read();if(Y!==null)return Promise.resolve({done:!1,value:Y});if(this[gZ])return J();let $,Q,K=(z)=>{this.off("data",W),this.off("end",G),this.off(C8,V),J(),Q(z)},W=(z)=>{this.off("error",K),this.off("end",G),this.off(C8,V),this.pause(),$({value:z,done:!!this[gZ]})},G=()=>{this.off("error",K),this.off("data",W),this.off(C8,V),J(),$({done:!0,value:void 0})},V=()=>K(new Error("stream destroyed"));return new Promise((z,F)=>{Q=F,$=z,this.once(C8,V),this.once("error",K),this.once("end",G),this.once("data",W)})},throw:J,return:J,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Q9]=!1;let Z=!1,J=()=>{return this.pause(),this.off(jT,J),this.off(C8,J),this.off("end",J),Z=!0,{done:!0,value:void 0}},X=()=>{if(Z)return J();let Y=this.read();return Y===null?J():{done:!1,value:Y}};return this.once("end",J),this.once(jT,J),this.once(C8,J),{next:X,throw:J,return:J,[Symbol.iterator](){return this}}}destroy(Z){if(this[C8]){if(Z)this.emit("error",Z);else this.emit(C8);return this}this[C8]=!0,this[Q9]=!0,this[J6].length=0,this[X6]=0;let J=this;if(typeof J.close==="function"&&!this[LL])J.close();if(Z)this.emit("error",Z);else this.emit(C8);return this}static get isStream(){return bN1}}var JR1=eN1.native,Jz={lstatSync:sN1,readdir:oN1,readdirSync:rN1,readlinkSync:tN1,realpathSync:JR1,promises:{lstat:XR1,readdir:YR1,readlink:$R1,realpath:QR1}},Ha=(Z)=>!Z||Z===Jz||Z===ZR1?Jz:{...Jz,...Z,promises:{...Jz.promises,...Z.promises||{}}},Fa=/^\\\\\?\\([a-z]:)\\?$/i,KR1=(Z)=>Z.replace(/\//g,"\\").replace(Fa,"$1\\"),WR1=/[\\\/]/,l9=0,qa=1,Ua=2,A7=4,Ba=6,La=8,C$=10,wa=12,c9=15,Zz=~c9,ET=16,Wa=32,Xz=64,p4=128,NL=256,jL=512,Ga=Xz|p4|jL,GR1=1023,IT=(Z)=>Z.isFile()?La:Z.isDirectory()?A7:Z.isSymbolicLink()?C$:Z.isCharacterDevice()?Ua:Z.isBlockDevice()?Ba:Z.isSocket()?wa:Z.isFIFO()?qa:l9,Va=new Map,Yz=(Z)=>{let J=Va.get(Z);if(J)return J;let X=Z.normalize("NFKD");return Va.set(Z,X),X},za=new Map,RL=(Z)=>{let J=za.get(Z);if(J)return J;let X=Yz(Z.toLowerCase());return za.set(Z,X),X};class vT extends sV{constructor(){super({max:256})}}class Oa extends sV{constructor(Z=16384){super({maxSize:Z,sizeCalculation:(J)=>J.length+1})}}var Ma=Symbol("PathScurry setAsCwd");class Q5{name;root;roots;parent;nocase;isCWD=!1;#Z;#J;get dev(){return this.#J}#Y;get mode(){return this.#Y}#X;get nlink(){return this.#X}#$;get uid(){return this.#$}#z;get gid(){return this.#z}#F;get rdev(){return this.#F}#W;get blksize(){return this.#W}#G;get ino(){return this.#G}#V;get size(){return this.#V}#H;get blocks(){return this.#H}#Q;get atimeMs(){return this.#Q}#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}#M;get ctime(){return this.#M}#E;get birthtime(){return this.#E}#j;#R;#N;#C;#w;#_;#K;#A;#D;#v;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(Z,J=l9,X,Y,$,Q,K){if(this.name=Z,this.#j=$?RL(Z):Yz(Z),this.#K=J&GR1,this.nocase=$,this.roots=Y,this.root=X||this,this.#A=Q,this.#N=K.fullpath,this.#w=K.relative,this.#_=K.relativePosix,this.parent=K.parent,this.parent)this.#Z=this.parent.#Z;else this.#Z=Ha(K.fs)}depth(){if(this.#R!==void 0)return this.#R;if(!this.parent)return this.#R=0;return this.#R=this.parent.depth()+1}childrenCache(){return this.#A}resolve(Z){if(!Z)return this;let J=this.getRootString(Z),Y=Z.substring(J.length).split(this.splitSep);return J?this.getRoot(J).#P(Y):this.#P(Y)}#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.#K&=~ET,J}child(Z,J){if(Z===""||Z===".")return this;if(Z==="..")return this.parent||this;let X=this.children(),Y=this.nocase?RL(Z):Yz(Z);for(let W of X)if(W.#j===Y)return W;let $=this.parent?this.sep:"",Q=this.#N?this.#N+$+Z:void 0,K=this.newChild(Z,l9,{...J,parent:this,fullpath:Q});if(!this.canReaddir())K.#K|=p4;return X.push(K),K}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.#_!==void 0)return this.#_;let Z=this.name,J=this.parent;if(!J)return this.#_=this.fullpathPosix();let X=J.relativePosix();return X+(!X||!J.parent?"":"/")+Z}fullpath(){if(this.#N!==void 0)return this.#N;let Z=this.name,J=this.parent;if(!J)return this.#N=this.name;let Y=J.fullpath()+(!J.parent?"":this.sep)+Z;return this.#N=Y}fullpathPosix(){if(this.#C!==void 0)return this.#C;if(this.sep==="/")return this.#C=this.fullpath();if(!this.parent){let Y=this.fullpath().replace(/\\/g,"/");if(/^[a-z]:\//i.test(Y))return this.#C=`//?/${Y}`;else return this.#C=Y}let Z=this.parent,J=Z.fullpathPosix(),X=J+(!J||!Z.parent?"":"/")+this.name;return this.#C=X}isUnknown(){return(this.#K&c9)===l9}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.#K&c9)===La}isDirectory(){return(this.#K&c9)===A7}isCharacterDevice(){return(this.#K&c9)===Ua}isBlockDevice(){return(this.#K&c9)===Ba}isFIFO(){return(this.#K&c9)===qa}isSocket(){return(this.#K&c9)===wa}isSymbolicLink(){return(this.#K&C$)===C$}lstatCached(){return this.#K&Wa?this:void 0}readlinkCached(){return this.#D}realpathCached(){return this.#v}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.#K&c9;return!(Z!==l9&&Z!==C$||this.#K&NL||this.#K&p4)}calledReaddir(){return!!(this.#K&ET)}isENOENT(){return!!(this.#K&p4)}isNamed(Z){return!this.nocase?this.#j===Yz(Z):this.#j===RL(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.#y(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.#y(J.code);return}}#m(Z){this.#K|=ET;for(let J=Z.provisional;J<Z.length;J++){let X=Z[J];if(X)X.#x()}}#x(){if(this.#K&p4)return;this.#K=(this.#K|p4)&Zz,this.#f()}#f(){let Z=this.children();Z.provisional=0;for(let J of Z)J.#x()}#u(){this.#K|=jL,this.#T()}#T(){if(this.#K&Xz)return;let Z=this.#K;if((Z&c9)===A7)Z&=Zz;this.#K=Z|Xz,this.#f()}#I(Z=""){if(Z==="ENOTDIR"||Z==="EPERM")this.#T();else if(Z==="ENOENT")this.#x();else this.children().provisional=0}#d(Z=""){if(Z==="ENOTDIR")this.parent.#T();else if(Z==="ENOENT")this.#x()}#y(Z=""){let J=this.#K;if(J|=NL,Z==="ENOENT")J|=p4;if(Z==="EINVAL"||Z==="UNKNOWN")J&=Zz;if(this.#K=J,Z==="ENOTDIR"&&this.parent)this.parent.#T()}#h(Z,J){return this.#c(Z,J)||this.#q(Z,J)}#q(Z,J){let X=IT(Z),Y=this.newChild(Z.name,X,{parent:this}),$=Y.#K&c9;if($!==A7&&$!==C$&&$!==l9)Y.#K|=Xz;return J.unshift(Y),J.provisional++,Y}#c(Z,J){for(let X=J.provisional;X<J.length;X++){let Y=J[X];if((this.nocase?RL(Z.name):Yz(Z.name))!==Y.#j)continue;return this.#b(Z,Y,X,J)}}#b(Z,J,X,Y){let $=J.name;if(J.#K=J.#K&Zz|IT(Z),$!==Z.name)J.name=Z.name;if(X!==Y.provisional){if(X===Y.length-1)Y.pop();else Y.splice(X,1);Y.unshift(J)}return Y.provisional++,J}async lstat(){if((this.#K&p4)===0)try{return this.#S(await this.#Z.promises.lstat(this.fullpath())),this}catch(Z){this.#d(Z.code)}}lstatSync(){if((this.#K&p4)===0)try{return this.#S(this.#Z.lstatSync(this.fullpath())),this}catch(Z){this.#d(Z.code)}}#S(Z){let{atime:J,atimeMs:X,birthtime:Y,birthtimeMs:$,blksize:Q,blocks:K,ctime:W,ctimeMs:G,dev:V,gid:z,ino:F,mode:H,mtime:q,mtimeMs:U,nlink:B,rdev:L,size:w,uid:M}=Z;this.#O=J,this.#Q=X,this.#E=Y,this.#B=$,this.#W=Q,this.#H=K,this.#M=W,this.#L=G,this.#J=V,this.#z=z,this.#G=F,this.#Y=H,this.#k=q,this.#U=U,this.#X=B,this.#F=L,this.#V=w,this.#$=M;let N=IT(Z);if(this.#K=this.#K&Zz|N|Wa,N!==l9&&N!==A7&&N!==C$)this.#K|=Xz}#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 $=X.slice(0,X.provisional);if(J)Z(null,$);else queueMicrotask(()=>Z(null,$));return}if(this.#g.push(Z),this.#p)return;this.#p=!0;let Y=this.fullpath();this.#Z.readdir(Y,{withFileTypes:!0},($,Q)=>{if($)this.#I($.code),X.provisional=0;else{for(let K of Q)this.#h(K,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((Y)=>X=Y);try{for(let Y of await this.#Z.promises.readdir(J,{withFileTypes:!0}))this.#h(Y,Z);this.#m(Z)}catch(Y){this.#I(Y.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.#h(X,Z);this.#m(Z)}catch(X){this.#I(X.code),Z.provisional=0}return Z.slice(0,Z.provisional)}canReaddir(){if(this.#K&Ga)return!1;let Z=c9&this.#K;if(!(Z===l9||Z===A7||Z===C$))return!1;return!0}shouldWalk(Z,J){return(this.#K&A7)===A7&&!(this.#K&Ga)&&!Z.has(this)&&(!J||J(this))}async realpath(){if(this.#v)return this.#v;if((jL|NL|p4)&this.#K)return;try{let Z=await this.#Z.promises.realpath(this.fullpath());return this.#v=this.resolve(Z)}catch(Z){this.#u()}}realpathSync(){if(this.#v)return this.#v;if((jL|NL|p4)&this.#K)return;try{let Z=this.#Z.realpathSync(this.fullpath());return this.#v=this.resolve(Z)}catch(Z){this.#u()}}[Ma](Z){if(Z===this)return;Z.isCWD=!1,this.isCWD=!0;let J=new Set([]),X=[],Y=this;while(Y&&Y.parent)J.add(Y),Y.#w=X.join(this.sep),Y.#_=X.join("/"),Y=Y.parent,X.push("..");Y=Z;while(Y&&Y.parent&&!J.has(Y))Y.#w=void 0,Y.#_=void 0,Y=Y.parent}}class DL extends Q5{sep="\\";splitSep=WR1;constructor(Z,J=l9,X,Y,$,Q,K){super(Z,J,X,Y,$,Q,K)}newChild(Z,J=l9,X={}){return new DL(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}getRootString(Z){return _T.parse(Z).root}getRoot(Z){if(Z=KR1(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 $z(Z,this).root}sameRoot(Z,J=this.root.name){return Z=Z.toUpperCase().replace(/\//g,"\\").replace(Fa,"$1\\"),Z===J}}class PL extends Q5{splitSep="/";sep="/";constructor(Z,J=l9,X,Y,$,Q,K){super(Z,J,X,Y,$,Q,K)}getRootString(Z){return Z.startsWith("/")?"/":""}getRoot(Z){return this.root}newChild(Z,J=l9,X={}){return new PL(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}}class ST{root;rootPath;roots;cwd;#Z;#J;#Y;nocase;#X;constructor(Z=process.cwd(),J,X,{nocase:Y,childrenCacheSize:$=16384,fs:Q=Jz}={}){if(this.#X=Ha(Q),Z instanceof URL||Z.startsWith("file://"))Z=aN1(Z);let K=J.resolve(Z);this.roots=Object.create(null),this.rootPath=this.parseRootPath(K),this.#Z=new vT,this.#J=new vT,this.#Y=new Oa($);let W=K.substring(this.rootPath.length).split(X);if(W.length===1&&!W[0])W.pop();if(Y===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=Y,this.root=this.newRoot(this.#X),this.roots[this.rootPath]=this.root;let G=this.root,V=W.length-1,z=J.sep,F=this.rootPath,H=!1;for(let q of W){let U=V--;G=G.child(q,{relative:new Array(U).fill("..").join(z),relativePosix:new Array(U).fill("..").join("/"),fullpath:F+=(H?"":z)+q}),H=!0}this.cwd=G}depth(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.depth()}childrenCache(){return this.#Y}resolve(...Z){let J="";for(let $=Z.length-1;$>=0;$--){let Q=Z[$];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 Y=this.cwd.resolve(J).fullpath();return this.#Z.set(J,Y),Y}resolvePosix(...Z){let J="";for(let $=Z.length-1;$>=0;$--){let Q=Z[$];if(!Q||Q===".")continue;if(J=J?`${Q}/${J}`:Q,this.isAbsolute(Q))break}let X=this.#J.get(J);if(X!==void 0)return X;let Y=this.cwd.resolve(J).fullpathPosix();return this.#J.set(J,Y),Y}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 Q5))J=Z,Z=this.cwd;let{withFileTypes:X}=J;if(!Z.canReaddir())return[];else{let Y=await Z.readdir();return X?Y:Y.map(($)=>$.name)}}readdirSync(Z=this.cwd,J={withFileTypes:!0}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof Q5))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((Y)=>Y.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 Q5))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 Q5))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 Q5))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 Q5))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 Q5))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=[];if(!$||$(Z))K.push(X?Z:Z.fullpath());let W=new Set,G=(z,F)=>{W.add(z),z.readdirCB((H,q)=>{if(H)return F(H);let U=q.length;if(!U)return F();let B=()=>{if(--U===0)F()};for(let L of q){if(!$||$(L))K.push(X?L:L.fullpath());if(Y&&L.isSymbolicLink())L.realpath().then((w)=>w?.isUnknown()?w.lstat():w).then((w)=>w?.shouldWalk(W,Q)?G(w,B):B());else if(L.shouldWalk(W,Q))G(L,B);else B()}},!0)},V=Z;return new Promise((z,F)=>{G(V,(H)=>{if(H)return F(H);z(K)})})}walkSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof Q5))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=[];if(!$||$(Z))K.push(X?Z:Z.fullpath());let W=new Set([Z]);for(let G of W){let V=G.readdirSync();for(let z of V){if(!$||$(z))K.push(X?z:z.fullpath());let F=z;if(z.isSymbolicLink()){if(!(Y&&(F=z.realpathSync())))continue;if(F.isUnknown())F.lstatSync()}if(F.shouldWalk(W,Q))W.add(F)}}return K}[Symbol.asyncIterator](){return this.iterate()}iterate(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof Q5))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 Q5))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J;if(!$||$(Z))yield X?Z:Z.fullpath();let K=new Set([Z]);for(let W of K){let G=W.readdirSync();for(let V of G){if(!$||$(V))yield X?V:V.fullpath();let z=V;if(V.isSymbolicLink()){if(!(Y&&(z=V.realpathSync())))continue;if(z.isUnknown())z.lstatSync()}if(z.shouldWalk(K,Q))K.add(z)}}}stream(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof Q5))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=new P$({objectMode:!0});if(!$||$(Z))K.write(X?Z:Z.fullpath());let W=new Set,G=[Z],V=0,z=()=>{let F=!1;while(!F){let H=G.shift();if(!H){if(V===0)K.end();return}V++,W.add(H);let q=(B,L,w=!1)=>{if(B)return K.emit("error",B);if(Y&&!w){let M=[];for(let N of L)if(N.isSymbolicLink())M.push(N.realpath().then((R)=>R?.isUnknown()?R.lstat():R));if(M.length){Promise.all(M).then(()=>q(null,L,!0));return}}for(let M of L)if(M&&(!$||$(M))){if(!K.write(X?M:M.fullpath()))F=!0}V--;for(let M of L){let N=M.realpathCached()||M;if(N.shouldWalk(W,Q))G.push(N)}if(F&&!K.flowing)K.once("drain",z);else if(!U)z()},U=!0;H.readdirCB(q,!0),U=!1}};return z(),K}streamSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof Q5))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=new P$({objectMode:!0}),W=new Set;if(!$||$(Z))K.write(X?Z:Z.fullpath());let G=[Z],V=0,z=()=>{let F=!1;while(!F){let H=G.shift();if(!H){if(V===0)K.end();return}V++,W.add(H);let q=H.readdirSync();for(let U of q)if(!$||$(U)){if(!K.write(X?U:U.fullpath()))F=!0}V--;for(let U of q){let B=U;if(U.isSymbolicLink()){if(!(Y&&(B=U.realpathSync())))continue;if(B.isUnknown())B.lstatSync()}if(B.shouldWalk(W,Q))G.push(B)}}if(F&&!K.flowing)K.once("drain",z)};return z(),K}chdir(Z=this.cwd){let J=this.cwd;this.cwd=typeof Z==="string"?this.cwd.resolve(Z):Z,this.cwd[Ma](J)}}class $z extends ST{sep="\\";constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,_T,"\\",{...J,nocase:X});this.nocase=X;for(let Y=this.cwd;Y;Y=Y.parent)Y.nocase=this.nocase}parseRootPath(Z){return _T.parse(Z).root.toUpperCase()}newRoot(Z){return new DL(this.rootPath,A7,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")||Z.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(Z)}}class Qz extends ST{sep="/";constructor(Z=process.cwd(),J={}){let{nocase:X=!1}=J;super(Z,nN1,"/",{...J,nocase:X});this.nocase=X}parseRootPath(Z){return"/"}newRoot(Z){return new PL(this.rootPath,A7,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")}}class CL extends Qz{constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,{...J,nocase:X})}}var XA6=process.platform==="win32"?DL:PL,Na=process.platform==="win32"?$z:process.platform==="darwin"?CL:Qz;var VR1=(Z)=>Z.length>=1,zR1=(Z)=>Z.length>=1;class WW{#Z;#J;#Y;length;#X;#$;#z;#F;#W;#G;#V=!0;constructor(Z,J,X,Y){if(!VR1(Z))throw new TypeError("empty pattern list");if(!zR1(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.#J=J,this.#Y=X,this.#X=Y,this.#Y===0){if(this.isUNC()){let[$,Q,K,W,...G]=this.#Z,[V,z,F,H,...q]=this.#J;if(G[0]==="")G.shift(),q.shift();let U=[$,Q,K,W,""].join("/"),B=[V,z,F,H,""].join("/");this.#Z=[U,...G],this.#J=[B,...q],this.length=this.#Z.length}else if(this.isDrive()||this.isAbsolute()){let[$,...Q]=this.#Z,[K,...W]=this.#J;if(Q[0]==="")Q.shift(),W.shift();let G=$+"/",V=K+"/";this.#Z=[G,...Q],this.#J=[V,...W],this.length=this.#Z.length}}}pattern(){return this.#Z[this.#Y]}isString(){return typeof this.#Z[this.#Y]==="string"}isGlobstar(){return this.#Z[this.#Y]===M6}isRegExp(){return this.#Z[this.#Y]instanceof RegExp}globString(){return this.#z=this.#z||(this.#Y===0?this.isAbsolute()?this.#J[0]+this.#J.slice(1).join("/"):this.#J.join("/"):this.#J.slice(this.#Y).join("/"))}hasMore(){return this.length>this.#Y+1}rest(){if(this.#$!==void 0)return this.#$;if(!this.hasMore())return this.#$=null;return this.#$=new WW(this.#Z,this.#J,this.#Y+1,this.#X),this.#$.#G=this.#G,this.#$.#W=this.#W,this.#$.#F=this.#F,this.#$}isUNC(){let Z=this.#Z;return this.#W!==void 0?this.#W:this.#W=this.#X==="win32"&&this.#Y===0&&Z[0]===""&&Z[1]===""&&typeof Z[2]==="string"&&!!Z[2]&&typeof Z[3]==="string"&&!!Z[3]}isDrive(){let Z=this.#Z;return this.#F!==void 0?this.#F:this.#F=this.#X==="win32"&&this.#Y===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.#Y===0?Z:""}checkFollowGlobstar(){return!(this.#Y===0||!this.isGlobstar()||!this.#V)}markFollowGlobstar(){if(this.#Y===0||!this.isGlobstar()||!this.#V)return!1;return this.#V=!1,!0}}var HR1=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class Kz{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(Z,{nobrace:J,nocase:X,noext:Y,noglobstar:$,platform:Q=HR1}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=Q,this.mmopts={dot:!0,nobrace:J,nocase:X,noext:Y,noglobstar:$,optimizationLevel:2,platform:Q,nocomment:!0,nonegate:!0};for(let K of Z)this.add(K)}add(Z){let J=new d9(Z,this.mmopts);for(let X=0;X<J.set.length;X++){let Y=J.set[X],$=J.globParts[X];if(!Y||!$)throw new Error("invalid pattern object");while(Y[0]==="."&&$[0]===".")Y.shift(),$.shift();let Q=new WW(Y,$,0,this.platform),K=new d9(Q.globString(),this.mmopts),W=$[$.length-1]==="**",G=Q.isAbsolute();if(G)this.absolute.push(K);else this.relative.push(K);if(W)if(G)this.absoluteChildren.push(K);else this.relativeChildren.push(K)}}ignored(Z){let J=Z.fullpath(),X=`${J}/`,Y=Z.relative()||".",$=`${Y}/`;for(let Q of this.relative)if(Q.match(Y)||Q.match($))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 Y of this.relativeChildren)if(Y.match(X))return!0;for(let Y of this.absoluteChildren)if(Y.match(J))return!0;return!1}}class AT{store;constructor(Z=new Map){this.store=Z}copy(){return new AT(new Map(this.store))}hasWalked(Z,J){return this.store.get(Z.fullpath())?.has(J.globString())}storeWalked(Z,J){let X=Z.fullpath(),Y=this.store.get(X);if(Y)Y.add(J.globString());else this.store.set(X,new Set([J.globString()]))}}class Ra{store=new Map;add(Z,J,X){let Y=(J?2:0)|(X?1:0),$=this.store.get(Z);this.store.set(Z,$===void 0?Y:Y&$)}entries(){return[...this.store.entries()].map(([Z,J])=>[Z,!!(J&2),!!(J&1)])}}class ja{store=new Map;add(Z,J){if(!Z.canReaddir())return;let X=this.store.get(Z);if(X){if(!X.find((Y)=>Y.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 Wz{hasWalkedCache;matches=new Ra;subwalks=new ja;patterns;follow;dot;opts;constructor(Z,J){this.opts=Z,this.follow=!!Z.follow,this.dot=!!Z.dot,this.hasWalkedCache=J?J.copy():new AT}processPatterns(Z,J){this.patterns=J;let X=J.map((Y)=>[Z,Y]);for(let[Y,$]of X){this.hasWalkedCache.storeWalked(Y,$);let Q=$.root(),K=$.isAbsolute()&&this.opts.absolute!==!1;if(Q){Y=Y.resolve(Q==="/"&&this.opts.root!==void 0?this.opts.root:Q);let z=$.rest();if(!z){this.matches.add(Y,!0,!1);continue}else $=z}if(Y.isENOENT())continue;let W,G,V=!1;while(typeof(W=$.pattern())==="string"&&(G=$.rest()))Y=Y.resolve(W),$=G,V=!0;if(W=$.pattern(),G=$.rest(),V){if(this.hasWalkedCache.hasWalked(Y,$))continue;this.hasWalkedCache.storeWalked(Y,$)}if(typeof W==="string"){let z=W===".."||W===""||W===".";this.matches.add(Y.resolve(W),K,z);continue}else if(W===M6){if(!Y.isSymbolicLink()||this.follow||$.checkFollowGlobstar())this.subwalks.add(Y,$);let z=G?.pattern(),F=G?.rest();if(!G||(z===""||z===".")&&!F)this.matches.add(Y,K,z===""||z===".");else if(z===".."){let H=Y.parent||Y;if(!F)this.matches.add(H,K,!0);else if(!this.hasWalkedCache.hasWalked(H,F))this.subwalks.add(H,F)}}else if(W instanceof RegExp)this.subwalks.add(Y,$)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new Wz(this.opts,this.hasWalkedCache)}filterEntries(Z,J){let X=this.subwalks.get(Z),Y=this.child();for(let $ of J)for(let Q of X){let K=Q.isAbsolute(),W=Q.pattern(),G=Q.rest();if(W===M6)Y.testGlobstar($,Q,G,K);else if(W instanceof RegExp)Y.testRegExp($,W,G,K);else Y.testString($,W,G,K)}return Y}testGlobstar(Z,J,X,Y){if(this.dot||!Z.name.startsWith(".")){if(!J.hasMore())this.matches.add(Z,Y,!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 $=X.pattern();if(typeof $==="string"&&$!==".."&&$!==""&&$!==".")this.testString(Z,$,X.rest(),Y);else if($===".."){let Q=Z.parent||Z;this.subwalks.add(Q,X)}else if($ instanceof RegExp)this.testRegExp(Z,$,X.rest(),Y)}}testRegExp(Z,J,X,Y){if(!J.test(Z.name))return;if(!X)this.matches.add(Z,Y,!1);else this.subwalks.add(Z,X)}testString(Z,J,X,Y){if(!Z.isNamed(J))return;if(!X)this.matches.add(Z,Y,!1);else this.subwalks.add(Z,X)}}var FR1=(Z,J)=>typeof Z==="string"?new Kz([Z],J):Array.isArray(Z)?new Kz(Z,J):Z;class xT{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#Z=[];#J;#Y;signal;maxDepth;includeChildMatches;constructor(Z,J,X){if(this.patterns=Z,this.path=J,this.opts=X,this.#Y=!X.posix&&X.platform==="win32"?"\\":"/",this.includeChildMatches=X.includeChildMatches!==!1,X.ignore||!this.includeChildMatches){if(this.#J=FR1(X.ignore??[],X),!this.includeChildMatches&&typeof this.#J.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})}#X(Z){return this.seen.has(Z)||!!this.#J?.ignored?.(Z)}#$(Z){return!!this.#J?.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 $=Z.isUnknown()||this.opts.stat?await Z.lstat():Z;if(this.opts.follow&&this.opts.nodir&&$?.isSymbolicLink()){let Q=await $.realpath();if(Q&&(Q.isUnknown()||this.opts.stat))await Q.lstat()}return this.matchCheckTest($,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.#X(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 $=Z.isUnknown()||this.opts.stat?Z.lstatSync():Z;if(this.opts.follow&&this.opts.nodir&&$?.isSymbolicLink()){let Q=$.realpathSync();if(Q&&(Q?.isUnknown()||this.opts.stat))Q.lstatSync()}return this.matchCheckTest($,J)}matchFinish(Z,J){if(this.#X(Z))return;if(!this.includeChildMatches&&this.#J?.add){let $=`${Z.relativePosix()}/**`;this.#J.add($)}let X=this.opts.absolute===void 0?J:this.opts.absolute;this.seen.add(Z);let Y=this.opts.mark&&Z.isDirectory()?this.#Y:"";if(this.opts.withFileTypes)this.matchEmit(Z);else if(X){let $=this.opts.posix?Z.fullpathPosix():Z.fullpath();this.matchEmit($+Y)}else{let $=this.opts.posix?Z.relativePosix():Z.relative(),Q=this.opts.dotRelative&&!$.startsWith(".."+this.#Y)?"."+this.#Y:"";this.matchEmit(!$?"."+Y:Q+$+Y)}}async match(Z,J,X){let Y=await this.matchCheck(Z,X);if(Y)this.matchFinish(Y,J)}matchSync(Z,J,X){let Y=this.matchCheckSync(Z,X);if(Y)this.matchFinish(Y,J)}walkCB(Z,J,X){if(this.signal?.aborted)X();this.walkCB2(Z,J,new Wz(this.opts),X)}walkCB2(Z,J,X,Y){if(this.#$(Z))return Y();if(this.signal?.aborted)Y();if(this.paused){this.onResume(()=>this.walkCB2(Z,J,X,Y));return}X.processPatterns(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;$++,this.match(K,W,G).then(()=>Q())}for(let K of X.subwalkTargets()){if(this.maxDepth!==1/0&&K.depth()>=this.maxDepth)continue;$++;let W=K.readdirCached();if(K.calledReaddir())this.walkCB3(K,W,X,Q);else K.readdirCB((G,V)=>this.walkCB3(K,V,X,Q),!0)}Q()}walkCB3(Z,J,X,Y){X=X.filterEntries(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;$++,this.match(K,W,G).then(()=>Q())}for(let[K,W]of X.subwalks.entries())$++,this.walkCB2(K,W,X.child(),Q);Q()}walkCBSync(Z,J,X){if(this.signal?.aborted)X();this.walkCB2Sync(Z,J,new Wz(this.opts),X)}walkCB2Sync(Z,J,X,Y){if(this.#$(Z))return Y();if(this.signal?.aborted)Y();if(this.paused){this.onResume(()=>this.walkCB2Sync(Z,J,X,Y));return}X.processPatterns(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;this.matchSync(K,W,G)}for(let K of X.subwalkTargets()){if(this.maxDepth!==1/0&&K.depth()>=this.maxDepth)continue;$++;let W=K.readdirSync();this.walkCB3Sync(K,W,X,Q)}Q()}walkCB3Sync(Z,J,X,Y){X=X.filterEntries(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;this.matchSync(K,W,G)}for(let[K,W]of X.subwalks.entries())$++,this.walkCB2Sync(K,W,X.child(),Q);Q()}}class TL extends xT{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 kL extends xT{results;constructor(Z,J,X){super(Z,J,X);this.results=new P$({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 UR1=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class x7{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=qR1(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((W)=>W.replace(/\\/g,"/"));if(this.matchBase){if(J.noglobstar)throw new TypeError("base matching requires globstar");Z=Z.map((W)=>W.includes("/")?W:`./**/${W}`)}if(this.pattern=Z,this.platform=J.platform||UR1,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 W=J.platform==="win32"?$z:J.platform==="darwin"?CL:J.platform?Qz:Na;this.scurry=new W(this.cwd,{nocase:J.nocase,fs:J.fs})}this.nocase=this.scurry.nocase;let X=this.platform==="darwin"||this.platform==="win32",Y={...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},$=this.pattern.map((W)=>new d9(W,Y)),[Q,K]=$.reduce((W,G)=>{return W[0].push(...G.set),W[1].push(...G.globParts),W},[[],[]]);this.patterns=Q.map((W,G)=>{let V=K[G];if(!V)throw new Error("invalid pattern object");return new WW(W,V,0,this.platform)})}async walk(){return[...await new TL(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 TL(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 kL(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 kL(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 hT=(Z,J={})=>{if(!Array.isArray(Z))Z=[Z];for(let X of Z)if(new d9(X,J).hasMagic())return!0;return!1};function IL(Z,J={}){return new x7(Z,J).streamSync()}function Pa(Z,J={}){return new x7(Z,J).stream()}function Ca(Z,J={}){return new x7(Z,J).walkSync()}async function Da(Z,J={}){return new x7(Z,J).walk()}function _L(Z,J={}){return new x7(Z,J).iterateSync()}function Ta(Z,J={}){return new x7(Z,J).iterate()}var BR1=IL,LR1=Object.assign(Pa,{sync:IL}),wR1=_L,OR1=Object.assign(Ta,{sync:_L}),MR1=Object.assign(Ca,{stream:IL,iterate:_L}),EL=Object.assign(Da,{glob:Da,globSync:Ca,sync:MR1,globStream:Pa,stream:LR1,globStreamSync:IL,streamSync:BR1,globIterate:Ta,iterate:OR1,globIterateSync:_L,iterateSync:wR1,Glob:x7,hasMagic:hT,escape:XW,unescape:c4});EL.glob=EL;class fT{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 Y=this._listeners[Z];if(Y!==void 0){let $=Y.indexOf(J);if($!==-1)Y.splice($,1)}return this}dispatchEvent(Z){let X=this._listeners[Z.type];if(X!==void 0){let Y=X.slice(0);for(let $=0,Q=Y.length;$<Q;$++)Y[$].call(this,Z)}return this}dispose(){for(let Z in this._listeners)delete this._listeners[Z]}}class x5{constructor(Z,J,X,Y={}){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=Y,!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 GW extends fT{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,Y){let $=new x5(Z,J,X,Y);this._edges.add($);let Q=$.getParent();if(!this._parentEdges.has(Q))this._parentEdges.set(Q,new Set);this._parentEdges.get(Q).add($);let K=$.getChild();if(!this._childEdges.has(K))this._childEdges.set(K,new Set);return this._childEdges.get(K).add($),$}_destroyEdge(Z){return this._edges.delete(Z),this._parentEdges.get(Z.getParent()).delete(Z),this._childEdges.get(Z.getChild()).delete(Z),this}}function Gz(){return Gz=Object.assign||function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))Z[Y]=X[Y]}return Z},Gz.apply(this,arguments)}class f6{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 Y8{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 b0=Symbol("attributes"),i4=Symbol("immutableKeys");class VW extends fT{constructor(Z){super();this._disposed=!1,this.graph=void 0,this[b0]=void 0,this[i4]=void 0,this.graph=Z,this[i4]=new Set,this[b0]=this._createAttributes()}getDefaults(){return{}}_createAttributes(){let Z=this.getDefaults(),J={};for(let X in Z){let Y=Z[X];if(Y instanceof VW){let $=this.graph._createEdge(X,this,Y);this[i4].add(X),J[X]=$}else J[X]=Y}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[b0]){let Y=this[b0][X];if(Y instanceof x5){let $=Y;if($.getChild()===Z)this.setRef(X,J,$.getAttributes())}else if(Y instanceof f6)for(let $ of Y.listRefsByChild(Z)){let Q=$.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}else if(Y instanceof I0){let $=Y.getRefByChild(Z);if($){let Q=$.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}}else if(Y instanceof Y8)for(let $ of Y.keys()){let Q=Y.get($);if(Q.getChild()===Z)this.setRefMap(X,$,J,Q.getAttributes())}}return this}get(Z){return this[b0][Z]}set(Z,J){return this[b0][Z]=J,this.dispatchEvent({type:"change",attribute:Z})}getRef(Z){let J=this[b0][Z];return J?J.getChild():null}setRef(Z,J,X){if(this[i4].has(Z))throw new Error(`Cannot overwrite immutable attribute, "${Z}".`);let Y=this[b0][Z];if(Y)Y.dispose();if(!J)return this;let $=this.graph._createEdge(Z,this,J,X);return this[b0][Z]=$,this.dispatchEvent({type:"change",attribute:Z})}listRefs(Z){return this.assertRefList(Z).values().map((X)=>X.getChild())}addRef(Z,J,X){let Y=this.graph._createEdge(Z,this,J,X);return this.assertRefList(Z).add(Y),this.dispatchEvent({type:"change",attribute:Z})}removeRef(Z,J){let X=this.assertRefList(Z);if(X instanceof f6)for(let Y of X.listRefsByChild(J))Y.dispose();else{let Y=X.getRefByChild(J);if(Y)Y.dispose()}return this}assertRefList(Z){let J=this[b0][Z];if(J instanceof f6||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 Y=this.assertRefMap(Z).get(J);return Y?Y.getChild():null}setRefMap(Z,J,X,Y){let $=this.assertRefMap(Z),Q=$.get(J);if(Q)Q.dispose();if(!X)return this;Y=Object.assign(Y||{},{key:J});let K=this.graph._createEdge(Z,this,X,Gz({},Y,{key:J}));return $.set(J,K),this.dispatchEvent({type:"change",attribute:Z,key:J})}assertRefMap(Z){let J=this[b0][Z];if(J instanceof Y8)return J;throw new Error(`Expected RefMap for attribute "${Z}"`)}dispatchEvent(Z){return super.dispatchEvent(Gz({},Z,{target:this})),this.graph.dispatchEvent(Gz({},Z,{target:this,type:`node:${Z.type}`})),this}_destroyRef(Z){let J=Z.getName();if(this[b0][J]===Z){if(this[b0][J]=null,this[i4].has(J))Z.getChild().dispose()}else if(this[b0][J]instanceof f6)this[b0][J].remove(Z);else if(this[b0][J]instanceof I0)this[b0][J].remove(Z);else if(this[b0][J]instanceof Y8){let X=this[b0][J];for(let Y of X.keys())if(X.get(Y)===Z)X.delete(Y)}else return;this.graph._destroyEdge(Z),this.dispatchEvent({type:"change",attribute:J})}}var Aa="v4.1.1",fL="@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 yL;(function(Z){Z.INTERLEAVED="interleaved",Z.SEPARATE="separate"})(yL||(yL={}));var K9;(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"})(K9||(K9={}));var bL;(function(Z){Z[Z.R=4096]="R",Z[Z.G=256]="G",Z[Z.B=16]="B",Z[Z.A=1]="A"})(bL||(bL={}));var uZ;(function(Z){Z.GLTF="GLTF",Z.GLB="GLB"})(uZ||(uZ={}));var jX={"5120":Int8Array,"5121":Uint8Array,"5122":Int16Array,"5123":Uint16Array,"5125":Uint32Array,"5126":Float32Array},bT=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 NR1(){var Z=new bT(3);if(bT!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function yT(Z){var J=Z[0],X=Z[1],Y=Z[2];return Math.hypot(J,X,Y)}function RR1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=X[3]*Y+X[7]*$+X[11]*Q+X[15];return K=K||1,Z[0]=(X[0]*Y+X[4]*$+X[8]*Q+X[12])/K,Z[1]=(X[1]*Y+X[5]*$+X[9]*Q+X[13])/K,Z[2]=(X[2]*Y+X[6]*$+X[10]*Q+X[14])/K,Z}(function(){var Z=NR1();return function(J,X,Y,$,Q,K){var W,G;if(!X)X=3;if(!Y)Y=0;if($)G=Math.min($*X+Y,J.length);else G=J.length;for(W=Y;W<G;W+=X)Z[0]=J[W],Z[1]=J[W+1],Z[2]=J[W+2],Q(Z,Z,K),J[W]=Z[0],J[W+1]=Z[1],J[W+2]=Z[2];return J}})();function dT(Z){let J=xa(),X=Z.propertyType===s.NODE?[Z]:Z.listChildren();for(let Y of X)Y.traverse(($)=>{let Q=$.getMesh();if(!Q)return;let K=jR1(Q,$.getWorldMatrix());if(K.min.every(isFinite)&&K.max.every(isFinite))gT(K.min,J),gT(K.max,J)});return J}function jR1(Z,J){let X=xa();for(let Y of Z.listPrimitives()){let $=Y.getAttribute("POSITION"),Q=Y.getIndices();if(!$)continue;let K=[0,0,0],W=[0,0,0];for(let G=0,V=Q?Q.getCount():$.getCount();G<V;G++){let z=Q?Q.getScalar(G):G;K=$.getElement(z,K),W=RR1(W,K,J),gT(W,X)}}return X}function gT(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 xa(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}class a0{static createBufferFromDataURI(Z){if(typeof Buffer==="undefined"){let J=atob(Z.split(",")[1]),X=new Uint8Array(J.length);for(let Y=0;Y<J.length;Y++)X[Y]=J.charCodeAt(Y);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 $ of Z)J+=$.byteLength;let X=new Uint8Array(J),Y=0;for(let $ 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 Y=new Uint8Array(X);if(Y.set(Z),J!==0)for(let $=Z.byteLength;$<X;$++)Y[$]=J;return Y}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 cT{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^Y*255<<8^$*255<<0}static convertSRGBToLinear(Z,J){let X=Z,Y=J;for(let $=0;$<3;$++)Y[$]=X[$]<0.04045?X[$]*0.0773993808:Math.pow(X[$]*0.9478672986+0.0521327014,2.4);return J}static convertLinearToSRGB(Z,J){let X=Z,Y=J;for(let $=0;$<3;$++)Y[$]=X[$]<0.0031308?X[$]*12.92:1.055*Math.pow(X[$],0.41666)-0.055;return J}}class ha{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,Y;while(J.byteLength){if(X=J.getUint16(0,!1),DR1(J,X),Y=J.getUint8(X+1),Y===192||Y===193||Y===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 uL{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(a0.decodeText(Z.slice(12,16))===uL.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}}uL.PNG_FRIED_CHUNK_NAME="CgBI";class dZ{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,Y=4,$=this.getSize(Z,J);if(!$)return null;while($[0]>1||$[1]>1)X+=$[0]*$[1]*Y,$[0]=Math.max(Math.floor($[0]/2),1),$[1]=Math.max(Math.floor($[1]/2),1);return X+=1*Y,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}`}}dZ.impls={"image/jpeg":new ha,"image/png":new uL};function DR1(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 cZ{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 dZ.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 ka(Z){return Object.prototype.toString.call(Z)==="[object Object]"}function T$(Z){if(ka(Z)===!1)return!1;let J=Z.constructor;if(J===void 0)return!0;let X=J.prototype;if(ka(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}var mT,Vz;(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"})(Vz||(Vz={}));class f5{constructor(Z){this.verbosity=void 0,this.verbosity=Z}debug(Z){if(this.verbosity<=f5.Verbosity.DEBUG)console.debug(Z)}info(Z){if(this.verbosity<=f5.Verbosity.INFO)console.info(Z)}warn(Z){if(this.verbosity<=f5.Verbosity.WARN)console.warn(Z)}error(Z){if(this.verbosity<=f5.Verbosity.ERROR)console.error(Z)}}mT=f5;f5.Verbosity=Vz;f5.DEFAULT_INSTANCE=new mT(mT.Verbosity.INFO);function PR1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3],Q=Z[4],K=Z[5],W=Z[6],G=Z[7],V=Z[8],z=Z[9],F=Z[10],H=Z[11],q=Z[12],U=Z[13],B=Z[14],L=Z[15],w=J*K-X*Q,M=J*W-Y*Q,N=J*G-$*Q,R=X*W-Y*K,P=X*G-$*K,D=Y*G-$*W,C=V*U-z*q,T=V*B-F*q,k=V*L-H*q,A=z*B-F*U,v=z*L-H*U,x=F*L-H*B;return w*x-M*v+N*A+R*k-P*T+D*C}function CR1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=J[3],W=J[4],G=J[5],V=J[6],z=J[7],F=J[8],H=J[9],q=J[10],U=J[11],B=J[12],L=J[13],w=J[14],M=J[15],N=X[0],R=X[1],P=X[2],D=X[3];return Z[0]=N*Y+R*W+P*F+D*B,Z[1]=N*$+R*G+P*H+D*L,Z[2]=N*Q+R*V+P*q+D*w,Z[3]=N*K+R*z+P*U+D*M,N=X[4],R=X[5],P=X[6],D=X[7],Z[4]=N*Y+R*W+P*F+D*B,Z[5]=N*$+R*G+P*H+D*L,Z[6]=N*Q+R*V+P*q+D*w,Z[7]=N*K+R*z+P*U+D*M,N=X[8],R=X[9],P=X[10],D=X[11],Z[8]=N*Y+R*W+P*F+D*B,Z[9]=N*$+R*G+P*H+D*L,Z[10]=N*Q+R*V+P*q+D*w,Z[11]=N*K+R*z+P*U+D*M,N=X[12],R=X[13],P=X[14],D=X[15],Z[12]=N*Y+R*W+P*F+D*B,Z[13]=N*$+R*G+P*H+D*L,Z[14]=N*Q+R*V+P*q+D*w,Z[15]=N*K+R*z+P*U+D*M,Z}function TR1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[4],K=J[5],W=J[6],G=J[8],V=J[9],z=J[10];return Z[0]=Math.hypot(X,Y,$),Z[1]=Math.hypot(Q,K,W),Z[2]=Math.hypot(G,V,z),Z}function kR1(Z,J){var X=new bT(3);TR1(X,J);var Y=1/X[0],$=1/X[1],Q=1/X[2],K=J[0]*Y,W=J[1]*$,G=J[2]*Q,V=J[4]*Y,z=J[5]*$,F=J[6]*Q,H=J[8]*Y,q=J[9]*$,U=J[10]*Q,B=K+z+U,L=0;if(B>0)L=Math.sqrt(B+1)*2,Z[3]=0.25*L,Z[0]=(F-q)/L,Z[1]=(H-G)/L,Z[2]=(W-V)/L;else if(K>z&&K>U)L=Math.sqrt(1+K-z-U)*2,Z[3]=(F-q)/L,Z[0]=0.25*L,Z[1]=(W+V)/L,Z[2]=(H+G)/L;else if(z>U)L=Math.sqrt(1+z-K-U)*2,Z[3]=(H-G)/L,Z[0]=(W+V)/L,Z[1]=0.25*L,Z[2]=(F+q)/L;else L=Math.sqrt(1+U-K-z)*2,Z[3]=(W-V)/L,Z[0]=(H+G)/L,Z[1]=(F+q)/L,Z[2]=0.25*L;return Z}class l0{static identity(Z){return Z}static eq(Z,J,X=0.00001){if(Z.length!==J.length)return!1;for(let Y=0;Y<Z.length;Y++)if(Math.abs(Z[Y]-J[Y])>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(l0.clamp(Z,0,1)*65535);case 5121:return Math.round(l0.clamp(Z,0,1)*255);case 5122:return Math.round(l0.clamp(Z,-1,1)*32767);case 5120:return Math.round(l0.clamp(Z,-1,1)*127);default:throw new Error("Invalid component type.")}}static decompose(Z,J,X,Y){let $=yT([Z[0],Z[1],Z[2]]),Q=yT([Z[4],Z[5],Z[6]]),K=yT([Z[8],Z[9],Z[10]]);if(PR1(Z)<0)$=-$;J[0]=Z[12],J[1]=Z[13],J[2]=Z[14];let G=Z.slice(),V=1/$,z=1/Q,F=1/K;G[0]*=V,G[1]*=V,G[2]*=V,G[4]*=z,G[5]*=z,G[6]*=z,G[8]*=F,G[9]*=F,G[10]*=F,kR1(X,G),Y[0]=$,Y[1]=Q,Y[2]=K}static compose(Z,J,X,Y){let $=Y,Q=J[0],K=J[1],W=J[2],G=J[3],V=Q+Q,z=K+K,F=W+W,H=Q*V,q=Q*z,U=Q*F,B=K*z,L=K*F,w=W*F,M=G*V,N=G*z,R=G*F,P=X[0],D=X[1],C=X[2];return $[0]=(1-(B+w))*P,$[1]=(q+R)*P,$[2]=(U-N)*P,$[3]=0,$[4]=(q-R)*D,$[5]=(1-(H+w))*D,$[6]=(L+M)*D,$[7]=0,$[8]=(U+N)*C,$[9]=(L-M)*C,$[10]=(1-(H+B))*C,$[11]=0,$[12]=Z[0],$[13]=Z[1],$[14]=Z[2],$[15]=1,$}}function ER1(Z,J){if(!!Z!==!!J)return!1;let X=Z.getChild(),Y=J.getChild();return X===Y||X.equals(Y)}function IR1(Z,J){if(!!Z!==!!J)return!1;let X=Z.values(),Y=J.values();if(X.length!==Y.length)return!1;for(let $=0;$<X.length;$++){let Q=X[$],K=Y[$];if(Q.getChild()===K.getChild())continue;if(!Q.getChild().equals(K.getChild()))return!1}return!0}function _R1(Z,J){if(!!Z!==!!J)return!1;let X=Z.keys(),Y=J.keys();if(X.length!==Y.length)return!1;for(let $ of X){let Q=Z.get($),K=J.get($);if(!!Q!==!!K)return!1;let W=Q.getChild(),G=K.getChild();if(W===G)continue;if(!W.equals(G))return!1}return!0}function fa(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 ya(Z,J){if(Z===J)return!0;if(!!Z!==!!J)return!1;if(!T$(Z)||!T$(J))return Z===J;let X=Z,Y=J,$=0,Q=0,K;for(K in X)$++;for(K in Y)Q++;if($!==Q)return!1;for(K in X){let W=X[K],G=Y[K];if(gL(W)&&gL(G)){if(!fa(W,G))return!1}else if(T$(W)&&T$(G)){if(!ya(W,G))return!1}else if(W!==G)return!1}return!0}function gL(Z){return Array.isArray(Z)||ArrayBuffer.isView(Z)}var Ea="23456789abdegjkmnpqrvwxyzABDEGJKMNPQRVWXYZ",vR1=999,SR1=6,Ia=new Set,AR1=function Z(){let J="";for(let X=0;X<SR1;X++)J+=Ea.charAt(Math.floor(Math.random()*Ea.length));return J},ba=function Z(){for(let J=0;J<vR1;J++){let X=AR1();if(!Ia.has(X))return Ia.add(X),X}return""},_a="https://null.example";class p9{static dirname(Z){let J=Z.lastIndexOf("/");if(J===-1)return"./";return Z.substring(0,J+1)}static basename(Z){return cZ.basename(new URL(Z,_a).pathname)}static extension(Z){return cZ.extension(new URL(Z,_a).pathname)}static resolve(Z,J){if(!this.isRelativePath(J))return J;let X=Z.split("/"),Y=J.split("/");X.pop();for(let $=0;$<Y.length;$++){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)}}p9.DEFAULT_INIT={};p9.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;var RX=(Z)=>Z,xR1=new Set;class dL extends VW{constructor(Z,J=""){super(Z);this[b0].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,RX)}copy(Z,J=RX){for(let X in this[b0]){let Y=this[b0][X];if(Y instanceof x5){if(!this[i4].has(X))Y.dispose()}else if(Y instanceof f6||Y instanceof I0)for(let $ of Y.values())$.dispose();else if(Y instanceof Y8)for(let $ of Y.values())$.dispose()}for(let X in Z[b0]){let Y=this[b0][X],$=Z[b0][X];if($ instanceof x5)if(this[i4].has(X))Y.getChild().copy(J($.getChild()),J);else this.setRef(X,J($.getChild()),$.getAttributes());else if($ instanceof I0||$ instanceof f6)for(let Q of $.values())this.addRef(X,J(Q.getChild()),Q.getAttributes());else if($ instanceof Y8)for(let Q of $.keys()){let K=$.get(Q);this.setRefMap(X,Q,J(K.getChild()),K.getAttributes())}else if(T$($))this[b0][X]=JSON.parse(JSON.stringify($));else if(Array.isArray($)||$ instanceof ArrayBuffer||ArrayBuffer.isView($))this[b0][X]=$.slice();else this[b0][X]=$}return this}equals(Z,J=xR1){if(this===Z)return!0;if(this.propertyType!==Z.propertyType)return!1;for(let X in this[b0]){if(J.has(X))continue;let Y=this[b0][X],$=Z[b0][X];if(Y instanceof x5||$ instanceof x5){if(!ER1(Y,$))return!1}else if(Y instanceof I0||$ instanceof I0||Y instanceof f6||$ instanceof f6){if(!IR1(Y,$))return!1}else if(Y instanceof Y8||$ instanceof Y8){if(!_R1(Y,$))return!1}else if(T$(Y)||T$($)){if(!ya(Y,$))return!1}else if(gL(Y)||gL($)){if(!fa(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 b6 extends dL{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new Y8})}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 x0 extends b6{init(){this.propertyType=s.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:x0.Type.SCALAR,componentType:x0.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(Z){switch(Z){case x0.Type.SCALAR:return 1;case x0.Type.VEC2:return 2;case x0.Type.VEC3:return 3;case x0.Type.VEC4:return 4;case x0.Type.MAT2:return 4;case x0.Type.MAT3:return 9;case x0.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+Z)}}static getComponentSize(Z){switch(Z){case x0.ComponentType.BYTE:return 1;case x0.ComponentType.UNSIGNED_BYTE:return 1;case x0.ComponentType.SHORT:return 2;case x0.ComponentType.UNSIGNED_SHORT:return 2;case x0.ComponentType.UNSIGNED_INT:return 4;case x0.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+Z)}}getMinNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMin(Z),J)for(let $=0;$<X;$++)Z[$]=l0.decodeNormalizedInt(Z[$],Y);return Z}getMin(Z){let J=this.getArray(),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.min(Z[Q],K)}return Z}getMaxNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMax(Z),J)for(let $=0;$<X;$++)Z[$]=l0.decodeNormalizedInt(Z[$],Y);return Z}getMax(Z){let J=this.get("array"),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=-1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.max(Z[Q],K)}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 x0.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(),Y=this.getArray();if(this.getNormalized())return l0.decodeNormalizedInt(Y[Z*J],X);return Y[Z*J]}setScalar(Z,J){let X=this.getElementSize(),Y=this.getComponentType(),$=this.getArray();if(this.getNormalized())$[Z*X]=l0.encodeNormalizedInt(J,Y);else $[Z*X]=J;return this}getElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)J[K]=l0.decodeNormalizedInt(Q[Z*Y+K],$);else J[K]=Q[Z*Y+K];return J}setElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)Q[Z*Y+K]=l0.encodeNormalizedInt(J[K],$);else Q[Z*Y+K]=J[K];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?hR1(Z):x0.ComponentType.FLOAT),this.set("array",Z),this}getByteLength(){let Z=this.get("array");return Z?Z.byteLength:0}}x0.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};x0.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};function hR1(Z){switch(Z.constructor){case Float32Array:return x0.ComponentType.FLOAT;case Uint32Array:return x0.ComponentType.UNSIGNED_INT;case Uint16Array:return x0.ComponentType.UNSIGNED_SHORT;case Uint8Array:return x0.ComponentType.UNSIGNED_BYTE;case Int16Array:return x0.ComponentType.SHORT;case Int8Array:return x0.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}class lT extends b6{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 k$ extends b6{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)}}k$.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class zW extends b6{init(){this.propertyType=s.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:zW.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:K9.OTHER})}getOutput(){return this.getRef("output")}setOutput(Z){return this.setRef("output",Z,{usage:K9.OTHER})}}zW.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class pT extends b6{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 E$ extends b6{init(){this.propertyType=s.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:E$.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)}}E$.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class HW extends dL{_validateParent(Z){if(!this.parentTypes.includes(Z.propertyType))throw new Error(`Parent "${Z.propertyType}" invalid for child "${this.propertyType}".`)}}HW.EXTENSION_NAME=void 0;class h5 extends b6{init(){this.propertyType=s.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:h5.WrapMode.REPEAT,wrapT:h5.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)}}h5.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};h5.MagFilter={NEAREST:9728,LINEAR:9729};h5.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};var{R:vL,G:SL,B:AL,A:fR1}=bL;class h7 extends b6{init(){this.propertyType=s.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:h7.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new h5(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new h5(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new h5(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new h5(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new h5(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:vL|SL|AL|fR1,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:vL|SL|AL,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:vL|SL|AL})}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:vL})}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:SL|AL})}}h7.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class Hz extends b6{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 cL extends b6{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=RX){if(J===RX)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 l0.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(Z){let J=this.get("translation").slice(),X=this.get("rotation").slice(),Y=this.get("scale").slice();return l0.decompose(Z,J,X,Y),this.set("translation",J).set("rotation",X).set("scale",Y)}getWorldTranslation(){let Z=[0,0,0];return l0.decompose(this.getWorldMatrix(),Z,[0,0,0,1],[1,1,1]),Z}getWorldRotation(){let Z=[0,0,0,1];return l0.decompose(this.getWorldMatrix(),[0,0,0],Z,[1,1,1]),Z}getWorldScale(){let Z=[1,1,1];return l0.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],Z),Z}getWorldMatrix(){let Z=[];for(let Y=this;Y!=null;Y=Y.getParentNode())Z.push(Y);let J,X=Z.pop().getMatrix();while(J=Z.pop())CR1(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 T8 extends b6{init(){this.propertyType=s.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:T8.Mode.TRIANGLES,material:null,indices:null,attributes:new Y8,targets:new I0})}getIndices(){return this.getRef("indices")}setIndices(Z){return this.setRef("indices",Z,{usage:K9.ELEMENT_ARRAY_BUFFER})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:K9.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)}}T8.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class iT extends dL{init(){this.propertyType=s.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new Y8})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:K9.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function K5(){return K5=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},K5.apply(null,arguments)}class FW extends b6{init(){this.propertyType=s.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:new I0})}copy(Z,J=RX){if(J===RX)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 nT extends b6{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:K9.INVERSE_BIND_MATRICES})}addJoint(Z){return this.addRef("joints",Z)}removeJoint(Z){return this.removeRef("joints",Z)}listJoints(){return this.listRefs("joints")}}class I$ extends b6{init(){this.propertyType=s.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||dZ.extensionToMimeType(cZ.extension(this.get("uri")))}setMimeType(Z){return this.set("mimeType",Z)}getURI(){return this.get("uri")}setURI(Z){this.set("uri",Z);let J=dZ.extensionToMimeType(cZ.extension(Z));if(J)this.set("mimeType",J);return this}getImage(){return this.get("image")}setImage(Z){return this.set("image",a0.assertView(Z))}getSize(){let Z=this.get("image");if(!Z)return null;return dZ.getSize(Z,this.getMimeType())}}class _$ extends b6{init(){this.propertyType=s.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${Aa}`,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=RX){if(J===RX)throw new Error("Root cannot be copied.");this.set("asset",K5({},Z.get("asset"))),this.setName(Z.getName()),this.setExtras(K5({},Z.getExtras())),this.setDefaultScene(Z.getDefaultScene()?J(Z.getDefaultScene()):null);for(let X of Z.listRefMapKeys("extensions")){let Y=Z.getExtension(X);this.setExtension(X,J(Y))}return this}_addChildOfRoot(Z){if(Z instanceof FW)this.addRef("scenes",Z);else if(Z instanceof cL)this.addRef("nodes",Z);else if(Z instanceof E$)this.addRef("cameras",Z);else if(Z instanceof nT)this.addRef("skins",Z);else if(Z instanceof Hz)this.addRef("meshes",Z);else if(Z instanceof h7)this.addRef("materials",Z);else if(Z instanceof I$)this.addRef("textures",Z);else if(Z instanceof lT)this.addRef("animations",Z);else if(Z instanceof x0)this.addRef("accessors",Z);else if(Z instanceof pT)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 y6{static fromGraph(Z){return y6._GRAPH_DOCUMENTS.get(Z)||null}constructor(){this._graph=new GW,this._root=new _$(this._graph),this._logger=f5.DEFAULT_INSTANCE,y6._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((Y)=>Y.extensionName===J)||new Z(this)}createScene(Z=""){return new FW(this._graph,Z)}createNode(Z=""){return new cL(this._graph,Z)}createCamera(Z=""){return new E$(this._graph,Z)}createSkin(Z=""){return new nT(this._graph,Z)}createMesh(Z=""){return new Hz(this._graph,Z)}createPrimitive(){return new T8(this._graph)}createPrimitiveTarget(Z=""){return new iT(this._graph,Z)}createMaterial(Z=""){return new h7(this._graph,Z)}createTexture(Z=""){return new I$(this._graph,Z)}createAnimation(Z=""){return new lT(this._graph,Z)}createAnimationChannel(Z=""){return new k$(this._graph,Z)}createAnimationSampler(Z=""){return new zW(this._graph,Z)}createAccessor(Z="",J=null){if(!J)J=this.getRoot().listBuffers()[0];return new x0(this._graph,Z).setBuffer(J)}createBuffer(Z=""){return new pT(this._graph,Z)}}y6._GRAPH_DOCUMENTS=new WeakMap;class ga{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 Y=X,$=Y.target;if($ instanceof HW&&$.extensionName===this.extensionName){if(Y.type==="node:create")this._addExtensionProperty($);if(Y.type==="node:dispose")this._removeExtensionProperty($)}};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}}ga.EXTENSION_NAME=void 0;class ma{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 Y=this.jsonDoc.json.samplers[X.sampler];if(Y.magFilter!==void 0)Z.setMagFilter(Y.magFilter);if(Y.minFilter!==void 0)Z.setMinFilter(Y.minFilter);if(Y.wrapS!==void 0)Z.setWrapS(Y.wrapS);if(Y.wrapT!==void 0)Z.setWrapT(Y.wrapT)}}var va={logger:f5.DEFAULT_INSTANCE,extensions:[],dependencies:{}},yR1=new Set([s.BUFFER,s.TEXTURE,s.MATERIAL,s.MESH,s.PRIMITIVE,s.NODE,s.SCENE]);class ua{static read(Z,J=va){let X=K5({},va,J),{json:Y}=Z,$=new y6().setLogger(X.logger);this.validate(Z,X);let Q=new ma(Z),K=Y.asset,W=$.getRoot().getAsset();if(K.copyright)W.copyright=K.copyright;if(K.extras)W.extras=K.extras;if(Y.extras!==void 0)$.getRoot().setExtras(K5({},Y.extras));let G=Y.extensionsUsed||[],V=Y.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=$.createExtension(D).setRequired(V.includes(D.EXTENSION_NAME)),T=C.prereadTypes.filter((k)=>!yR1.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 z=Y.buffers||[];$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.BUFFER)).forEach((D)=>D.preread(Q,s.BUFFER)),Q.buffers=z.map((D)=>{let C=$.createBuffer(D.name);if(D.extras)C.setExtras(D.extras);if(D.uri&&D.uri.indexOf("__")!==0)C.setURI(D.uri);return C});let F=Y.bufferViews||[];Q.bufferViewBuffers=F.map((D,C)=>{if(!Q.bufferViews[C]){let T=Z.json.buffers[D.buffer],k=T.uri?Z.resources[T.uri]:Z.resources[fL],A=D.byteOffset||0;Q.bufferViews[C]=a0.toView(k,A,D.byteLength)}return Q.buffers[D.buffer]});let H=Y.accessors||[];Q.accessors=H.map((D)=>{let C=Q.bufferViewBuffers[D.bufferView],T=$.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(hL(D,Q)),T});let q=Y.images||[],U=Y.textures||[];$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.TEXTURE)).forEach((D)=>D.preread(Q,s.TEXTURE)),Q.textures=q.map((D)=>{let C=$.createTexture(D.name);if(D.extras)C.setExtras(D.extras);if(D.bufferView!==void 0){let T=Y.bufferViews[D.bufferView],k=Z.json.buffers[T.buffer],A=k.uri?Z.resources[k.uri]:Z.resources[fL],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=cZ.extension(D.uri);C.setMimeType(dZ.extensionToMimeType(T))}return C}),$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.MATERIAL)).forEach((D)=>D.preread(Q,s.MATERIAL));let B=Y.materials||[];Q.materials=B.map((D)=>{let C=$.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}),$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.MESH)).forEach((D)=>D.preread(Q,s.MESH));let L=Y.meshes||[];$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.PRIMITIVE)).forEach((D)=>D.preread(Q,s.PRIMITIVE)),Q.meshes=L.map((D)=>{let C=$.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=$.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,_]of Object.entries(k.attributes||{}))A.setAttribute(I,Q.accessors[_]);if(k.indices!==void 0)A.setIndices(Q.accessors[k.indices]);let v=D.extras&&D.extras.targetNames||[];(k.targets||[]).forEach((I,_)=>{let b=v[_]||_.toString(),u=$.createPrimitiveTarget(b);for(let[i,e]of Object.entries(I))u.setAttribute(i,Q.accessors[e]);A.addTarget(u)}),C.addPrimitive(A)}),C});let w=Y.cameras||[];Q.cameras=w.map((D)=>{let C=$.createCamera(D.name).setType(D.type);if(D.extras)C.setExtras(D.extras);if(D.type===E$.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 M=Y.nodes||[];$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.NODE)).forEach((D)=>D.preread(Q,s.NODE)),Q.nodes=M.map((D)=>{let C=$.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];l0.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 N=Y.skins||[];Q.skins=N.map((D)=>{let C=$.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}),M.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 R=Y.animations||[];Q.animations=R.map((D)=>{let C=$.createAnimation(D.name);if(D.extras)C.setExtras(D.extras);let k=(D.samplers||[]).map((v)=>{let x=$.createAnimationSampler().setInput(Q.accessors[v.input]).setOutput(Q.accessors[v.output]).setInterpolation(v.interpolation||zW.Interpolation.LINEAR);if(v.extras)x.setExtras(v.extras);return C.addSampler(x),x});return(D.channels||[]).forEach((v)=>{let x=$.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=Y.scenes||[];if($.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.SCENE)).forEach((D)=>D.preread(Q,s.SCENE)),Q.scenes=P.map((D)=>{let C=$.createScene(D.name);if(D.extras)C.setExtras(D.extras);return(D.nodes||[]).map((k)=>Q.nodes[k]).forEach((k)=>C.addChild(k)),C}),Y.scene!==void 0)$.getRoot().setDefaultScene(Q.scenes[Y.scene]);return $.getRoot().listExtensionsUsed().forEach((D)=>D.read(Q)),H.forEach((D,C)=>{let T=Q.accessors[C],k=!!D.sparse,A=!D.bufferView&&!T.getArray();if(k||A)T.setSparse(!0).setArray(gR1(D,Q))}),$}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 Y of X.extensionsRequired)if(!J.extensions.find(($)=>$.EXTENSION_NAME===Y))throw new Error(`Missing required extension, "${Y}".`)}if(X.extensionsUsed){for(let Y of X.extensionsUsed)if(!J.extensions.find(($)=>$.EXTENSION_NAME===Y))J.logger.warn(`Missing optional extension, "${Y}".`)}}}function bR1(Z,J){let X=J.jsonDoc,Y=J.bufferViews[Z.bufferView],$=X.json.bufferViews[Z.bufferView],Q=jX[Z.componentType],K=x0.getElementSize(Z.type),W=Q.BYTES_PER_ELEMENT,G=Z.byteOffset||0,V=new Q(Z.count*K),z=new DataView(Y.buffer,Y.byteOffset,Y.byteLength),F=$.byteStride;for(let H=0;H<Z.count;H++)for(let q=0;q<K;q++){let U=G+H*F+q*W,B;switch(Z.componentType){case x0.ComponentType.FLOAT:B=z.getFloat32(U,!0);break;case x0.ComponentType.UNSIGNED_INT:B=z.getUint32(U,!0);break;case x0.ComponentType.UNSIGNED_SHORT:B=z.getUint16(U,!0);break;case x0.ComponentType.UNSIGNED_BYTE:B=z.getUint8(U);break;case x0.ComponentType.SHORT:B=z.getInt16(U,!0);break;case x0.ComponentType.BYTE:B=z.getInt8(U);break;default:throw new Error(`Unexpected componentType "${Z.componentType}".`)}V[H*K+q]=B}return V}function hL(Z,J){let X=J.jsonDoc,Y=J.bufferViews[Z.bufferView],$=X.json.bufferViews[Z.bufferView],Q=jX[Z.componentType],K=x0.getElementSize(Z.type),W=Q.BYTES_PER_ELEMENT,G=K*W;if($.byteStride!==void 0&&$.byteStride!==G)return bR1(Z,J);let V=Y.byteOffset+(Z.byteOffset||0),z=Z.count*K*W;return new Q(Y.buffer.slice(V,V+z))}function gR1(Z,J){let X=jX[Z.componentType],Y=x0.getElementSize(Z.type),$;if(Z.bufferView!==void 0)$=hL(Z,J);else $=new X(Z.count*Y);let Q=Z.sparse;if(!Q)return $;let K=Q.count,W=K5({},Z,Q.indices,{count:K,type:"SCALAR"}),G=K5({},Z,Q.values,{count:K}),V=hL(W,J),z=hL(G,J);for(let F=0;F<W.count;F++)for(let H=0;H<Y;H++)$[V[F]*Y+H]=z[F*Y+H];return $}var zz;(function(Z){Z[Z.ARRAY_BUFFER=34962]="ARRAY_BUFFER",Z[Z.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"})(zz||(zz={}));class NX{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 Y=Z.getRoot(),$=Y.listBuffers().length,Q=Y.listTextures().length;this.bufferURIGenerator=new uT($>1,()=>X.basename||"buffer"),this.imageURIGenerator=new uT(Q>1,(K)=>mR1(Z,K)||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()},Y=JSON.stringify(X);if(!this.samplerDefIndexMap.has(Y))this.samplerDefIndexMap.set(Y,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(X);let $={source:this.imageIndexMap.get(Z),sampler:this.samplerDefIndexMap.get(Y)},Q=JSON.stringify($);if(!this.textureDefIndexMap.has(Q))this.textureDefIndexMap.set(Q,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push($);let K={index:this.textureDefIndexMap.get(Q)};if(J.getTexCoord()!==0)K.texCoord=J.getTexCoord();if(Object.keys(J.getExtras()).length>0)K.extras=J.getExtras();return this.textureInfoDefMap.set(J,K),K}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((Y)=>Y.getName()==="attributes"&&Y.getAttributes().key==="POSITION"||Y.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===uZ.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 Y=dZ.mimeTypeToExtension(X.getMimeType());Z.uri=this.imageURIGenerator.createURI(X,Y),this.assignResourceURI(Z.uri,J,!1)}}assignResourceURI(Z,J,X){let Y=this.jsonDoc.resources;if(!(Z in Y)){Y[Z]=J;return}if(J===Y[Z]){this.logger.warn(`Duplicate resource URI, "${Z}".`);return}let $=`Resource URI "${Z}" already assigned to different data.`;if(!X){this.logger.warn($);return}throw new Error($)}getAccessorUsage(Z){let J=this._accessorUsageMap.get(Z);if(J)return J;if(Z.getSparse())return K9.SPARSE;for(let X of this._doc.getGraph().listParentEdges(Z)){let{usage:Y}=X.getAttributes();if(Y)return Y;if(X.getParent().propertyType!==s.ROOT)this.logger.warn(`Missing attribute ".usage" on edge, "${X.getName()}".`)}return K9.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}}NX.BufferViewTarget=zz;NX.BufferViewUsage=K9;NX.USAGE_TO_TARGET={[K9.ARRAY_BUFFER]:zz.ARRAY_BUFFER,[K9.ELEMENT_ARRAY_BUFFER]:zz.ELEMENT_ARRAY_BUFFER};class uT{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 mR1(Z,J){let X=Z.getGraph().listParentEdges(J).find((Y)=>Y.getParent()!==Z.getRoot());return X?X.getName().replace(/texture$/i,""):""}var{BufferViewUsage:xL}=NX,{UNSIGNED_INT:uR1,UNSIGNED_SHORT:dR1,UNSIGNED_BYTE:cR1}=x0.ComponentType,lR1=new Set([s.ACCESSOR,s.BUFFER,s.MATERIAL,s.MESH]);class da{static write(Z,J){let X=Z.getGraph(),Y=Z.getRoot(),$={asset:K5({generator:`glTF-Transform ${Aa}`},Y.getAsset()),extras:K5({},Y.getExtras())},Q={json:$,resources:{}},K=new NX(Z,Q,J),W=J.logger||f5.DEFAULT_INSTANCE,G=new Set(J.extensions.map((L)=>L.EXTENSION_NAME)),V=Z.getRoot().listExtensionsUsed().filter((L)=>G.has(L.extensionName)).sort((L,w)=>L.extensionName>w.extensionName?1:-1),z=Z.getRoot().listExtensionsRequired().filter((L)=>G.has(L.extensionName)).sort((L,w)=>L.extensionName>w.extensionName?1:-1);if(V.length<Z.getRoot().listExtensionsUsed().length)W.warn("Some extensions were not registered for I/O, and will not be written.");for(let L of V){let w=L.prewriteTypes.filter((M)=>!lR1.has(M));if(w.length)W.warn(`Prewrite hooks for some types (${w.join()}), requested by extension ${L.extensionName}, are unsupported. Please file an issue or a PR.`);for(let M of L.writeDependencies)L.install(M,J.dependencies[M])}function F(L,w,M,N){let R=[],P=0;for(let T of L){let k=K.createAccessorDef(T);k.bufferView=$.bufferViews.length;let A=T.getArray(),v=a0.pad(a0.toView(A));k.byteOffset=P,P+=v.byteLength,R.push(v),K.accessorIndexMap.set(T,$.accessors.length),$.accessors.push(k)}let D=a0.concat(R),C={buffer:w,byteOffset:M,byteLength:D.byteLength};if(N)C.target=N;return $.bufferViews.push(C),{buffers:R,byteLength:P}}function H(L,w,M){let N=L[0].getCount(),R=0;for(let k of L){let A=K.createAccessorDef(k);A.bufferView=$.bufferViews.length,A.byteOffset=R;let v=k.getElementSize(),x=k.getComponentSize();R+=a0.padNumber(v*x),K.accessorIndexMap.set(k,$.accessors.length),$.accessors.push(A)}let P=N*R,D=new ArrayBuffer(P),C=new DataView(D);for(let k=0;k<N;k++){let A=0;for(let v of L){let x=v.getElementSize(),I=v.getComponentSize(),_=v.getComponentType(),b=v.getArray();for(let u=0;u<x;u++){let i=k*R+A+u*I,e=b[k*x+u];switch(_){case x0.ComponentType.FLOAT:C.setFloat32(i,e,!0);break;case x0.ComponentType.BYTE:C.setInt8(i,e);break;case x0.ComponentType.SHORT:C.setInt16(i,e,!0);break;case x0.ComponentType.UNSIGNED_BYTE:C.setUint8(i,e);break;case x0.ComponentType.UNSIGNED_SHORT:C.setUint16(i,e,!0);break;case x0.ComponentType.UNSIGNED_INT:C.setUint32(i,e,!0);break;default:throw new Error("Unexpected component type: "+_)}}A+=a0.padNumber(x*I)}}let T={buffer:w,byteOffset:M,byteLength:P,byteStride:R,target:NX.BufferViewTarget.ARRAY_BUFFER};return $.bufferViews.push(T),{byteLength:P,buffers:[new Uint8Array(D)]}}function q(L,w,M){let N=[],R=0,P=new Map,D=-1/0,C=!1;for(let _ of L){let b=K.createAccessorDef(_);$.accessors.push(b),K.accessorIndexMap.set(_,$.accessors.length-1);let u=[],i=[],e=[],Z0=new Array(_.getElementSize()).fill(0);for(let s0=0,x8=_.getCount();s0<x8;s0++){if(_.getElement(s0,e),l0.eq(e,Z0,0))continue;D=Math.max(s0,D),u.push(s0);for(let J8=0;J8<e.length;J8++)i.push(e[J8])}let K0=u.length,S0={accessorDef:b,count:K0};if(P.set(_,S0),K0===0)continue;if(K0>_.getCount()/2)C=!0;let A0=jX[_.getComponentType()];S0.indices=u,S0.values=new A0(i)}if(!Number.isFinite(D))return{buffers:N,byteLength:R};if(C)W.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?cR1:D<65535?dR1:uR1,A={buffer:w,byteOffset:M+R,byteLength:0};for(let _ of L){let b=P.get(_);if(b.count===0)continue;b.indicesByteOffset=A.byteLength;let u=a0.pad(a0.toView(new T(b.indices)));N.push(u),R+=u.byteLength,A.byteLength+=u.byteLength}$.bufferViews.push(A);let v=$.bufferViews.length-1,x={buffer:w,byteOffset:M+R,byteLength:0};for(let _ of L){let b=P.get(_);if(b.count===0)continue;b.valuesByteOffset=x.byteLength;let u=a0.pad(a0.toView(b.values));N.push(u),R+=u.byteLength,x.byteLength+=u.byteLength}$.bufferViews.push(x);let I=$.bufferViews.length-1;for(let _ of L){let b=P.get(_);if(b.count===0)continue;b.accessorDef.sparse={count:b.count,indices:{bufferView:v,byteOffset:b.indicesByteOffset,componentType:k},values:{bufferView:I,byteOffset:b.valuesByteOffset}}}return{buffers:N,byteLength:R}}if($.accessors=[],$.bufferViews=[],$.samplers=[],$.textures=[],$.images=Y.listTextures().map((L,w)=>{let M=K.createPropertyDef(L);if(L.getMimeType())M.mimeType=L.getMimeType();let N=L.getImage();if(N)K.createImageData(M,N,L);return K.imageIndexMap.set(L,w),M}),V.filter((L)=>L.prewriteTypes.includes(s.ACCESSOR)).forEach((L)=>L.prewrite(K,s.ACCESSOR)),Y.listAccessors().forEach((L)=>{let{accessorUsageGroupedByParent:w,accessorParents:M}=K;if(K.accessorIndexMap.has(L))return;let N=K.getAccessorUsage(L);if(K.addAccessorToUsageGroup(L,N),w.has(N)){let R=X.listParents(L).find((P)=>P.propertyType!==s.ROOT);M.set(L,R)}}),V.filter((L)=>L.prewriteTypes.includes(s.BUFFER)).forEach((L)=>L.prewrite(K,s.BUFFER)),(Y.listAccessors().length>0||K.otherBufferViews.size>0||Y.listTextures().length>0&&J.format===uZ.GLB)&&Y.listBuffers().length===0)throw new Error("Buffer required for Document resources, but none was found.");if($.buffers=[],Y.listBuffers().forEach((L,w)=>{let M=K.createPropertyDef(L),N=K.accessorUsageGroupedByParent,R=L.listParents().filter((x)=>x instanceof x0),P=new Set(R.map((x)=>K.accessorParents.get(x))),D=new Map(Array.from(P).map((x,I)=>[x,I])),C={};for(let x of R){var T;if(K.accessorIndexMap.has(x))continue;let I=K.getAccessorUsage(x),_=I;if(N.has(I)){let b=K.accessorParents.get(x);_+=`:${D.get(b)}`}C[T=_]||(C[T]={usage:I,accessors:[]}),C[_].accessors.push(x)}let k=[],A=$.buffers.length,v=0;for(let{usage:x,accessors:I}of Object.values(C))if(x===xL.ARRAY_BUFFER&&J.vertexLayout===yL.INTERLEAVED){let _=H(I,A,v);v+=_.byteLength;for(let b of _.buffers)k.push(b)}else if(x===xL.ARRAY_BUFFER)for(let _ of I){let b=H([_],A,v);v+=b.byteLength;for(let u of b.buffers)k.push(u)}else if(x===xL.SPARSE){let _=q(I,A,v);v+=_.byteLength;for(let b of _.buffers)k.push(b)}else if(x===xL.ELEMENT_ARRAY_BUFFER){let _=NX.BufferViewTarget.ELEMENT_ARRAY_BUFFER,b=F(I,A,v,_);v+=b.byteLength;for(let u of b.buffers)k.push(u)}else{let _=F(I,A,v);v+=_.byteLength;for(let b of _.buffers)k.push(b)}if(K.imageBufferViews.length&&w===0){for(let x=0;x<K.imageBufferViews.length;x++)if($.bufferViews[$.images[x].bufferView].byteOffset=v,v+=K.imageBufferViews[x].byteLength,k.push(K.imageBufferViews[x]),v%8){let I=8-v%8;v+=I,k.push(new Uint8Array(I))}}if(K.otherBufferViews.has(L))for(let x of K.otherBufferViews.get(L))$.bufferViews.push({buffer:A,byteOffset:v,byteLength:x.byteLength}),K.otherBufferViewsIndexMap.set(x,$.bufferViews.length-1),v+=x.byteLength,k.push(x);if(v){let x;if(J.format===uZ.GLB)x=fL;else x=K.bufferURIGenerator.createURI(L,"bin"),M.uri=x;M.byteLength=v,K.assignResourceURI(x,a0.concat(k),!0)}$.buffers.push(M),K.bufferIndexMap.set(L,w)}),Y.listAccessors().find((L)=>!L.getBuffer()))W.warn("Skipped writing one or more Accessors: no Buffer assigned.");V.filter((L)=>L.prewriteTypes.includes(s.MATERIAL)).forEach((L)=>L.prewrite(K,s.MATERIAL)),$.materials=Y.listMaterials().map((L,w)=>{let M=K.createPropertyDef(L);if(L.getAlphaMode()!==h7.AlphaMode.OPAQUE)M.alphaMode=L.getAlphaMode();if(L.getAlphaMode()===h7.AlphaMode.MASK)M.alphaCutoff=L.getAlphaCutoff();if(L.getDoubleSided())M.doubleSided=!0;if(M.pbrMetallicRoughness={},!l0.eq(L.getBaseColorFactor(),[1,1,1,1]))M.pbrMetallicRoughness.baseColorFactor=L.getBaseColorFactor();if(!l0.eq(L.getEmissiveFactor(),[0,0,0]))M.emissiveFactor=L.getEmissiveFactor();if(L.getRoughnessFactor()!==1)M.pbrMetallicRoughness.roughnessFactor=L.getRoughnessFactor();if(L.getMetallicFactor()!==1)M.pbrMetallicRoughness.metallicFactor=L.getMetallicFactor();if(L.getBaseColorTexture()){let N=L.getBaseColorTexture(),R=L.getBaseColorTextureInfo();M.pbrMetallicRoughness.baseColorTexture=K.createTextureInfoDef(N,R)}if(L.getEmissiveTexture()){let N=L.getEmissiveTexture(),R=L.getEmissiveTextureInfo();M.emissiveTexture=K.createTextureInfoDef(N,R)}if(L.getNormalTexture()){let N=L.getNormalTexture(),R=L.getNormalTextureInfo(),P=K.createTextureInfoDef(N,R);if(L.getNormalScale()!==1)P.scale=L.getNormalScale();M.normalTexture=P}if(L.getOcclusionTexture()){let N=L.getOcclusionTexture(),R=L.getOcclusionTextureInfo(),P=K.createTextureInfoDef(N,R);if(L.getOcclusionStrength()!==1)P.strength=L.getOcclusionStrength();M.occlusionTexture=P}if(L.getMetallicRoughnessTexture()){let N=L.getMetallicRoughnessTexture(),R=L.getMetallicRoughnessTextureInfo();M.pbrMetallicRoughness.metallicRoughnessTexture=K.createTextureInfoDef(N,R)}return K.materialIndexMap.set(L,w),M}),V.filter((L)=>L.prewriteTypes.includes(s.MESH)).forEach((L)=>L.prewrite(K,s.MESH)),$.meshes=Y.listMeshes().map((L,w)=>{let M=K.createPropertyDef(L),N=null;if(M.primitives=L.listPrimitives().map((R)=>{let P={attributes:{}};P.mode=R.getMode();let D=R.getMaterial();if(D)P.material=K.materialIndexMap.get(D);if(Object.keys(R.getExtras()).length)P.extras=R.getExtras();let C=R.getIndices();if(C)P.indices=K.accessorIndexMap.get(C);for(let T of R.listSemantics())P.attributes[T]=K.accessorIndexMap.get(R.getAttribute(T));for(let T of R.listTargets()){let k={};for(let A of T.listSemantics())k[A]=K.accessorIndexMap.get(T.getAttribute(A));P.targets=P.targets||[],P.targets.push(k)}if(R.listTargets().length&&!N)N=R.listTargets().map((T)=>T.getName());return P}),L.getWeights().length)M.weights=L.getWeights();if(N)M.extras=M.extras||{},M.extras.targetNames=N;return K.meshIndexMap.set(L,w),M}),$.cameras=Y.listCameras().map((L,w)=>{let M=K.createPropertyDef(L);if(M.type=L.getType(),M.type===E$.Type.PERSPECTIVE){M.perspective={znear:L.getZNear(),zfar:L.getZFar(),yfov:L.getYFov()};let N=L.getAspectRatio();if(N!==null)M.perspective.aspectRatio=N}else M.orthographic={znear:L.getZNear(),zfar:L.getZFar(),xmag:L.getXMag(),ymag:L.getYMag()};return K.cameraIndexMap.set(L,w),M}),$.nodes=Y.listNodes().map((L,w)=>{let M=K.createPropertyDef(L);if(!l0.eq(L.getTranslation(),[0,0,0]))M.translation=L.getTranslation();if(!l0.eq(L.getRotation(),[0,0,0,1]))M.rotation=L.getRotation();if(!l0.eq(L.getScale(),[1,1,1]))M.scale=L.getScale();if(L.getWeights().length)M.weights=L.getWeights();return K.nodeIndexMap.set(L,w),M}),$.skins=Y.listSkins().map((L,w)=>{let M=K.createPropertyDef(L),N=L.getInverseBindMatrices();if(N)M.inverseBindMatrices=K.accessorIndexMap.get(N);let R=L.getSkeleton();if(R)M.skeleton=K.nodeIndexMap.get(R);return M.joints=L.listJoints().map((P)=>K.nodeIndexMap.get(P)),K.skinIndexMap.set(L,w),M}),Y.listNodes().forEach((L,w)=>{let M=$.nodes[w],N=L.getMesh();if(N)M.mesh=K.meshIndexMap.get(N);let R=L.getCamera();if(R)M.camera=K.cameraIndexMap.get(R);let P=L.getSkin();if(P)M.skin=K.skinIndexMap.get(P);if(L.listChildren().length>0)M.children=L.listChildren().map((D)=>K.nodeIndexMap.get(D))}),$.animations=Y.listAnimations().map((L,w)=>{let M=K.createPropertyDef(L),N=new Map;return M.samplers=L.listSamplers().map((R,P)=>{let D=K.createPropertyDef(R);return D.input=K.accessorIndexMap.get(R.getInput()),D.output=K.accessorIndexMap.get(R.getOutput()),D.interpolation=R.getInterpolation(),N.set(R,P),D}),M.channels=L.listChannels().map((R)=>{let P=K.createPropertyDef(R);return P.sampler=N.get(R.getSampler()),P.target={node:K.nodeIndexMap.get(R.getTargetNode()),path:R.getTargetPath()},P}),K.animationIndexMap.set(L,w),M}),$.scenes=Y.listScenes().map((L,w)=>{let M=K.createPropertyDef(L);return M.nodes=L.listChildren().map((N)=>K.nodeIndexMap.get(N)),K.sceneIndexMap.set(L,w),M});let B=Y.getDefaultScene();if(B)$.scene=Y.listScenes().indexOf(B);return $.extensionsUsed=V.map((L)=>L.extensionName),$.extensionsRequired=z.map((L)=>L.extensionName),V.forEach((L)=>L.write(K)),pR1($),Q}}function pR1(Z){let J=[];for(let X in Z){let Y=Z[X];if(Array.isArray(Y)&&Y.length===0)J.push(X);else if(Y===null||Y==="")J.push(X);else if(Y&&typeof Y==="object"&&Object.keys(Y).length===0)J.push(X)}for(let X of J)delete Z[X]}var mL;(function(Z){Z[Z.JSON=1313821514]="JSON",Z[Z.BIN=5130562]="BIN"})(mL||(mL={}));class ca{constructor(){this._logger=f5.DEFAULT_INSTANCE,this._extensions=new Set,this._dependencies={},this._vertexLayout=yL.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=Sa(J)?this._binaryToJSON(J):{json:JSON.parse(a0.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),ua.read(Z,{extensions:Array.from(this._extensions),dependencies:this._dependencies,logger:this._logger})}async binaryToJSON(Z){let J=this._binaryToJSON(a0.assertView(Z));this._readResourcesInternal(J);let X=J.json;if(X.buffers&&X.buffers.some((Y)=>iR1(J,Y)))throw new Error("Cannot resolve external buffers with binaryToJSON().");else if(X.images&&X.images.some((Y)=>nR1(J,Y)))throw new Error("Cannot resolve external images with binaryToJSON().");return J}async readBinary(Z){return this.readJSON(await this.binaryToJSON(a0.assertView(Z)))}async writeJSON(Z,J={}){if(J.format===uZ.GLB&&Z.getRoot().listBuffers().length>1)throw new Error("GLB must have 0–1 buffers.");return da.write(Z,{format:J.format||uZ.GLTF,basename:J.basename||"",logger:this._logger,vertexLayout:this._vertexLayout,dependencies:K5({},this._dependencies),extensions:Array.from(this._extensions)})}async writeBinary(Z){let{json:J,resources:X}=await this.writeJSON(Z,{format:uZ.GLB}),Y=new Uint32Array([1179937895,2,12]),$=JSON.stringify(J),Q=a0.pad(a0.encodeText($),32),K=a0.toView(new Uint32Array([Q.byteLength,1313821514])),W=a0.concat([K,Q]);Y[Y.length-1]+=W.byteLength;let G=Object.values(X)[0];if(!G||!G.byteLength)return a0.concat([a0.toView(Y),W]);let V=a0.pad(G,0),z=a0.toView(new Uint32Array([V.byteLength,5130562])),F=a0.concat([z,V]);return Y[Y.length-1]+=F.byteLength,a0.concat([a0.toView(Y),W,F])}async _readResourcesExternal(Z,J){var X=this;let Y=Z.json.images||[],$=Z.json.buffers||[],Q=[...Y,...$].map(async function(K){let W=K.uri;if(!W||W.match(/data:/))return Promise.resolve();Z.resources[W]=await X.readURI(X.resolve(J,W),"view"),X.lastReadBytes+=Z.resources[W].byteLength});await Promise.all(Q)}_readResourcesInternal(Z){function J($){if(!$.uri)return;if($.uri in Z.resources){a0.assertView(Z.resources[$.uri]);return}if($.uri.match(/data:/)){let Q=`__${ba()}.${cZ.extension($.uri)}`;Z.resources[Q]=a0.createBufferFromDataURI($.uri),$.uri=Q}}(Z.json.images||[]).forEach(($)=>{if($.bufferView===void 0&&$.uri===void 0)throw new Error("Missing resource URI or buffer view.");J($)}),(Z.json.buffers||[]).forEach(J)}_copyJSON(Z){let{images:J,buffers:X}=Z.json;if(Z={json:K5({},Z.json),resources:K5({},Z.resources)},J)Z.json.images=J.map((Y)=>K5({},Y));if(X)Z.json.buffers=X.map((Y)=>K5({},Y));return Z}_binaryToJSON(Z){if(!Sa(Z))throw new Error("Invalid glTF 2.0 binary.");let J=new Uint32Array(Z.buffer,Z.byteOffset+12,2);if(J[1]!==mL.JSON)throw new Error("Missing required GLB JSON chunk.");let X=20,Y=J[0],$=a0.decodeText(a0.toView(Z,X,Y)),Q=JSON.parse($),K=X+Y;if(Z.byteLength<=K)return{json:Q,resources:{}};let W=new Uint32Array(Z.buffer,Z.byteOffset+K,2);if(W[1]!==mL.BIN)return{json:Q,resources:{}};let G=W[0],V=a0.toView(Z,K+8,G);return{json:Q,resources:{[fL]:V}}}}function iR1(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)}function nR1(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)&&J.bufferView===void 0}function Sa(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 aT extends ca{constructor(Z=null,J=p9.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(),p9.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(p9.isAbsoluteURL(Z)||p9.isAbsoluteURL(J))return p9.resolve(Z,J);return this._path.resolve(Z,decodeURIComponent(J))}dirname(Z){if(p9.isAbsoluteURL(Z))return p9.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:Y,resources:$}=await this.writeJSON(J,{format:uZ.GLTF,basename:cZ.basename(Z)}),{_fs:Q,_path:K}=this,W=K.dirname(Z),G=JSON.stringify(Y,null,2);await Q.writeFile(Z,G),this.lastWriteBytes+=G.length;for(let V of aR1(Object.keys($),10))await Promise.all(V.map(async function(z){if(p9.isAbsoluteURL(z)){if(p9.extension(z)==="bin")throw new Error(`Cannot write buffer to path "${z}".`);return}let F=K.join(W,decodeURIComponent(z));await Q.mkdir(K.dirname(F),{recursive:!0}),await Q.writeFile(F,$[z]),X.lastWriteBytes+=$[z].byteLength}))}async _writeGLB(Z,J){let X=await this.writeBinary(J);await this._fs.writeFile(Z,X),this.lastWriteBytes=X.byteLength}}function aR1(Z,J){let X=[];for(let Y=0,$=Z.length;Y<$;Y+=J){let Q=[];for(let K=0;K<J&&Y+K<$;K++)Q.push(Z[Y+K]);X.push(Q)}return X}var br=r(sT(),1),gr=r(Rr(),1),gT1=r(yr(),1);async function mT1(Z,J){if(!(Z instanceof Uint8Array))throw new Error("[ndarray-pixels] Input must be Uint8Array or Buffer.");let{data:X,info:Y}=await gr.default(Z).ensureAlpha().raw().toBuffer({resolveWithObject:!0});return br.default(new Uint8Array(X),[Y.width,Y.height,4],[4,4*Y.width|0,1],0)}async function mr(Z,J){return mT1(Z)}var uT1="v4.2.1",kk="@glb.bin",o;(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"})(o||(o={}));var ur;(function(Z){Z.INTERLEAVED="interleaved",Z.SEPARATE="separate"})(ur||(ur={}));var V9;(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"})(V9||(V9={}));var z9;(function(Z){Z[Z.R=4096]="R",Z[Z.G=256]="G",Z[Z.B=16]="B",Z[Z.A=1]="A"})(z9||(z9={}));var Rk;(function(Z){Z.GLTF="GLTF",Z.GLB="GLB"})(Rk||(Rk={}));class g6{static createBufferFromDataURI(Z){if(typeof Buffer==="undefined"){let J=atob(Z.split(",")[1]),X=new Uint8Array(J.length);for(let Y=0;Y<J.length;Y++)X[Y]=J.charCodeAt(Y);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 $ of Z)J+=$.byteLength;let X=new Uint8Array(J),Y=0;for(let $ 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 Y=new Uint8Array(X);if(Y.set(Z),J!==0)for(let $=Z.byteLength;$<X;$++)Y[$]=J;return Y}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 pr{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,Y;while(J.byteLength){if(X=J.getUint16(0,!1),dT1(J,X),Y=J.getUint8(X+1),Y===192||Y===193||Y===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 Mw{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(g6.decodeText(Z.slice(12,16))===Mw.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}}Mw.PNG_FRIED_CHUNK_NAME="CgBI";class a4{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,Y=4,$=this.getSize(Z,J);if(!$)return null;while($[0]>1||$[1]>1)X+=$[0]*$[1]*Y,$[0]=Math.max(Math.floor($[0]/2),1),$[1]=Math.max(Math.floor($[1]/2),1);return X+=1*Y,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}`}}a4.impls={"image/jpeg":new pr,"image/png":new Mw};function dT1(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 Rz{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 a4.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()}}var jk=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 cT1(){var Z=new jk(3);if(jk!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function Nk(Z){var J=Z[0],X=Z[1],Y=Z[2];return Math.hypot(J,X,Y)}function lT1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=X[3]*Y+X[7]*$+X[11]*Q+X[15];return K=K||1,Z[0]=(X[0]*Y+X[4]*$+X[8]*Q+X[12])/K,Z[1]=(X[1]*Y+X[5]*$+X[9]*Q+X[13])/K,Z[2]=(X[2]*Y+X[6]*$+X[10]*Q+X[14])/K,Z}(function(){var Z=cT1();return function(J,X,Y,$,Q,K){var W,G;if(!X)X=3;if(!Y)Y=0;if($)G=Math.min($*X+Y,J.length);else G=J.length;for(W=Y;W<G;W+=X)Z[0]=J[W],Z[1]=J[W+1],Z[2]=J[W+2],Q(Z,Z,K),J[W]=Z[0],J[W+1]=Z[1],J[W+2]=Z[2];return J}})();function ir(Z){let J=nr(),X=Z.propertyType===o.NODE?[Z]:Z.listChildren();for(let Y of X)Y.traverse(($)=>{let Q=$.getMesh();if(!Q)return;let K=pT1(Q,$.getWorldMatrix());if(K.min.every(isFinite)&&K.max.every(isFinite))Dk(K.min,J),Dk(K.max,J)});return J}function pT1(Z,J){let X=nr();for(let Y of Z.listPrimitives()){let $=Y.getAttribute("POSITION"),Q=Y.getIndices();if(!$)continue;let K=[0,0,0],W=[0,0,0];for(let G=0,V=Q?Q.getCount():$.getCount();G<V;G++){let z=Q?Q.getScalar(G):G;K=$.getElement(z,K),W=lT1(W,K,J),Dk(W,X)}}return X}function Dk(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 nr(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}var dr="https://null.example";class Ek{static dirname(Z){let J=Z.lastIndexOf("/");if(J===-1)return"./";return Z.substring(0,J+1)}static basename(Z){return Rz.basename(new URL(Z,dr).pathname)}static extension(Z){return Rz.extension(new URL(Z,dr).pathname)}static resolve(Z,J){if(!this.isRelativePath(J))return J;let X=Z.split("/"),Y=J.split("/");X.pop();for(let $=0;$<Y.length;$++){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)}}Ek.DEFAULT_INIT={};Ek.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;function cr(Z){return Object.prototype.toString.call(Z)==="[object Object]"}function x$(Z){if(cr(Z)===!1)return!1;let J=Z.constructor;if(J===void 0)return!0;let X=J.prototype;if(cr(X)===!1)return!1;if(Object.hasOwn(X,"isPrototypeOf")===!1)return!1;return!0}var Pk,Ck;(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"})(Ck||(Ck={}));class u7{constructor(Z){this.verbosity=void 0,this.verbosity=Z}debug(Z){if(this.verbosity<=u7.Verbosity.DEBUG)console.debug(Z)}info(Z){if(this.verbosity<=u7.Verbosity.INFO)console.info(Z)}warn(Z){if(this.verbosity<=u7.Verbosity.WARN)console.warn(Z)}error(Z){if(this.verbosity<=u7.Verbosity.ERROR)console.error(Z)}}Pk=u7;u7.Verbosity=Ck;u7.DEFAULT_INSTANCE=new Pk(Pk.Verbosity.INFO);function iT1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3],Q=Z[4],K=Z[5],W=Z[6],G=Z[7],V=Z[8],z=Z[9],F=Z[10],H=Z[11],q=Z[12],U=Z[13],B=Z[14],L=Z[15],w=J*K-X*Q,M=J*W-Y*Q,N=J*G-$*Q,R=X*W-Y*K,P=X*G-$*K,D=Y*G-$*W,C=V*U-z*q,T=V*B-F*q,k=V*L-H*q,A=z*B-F*U,v=z*L-H*U,x=F*L-H*B;return w*x-M*v+N*A+R*k-P*T+D*C}function nT1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=J[3],W=J[4],G=J[5],V=J[6],z=J[7],F=J[8],H=J[9],q=J[10],U=J[11],B=J[12],L=J[13],w=J[14],M=J[15],N=X[0],R=X[1],P=X[2],D=X[3];return Z[0]=N*Y+R*W+P*F+D*B,Z[1]=N*$+R*G+P*H+D*L,Z[2]=N*Q+R*V+P*q+D*w,Z[3]=N*K+R*z+P*U+D*M,N=X[4],R=X[5],P=X[6],D=X[7],Z[4]=N*Y+R*W+P*F+D*B,Z[5]=N*$+R*G+P*H+D*L,Z[6]=N*Q+R*V+P*q+D*w,Z[7]=N*K+R*z+P*U+D*M,N=X[8],R=X[9],P=X[10],D=X[11],Z[8]=N*Y+R*W+P*F+D*B,Z[9]=N*$+R*G+P*H+D*L,Z[10]=N*Q+R*V+P*q+D*w,Z[11]=N*K+R*z+P*U+D*M,N=X[12],R=X[13],P=X[14],D=X[15],Z[12]=N*Y+R*W+P*F+D*B,Z[13]=N*$+R*G+P*H+D*L,Z[14]=N*Q+R*V+P*q+D*w,Z[15]=N*K+R*z+P*U+D*M,Z}function aT1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[4],K=J[5],W=J[6],G=J[8],V=J[9],z=J[10];return Z[0]=Math.hypot(X,Y,$),Z[1]=Math.hypot(Q,K,W),Z[2]=Math.hypot(G,V,z),Z}function sT1(Z,J){var X=new jk(3);aT1(X,J);var Y=1/X[0],$=1/X[1],Q=1/X[2],K=J[0]*Y,W=J[1]*$,G=J[2]*Q,V=J[4]*Y,z=J[5]*$,F=J[6]*Q,H=J[8]*Y,q=J[9]*$,U=J[10]*Q,B=K+z+U,L=0;if(B>0)L=Math.sqrt(B+1)*2,Z[3]=0.25*L,Z[0]=(F-q)/L,Z[1]=(H-G)/L,Z[2]=(W-V)/L;else if(K>z&&K>U)L=Math.sqrt(1+K-z-U)*2,Z[3]=(F-q)/L,Z[0]=0.25*L,Z[1]=(W+V)/L,Z[2]=(H+G)/L;else if(z>U)L=Math.sqrt(1+z-K-U)*2,Z[3]=(H-G)/L,Z[0]=(W+V)/L,Z[1]=0.25*L,Z[2]=(F+q)/L;else L=Math.sqrt(1+U-K-z)*2,Z[3]=(W-V)/L,Z[0]=(H+G)/L,Z[1]=(F+q)/L,Z[2]=0.25*L;return Z}class U8{static identity(Z){return Z}static eq(Z,J,X=0.00001){if(Z.length!==J.length)return!1;for(let Y=0;Y<Z.length;Y++)if(Math.abs(Z[Y]-J[Y])>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(U8.clamp(Z,0,1)*65535);case 5121:return Math.round(U8.clamp(Z,0,1)*255);case 5122:return Math.round(U8.clamp(Z,-1,1)*32767);case 5120:return Math.round(U8.clamp(Z,-1,1)*127);default:throw new Error("Invalid component type.")}}static decompose(Z,J,X,Y){let $=Nk([Z[0],Z[1],Z[2]]),Q=Nk([Z[4],Z[5],Z[6]]),K=Nk([Z[8],Z[9],Z[10]]);if(iT1(Z)<0)$=-$;J[0]=Z[12],J[1]=Z[13],J[2]=Z[14];let G=Z.slice(),V=1/$,z=1/Q,F=1/K;G[0]*=V,G[1]*=V,G[2]*=V,G[4]*=z,G[5]*=z,G[6]*=z,G[8]*=F,G[9]*=F,G[10]*=F,sT1(X,G),Y[0]=$,Y[1]=Q,Y[2]=K}static compose(Z,J,X,Y){let $=Y,Q=J[0],K=J[1],W=J[2],G=J[3],V=Q+Q,z=K+K,F=W+W,H=Q*V,q=Q*z,U=Q*F,B=K*z,L=K*F,w=W*F,M=G*V,N=G*z,R=G*F,P=X[0],D=X[1],C=X[2];return $[0]=(1-(B+w))*P,$[1]=(q+R)*P,$[2]=(U-N)*P,$[3]=0,$[4]=(q-R)*D,$[5]=(1-(H+w))*D,$[6]=(L+M)*D,$[7]=0,$[8]=(U+N)*C,$[9]=(L-M)*C,$[10]=(1-(H+B))*C,$[11]=0,$[12]=Z[0],$[13]=Z[1],$[14]=Z[2],$[15]=1,$}}function oT1(Z,J){if(!!Z!==!!J)return!1;let X=Z.getChild(),Y=J.getChild();return X===Y||X.equals(Y)}function rT1(Z,J){if(!!Z!==!!J)return!1;let X=Z.values(),Y=J.values();if(X.length!==Y.length)return!1;for(let $=0;$<X.length;$++){let Q=X[$],K=Y[$];if(Q.getChild()===K.getChild())continue;if(!Q.getChild().equals(K.getChild()))return!1}return!0}function tT1(Z,J){if(!!Z!==!!J)return!1;let X=Z.keys(),Y=J.keys();if(X.length!==Y.length)return!1;for(let $ of X){let Q=Z.get($),K=J.get($);if(!!Q!==!!K)return!1;let W=Q.getChild(),G=K.getChild();if(W===G)continue;if(!W.equals(G))return!1}return!0}function ar(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 sr(Z,J){if(Z===J)return!0;if(!!Z!==!!J)return!1;if(!x$(Z)||!x$(J))return Z===J;let X=Z,Y=J,$=0,Q=0,K;for(K in X)$++;for(K in Y)Q++;if($!==Q)return!1;for(K in X){let W=X[K],G=Y[K];if(Lw(W)&&Lw(G)){if(!ar(W,G))return!1}else if(x$(W)&&x$(G)){if(!sr(W,G))return!1}else if(W!==G)return!1}return!0}function Lw(Z){return Array.isArray(Z)||ArrayBuffer.isView(Z)}var EX=(Z)=>Z,eT1=new Set;class Nw extends VW{constructor(Z,J=""){super(Z);this[b0].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,EX)}copy(Z,J=EX){for(let X in this[b0]){let Y=this[b0][X];if(Y instanceof x5){if(!this[i4].has(X))Y.dispose()}else if(Y instanceof f6||Y instanceof I0)for(let $ of Y.values())$.dispose();else if(Y instanceof Y8)for(let $ of Y.values())$.dispose()}for(let X in Z[b0]){let Y=this[b0][X],$=Z[b0][X];if($ instanceof x5)if(this[i4].has(X))Y.getChild().copy(J($.getChild()),J);else this.setRef(X,J($.getChild()),$.getAttributes());else if($ instanceof I0||$ instanceof f6)for(let Q of $.values())this.addRef(X,J(Q.getChild()),Q.getAttributes());else if($ instanceof Y8)for(let Q of $.keys()){let K=$.get(Q);this.setRefMap(X,Q,J(K.getChild()),K.getAttributes())}else if(x$($))this[b0][X]=JSON.parse(JSON.stringify($));else if(Array.isArray($)||$ instanceof ArrayBuffer||ArrayBuffer.isView($))this[b0][X]=$.slice();else this[b0][X]=$}return this}equals(Z,J=eT1){if(this===Z)return!0;if(this.propertyType!==Z.propertyType)return!1;for(let X in this[b0]){if(J.has(X))continue;let Y=this[b0][X],$=Z[b0][X];if(Y instanceof x5||$ instanceof x5){if(!oT1(Y,$))return!1}else if(Y instanceof I0||$ instanceof I0||Y instanceof f6||$ instanceof f6){if(!rT1(Y,$))return!1}else if(Y instanceof Y8||$ instanceof Y8){if(!tT1(Y,$))return!1}else if(x$(Y)||x$($)){if(!sr(Y,$))return!1}else if(Lw(Y)||Lw($)){if(!ar(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 m6 extends Nw{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new Y8})}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 C0 extends m6{init(){this.propertyType=o.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:C0.Type.SCALAR,componentType:C0.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(Z){switch(Z){case C0.Type.SCALAR:return 1;case C0.Type.VEC2:return 2;case C0.Type.VEC3:return 3;case C0.Type.VEC4:return 4;case C0.Type.MAT2:return 4;case C0.Type.MAT3:return 9;case C0.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+Z)}}static getComponentSize(Z){switch(Z){case C0.ComponentType.BYTE:return 1;case C0.ComponentType.UNSIGNED_BYTE:return 1;case C0.ComponentType.SHORT:return 2;case C0.ComponentType.UNSIGNED_SHORT:return 2;case C0.ComponentType.UNSIGNED_INT:return 4;case C0.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+Z)}}getMinNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMin(Z),J)for(let $=0;$<X;$++)Z[$]=U8.decodeNormalizedInt(Z[$],Y);return Z}getMin(Z){let J=this.getArray(),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.min(Z[Q],K)}return Z}getMaxNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMax(Z),J)for(let $=0;$<X;$++)Z[$]=U8.decodeNormalizedInt(Z[$],Y);return Z}getMax(Z){let J=this.get("array"),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=-1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.max(Z[Q],K)}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 C0.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(),Y=this.getArray();if(this.getNormalized())return U8.decodeNormalizedInt(Y[Z*J],X);return Y[Z*J]}setScalar(Z,J){let X=this.getElementSize(),Y=this.getComponentType(),$=this.getArray();if(this.getNormalized())$[Z*X]=U8.encodeNormalizedInt(J,Y);else $[Z*X]=J;return this}getElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)J[K]=U8.decodeNormalizedInt(Q[Z*Y+K],$);else J[K]=Q[Z*Y+K];return J}setElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)Q[Z*Y+K]=U8.encodeNormalizedInt(J[K],$);else Q[Z*Y+K]=J[K];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?Zk1(Z):C0.ComponentType.FLOAT),this.set("array",Z),this}getByteLength(){let Z=this.get("array");return Z?Z.byteLength:0}}C0.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};C0.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};function Zk1(Z){switch(Z.constructor){case Float32Array:return C0.ComponentType.FLOAT;case Uint32Array:return C0.ComponentType.UNSIGNED_INT;case Uint16Array:return C0.ComponentType.UNSIGNED_SHORT;case Uint8Array:return C0.ComponentType.UNSIGNED_BYTE;case Int16Array:return C0.ComponentType.SHORT;case Int8Array:return C0.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}class Ik extends m6{init(){this.propertyType=o.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 Dz extends m6{init(){this.propertyType=o.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)}}Dz.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class jW extends m6{init(){this.propertyType=o.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:jW.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:V9.OTHER})}getOutput(){return this.getRef("output")}setOutput(Z){return this.setRef("output",Z,{usage:V9.OTHER})}}jW.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class _k extends m6{init(){this.propertyType=o.BUFFER}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(Z){return this.set("uri",Z)}}class Pz extends m6{init(){this.propertyType=o.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:Pz.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)}}Pz.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class t1 extends Nw{_validateParent(Z){if(!this.parentTypes.includes(Z.propertyType))throw new Error(`Parent "${Z.propertyType}" invalid for child "${this.propertyType}".`)}}t1.EXTENSION_NAME=void 0;class E1 extends m6{init(){this.propertyType=o.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:E1.WrapMode.REPEAT,wrapT:E1.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)}}E1.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};E1.MagFilter={NEAREST:9728,LINEAR:9729};E1.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};var{R:qw,G:Uw,B:Bw,A:Jk1}=z9;class Cz extends m6{init(){this.propertyType=o.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:Cz.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new E1(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new E1(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new E1(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new E1(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new E1(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:qw|Uw|Bw|Jk1,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:qw|Uw|Bw,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:qw|Uw|Bw})}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:qw})}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:Uw|Bw})}}Cz.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class vk extends m6{init(){this.propertyType=o.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 Sk extends m6{init(){this.propertyType=o.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=EX){if(J===EX)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 U8.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(Z){let J=this.get("translation").slice(),X=this.get("rotation").slice(),Y=this.get("scale").slice();return U8.decompose(Z,J,X,Y),this.set("translation",J).set("rotation",X).set("scale",Y)}getWorldTranslation(){let Z=[0,0,0];return U8.decompose(this.getWorldMatrix(),Z,[0,0,0,1],[1,1,1]),Z}getWorldRotation(){let Z=[0,0,0,1];return U8.decompose(this.getWorldMatrix(),[0,0,0],Z,[1,1,1]),Z}getWorldScale(){let Z=[1,1,1];return U8.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],Z),Z}getWorldMatrix(){let Z=[];for(let Y=this;Y!=null;Y=Y.getParentNode())Z.push(Y);let J,X=Z.pop().getMatrix();while(J=Z.pop())nT1(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===o.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===o.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 IX extends m6{init(){this.propertyType=o.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:IX.Mode.TRIANGLES,material:null,indices:null,attributes:new Y8,targets:new I0})}getIndices(){return this.getRef("indices")}setIndices(Z){return this.setRef("indices",Z,{usage:V9.ELEMENT_ARRAY_BUFFER})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:V9.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)}}IX.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class or extends Nw{init(){this.propertyType=o.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new Y8})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:V9.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function ww(){return ww=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},ww.apply(null,arguments)}class Ak extends m6{init(){this.propertyType=o.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:new I0})}copy(Z,J=EX){if(J===EX)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 xk extends m6{init(){this.propertyType=o.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:V9.INVERSE_BIND_MATRICES})}addJoint(Z){return this.addRef("joints",Z)}removeJoint(Z){return this.removeRef("joints",Z)}listJoints(){return this.listRefs("joints")}}class hk extends m6{init(){this.propertyType=o.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||a4.extensionToMimeType(Rz.extension(this.get("uri")))}setMimeType(Z){return this.set("mimeType",Z)}getURI(){return this.get("uri")}setURI(Z){this.set("uri",Z);let J=a4.extensionToMimeType(Rz.extension(Z));if(J)this.set("mimeType",J);return this}getImage(){return this.get("image")}setImage(Z){return this.set("image",g6.assertView(Z))}getSize(){let Z=this.get("image");if(!Z)return null;return a4.getSize(Z,this.getMimeType())}}class Rw extends m6{init(){this.propertyType=o.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${uT1}`,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=EX){if(J===EX)throw new Error("Root cannot be copied.");this.set("asset",ww({},Z.get("asset"))),this.setName(Z.getName()),this.setExtras(ww({},Z.getExtras())),this.setDefaultScene(Z.getDefaultScene()?J(Z.getDefaultScene()):null);for(let X of Z.listRefMapKeys("extensions")){let Y=Z.getExtension(X);this.setExtension(X,J(Y))}return this}_addChildOfRoot(Z){if(Z instanceof Ak)this.addRef("scenes",Z);else if(Z instanceof Sk)this.addRef("nodes",Z);else if(Z instanceof Pz)this.addRef("cameras",Z);else if(Z instanceof xk)this.addRef("skins",Z);else if(Z instanceof vk)this.addRef("meshes",Z);else if(Z instanceof Cz)this.addRef("materials",Z);else if(Z instanceof hk)this.addRef("textures",Z);else if(Z instanceof Ik)this.addRef("animations",Z);else if(Z instanceof C0)this.addRef("accessors",Z);else if(Z instanceof _k)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 Ow{static fromGraph(Z){return Ow._GRAPH_DOCUMENTS.get(Z)||null}constructor(){this._graph=new GW,this._root=new Rw(this._graph),this._logger=u7.DEFAULT_INSTANCE,Ow._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((Y)=>Y.extensionName===J)||new Z(this)}createScene(Z=""){return new Ak(this._graph,Z)}createNode(Z=""){return new Sk(this._graph,Z)}createCamera(Z=""){return new Pz(this._graph,Z)}createSkin(Z=""){return new xk(this._graph,Z)}createMesh(Z=""){return new vk(this._graph,Z)}createPrimitive(){return new IX(this._graph)}createPrimitiveTarget(Z=""){return new or(this._graph,Z)}createMaterial(Z=""){return new Cz(this._graph,Z)}createTexture(Z=""){return new hk(this._graph,Z)}createAnimation(Z=""){return new Ik(this._graph,Z)}createAnimationChannel(Z=""){return new Dz(this._graph,Z)}createAnimationSampler(Z=""){return new jW(this._graph,Z)}createAccessor(Z="",J=null){if(!J)J=this.getRoot().listBuffers()[0];return new C0(this._graph,Z).setBuffer(J)}createBuffer(Z=""){return new _k(this._graph,Z)}}Ow._GRAPH_DOCUMENTS=new WeakMap;class v1{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 Y=X,$=Y.target;if($ instanceof t1&&$.extensionName===this.extensionName){if(Y.type==="node:create")this._addExtensionProperty($);if(Y.type==="node:dispose")this._removeExtensionProperty($)}};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}}v1.EXTENSION_NAME=void 0;var yx6={logger:u7.DEFAULT_INSTANCE,extensions:[],dependencies:{}},bx6=new Set([o.BUFFER,o.TEXTURE,o.MATERIAL,o.MESH,o.PRIMITIVE,o.NODE,o.SCENE]);var jz;(function(Z){Z[Z.ARRAY_BUFFER=34962]="ARRAY_BUFFER",Z[Z.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"})(jz||(jz={}));class _X{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 Y=Z.getRoot(),$=Y.listBuffers().length,Q=Y.listTextures().length;this.bufferURIGenerator=new Tk($>1,()=>X.basename||"buffer"),this.imageURIGenerator=new Tk(Q>1,(K)=>Xk1(Z,K)||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()},Y=JSON.stringify(X);if(!this.samplerDefIndexMap.has(Y))this.samplerDefIndexMap.set(Y,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(X);let $={source:this.imageIndexMap.get(Z),sampler:this.samplerDefIndexMap.get(Y)},Q=JSON.stringify($);if(!this.textureDefIndexMap.has(Q))this.textureDefIndexMap.set(Q,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push($);let K={index:this.textureDefIndexMap.get(Q)};if(J.getTexCoord()!==0)K.texCoord=J.getTexCoord();if(Object.keys(J.getExtras()).length>0)K.extras=J.getExtras();return this.textureInfoDefMap.set(J,K),K}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((Y)=>Y.getName()==="attributes"&&Y.getAttributes().key==="POSITION"||Y.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===Rk.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 Y=a4.mimeTypeToExtension(X.getMimeType());Z.uri=this.imageURIGenerator.createURI(X,Y),this.assignResourceURI(Z.uri,J,!1)}}assignResourceURI(Z,J,X){let Y=this.jsonDoc.resources;if(!(Z in Y)){Y[Z]=J;return}if(J===Y[Z]){this.logger.warn(`Duplicate resource URI, "${Z}".`);return}let $=`Resource URI "${Z}" already assigned to different data.`;if(!X){this.logger.warn($);return}throw new Error($)}getAccessorUsage(Z){let J=this._accessorUsageMap.get(Z);if(J)return J;if(Z.getSparse())return V9.SPARSE;for(let X of this._doc.getGraph().listParentEdges(Z)){let{usage:Y}=X.getAttributes();if(Y)return Y;if(X.getParent().propertyType!==o.ROOT)this.logger.warn(`Missing attribute ".usage" on edge, "${X.getName()}".`)}return V9.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}}_X.BufferViewTarget=jz;_X.BufferViewUsage=V9;_X.USAGE_TO_TARGET={[V9.ARRAY_BUFFER]:jz.ARRAY_BUFFER,[V9.ELEMENT_ARRAY_BUFFER]:jz.ELEMENT_ARRAY_BUFFER};class Tk{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 Xk1(Z,J){let X=Z.getGraph().listParentEdges(J).find((Y)=>Y.getParent()!==Z.getRoot());return X?X.getName().replace(/texture$/i,""):""}var{UNSIGNED_INT:gx6,UNSIGNED_SHORT:mx6,UNSIGNED_BYTE:ux6}=C0.ComponentType,dx6=new Set([o.ACCESSOR,o.BUFFER,o.MATERIAL,o.MESH]);var lr;(function(Z){Z[Z.JSON=1313821514]="JSON",Z[Z.BIN=5130562]="BIN"})(lr||(lr={}));var tr=163,er=166;function Yk1(){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 DW{constructor(Z,J,X,Y){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(Z.buffer,Z.byteOffset+J,X),this._littleEndian=Y,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,Y=0;while(this._dataView.getUint8(this._offset)!==J&&Y<Z)Y++,this._offset++;if(Y<Z)this._offset++;return new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+X,Y)}}var px6=new Uint8Array([0]),z5=[171,75,84,88,32,50,48,187,13,10,26,10];function rr(Z){return new TextDecoder().decode(Z)}function jw(Z){let J=new Uint8Array(Z.buffer,Z.byteOffset,z5.length);if(J[0]!==z5[0]||J[1]!==z5[1]||J[2]!==z5[2]||J[3]!==z5[3]||J[4]!==z5[4]||J[5]!==z5[5]||J[6]!==z5[6]||J[7]!==z5[7]||J[8]!==z5[8]||J[9]!==z5[9]||J[10]!==z5[10]||J[11]!==z5[11])throw new Error("Missing KTX 2.0 identifier.");let X=Yk1(),Y=17*Uint32Array.BYTES_PER_ELEMENT,$=new DW(Z,z5.length,Y,!0);X.vkFormat=$._nextUint32(),X.typeSize=$._nextUint32(),X.pixelWidth=$._nextUint32(),X.pixelHeight=$._nextUint32(),X.pixelDepth=$._nextUint32(),X.layerCount=$._nextUint32(),X.faceCount=$._nextUint32();let Q=$._nextUint32();X.supercompressionScheme=$._nextUint32();let K=$._nextUint32(),W=$._nextUint32(),G=$._nextUint32(),V=$._nextUint32(),z=$._nextUint64(),F=$._nextUint64(),H=Q*3*8,q=new DW(Z,z5.length+Y,H,!0);for(let L6=0;L6<Q;L6++)X.levels.push({levelData:new Uint8Array(Z.buffer,Z.byteOffset+q._nextUint64(),q._nextUint64()),uncompressedByteLength:q._nextUint64()});let U=new DW(Z,K,W,!0);U._skip(4);let B=U._nextUint16(),L=U._nextUint16(),w=U._nextUint16(),M=U._nextUint16(),N=U._nextUint8(),R=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:B,descriptorType:L,versionNumber:w,colorModel:N,colorPrimaries:R,transferFunction:P,flags:D,texelBlockDimension:C,bytesPlane:T,samples:[]},v=6,x=4,I=(M/4-v)/x;for(let L6=0;L6<I;L6++){let EZ={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(EZ.channelType&64)EZ.sampleLower=U._nextInt32(),EZ.sampleUpper=U._nextInt32();else EZ.sampleLower=U._nextUint32(),EZ.sampleUpper=U._nextUint32();A.samples[L6]=EZ}X.dataFormatDescriptor.length=0,X.dataFormatDescriptor.push(A);let _=new DW(Z,G,V,!0);while(_._offset<V){let L6=_._nextUint32(),EZ=_._scan(L6),G2=rr(EZ);if(X.keyValue[G2]=_._nextUint8Array(L6-EZ.byteLength-1),G2.match(/^ktx/i)){let Iu=rr(X.keyValue[G2]);X.keyValue[G2]=Iu.substring(0,Iu.lastIndexOf("\x00"))}let rF1=L6%4?4-L6%4:0;_._skip(rF1)}if(F<=0)return X;let b=new DW(Z,z,F,!0),u=b._nextUint16(),i=b._nextUint16(),e=b._nextUint32(),Z0=b._nextUint32(),K0=b._nextUint32(),S0=b._nextUint32(),A0=[];for(let L6=0;L6<Q;L6++)A0.push({imageFlags:b._nextUint32(),rgbSliceByteOffset:b._nextUint32(),rgbSliceByteLength:b._nextUint32(),alphaSliceByteOffset:b._nextUint32(),alphaSliceByteLength:b._nextUint32()});let s0=z+b._offset,x8=s0+e,J8=x8+Z0,C7=J8+K0,h4=new Uint8Array(Z.buffer,Z.byteOffset+s0,e),TK=new Uint8Array(Z.buffer,Z.byteOffset+x8,Z0),kK=new Uint8Array(Z.buffer,Z.byteOffset+J8,K0),G$=new Uint8Array(Z.buffer,Z.byteOffset+C7,S0);return X.globalData={endpointCount:u,selectorCount:i,imageDescs:A0,endpointsData:h4,selectorsData:TK,tablesData:kK,extendedData:G$},X}var iZ="EXT_mesh_gpu_instancing",N6="EXT_meshopt_compression",Tz="EXT_texture_webp",kz="EXT_texture_avif",Q8="KHR_draco_mesh_compression",a9="KHR_lights_punctual",nZ="KHR_materials_anisotropy",aZ="KHR_materials_clearcoat",sZ="KHR_materials_diffuse_transmission",oZ="KHR_materials_dispersion",rZ="KHR_materials_emissive_strength",tZ="KHR_materials_ior",eZ="KHR_materials_iridescence",ZJ="KHR_materials_pbrSpecularGlossiness",JJ="KHR_materials_sheen",XJ="KHR_materials_specular",YJ="KHR_materials_transmission",vX="KHR_materials_unlit",$J="KHR_materials_volume",u6="KHR_materials_variants",Ft="KHR_mesh_quantization",Ez="KHR_texture_basisu",QJ="KHR_texture_transform",s9="KHR_xmp_json_ld",yk="INSTANCE_ATTRIBUTE";class gk extends t1{init(){this.extensionName=iZ,this.propertyType="InstancedMesh",this.parentTypes=[o.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new Y8})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:yk})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}gk.EXTENSION_NAME=iZ;class Cw extends v1{constructor(...Z){super(...Z);this.extensionName=iZ,this.provideTypes=[o.NODE],this.prewriteTypes=[o.ACCESSOR]}createInstancedMesh(){return new gk(this.document.getGraph())}read(Z){return(Z.jsonDoc.json.nodes||[]).forEach((Y,$)=>{if(!Y.extensions||!Y.extensions[iZ])return;let Q=Y.extensions[iZ],K=this.createInstancedMesh();for(let W in Q.attributes)K.setAttribute(W,Z.accessors[Q.attributes[W]]);Z.nodes[$].setExtension(iZ,K)}),this}prewrite(Z){Z.accessorUsageGroupedByParent.add(yk);for(let J of this.properties)for(let X of J.listAttributes())Z.addAccessorToUsageGroup(X,yk);return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listNodes().forEach((X)=>{let Y=X.getExtension(iZ);if(Y){let $=Z.nodeIndexMap.get(X),Q=J.json.nodes[$],K={attributes:{}};Y.listSemantics().forEach((W)=>{let G=Y.getAttribute(W);K.attributes[W]=Z.accessorIndexMap.get(G)}),Q.extensions=Q.extensions||{},Q.extensions[iZ]=K}}),this}}Cw.EXTENSION_NAME=iZ;function KJ(){return KJ=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},KJ.apply(null,arguments)}var Iz;(function(Z){Z.QUANTIZE="quantize",Z.FILTER="filter"})(Iz||(Iz={}));var PW;(function(Z){Z.ATTRIBUTES="ATTRIBUTES",Z.TRIANGLES="TRIANGLES",Z.INDICES="INDICES"})(PW||(PW={}));var B8;(function(Z){Z.NONE="NONE",Z.OCTAHEDRAL="OCTAHEDRAL",Z.QUATERNION="QUATERNION",Z.EXPONENTIAL="EXPONENTIAL"})(B8||(B8={}));function $k1(Z){if(!Z.extensions||!Z.extensions[N6])return!1;return!!Z.extensions[N6].fallback}var{BYTE:Qk1,SHORT:Zt,FLOAT:Kk1}=C0.ComponentType,{encodeNormalizedInt:Jt,decodeNormalizedInt:bk}=U8;function Wk1(Z,J,X,Y){let{filter:$,bits:Q}=Y,K={array:Z.getArray(),byteStride:Z.getElementSize()*Z.getComponentSize(),componentType:Z.getComponentType(),normalized:Z.getNormalized()};if(X!==PW.ATTRIBUTES)return K;if($!==B8.NONE){let W=Z.getNormalized()?Gk1(Z):new Float32Array(K.array);switch($){case B8.EXPONENTIAL:K.byteStride=Z.getElementSize()*4,K.componentType=Kk1,K.normalized=!1,K.array=J.encodeFilterExp(W,Z.getCount(),K.byteStride,Q);break;case B8.OCTAHEDRAL:K.byteStride=Q>8?8:4,K.componentType=Q>8?Zt:Qk1,K.normalized=!0,W=Z.getElementSize()===3?zk1(W):W,K.array=J.encodeFilterOct(W,Z.getCount(),K.byteStride,Q);break;case B8.QUATERNION:K.byteStride=8,K.componentType=Zt,K.normalized=!0,K.array=J.encodeFilterQuat(W,Z.getCount(),K.byteStride,Q);break;default:throw new Error("Invalid filter.")}if(K.min=Z.getMin([]),K.max=Z.getMax([]),Z.getNormalized())K.min=K.min.map((G)=>bk(G,Z.getComponentType())),K.max=K.max.map((G)=>bk(G,Z.getComponentType()));if(K.normalized)K.min=K.min.map((G)=>Jt(G,K.componentType)),K.max=K.max.map((G)=>Jt(G,K.componentType))}else if(K.byteStride%4)K.array=Vk1(K.array,Z.getElementSize()),K.byteStride=K.array.byteLength/Z.getCount();return K}function Gk1(Z){let J=Z.getComponentType(),X=Z.getArray(),Y=new Float32Array(X.length);for(let $=0;$<X.length;$++)Y[$]=bk(X[$],J);return Y}function Vk1(Z,J){let Y=g6.padNumber(Z.BYTES_PER_ELEMENT*J)/Z.BYTES_PER_ELEMENT,$=Z.length/J,Q=new Z.constructor($*Y);for(let K=0;K*J<Z.length;K++)for(let W=0;W<J;W++)Q[K*Y+W]=Z[K*J+W];return Q}function zk1(Z){let J=new Float32Array(Z.length*4/3);for(let X=0,Y=Z.length/3;X<Y;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 Hk1(Z,J){if(J===_X.BufferViewUsage.ELEMENT_ARRAY_BUFFER)return Z.listParents().some((Y)=>{return Y instanceof IX&&Y.getMode()===IX.Mode.TRIANGLES})?PW.TRIANGLES:PW.INDICES;return PW.ATTRIBUTES}function Fk1(Z,J){let X=J.getGraph().listParentEdges(Z).filter((Y)=>!(Y.getParent()instanceof Rw));for(let Y of X){let $=Y.getName(),Q=Y.getAttributes().key||"",K=Y.getParent().propertyType===o.PRIMITIVE_TARGET;if($==="indices")return{filter:B8.NONE};if($==="attributes"){if(Q==="POSITION")return{filter:B8.NONE};if(Q==="TEXCOORD_0")return{filter:B8.NONE};if(Q.startsWith("JOINTS_"))return{filter:B8.NONE};if(Q.startsWith("WEIGHTS_"))return{filter:B8.NONE};if(Q==="NORMAL"||Q==="TANGENT")return K?{filter:B8.NONE}:{filter:B8.OCTAHEDRAL,bits:8}}if($==="output"){let W=qt(Z);if(W==="rotation")return{filter:B8.QUATERNION,bits:16};if(W==="translation")return{filter:B8.EXPONENTIAL,bits:12};if(W==="scale")return{filter:B8.EXPONENTIAL,bits:12};return{filter:B8.NONE}}if($==="input")return{filter:B8.NONE};if($==="inverseBindMatrices")return{filter:B8.NONE}}return{filter:B8.NONE}}function qt(Z){for(let J of Z.listParents()){if(!(J instanceof jW))continue;for(let X of J.listParents()){if(!(X instanceof Dz))continue;return X.getTargetPath()}}return null}var Xt={method:Iz.QUANTIZE};class vz extends v1{constructor(...Z){super(...Z);this.extensionName=N6,this.prereadTypes=[o.BUFFER,o.PRIMITIVE],this.prewriteTypes=[o.BUFFER,o.ACCESSOR],this.readDependencies=["meshopt.decoder"],this.writeDependencies=["meshopt.encoder"],this._decoder=null,this._decoderFallbackBufferMap=new Map,this._encoder=null,this._encoderOptions=Xt,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=KJ({},Xt,Z),this}preread(Z,J){if(!this._decoder){if(!this.isRequired())return this;throw new Error(`[${N6}] Please install extension dependency, "meshopt.decoder".`)}if(!this._decoder.supported){if(!this.isRequired())return this;throw new Error(`[${N6}]: Missing WASM support.`)}if(J===o.BUFFER)this._prereadBuffers(Z);else if(J===o.PRIMITIVE)this._prereadPrimitives(Z);return this}_prereadBuffers(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach((Y,$)=>{if(!Y.extensions||!Y.extensions[N6])return;let Q=Y.extensions[N6],K=Q.byteOffset||0,W=Q.byteLength||0,G=Q.count,V=Q.byteStride,z=new Uint8Array(G*V),F=J.json.buffers[Q.buffer],H=F.uri?J.resources[F.uri]:J.resources[kk],q=g6.toView(H,K,W);this._decoder.decodeGltfBuffer(z,G,V,q,Q.mode,Q.filter),Z.bufferViews[$]=z})}_prereadPrimitives(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach((Y)=>{if(!Y.extensions||!Y.extensions[N6])return;let $=Y.extensions[N6],Q=Z.buffers[$.buffer],K=Z.buffers[Y.buffer],W=J.json.buffers[Y.buffer];if($k1(W))this._decoderFallbackBufferMap.set(K,Q)})}read(Z){if(!this.isRequired())return this;for(let[J,X]of this._decoderFallbackBufferMap){for(let Y of J.listParents())if(Y instanceof C0)Y.swap(J,X);J.dispose()}return this}prewrite(Z,J){if(J===o.ACCESSOR)this._prewriteAccessors(Z);else if(J===o.BUFFER)this._prewriteBuffers(Z);return this}_prewriteAccessors(Z){let J=Z.jsonDoc.json,X=this._encoder,Y=this._encoderOptions,$=this.document.getGraph(),Q=this.document.createBuffer(),K=this.document.getRoot().listBuffers().indexOf(Q),W=1,G=new Map,V=(z)=>{for(let F of $.listParents(z)){if(F.propertyType===o.ROOT)continue;let H=G.get(z);if(H===void 0)G.set(z,H=W++);return H}return-1};this._encoderFallbackBuffer=Q,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={};for(let z of this.document.getRoot().listAccessors()){if(qt(z)==="weights")continue;if(z.getSparse())continue;let F=Z.getAccessorUsage(z),H=Z.accessorUsageGroupedByParent.has(F)?V(z):null,q=Hk1(z,F),U=Y.method===Iz.FILTER?Fk1(z,this.document):{filter:B8.NONE},B=Wk1(z,X,q,U),{array:L,byteStride:w}=B,M=z.getBuffer();if(!M)throw new Error(`${N6}: Missing buffer for accessor.`);let N=this.document.getRoot().listBuffers().indexOf(M),R=[F,H,q,U.filter,w,N].join(":"),P=this._encoderBufferViews[R],D=this._encoderBufferViewData[R],C=this._encoderBufferViewAccessors[R];if(!P||!D)C=this._encoderBufferViewAccessors[R]=[],D=this._encoderBufferViewData[R]=[],P=this._encoderBufferViews[R]={buffer:K,target:_X.USAGE_TO_TARGET[F],byteOffset:0,byteLength:0,byteStride:F===_X.BufferViewUsage.ARRAY_BUFFER?w:void 0,extensions:{[N6]:{buffer:N,byteOffset:0,byteLength:0,mode:q,filter:U.filter!==B8.NONE?U.filter:void 0,byteStride:w,count:0}}};let T=Z.createAccessorDef(z);if(T.componentType=B.componentType,T.normalized=B.normalized,T.byteOffset=P.byteLength,T.min&&B.min)T.min=B.min;if(T.max&&B.max)T.max=B.max;Z.accessorIndexMap.set(z,J.accessors.length),J.accessors.push(T),C.push(T),D.push(new Uint8Array(L.buffer,L.byteOffset,L.byteLength)),P.byteLength+=L.byteLength,P.extensions.EXT_meshopt_compression.count+=z.getCount()}}_prewriteBuffers(Z){let J=this._encoder;for(let X in this._encoderBufferViews){let Y=this._encoderBufferViews[X],$=this._encoderBufferViewData[X],Q=this.document.getRoot().listBuffers()[Y.extensions[N6].buffer],K=Z.otherBufferViews.get(Q)||[],{count:W,byteStride:G,mode:V}=Y.extensions[N6],z=g6.concat($),F=J.encodeGltfBuffer(z,W,G,V),H=g6.pad(F);Y.extensions[N6].byteLength=F.byteLength,$.length=0,$.push(H),K.push(H),Z.otherBufferViews.set(Q,K)}}write(Z){let J=0;for(let Q in this._encoderBufferViews){let K=this._encoderBufferViews[Q],W=this._encoderBufferViewData[Q][0],G=Z.otherBufferViewsIndexMap.get(W),V=this._encoderBufferViewAccessors[Q];for(let q of V)q.bufferView=G;let z=Z.jsonDoc.json.bufferViews[G],F=z.byteOffset||0;Object.assign(z,K),z.byteOffset=J;let H=z.extensions[N6];H.byteOffset=F,J+=g6.padNumber(K.byteLength)}let X=this._encoderFallbackBuffer,Y=Z.bufferIndexMap.get(X),$=Z.jsonDoc.json.buffers[Y];return $.byteLength=J,$.extensions={[N6]:{fallback:!0}},X.dispose(),this}}vz.EXTENSION_NAME=N6;vz.EncoderMethod=Iz;class Ut{match(Z){return Z.length>=12&&g6.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=Yt(J,0);if(!X)return null;let Y=X.end;while(X=Yt(J,Y))if(X.type==="meta")Y=X.start+4;else if(X.type==="iprp"||X.type==="ipco")Y=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 Y=X.end;return null}getChannels(Z){return 4}}class Tw extends v1{constructor(...Z){super(...Z);this.extensionName=kz,this.prereadTypes=[o.TEXTURE]}static register(){a4.registerFormat("image/avif",new Ut)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[kz])X.source=X.extensions[kz].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 Y=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===Y)Q.extensions=Q.extensions||{},Q.extensions[kz]={source:Q.source},delete Q.source})}}),this}}Tw.EXTENSION_NAME=kz;function Yt(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:g6.decodeText(new Uint8Array(Z.buffer,Z.byteOffset+J+4,4)),start:J+8,end:J+X}}class Bt{match(Z){return Z.length>=12&&Z[8]===87&&Z[9]===69&&Z[10]===66&&Z[11]===80}getSize(Z){let J=g6.decodeText(Z.slice(0,4)),X=g6.decodeText(Z.slice(8,12));if(J!=="RIFF"||X!=="WEBP")return null;let Y=new DataView(Z.buffer,Z.byteOffset),$=12;while($<Y.byteLength){let Q=g6.decodeText(new Uint8Array([Y.getUint8($),Y.getUint8($+1),Y.getUint8($+2),Y.getUint8($+3)])),K=Y.getUint32($+4,!0);if(Q==="VP8 "){let W=Y.getInt16($+14,!0)&16383,G=Y.getInt16($+16,!0)&16383;return[W,G]}else if(Q==="VP8L"){let W=Y.getUint8($+9),G=Y.getUint8($+10),V=Y.getUint8($+11),z=Y.getUint8($+12),F=1+((G&63)<<8|W),H=1+((z&15)<<10|V<<2|(G&192)>>6);return[F,H]}$+=8+K+K%2}return null}getChannels(Z){return 4}}class kw extends v1{constructor(...Z){super(...Z);this.extensionName=Tz,this.prereadTypes=[o.TEXTURE]}static register(){a4.registerFormat("image/webp",new Bt)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[Tz])X.source=X.extensions[Tz].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 Y=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===Y)Q.extensions=Q.extensions||{},Q.extensions[Tz]={source:Q.source},delete Q.source})}}),this}}kw.EXTENSION_NAME=Tz;var i8,Lt,wt;function qk1(Z,J){let X=new i8.DecoderBuffer;try{if(X.Init(J,J.length),Z.GetEncodedGeometryType(X)!==i8.TRIANGULAR_MESH)throw new Error(`[${Q8}] Unknown geometry type.`);let $=new i8.Mesh;if(!Z.DecodeBufferToMesh(X,$).ok()||$.ptr===0)throw new Error(`[${Q8}] Decoding failure.`);return $}finally{i8.destroy(X)}}function Uk1(Z,J){let Y=J.num_faces()*3,$,Q;if(J.num_points()<=65534){let K=Y*Uint16Array.BYTES_PER_ELEMENT;$=i8._malloc(K),Z.GetTrianglesUInt16Array(J,K,$),Q=new Uint16Array(i8.HEAPU16.buffer,$,Y).slice()}else{let K=Y*Uint32Array.BYTES_PER_ELEMENT;$=i8._malloc(K),Z.GetTrianglesUInt32Array(J,K,$),Q=new Uint32Array(i8.HEAPU32.buffer,$,Y).slice()}return i8._free($),Q}function Bk1(Z,J,X,Y){let $=wt[Y.componentType],Q=Lt[Y.componentType],K=X.num_components(),G=J.num_points()*K,V=G*Q.BYTES_PER_ELEMENT,z=i8._malloc(V);Z.GetAttributeDataArrayForAllPoints(J,X,$,V,z);let F=new Q(i8.HEAPF32.buffer,z,G).slice();return i8._free(z),F}function Lk1(Z){i8=Z,Lt={[C0.ComponentType.FLOAT]:Float32Array,[C0.ComponentType.UNSIGNED_INT]:Uint32Array,[C0.ComponentType.UNSIGNED_SHORT]:Uint16Array,[C0.ComponentType.UNSIGNED_BYTE]:Uint8Array,[C0.ComponentType.SHORT]:Int16Array,[C0.ComponentType.BYTE]:Int8Array},wt={[C0.ComponentType.FLOAT]:i8.DT_FLOAT32,[C0.ComponentType.UNSIGNED_INT]:i8.DT_UINT32,[C0.ComponentType.UNSIGNED_SHORT]:i8.DT_UINT16,[C0.ComponentType.UNSIGNED_BYTE]:i8.DT_UINT8,[C0.ComponentType.SHORT]:i8.DT_INT16,[C0.ComponentType.BYTE]:i8.DT_INT8}}var n9,_z;(function(Z){Z[Z.EDGEBREAKER=1]="EDGEBREAKER",Z[Z.SEQUENTIAL=0]="SEQUENTIAL"})(_z||(_z={}));var o9;(function(Z){Z.POSITION="POSITION",Z.NORMAL="NORMAL",Z.COLOR="COLOR",Z.TEX_COORD="TEX_COORD",Z.GENERIC="GENERIC"})(o9||(o9={}));var Ot={[o9.POSITION]:14,[o9.NORMAL]:10,[o9.COLOR]:8,[o9.TEX_COORD]:12,[o9.GENERIC]:12},$t={decodeSpeed:5,encodeSpeed:5,method:_z.EDGEBREAKER,quantizationBits:Ot,quantizationVolume:"mesh"};function wk1(Z){n9=Z}function Ok1(Z,J=$t){let X=KJ({},$t,J);X.quantizationBits=KJ({},Ot,J.quantizationBits);let Y=new n9.MeshBuilder,$=new n9.Mesh,Q=new n9.ExpertEncoder($),K={},W=new n9.DracoInt8Array,G=Z.listTargets().length>0,V=!1;for(let B of Z.listSemantics()){let L=Z.getAttribute(B);if(L.getSparse()){V=!0;continue}let w=Mk1(B),M=Nk1(Y,L.getComponentType(),$,n9[w],L.getCount(),L.getElementSize(),L.getArray());if(M===-1)throw new Error(`Error compressing "${B}" attribute.`);if(K[B]=M,X.quantizationVolume==="mesh"||B!=="POSITION")Q.SetAttributeQuantization(M,X.quantizationBits[w]);else if(typeof X.quantizationVolume==="object"){let{quantizationVolume:N}=X,R=Math.max(N.max[0]-N.min[0],N.max[1]-N.min[1],N.max[2]-N.min[2]);Q.SetAttributeExplicitQuantization(M,X.quantizationBits[w],L.getElementSize(),N.min,R)}else throw new Error("Invalid quantization volume state.")}let z=Z.getIndices();if(!z)throw new Dw("Primitive must have indices.");if(Y.AddFacesToMesh($,z.getCount()/3,z.getArray()),Q.SetSpeedOptions(X.encodeSpeed,X.decodeSpeed),Q.SetTrackEncodedProperties(!0),X.method===_z.SEQUENTIAL||G||V)Q.SetEncodingMethod(n9.MESH_SEQUENTIAL_ENCODING);else Q.SetEncodingMethod(n9.MESH_EDGEBREAKER_ENCODING);let F=Q.EncodeToDracoBuffer(!(G||V),W);if(F<=0)throw new Dw("Error applying Draco compression.");let H=new Uint8Array(F);for(let B=0;B<F;++B)H[B]=W.GetValue(B);let q=Q.GetNumberOfEncodedPoints(),U=Q.GetNumberOfEncodedFaces()*3;return n9.destroy(W),n9.destroy($),n9.destroy(Y),n9.destroy(Q),{numVertices:q,numIndices:U,data:H,attributeIDs:K}}function Mk1(Z){if(Z==="POSITION")return o9.POSITION;else if(Z==="NORMAL")return o9.NORMAL;else if(Z.startsWith("COLOR_"))return o9.COLOR;else if(Z.startsWith("TEXCOORD_"))return o9.TEX_COORD;return o9.GENERIC}function Nk1(Z,J,X,Y,$,Q,K){switch(J){case C0.ComponentType.UNSIGNED_BYTE:return Z.AddUInt8Attribute(X,Y,$,Q,K);case C0.ComponentType.BYTE:return Z.AddInt8Attribute(X,Y,$,Q,K);case C0.ComponentType.UNSIGNED_SHORT:return Z.AddUInt16Attribute(X,Y,$,Q,K);case C0.ComponentType.SHORT:return Z.AddInt16Attribute(X,Y,$,Q,K);case C0.ComponentType.UNSIGNED_INT:return Z.AddUInt32Attribute(X,Y,$,Q,K);case C0.ComponentType.FLOAT:return Z.AddFloatAttribute(X,Y,$,Q,K);default:throw new Error(`Unexpected component type, "${J}".`)}}class Dw extends Error{}class Sz extends v1{constructor(...Z){super(...Z);this.extensionName=Q8,this.prereadTypes=[o.PRIMITIVE],this.prewriteTypes=[o.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,Lk1(this._decoderModule);if(Z==="draco3d.encoder")this._encoderModule=J,wk1(this._encoderModule);return this}setEncoderOptions(Z){return this._encoderOptions=Z,this}preread(Z){if(!this._decoderModule)throw new Error(`[${Q8}] Please install extension dependency, "draco3d.decoder".`);let J=this.document.getLogger(),X=Z.jsonDoc,Y=new Map;try{let $=X.json.meshes||[];for(let Q of $)for(let K of Q.primitives){if(!K.extensions||!K.extensions[Q8])continue;let W=K.extensions[Q8],[G,V]=Y.get(W.bufferView)||[];if(!V||!G){let z=X.json.bufferViews[W.bufferView],F=X.json.buffers[z.buffer],H=F.uri?X.resources[F.uri]:X.resources[kk],q=z.byteOffset||0,U=z.byteLength,B=g6.toView(H,q,U);G=new this._decoderModule.Decoder,V=qk1(G,B),Y.set(W.bufferView,[G,V]),J.debug(`[${Q8}] Decompressed ${B.byteLength} bytes.`)}for(let z in W.attributes){let F=Z.jsonDoc.json.accessors[K.attributes[z]],H=G.GetAttributeByUniqueId(V,W.attributes[z]),q=Bk1(G,V,H,F);Z.accessors[K.attributes[z]].setArray(q)}if(K.indices!==void 0)Z.accessors[K.indices].setArray(Uk1(G,V))}}finally{for(let[$,Q]of Array.from(Y.values()))this._decoderModule.destroy($),this._decoderModule.destroy(Q)}return this}read(Z){return this}prewrite(Z,J){if(!this._encoderModule)throw new Error(`[${Q8}] Please install extension dependency, "draco3d.encoder".`);let X=this.document.getLogger();X.debug(`[${Q8}] Compression options: ${JSON.stringify(this._encoderOptions)}`);let Y=Rk1(this.document),$=new Map,Q="mesh";if(this._encoderOptions.quantizationVolume==="scene")if(this.document.getRoot().listScenes().length!==1)X.warn(`[${Q8}]: quantizationVolume=scene requires exactly 1 scene.`);else Q=ir(this.document.getRoot().listScenes().pop());for(let K of Array.from(Y.keys())){let W=Y.get(K);if(!W)throw new Error("Unexpected primitive.");if($.has(W)){$.set(W,$.get(W));continue}let G=K.getIndices(),V=Z.jsonDoc.json.accessors,z;try{z=Ok1(K,KJ({},this._encoderOptions,{quantizationVolume:Q}))}catch(q){if(q instanceof Dw){X.warn(`[${Q8}]: ${q.message} Skipping primitive compression.`);continue}throw q}$.set(W,z);let F=Z.createAccessorDef(G);if(F.count=z.numIndices,Z.accessorIndexMap.set(G,V.length),V.push(F),z.numVertices>65534&&C0.getComponentSize(F.componentType)<=2)F.componentType=C0.ComponentType.UNSIGNED_INT;else if(z.numVertices>254&&C0.getComponentSize(F.componentType)<=1)F.componentType=C0.ComponentType.UNSIGNED_SHORT;for(let q of K.listSemantics()){let U=K.getAttribute(q);if(z.attributeIDs[q]===void 0)continue;let B=Z.createAccessorDef(U);B.count=z.numVertices,Z.accessorIndexMap.set(U,V.length),V.push(B)}let H=K.getAttribute("POSITION").getBuffer()||this.document.getRoot().listBuffers()[0];if(!Z.otherBufferViews.has(H))Z.otherBufferViews.set(H,[]);Z.otherBufferViews.get(H).push(z.data)}return X.debug(`[${Q8}] Compressed ${Y.size} primitives.`),Z.extensionData[Q8]={primitiveHashMap:Y,primitiveEncodingMap:$},this}write(Z){let J=Z.extensionData[Q8];for(let X of this.document.getRoot().listMeshes()){let Y=Z.jsonDoc.json.meshes[Z.meshIndexMap.get(X)];for(let $=0;$<X.listPrimitives().length;$++){let Q=X.listPrimitives()[$],K=Y.primitives[$],W=J.primitiveHashMap.get(Q);if(!W)continue;let G=J.primitiveEncodingMap.get(W);if(!G)continue;K.extensions=K.extensions||{},K.extensions[Q8]={bufferView:Z.otherBufferViewsIndexMap.get(G.data),attributes:G.attributeIDs}}}if(!J.primitiveHashMap.size){let X=Z.jsonDoc.json;X.extensionsUsed=(X.extensionsUsed||[]).filter((Y)=>Y!==Q8),X.extensionsRequired=(X.extensionsRequired||[]).filter((Y)=>Y!==Q8)}return this}}Sz.EXTENSION_NAME=Q8;Sz.EncoderMethod=_z;function Rk1(Z){let J=Z.getLogger(),X=new Set,Y=new Set,$=0,Q=0;for(let F of Z.getRoot().listMeshes())for(let H of F.listPrimitives())if(!H.getIndices())Y.add(H),$++;else if(H.getMode()!==IX.Mode.TRIANGLES)Y.add(H),Q++;else X.add(H);if($>0)J.warn(`[${Q8}] Skipping Draco compression of ${$} non-indexed primitives.`);if(Q>0)J.warn(`[${Q8}] Skipping Draco compression of ${Q} non-TRIANGLES primitives.`);let K=Z.getRoot().listAccessors(),W=new Map;for(let F=0;F<K.length;F++)W.set(K[F],F);let G=new Map,V=new Set,z=new Map;for(let F of Array.from(X)){let H=Qt(F,W);if(V.has(H)){z.set(F,H);continue}if(G.has(F.getIndices())){let q=F.getIndices(),U=q.clone();W.set(U,Z.getRoot().listAccessors().length-1),F.swap(q,U)}for(let q of F.listAttributes())if(G.has(q)){let U=q.clone();W.set(U,Z.getRoot().listAccessors().length-1),F.swap(q,U)}H=Qt(F,W),V.add(H),z.set(F,H),G.set(F.getIndices(),H);for(let q of F.listAttributes())G.set(q,H)}for(let F of Array.from(G.keys())){let H=new Set(F.listParents().map((q)=>q.propertyType));if(H.size!==2||!H.has(o.PRIMITIVE)||!H.has(o.ROOT))throw new Error(`[${Q8}] Compressed accessors must only be used as indices or vertex attributes.`)}for(let F of Array.from(X)){let H=z.get(F),q=F.getIndices();if(G.get(q)!==H||F.listAttributes().some((U)=>G.get(U)!==H))throw new Error(`[${Q8}] Draco primitives must share all, or no, accessors.`)}for(let F of Array.from(Y)){let H=F.getIndices();if(G.has(H)||F.listAttributes().some((q)=>G.has(q)))throw new Error(`[${Q8}] Accessor cannot be shared by compressed and uncompressed primitives.`)}return z}function Qt(Z,J){let X=[],Y=Z.getIndices();X.push(J.get(Y));for(let $ of Z.listAttributes())X.push(J.get($));return X.sort().join("|")}class CW extends t1{init(){this.extensionName=a9,this.propertyType="Light",this.parentTypes=[o.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{color:[1,1,1],intensity:1,type:CW.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)}}CW.EXTENSION_NAME=a9;CW.Type={POINT:"point",SPOT:"spot",DIRECTIONAL:"directional"};class mk extends v1{constructor(...Z){super(...Z);this.extensionName=a9}createLight(Z=""){return new CW(this.document.getGraph(),Z)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[a9])return this;let $=(J.json.extensions[a9].lights||[]).map((Q)=>{var K,W;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(((K=Q.spot)==null?void 0:K.innerConeAngle)!==void 0)G.setInnerConeAngle(Q.spot.innerConeAngle);if(((W=Q.spot)==null?void 0:W.outerConeAngle)!==void 0)G.setOuterConeAngle(Q.spot.outerConeAngle);return G});return J.json.nodes.forEach((Q,K)=>{if(!Q.extensions||!Q.extensions[a9])return;let W=Q.extensions[a9];Z.nodes[K].setExtension(a9,$[W.light])}),this}write(Z){let J=Z.jsonDoc;if(this.properties.size===0)return this;let X=[],Y=new Map;for(let $ of this.properties){let Q=$,K={type:Q.getType()};if(!U8.eq(Q.getColor(),[1,1,1]))K.color=Q.getColor();if(Q.getIntensity()!==1)K.intensity=Q.getIntensity();if(Q.getRange()!=null)K.range=Q.getRange();if(Q.getName())K.name=Q.getName();if(Q.getType()===CW.Type.SPOT)K.spot={innerConeAngle:Q.getInnerConeAngle(),outerConeAngle:Q.getOuterConeAngle()};X.push(K),Y.set(Q,X.length-1)}return this.document.getRoot().listNodes().forEach(($)=>{let Q=$.getExtension(a9);if(Q){let K=Z.nodeIndexMap.get($),W=J.json.nodes[K];W.extensions=W.extensions||{},W.extensions[a9]={light:Y.get(Q)}}}),J.json.extensions=J.json.extensions||{},J.json.extensions[a9]={lights:X},this}}mk.EXTENSION_NAME=a9;var{R:jk1,G:Dk1,B:Pk1}=z9;class uk extends t1{init(){this.extensionName=nZ,this.propertyType="Anisotropy",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{anisotropyStrength:0,anisotropyRotation:0,anisotropyTexture:null,anisotropyTextureInfo:new E1(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:jk1|Dk1|Pk1})}}uk.EXTENSION_NAME=nZ;class dk extends v1{constructor(...Z){super(...Z);this.extensionName=nZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createAnisotropy(){return new uk(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[nZ]){let K=this.createAnisotropy();Z.materials[Q].setExtension(nZ,K);let W=$.extensions[nZ];if(W.anisotropyStrength!==void 0)K.setAnisotropyStrength(W.anisotropyStrength);if(W.anisotropyRotation!==void 0)K.setAnisotropyRotation(W.anisotropyRotation);if(W.anisotropyTexture!==void 0){let G=W.anisotropyTexture,V=Z.textures[Y[G.index].source];K.setAnisotropyTexture(V),Z.setTextureInfo(K.getAnisotropyTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(nZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[nZ]={};if(Y.getAnisotropyStrength()>0)K.anisotropyStrength=Y.getAnisotropyStrength();if(Y.getAnisotropyRotation()!==0)K.anisotropyRotation=Y.getAnisotropyRotation();if(Y.getAnisotropyTexture()){let W=Y.getAnisotropyTexture(),G=Y.getAnisotropyTextureInfo();K.anisotropyTexture=Z.createTextureInfoDef(W,G)}}}),this}}dk.EXTENSION_NAME=nZ;var{R:Kt,G:Wt,B:Ck1}=z9;class ck extends t1{init(){this.extensionName=aZ,this.propertyType="Clearcoat",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{clearcoatFactor:0,clearcoatTexture:null,clearcoatTextureInfo:new E1(this.graph,"clearcoatTextureInfo"),clearcoatRoughnessFactor:0,clearcoatRoughnessTexture:null,clearcoatRoughnessTextureInfo:new E1(this.graph,"clearcoatRoughnessTextureInfo"),clearcoatNormalScale:1,clearcoatNormalTexture:null,clearcoatNormalTextureInfo:new E1(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:Kt})}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:Wt})}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:Kt|Wt|Ck1})}}ck.EXTENSION_NAME=aZ;class lk extends v1{constructor(...Z){super(...Z);this.extensionName=aZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createClearcoat(){return new ck(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[aZ]){let K=this.createClearcoat();Z.materials[Q].setExtension(aZ,K);let W=$.extensions[aZ];if(W.clearcoatFactor!==void 0)K.setClearcoatFactor(W.clearcoatFactor);if(W.clearcoatRoughnessFactor!==void 0)K.setClearcoatRoughnessFactor(W.clearcoatRoughnessFactor);if(W.clearcoatTexture!==void 0){let G=W.clearcoatTexture,V=Z.textures[Y[G.index].source];K.setClearcoatTexture(V),Z.setTextureInfo(K.getClearcoatTextureInfo(),G)}if(W.clearcoatRoughnessTexture!==void 0){let G=W.clearcoatRoughnessTexture,V=Z.textures[Y[G.index].source];K.setClearcoatRoughnessTexture(V),Z.setTextureInfo(K.getClearcoatRoughnessTextureInfo(),G)}if(W.clearcoatNormalTexture!==void 0){let G=W.clearcoatNormalTexture,V=Z.textures[Y[G.index].source];if(K.setClearcoatNormalTexture(V),Z.setTextureInfo(K.getClearcoatNormalTextureInfo(),G),G.scale!==void 0)K.setClearcoatNormalScale(G.scale)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(aZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[aZ]={clearcoatFactor:Y.getClearcoatFactor(),clearcoatRoughnessFactor:Y.getClearcoatRoughnessFactor()};if(Y.getClearcoatTexture()){let W=Y.getClearcoatTexture(),G=Y.getClearcoatTextureInfo();K.clearcoatTexture=Z.createTextureInfoDef(W,G)}if(Y.getClearcoatRoughnessTexture()){let W=Y.getClearcoatRoughnessTexture(),G=Y.getClearcoatRoughnessTextureInfo();K.clearcoatRoughnessTexture=Z.createTextureInfoDef(W,G)}if(Y.getClearcoatNormalTexture()){let W=Y.getClearcoatNormalTexture(),G=Y.getClearcoatNormalTextureInfo();if(K.clearcoatNormalTexture=Z.createTextureInfoDef(W,G),Y.getClearcoatNormalScale()!==1)K.clearcoatNormalTexture.scale=Y.getClearcoatNormalScale()}}}),this}}lk.EXTENSION_NAME=aZ;var{R:Tk1,G:kk1,B:Ek1,A:Ik1}=z9;class pk extends t1{init(){this.extensionName=sZ,this.propertyType="DiffuseTransmission",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseTransmissionFactor:0,diffuseTransmissionTexture:null,diffuseTransmissionTextureInfo:new E1(this.graph,"diffuseTransmissionTextureInfo"),diffuseTransmissionColorFactor:[1,1,1],diffuseTransmissionColorTexture:null,diffuseTransmissionColorTextureInfo:new E1(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:Ik1})}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:Tk1|kk1|Ek1})}}pk.EXTENSION_NAME=sZ;class ik extends v1{constructor(...Z){super(...Z);this.extensionName=sZ}createDiffuseTransmission(){return new pk(this.document.getGraph())}read(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[sZ]){let K=this.createDiffuseTransmission();Z.materials[Q].setExtension(sZ,K);let W=$.extensions[sZ];if(W.diffuseTransmissionFactor!==void 0)K.setDiffuseTransmissionFactor(W.diffuseTransmissionFactor);if(W.diffuseTransmissionColorFactor!==void 0)K.setDiffuseTransmissionColorFactor(W.diffuseTransmissionColorFactor);if(W.diffuseTransmissionTexture!==void 0){let G=W.diffuseTransmissionTexture,V=Z.textures[Y[G.index].source];K.setDiffuseTransmissionTexture(V),Z.setTextureInfo(K.getDiffuseTransmissionTextureInfo(),G)}if(W.diffuseTransmissionColorTexture!==void 0){let G=W.diffuseTransmissionColorTexture,V=Z.textures[Y[G.index].source];K.setDiffuseTransmissionColorTexture(V),Z.setTextureInfo(K.getDiffuseTransmissionColorTextureInfo(),G)}}}),this}write(Z){let J=Z.jsonDoc;for(let X of this.document.getRoot().listMaterials()){let Y=X.getExtension(sZ);if(!Y)continue;let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[sZ]={diffuseTransmissionFactor:Y.getDiffuseTransmissionFactor(),diffuseTransmissionColorFactor:Y.getDiffuseTransmissionColorFactor()};if(Y.getDiffuseTransmissionTexture()){let W=Y.getDiffuseTransmissionTexture(),G=Y.getDiffuseTransmissionTextureInfo();K.diffuseTransmissionTexture=Z.createTextureInfoDef(W,G)}if(Y.getDiffuseTransmissionColorTexture()){let W=Y.getDiffuseTransmissionColorTexture(),G=Y.getDiffuseTransmissionColorTextureInfo();K.diffuseTransmissionColorTexture=Z.createTextureInfoDef(W,G)}}return this}}ik.EXTENSION_NAME=sZ;class nk extends t1{init(){this.extensionName=oZ,this.propertyType="Dispersion",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{dispersion:0})}getDispersion(){return this.get("dispersion")}setDispersion(Z){return this.set("dispersion",Z)}}nk.EXTENSION_NAME=oZ;class ak extends v1{constructor(...Z){super(...Z);this.extensionName=oZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createDispersion(){return new nk(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((Y,$)=>{if(Y.extensions&&Y.extensions[oZ]){let Q=this.createDispersion();Z.materials[$].setExtension(oZ,Q);let K=Y.extensions[oZ];if(K.dispersion!==void 0)Q.setDispersion(K.dispersion)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(oZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{},Q.extensions[oZ]={dispersion:Y.getDispersion()}}}),this}}ak.EXTENSION_NAME=oZ;class sk extends t1{init(){this.extensionName=rZ,this.propertyType="EmissiveStrength",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{emissiveStrength:1})}getEmissiveStrength(){return this.get("emissiveStrength")}setEmissiveStrength(Z){return this.set("emissiveStrength",Z)}}sk.EXTENSION_NAME=rZ;class ok extends v1{constructor(...Z){super(...Z);this.extensionName=rZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createEmissiveStrength(){return new sk(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((Y,$)=>{if(Y.extensions&&Y.extensions[rZ]){let Q=this.createEmissiveStrength();Z.materials[$].setExtension(rZ,Q);let K=Y.extensions[rZ];if(K.emissiveStrength!==void 0)Q.setEmissiveStrength(K.emissiveStrength)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(rZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{},Q.extensions[rZ]={emissiveStrength:Y.getEmissiveStrength()}}}),this}}ok.EXTENSION_NAME=rZ;class rk extends t1{init(){this.extensionName=tZ,this.propertyType="IOR",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{ior:1.5})}getIOR(){return this.get("ior")}setIOR(Z){return this.set("ior",Z)}}rk.EXTENSION_NAME=tZ;class Ew extends v1{constructor(...Z){super(...Z);this.extensionName=tZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createIOR(){return new rk(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((Y,$)=>{if(Y.extensions&&Y.extensions[tZ]){let Q=this.createIOR();Z.materials[$].setExtension(tZ,Q);let K=Y.extensions[tZ];if(K.ior!==void 0)Q.setIOR(K.ior)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(tZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{},Q.extensions[tZ]={ior:Y.getIOR()}}}),this}}Ew.EXTENSION_NAME=tZ;var{R:_k1,G:vk1}=z9;class tk extends t1{init(){this.extensionName=eZ,this.propertyType="Iridescence",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{iridescenceFactor:0,iridescenceTexture:null,iridescenceTextureInfo:new E1(this.graph,"iridescenceTextureInfo"),iridescenceIOR:1.3,iridescenceThicknessMinimum:100,iridescenceThicknessMaximum:400,iridescenceThicknessTexture:null,iridescenceThicknessTextureInfo:new E1(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:_k1})}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:vk1})}}tk.EXTENSION_NAME=eZ;class ek extends v1{constructor(...Z){super(...Z);this.extensionName=eZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createIridescence(){return new tk(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[eZ]){let K=this.createIridescence();Z.materials[Q].setExtension(eZ,K);let W=$.extensions[eZ];if(W.iridescenceFactor!==void 0)K.setIridescenceFactor(W.iridescenceFactor);if(W.iridescenceIor!==void 0)K.setIridescenceIOR(W.iridescenceIor);if(W.iridescenceThicknessMinimum!==void 0)K.setIridescenceThicknessMinimum(W.iridescenceThicknessMinimum);if(W.iridescenceThicknessMaximum!==void 0)K.setIridescenceThicknessMaximum(W.iridescenceThicknessMaximum);if(W.iridescenceTexture!==void 0){let G=W.iridescenceTexture,V=Z.textures[Y[G.index].source];K.setIridescenceTexture(V),Z.setTextureInfo(K.getIridescenceTextureInfo(),G)}if(W.iridescenceThicknessTexture!==void 0){let G=W.iridescenceThicknessTexture,V=Z.textures[Y[G.index].source];K.setIridescenceThicknessTexture(V),Z.setTextureInfo(K.getIridescenceThicknessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(eZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[eZ]={};if(Y.getIridescenceFactor()>0)K.iridescenceFactor=Y.getIridescenceFactor();if(Y.getIridescenceIOR()!==1.3)K.iridescenceIor=Y.getIridescenceIOR();if(Y.getIridescenceThicknessMinimum()!==100)K.iridescenceThicknessMinimum=Y.getIridescenceThicknessMinimum();if(Y.getIridescenceThicknessMaximum()!==400)K.iridescenceThicknessMaximum=Y.getIridescenceThicknessMaximum();if(Y.getIridescenceTexture()){let W=Y.getIridescenceTexture(),G=Y.getIridescenceTextureInfo();K.iridescenceTexture=Z.createTextureInfoDef(W,G)}if(Y.getIridescenceThicknessTexture()){let W=Y.getIridescenceThicknessTexture(),G=Y.getIridescenceThicknessTextureInfo();K.iridescenceThicknessTexture=Z.createTextureInfoDef(W,G)}}}),this}}ek.EXTENSION_NAME=eZ;var{R:Gt,G:Vt,B:zt,A:Ht}=z9;class ZE extends t1{init(){this.extensionName=ZJ,this.propertyType="PBRSpecularGlossiness",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseFactor:[1,1,1,1],diffuseTexture:null,diffuseTextureInfo:new E1(this.graph,"diffuseTextureInfo"),specularFactor:[1,1,1],glossinessFactor:1,specularGlossinessTexture:null,specularGlossinessTextureInfo:new E1(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:Gt|Vt|zt|Ht,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:Gt|Vt|zt|Ht})}}ZE.EXTENSION_NAME=ZJ;class Iw extends v1{constructor(...Z){super(...Z);this.extensionName=ZJ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createPBRSpecularGlossiness(){return new ZE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[ZJ]){let K=this.createPBRSpecularGlossiness();Z.materials[Q].setExtension(ZJ,K);let W=$.extensions[ZJ];if(W.diffuseFactor!==void 0)K.setDiffuseFactor(W.diffuseFactor);if(W.specularFactor!==void 0)K.setSpecularFactor(W.specularFactor);if(W.glossinessFactor!==void 0)K.setGlossinessFactor(W.glossinessFactor);if(W.diffuseTexture!==void 0){let G=W.diffuseTexture,V=Z.textures[Y[G.index].source];K.setDiffuseTexture(V),Z.setTextureInfo(K.getDiffuseTextureInfo(),G)}if(W.specularGlossinessTexture!==void 0){let G=W.specularGlossinessTexture,V=Z.textures[Y[G.index].source];K.setSpecularGlossinessTexture(V),Z.setTextureInfo(K.getSpecularGlossinessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(ZJ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[ZJ]={diffuseFactor:Y.getDiffuseFactor(),specularFactor:Y.getSpecularFactor(),glossinessFactor:Y.getGlossinessFactor()};if(Y.getDiffuseTexture()){let W=Y.getDiffuseTexture(),G=Y.getDiffuseTextureInfo();K.diffuseTexture=Z.createTextureInfoDef(W,G)}if(Y.getSpecularGlossinessTexture()){let W=Y.getSpecularGlossinessTexture(),G=Y.getSpecularGlossinessTextureInfo();K.specularGlossinessTexture=Z.createTextureInfoDef(W,G)}}}),this}}Iw.EXTENSION_NAME=ZJ;var{R:Sk1,G:Ak1,B:xk1,A:hk1}=z9;class JE extends t1{init(){this.extensionName=JJ,this.propertyType="Sheen",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{sheenColorFactor:[0,0,0],sheenColorTexture:null,sheenColorTextureInfo:new E1(this.graph,"sheenColorTextureInfo"),sheenRoughnessFactor:0,sheenRoughnessTexture:null,sheenRoughnessTextureInfo:new E1(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:Sk1|Ak1|xk1,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:hk1})}}JE.EXTENSION_NAME=JJ;class XE extends v1{constructor(...Z){super(...Z);this.extensionName=JJ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createSheen(){return new JE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[JJ]){let K=this.createSheen();Z.materials[Q].setExtension(JJ,K);let W=$.extensions[JJ];if(W.sheenColorFactor!==void 0)K.setSheenColorFactor(W.sheenColorFactor);if(W.sheenRoughnessFactor!==void 0)K.setSheenRoughnessFactor(W.sheenRoughnessFactor);if(W.sheenColorTexture!==void 0){let G=W.sheenColorTexture,V=Z.textures[Y[G.index].source];K.setSheenColorTexture(V),Z.setTextureInfo(K.getSheenColorTextureInfo(),G)}if(W.sheenRoughnessTexture!==void 0){let G=W.sheenRoughnessTexture,V=Z.textures[Y[G.index].source];K.setSheenRoughnessTexture(V),Z.setTextureInfo(K.getSheenRoughnessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(JJ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[JJ]={sheenColorFactor:Y.getSheenColorFactor(),sheenRoughnessFactor:Y.getSheenRoughnessFactor()};if(Y.getSheenColorTexture()){let W=Y.getSheenColorTexture(),G=Y.getSheenColorTextureInfo();K.sheenColorTexture=Z.createTextureInfoDef(W,G)}if(Y.getSheenRoughnessTexture()){let W=Y.getSheenRoughnessTexture(),G=Y.getSheenRoughnessTextureInfo();K.sheenRoughnessTexture=Z.createTextureInfoDef(W,G)}}}),this}}XE.EXTENSION_NAME=JJ;var{R:fk1,G:yk1,B:bk1,A:gk1}=z9;class YE extends t1{init(){this.extensionName=XJ,this.propertyType="Specular",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{specularFactor:1,specularTexture:null,specularTextureInfo:new E1(this.graph,"specularTextureInfo"),specularColorFactor:[1,1,1],specularColorTexture:null,specularColorTextureInfo:new E1(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:gk1})}getSpecularColorTexture(){return this.getRef("specularColorTexture")}getSpecularColorTextureInfo(){return this.getRef("specularColorTexture")?this.getRef("specularColorTextureInfo"):null}setSpecularColorTexture(Z){return this.setRef("specularColorTexture",Z,{channels:fk1|yk1|bk1,isColor:!0})}}YE.EXTENSION_NAME=XJ;class _w extends v1{constructor(...Z){super(...Z);this.extensionName=XJ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createSpecular(){return new YE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[XJ]){let K=this.createSpecular();Z.materials[Q].setExtension(XJ,K);let W=$.extensions[XJ];if(W.specularFactor!==void 0)K.setSpecularFactor(W.specularFactor);if(W.specularColorFactor!==void 0)K.setSpecularColorFactor(W.specularColorFactor);if(W.specularTexture!==void 0){let G=W.specularTexture,V=Z.textures[Y[G.index].source];K.setSpecularTexture(V),Z.setTextureInfo(K.getSpecularTextureInfo(),G)}if(W.specularColorTexture!==void 0){let G=W.specularColorTexture,V=Z.textures[Y[G.index].source];K.setSpecularColorTexture(V),Z.setTextureInfo(K.getSpecularColorTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(XJ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[XJ]={};if(Y.getSpecularFactor()!==1)K.specularFactor=Y.getSpecularFactor();if(!U8.eq(Y.getSpecularColorFactor(),[1,1,1]))K.specularColorFactor=Y.getSpecularColorFactor();if(Y.getSpecularTexture()){let W=Y.getSpecularTexture(),G=Y.getSpecularTextureInfo();K.specularTexture=Z.createTextureInfoDef(W,G)}if(Y.getSpecularColorTexture()){let W=Y.getSpecularColorTexture(),G=Y.getSpecularColorTextureInfo();K.specularColorTexture=Z.createTextureInfoDef(W,G)}}}),this}}_w.EXTENSION_NAME=XJ;var{R:mk1}=z9;class $E extends t1{init(){this.extensionName=YJ,this.propertyType="Transmission",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{transmissionFactor:0,transmissionTexture:null,transmissionTextureInfo:new E1(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:mk1})}}$E.EXTENSION_NAME=YJ;class QE extends v1{constructor(...Z){super(...Z);this.extensionName=YJ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createTransmission(){return new $E(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[YJ]){let K=this.createTransmission();Z.materials[Q].setExtension(YJ,K);let W=$.extensions[YJ];if(W.transmissionFactor!==void 0)K.setTransmissionFactor(W.transmissionFactor);if(W.transmissionTexture!==void 0){let G=W.transmissionTexture,V=Z.textures[Y[G.index].source];K.setTransmissionTexture(V),Z.setTextureInfo(K.getTransmissionTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(YJ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[YJ]={transmissionFactor:Y.getTransmissionFactor()};if(Y.getTransmissionTexture()){let W=Y.getTransmissionTexture(),G=Y.getTransmissionTextureInfo();K.transmissionTexture=Z.createTextureInfoDef(W,G)}}}),this}}QE.EXTENSION_NAME=YJ;class KE extends t1{init(){this.extensionName=vX,this.propertyType="Unlit",this.parentTypes=[o.MATERIAL]}}KE.EXTENSION_NAME=vX;class vw extends v1{constructor(...Z){super(...Z);this.extensionName=vX,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createUnlit(){return new KE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((X,Y)=>{if(X.extensions&&X.extensions[vX])Z.materials[Y].setExtension(vX,this.createUnlit())}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{if(X.getExtension(vX)){let Y=Z.materialIndexMap.get(X),$=J.json.materials[Y];$.extensions=$.extensions||{},$.extensions[vX]={}}}),this}}vw.EXTENSION_NAME=vX;class WE extends t1{init(){this.extensionName=u6,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")}}WE.EXTENSION_NAME=u6;class GE extends t1{init(){this.extensionName=u6,this.propertyType="MappingList",this.parentTypes=[o.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")}}GE.EXTENSION_NAME=u6;class Pw extends t1{init(){this.extensionName=u6,this.propertyType="Variant",this.parentTypes=["MappingList"]}}Pw.EXTENSION_NAME=u6;class VE extends v1{constructor(...Z){super(...Z);this.extensionName=u6}createMappingList(){return new GE(this.document.getGraph())}createVariant(Z=""){return new Pw(this.document.getGraph(),Z)}createMapping(){return new WE(this.document.getGraph())}listVariants(){return Array.from(this.properties).filter((Z)=>Z instanceof Pw)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[u6])return this;let $=(J.json.extensions[u6].variants||[]).map((K)=>this.createVariant().setName(K.name||""));return(J.json.meshes||[]).forEach((K,W)=>{let G=Z.meshes[W];(K.primitives||[]).forEach((z,F)=>{if(!z.extensions||!z.extensions[u6])return;let H=this.createMappingList(),q=z.extensions[u6];for(let U of q.mappings){let B=this.createMapping();if(U.material!==void 0)B.setMaterial(Z.materials[U.material]);for(let L of U.variants||[])B.addVariant($[L]);H.addMapping(B)}G.listPrimitives()[F].setExtension(u6,H)})}),this}write(Z){let J=Z.jsonDoc,X=this.listVariants();if(!X.length)return this;let Y=[],$=new Map;for(let Q of X)$.set(Q,Y.length),Y.push(Z.createPropertyDef(Q));for(let Q of this.document.getRoot().listMeshes()){let K=Z.meshIndexMap.get(Q);Q.listPrimitives().forEach((W,G)=>{let V=W.getExtension(u6);if(!V)return;let z=Z.jsonDoc.json.meshes[K].primitives[G],F=V.listMappings().map((H)=>{let q=Z.createPropertyDef(H),U=H.getMaterial();if(U)q.material=Z.materialIndexMap.get(U);return q.variants=H.listVariants().map((B)=>$.get(B)),q});z.extensions=z.extensions||{},z.extensions[u6]={mappings:F}})}return J.json.extensions=J.json.extensions||{},J.json.extensions[u6]={variants:Y},this}}VE.EXTENSION_NAME=u6;var{G:uk1}=z9;class zE extends t1{init(){this.extensionName=$J,this.propertyType="Volume",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{thicknessFactor:0,thicknessTexture:null,thicknessTextureInfo:new E1(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:uk1})}getAttenuationDistance(){return this.get("attenuationDistance")}setAttenuationDistance(Z){return this.set("attenuationDistance",Z)}getAttenuationColor(){return this.get("attenuationColor")}setAttenuationColor(Z){return this.set("attenuationColor",Z)}}zE.EXTENSION_NAME=$J;class HE extends v1{constructor(...Z){super(...Z);this.extensionName=$J,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createVolume(){return new zE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[$J]){let K=this.createVolume();Z.materials[Q].setExtension($J,K);let W=$.extensions[$J];if(W.thicknessFactor!==void 0)K.setThicknessFactor(W.thicknessFactor);if(W.attenuationDistance!==void 0)K.setAttenuationDistance(W.attenuationDistance);if(W.attenuationColor!==void 0)K.setAttenuationColor(W.attenuationColor);if(W.thicknessTexture!==void 0){let G=W.thicknessTexture,V=Z.textures[Y[G.index].source];K.setThicknessTexture(V),Z.setTextureInfo(K.getThicknessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension($J);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[$J]={};if(Y.getThicknessFactor()>0)K.thicknessFactor=Y.getThicknessFactor();if(Number.isFinite(Y.getAttenuationDistance()))K.attenuationDistance=Y.getAttenuationDistance();if(!U8.eq(Y.getAttenuationColor(),[1,1,1]))K.attenuationColor=Y.getAttenuationColor();if(Y.getThicknessTexture()){let W=Y.getThicknessTexture(),G=Y.getThicknessTextureInfo();K.thicknessTexture=Z.createTextureInfoDef(W,G)}}}),this}}HE.EXTENSION_NAME=$J;class Az extends v1{constructor(...Z){super(...Z);this.extensionName=Ft}read(Z){return this}write(Z){return this}}Az.EXTENSION_NAME=Ft;class Mt{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=jw(Z);return[J.pixelWidth,J.pixelHeight]}getChannels(Z){let X=jw(Z).dataFormatDescriptor[0];if(X.colorModel===tr)return X.samples.length===2&&(X.samples[1].channelType&15)===15?4:3;else if(X.colorModel===er)return(X.samples[0].channelType&15)===3?4:3;throw new Error(`Unexpected KTX2 colorModel, "${X.colorModel}".`)}getVRAMByteLength(Z){let J=jw(Z),X=this.getChannels(Z)>3,Y=0;for(let $=0;$<J.levels.length;$++){let Q=J.levels[$];if(Q.uncompressedByteLength)Y+=Q.uncompressedByteLength;else{let K=Math.max(1,Math.floor(J.pixelWidth/Math.pow(2,$))),W=Math.max(1,Math.floor(J.pixelHeight/Math.pow(2,$))),G=X?16:8;Y+=K/4*(W/4)*G}}return Y}}class FE extends v1{constructor(...Z){super(...Z);this.extensionName=Ez,this.prereadTypes=[o.TEXTURE]}static register(){a4.registerFormat("image/ktx2",new Mt)}preread(Z){return Z.jsonDoc.json.textures.forEach((J)=>{if(J.extensions&&J.extensions[Ez]){let X=J.extensions[Ez];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 Y=Z.imageIndexMap.get(X);J.json.textures.forEach(($)=>{if($.source===Y)$.extensions=$.extensions||{},$.extensions[Ez]={source:$.source},delete $.source})}}),this}}FE.EXTENSION_NAME=Ez;class qE extends t1{init(){this.extensionName=QJ,this.propertyType="Transform",this.parentTypes=[o.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)}}qE.EXTENSION_NAME=QJ;class UE extends v1{constructor(...Z){super(...Z);this.extensionName=QJ}createTransform(){return new qE(this.document.getGraph())}read(Z){for(let[J,X]of Array.from(Z.textureInfos.entries())){if(!X.extensions||!X.extensions[QJ])continue;let Y=this.createTransform(),$=X.extensions[QJ];if($.offset!==void 0)Y.setOffset($.offset);if($.rotation!==void 0)Y.setRotation($.rotation);if($.scale!==void 0)Y.setScale($.scale);if($.texCoord!==void 0)Y.setTexCoord($.texCoord);J.setExtension(QJ,Y)}return this}write(Z){let J=Array.from(Z.textureInfoDefMap.entries());for(let[X,Y]of J){let $=X.getExtension(QJ);if(!$)continue;Y.extensions=Y.extensions||{};let Q={},K=U8.eq;if(!K($.getOffset(),[0,0]))Q.offset=$.getOffset();if($.getRotation()!==0)Q.rotation=$.getRotation();if(!K($.getScale(),[1,1]))Q.scale=$.getScale();if($.getTexCoord()!=null)Q.texCoord=$.getTexCoord();Y.extensions[QJ]=Q}return this}}UE.EXTENSION_NAME=QJ;var dk1=[o.ROOT,o.SCENE,o.NODE,o.MESH,o.MATERIAL,o.TEXTURE,o.ANIMATION];class BE extends t1{init(){this.extensionName=s9,this.propertyType="Packet",this.parentTypes=dk1}getDefaults(){return Object.assign(super.getDefaults(),{context:{},properties:{}})}getContext(){return this.get("context")}setContext(Z){return this.set("context",KJ({},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=KJ({},this.get("properties"));if(J)X[Z]=J;else delete X[Z];return this.set("properties",X)}toJSONLD(){let Z=fk(this.get("context")),J=fk(this.get("properties"));return KJ({"@context":Z},J)}fromJSONLD(Z){Z=fk(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(`${s9}: Missing context for term, "${Z}".`)}}BE.EXTENSION_NAME=s9;function fk(Z){return JSON.parse(JSON.stringify(Z))}class LE extends v1{constructor(...Z){super(...Z);this.extensionName=s9}createPacket(){return new BE(this.document.getGraph())}listPackets(){return Array.from(this.properties)}read(Z){var J;let X=(J=Z.jsonDoc.json.extensions)==null?void 0:J[s9];if(!X||!X.packets)return this;let Y=Z.jsonDoc.json,$=this.document.getRoot(),Q=X.packets.map((G)=>this.createPacket().fromJSONLD(G)),K=[[Y.asset],Y.scenes,Y.nodes,Y.meshes,Y.materials,Y.images,Y.animations],W=[[$],$.listScenes(),$.listNodes(),$.listMeshes(),$.listMaterials(),$.listTextures(),$.listAnimations()];for(let G=0;G<K.length;G++){let V=K[G]||[];for(let z=0;z<V.length;z++){let F=V[z];if(F.extensions&&F.extensions[s9]){let H=F.extensions[s9];W[G][z].setExtension(s9,Q[H.packet])}}}return this}write(Z){let{json:J}=Z.jsonDoc,X=[];for(let Y of this.properties){X.push(Y.toJSONLD());for(let $ of Y.listParents()){let Q;switch($.propertyType){case o.ROOT:Q=J.asset;break;case o.SCENE:Q=J.scenes[Z.sceneIndexMap.get($)];break;case o.NODE:Q=J.nodes[Z.nodeIndexMap.get($)];break;case o.MESH:Q=J.meshes[Z.meshIndexMap.get($)];break;case o.MATERIAL:Q=J.materials[Z.materialIndexMap.get($)];break;case o.TEXTURE:Q=J.images[Z.imageIndexMap.get($)];break;case o.ANIMATION:Q=J.animations[Z.animationIndexMap.get($)];break;default:Q=null,this.document.getLogger().warn(`[${s9}]: Unsupported parent property, "${$.propertyType}"`);break}if(!Q)continue;Q.extensions=Q.extensions||{},Q.extensions[s9]={packet:X.length-1}}}if(X.length>0)J.extensions=J.extensions||{},J.extensions[s9]={packets:X};return this}}LE.EXTENSION_NAME=s9;var ck1=[Sz,mk,dk,lk,ik,ak,ok,Ew,ek,Iw,_w,XE,QE,vw,VE,HE,Az,FE,UE,LE],sx6=[Cw,vz,Tw,kw,...ck1];var lk1=r(sT(),1);function EW(){return EW=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},EW.apply(null,arguments)}var{POINTS:Nt,LINES:Sw,LINE_STRIP:pk1,LINE_LOOP:ik1,TRIANGLES:Aw,TRIANGLE_STRIP:nk1,TRIANGLE_FAN:ak1}=T8.Mode;function hX(Z,J){return Object.defineProperty(J,"name",{value:Z}),J}function d7(Z,J){let X=EW({},Z);for(let Y in J)if(J[Y]!==void 0)X[Y]=J[Y];return X}function mt(Z){let J=Z.getIndices(),X=Z.getAttribute("POSITION");switch(Z.getMode()){case T8.Mode.POINTS:return J?J.getCount():X.getCount();case T8.Mode.LINES:return J?J.getCount()/2:X.getCount()/2;case T8.Mode.LINE_LOOP:return J?J.getCount():X.getCount();case T8.Mode.LINE_STRIP:return J?J.getCount()-1:X.getCount()-1;case T8.Mode.TRIANGLES:return J?J.getCount()/3:X.getCount()/3;case T8.Mode.TRIANGLE_STRIP:case T8.Mode.TRIANGLE_FAN:return J?J.getCount()-2:X.getCount()-2;default:throw new Error("Unexpected mode: "+Z.getMode())}}var sk1=new Intl.NumberFormat(void 0,{maximumFractionDigits:0});function NE(Z){return sk1.format(Z)}function ok1(Z,J,X=2){let Y=Z>J?"–":"+",$="%";return Y+(Math.abs(Z-J)/Z*100).toFixed(X)+"%"}function bw(Z,J){return`${NE(Z)} → ${NE(J)} (${ok1(Z,J)})`}function kE(Z){let J=[];for(let X of Z.listAttributes())J.push(X);for(let X of Z.listTargets())for(let Y of X.listAttributes())J.push(Y);return Array.from(new Set(J))}function rk1(Z,J,X){Z.swap(J,X);for(let Y of Z.listTargets())Y.swap(J,X)}function tk1(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 WJ(Z,J){return Z.createAccessor(J.getName()).setArray(J.getArray()).setType(J.getType()).setBuffer(J.getBuffer()).setNormalized(J.getNormalized()).setSparse(J.getSparse())}function ek1(Z,J=Z){let X=EE(Z,J);for(let Y=0;Y<X.length;Y++)X[Y]=Y;return X}function EE(Z,J=Z){return J<=65534?new Uint16Array(Z):new Uint32Array(Z)}function ZE1(Z){return Z.listParents().some((J)=>J.propertyType!==s.ROOT)}function ut(Z){for(let J in Z)return!1;return!0}function dt(Z){let J=y6.fromGraph(Z.getGraph()),X=Z.getMaterial(),Y=J.getRoot().listMaterials().indexOf(X),$=XE1[Z.getMode()],Q=!!Z.getIndices(),K=Z.listSemantics().sort().map((G)=>{let V=Z.getAttribute(G),z=V.getElementSize(),F=V.getComponentType();return`${G}:${z}:${F}`}).join("+"),W=Z.listTargets().map((G)=>{return G.listSemantics().sort().map((V)=>{let z=Z.getAttribute(V),F=z.getElementSize(),H=z.getComponentType();return`${V}:${F}:${H}`}).join("+")}).join("~");return`${Y}|${$}|${Q}|${K}|${W}`}function JE1(Z){return Math.pow(2,Math.ceil(Math.log(Z)/Math.LN2))}var XE1={[Nt]:Nt,[Sw]:Sw,[pk1]:Sw,[ik1]:Sw,[Aw]:Aw,[nk1]:Aw,[ak1]:Aw},TW="center",Rt={pivot:"center"};function ct(Z=Rt){let J=d7(Rt,Z);return hX(TW,(X)=>{let Y=X.getLogger(),$=X.getRoot(),Q=$.listAnimations().length>0||$.listSkins().length>0;X.getRoot().listScenes().forEach((K,W)=>{Y.debug(`${TW}: Scene ${W+1} / ${$.listScenes().length}.`);let G;if(typeof J.pivot==="string"){let z=dT(K);if(G=[(z.max[0]-z.min[0])/2+z.min[0],(z.max[1]-z.min[1])/2+z.min[1],(z.max[2]-z.min[2])/2+z.min[2]],J.pivot==="above")G[1]=z.max[1];if(J.pivot==="below")G[1]=z.min[1]}else G=J.pivot;Y.debug(`${TW}: Pivot "${G.join(", ")}".`);let V=[-1*G[0],-1*G[1],-1*G[2]];if(Q){Y.debug(`${TW}: Model contains animation or skin. Adding a wrapper node.`);let z=X.createNode("Pivot").setTranslation(V);K.listChildren().forEach((F)=>z.addChild(F)),K.addChild(z)}else Y.debug(`${TW}: Skipping wrapper, offsetting all root nodes.`),K.listChildren().forEach((z)=>{let F=z.getTranslation();z.setTranslation([F[0]+V[0],F[1]+V[1],F[2]+V[2]])})}),Y.debug(`${TW}: Complete.`)})}function YE1(Z){let J=new Set,X=Z,Y;while(Y=X.getParentNode()){if(J.has(Y))throw new Error("Circular dependency in scene graph.");J.add(Y),X=Y}return X.listParents().filter(($)=>$ instanceof FW)}function $E1(Z){let J=YE1(Z),X=Z.getParentNode();if(!X)return Z;Z.setMatrix(Z.getWorldMatrix()),X.removeChild(Z);for(let Y of J)Y.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 QE1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[3],K=J[4],W=J[5],G=J[6],V=J[7],z=J[8],F=J[9],H=J[10],q=J[11],U=J[12],B=J[13],L=J[14],w=J[15],M=X*W-Y*K,N=X*G-$*K,R=X*V-Q*K,P=Y*G-$*W,D=Y*V-Q*W,C=$*V-Q*G,T=z*B-F*U,k=z*L-H*U,A=z*w-q*U,v=F*L-H*B,x=F*w-q*B,I=H*w-q*L,_=M*I-N*x+R*v+P*A-D*k+C*T;if(!_)return null;return _=1/_,Z[0]=(W*I-G*x+V*v)*_,Z[1]=($*x-Y*I-Q*v)*_,Z[2]=(B*C-L*D+w*P)*_,Z[3]=(H*D-F*C-q*P)*_,Z[4]=(G*A-K*I-V*k)*_,Z[5]=(X*I-$*A+Q*k)*_,Z[6]=(L*R-U*C-w*N)*_,Z[7]=(z*C-H*R+q*N)*_,Z[8]=(K*x-W*A+V*T)*_,Z[9]=(Y*A-X*x-Q*T)*_,Z[10]=(U*D-B*R+w*M)*_,Z[11]=(F*R-z*D-q*M)*_,Z[12]=(W*k-K*v-G*T)*_,Z[13]=(X*v-Y*k+$*T)*_,Z[14]=(B*N-U*P-L*M)*_,Z[15]=(z*P-F*N+H*M)*_,Z}function KE1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3],Q=Z[4],K=Z[5],W=Z[6],G=Z[7],V=Z[8],z=Z[9],F=Z[10],H=Z[11],q=Z[12],U=Z[13],B=Z[14],L=Z[15],w=J*K-X*Q,M=J*W-Y*Q,N=J*G-$*Q,R=X*W-Y*K,P=X*G-$*K,D=Y*G-$*W,C=V*U-z*q,T=V*B-F*q,k=V*L-H*q,A=z*B-F*U,v=z*L-H*U,x=F*L-H*B;return w*x-M*v+N*A+R*k-P*T+D*C}function lt(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=J[3],W=J[4],G=J[5],V=J[6],z=J[7],F=J[8],H=J[9],q=J[10],U=J[11],B=J[12],L=J[13],w=J[14],M=J[15],N=X[0],R=X[1],P=X[2],D=X[3];return Z[0]=N*Y+R*W+P*F+D*B,Z[1]=N*$+R*G+P*H+D*L,Z[2]=N*Q+R*V+P*q+D*w,Z[3]=N*K+R*z+P*U+D*M,N=X[4],R=X[5],P=X[6],D=X[7],Z[4]=N*Y+R*W+P*F+D*B,Z[5]=N*$+R*G+P*H+D*L,Z[6]=N*Q+R*V+P*q+D*w,Z[7]=N*K+R*z+P*U+D*M,N=X[8],R=X[9],P=X[10],D=X[11],Z[8]=N*Y+R*W+P*F+D*B,Z[9]=N*$+R*G+P*H+D*L,Z[10]=N*Q+R*V+P*q+D*w,Z[11]=N*K+R*z+P*U+D*M,N=X[12],R=X[13],P=X[14],D=X[15],Z[12]=N*Y+R*W+P*F+D*B,Z[13]=N*$+R*G+P*H+D*L,Z[14]=N*Q+R*V+P*q+D*w,Z[15]=N*K+R*z+P*U+D*M,Z}function WE1(){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 GE1(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 VE1(Z,J){if(Z===J){var X=J[1],Y=J[2],$=J[5];Z[1]=J[3],Z[2]=J[6],Z[3]=X,Z[5]=J[7],Z[6]=Y,Z[7]=$}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 zE1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[3],K=J[4],W=J[5],G=J[6],V=J[7],z=J[8],F=z*K-W*V,H=-z*Q+W*G,q=V*Q-K*G,U=X*F+Y*H+$*q;if(!U)return null;return U=1/U,Z[0]=F*U,Z[1]=(-z*Y+$*V)*U,Z[2]=(W*Y-$*K)*U,Z[3]=H*U,Z[4]=(z*X-$*G)*U,Z[5]=(-W*X+$*Q)*U,Z[6]=q*U,Z[7]=(-V*X+Y*G)*U,Z[8]=(K*X-Y*Q)*U,Z}function gw(){var Z=new IW(3);if(IW!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function HE1(Z,J,X){return Z[0]=J[0]*X[0],Z[1]=J[1]*X[1],Z[2]=J[2]*X[2],Z}function pt(Z,J){var X=J[0],Y=J[1],$=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 FE1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=X[3]*Y+X[7]*$+X[11]*Q+X[15];return K=K||1,Z[0]=(X[0]*Y+X[4]*$+X[8]*Q+X[12])/K,Z[1]=(X[1]*Y+X[5]*$+X[9]*Q+X[13])/K,Z[2]=(X[2]*Y+X[6]*$+X[10]*Q+X[14])/K,Z}function qE1(Z,J,X){var Y=J[0],$=J[1],Q=J[2];return Z[0]=Y*X[0]+$*X[3]+Q*X[6],Z[1]=Y*X[1]+$*X[4]+Q*X[7],Z[2]=Y*X[2]+$*X[5]+Q*X[8],Z}var UE1=HE1;(function(){var Z=gw();return function(J,X,Y,$,Q,K){var W,G;if(!X)X=3;if(!Y)Y=0;if($)G=Math.min($*X+Y,J.length);else G=J.length;for(W=Y;W<G;W+=X)Z[0]=J[W],Z[1]=J[W+1],Z[2]=J[W+2],Q(Z,Z,K),J[W]=Z[0],J[W+1]=Z[1],J[W+2]=Z[2];return J}})();var AX="dedup",wE={keepUniqueNames:!1,propertyTypes:[s.ACCESSOR,s.MESH,s.TEXTURE,s.MATERIAL,s.SKIN]};function it(Z=wE){let J=d7(wE,Z),X=new Set(J.propertyTypes);for(let Y of J.propertyTypes)if(!wE.propertyTypes.includes(Y))throw new Error(`${AX}: Unsupported deduplication on type "${Y}".`);return hX(AX,(Y)=>{let $=Y.getLogger();if(X.has(s.ACCESSOR))BE1(Y);if(X.has(s.TEXTURE))wE1(Y,J);if(X.has(s.MATERIAL))OE1(Y,J);if(X.has(s.MESH))LE1(Y,J);if(X.has(s.SKIN))ME1(Y,J);$.debug(`${AX}: Complete.`)})}function BE1(Z){let J=Z.getLogger(),X=new Map,Y=new Map,$=new Map,Q=new Map,K=Z.getRoot().listMeshes();K.forEach((F)=>{F.listPrimitives().forEach((H)=>{H.listAttributes().forEach((q)=>W(q,Y)),W(H.getIndices(),X)})});for(let F of Z.getRoot().listAnimations())for(let H of F.listSamplers())W(H.getInput(),$),W(H.getOutput(),Q);function W(F,H){if(!F)return;let q=[F.getCount(),F.getType(),F.getComponentType(),F.getNormalized(),F.getSparse()].join(":"),U=H.get(q);if(!U)H.set(q,U=new Set);U.add(F)}function G(F,H){for(let q=0;q<F.length;q++){let U=F[q],B=a0.toView(U.getArray());if(H.has(U))continue;for(let L=q+1;L<F.length;L++){let w=F[L];if(H.has(w))continue;if(a0.equals(B,a0.toView(w.getArray())))H.set(w,U)}}}let V=0,z=new Map;for(let F of[Y,X,$,Q])for(let H of F.values())V+=H.size,G(Array.from(H),z);J.debug(`${AX}: Merged ${z.size} of ${V} accessors.`),K.forEach((F)=>{F.listPrimitives().forEach((H)=>{H.listAttributes().forEach((U)=>{if(z.has(U))H.swap(U,z.get(U))});let q=H.getIndices();if(q&&z.has(q))H.swap(q,z.get(q))})});for(let F of Z.getRoot().listAnimations())for(let H of F.listSamplers()){let q=H.getInput(),U=H.getOutput();if(q&&z.has(q))H.swap(q,z.get(q));if(U&&z.has(U))H.swap(U,z.get(U))}Array.from(z.keys()).forEach((F)=>F.dispose())}function LE1(Z,J){let X=Z.getLogger(),Y=Z.getRoot(),$=new Map;Y.listAccessors().forEach((W,G)=>$.set(W,G)),Y.listMaterials().forEach((W,G)=>$.set(W,G));let Q=Y.listMeshes().length,K=new Map;for(let W of Y.listMeshes()){let G=[];for(let z of W.listPrimitives())G.push(nt(z,$));let V="";if(J.keepUniqueNames)V+=W.getName()+";";if(V+=G.join(";"),K.has(V)){let z=K.get(V);W.listParents().forEach((F)=>{if(F.propertyType!==s.ROOT)F.swap(W,z)}),W.dispose()}else K.set(V,W)}X.debug(`${AX}: Merged ${Q-K.size} of ${Q} meshes.`)}function wE1(Z,J){let X=Z.getLogger(),Y=Z.getRoot(),$=Y.listTextures(),Q=new Map;for(let K=0;K<$.length;K++){let W=$[K],G=W.getImage();if(Q.has(W))continue;for(let V=K+1;V<$.length;V++){let z=$[V],F=z.getImage();if(Q.has(z))continue;if(W.getMimeType()!==z.getMimeType())continue;if(J.keepUniqueNames&&W.getName()!==z.getName())continue;let H=W.getSize(),q=z.getSize();if(!H||!q)continue;if(H[0]!==q[0])continue;if(H[1]!==q[1])continue;if(!G||!F)continue;if(a0.equals(G,F))Q.set(z,W)}}X.debug(`${AX}: Merged ${Q.size} of ${Y.listTextures().length} textures.`),Array.from(Q.entries()).forEach(([K,W])=>{K.listParents().forEach((G)=>{if(!(G instanceof _$))G.swap(K,W)}),K.dispose()})}function OE1(Z,J){let X=Z.getLogger(),$=Z.getRoot().listMaterials(),Q=new Map,K=new Map,W=new Set;if(!J.keepUniqueNames)W.add("name");for(let G=0;G<$.length;G++){let V=$[G];if(Q.has(V))continue;if(jt(V,K))continue;for(let z=G+1;z<$.length;z++){let F=$[z];if(Q.has(F))continue;if(jt(F,K))continue;if(V.equals(F,W))Q.set(F,V)}}X.debug(`${AX}: Merged ${Q.size} of ${$.length} materials.`),Array.from(Q.entries()).forEach(([G,V])=>{G.listParents().forEach((z)=>{if(!(z instanceof _$))z.swap(G,V)}),G.dispose()})}function ME1(Z,J){let X=Z.getLogger(),$=Z.getRoot().listSkins(),Q=new Map,K=new Set(["joints"]);if(!J.keepUniqueNames)K.add("name");for(let W=0;W<$.length;W++){let G=$[W];if(Q.has(G))continue;for(let V=W+1;V<$.length;V++){let z=$[V];if(Q.has(z))continue;if(G.equals(z,K)&&tk1(G.listJoints(),z.listJoints()))Q.set(z,G)}}X.debug(`${AX}: Merged ${Q.size} of ${$.length} skins.`),Array.from(Q.entries()).forEach(([W,G])=>{W.listParents().forEach((V)=>{if(!(V instanceof _$))V.swap(W,G)}),W.dispose()})}function nt(Z,J){let X=[];for(let Y of Z.listSemantics()){let $=Z.getAttribute(Y);X.push(Y+":"+J.get($))}if(Z instanceof T8){let Y=Z.getIndices();if(Y)X.push("indices:"+J.get(Y));let $=Z.getMaterial();if($)X.push("material:"+J.get($));X.push("mode:"+Z.getMode());for(let Q of Z.listTargets())X.push("target:"+nt(Q,J))}return X.join(",")}function jt(Z,J){if(J.has(Z))return J.get(Z);let X=Z.getGraph(),Y=new Set,$=X.listParentEdges(Z);while($.length>0){let Q=$.pop();if(Q.getAttributes().modifyChild===!0)return J.set(Z,!0),!0;let K=Q.getChild();if(Y.has(K))continue;for(let W of X.listChildEdges(K))$.push(W)}return J.set(Z,!1),!1}function at(){var Z=new IW(4);if(IW!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0,Z[3]=0;return Z}function NE1(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 RE1(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 jE1(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 DE1(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 PE1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3];return Math.hypot(J,X,Y,$)}var st=RE1,CE1=jE1,ot=PE1;(function(){var Z=at();return function(J,X,Y,$,Q,K){var W,G;if(!X)X=4;if(!Y)Y=0;if($)G=Math.min($*X+Y,J.length);else G=J.length;for(W=Y;W<G;W+=X)Z[0]=J[W],Z[1]=J[W+1],Z[2]=J[W+2],Z[3]=J[W+3],Q(Z,Z,K),J[W]=Z[0],J[W+1]=Z[1],J[W+2]=Z[2],J[W+3]=Z[3];return J}})();var TE1=/color|emissive|diffuse/i;function kE1(Z){return Z.getGraph().listParentEdges(Z).some(($)=>{return $.getAttributes().isColor||TE1.test($.getName())})?"srgb":null}function EE1(Z){let J=Z.getGraph(),X=new Set,Y=new Set;function $(Q){let K=new Set;for(let W of J.listChildEdges(Q))if(W.getChild()instanceof I$)K.add(W.getName()+"Info");for(let W of J.listChildEdges(Q)){let G=W.getChild();if(X.has(G))continue;if(X.add(G),G instanceof h5&&K.has(W.getName()))Y.add(G);else if(G instanceof HW)$(G)}}return $(Z),Array.from(Y)}function IE1(Z){let X=y6.fromGraph(Z.getGraph()).getRoot(),Y=Z.getGraph().listParentEdges(Z).filter(($)=>$.getParent()!==X).map(($)=>$.getName());return Array.from(new Set(Y))}var kW="prune",RE=0.011764705882352941,Dt={propertyTypes:[s.NODE,s.SKIN,s.MESH,s.CAMERA,s.PRIMITIVE,s.PRIMITIVE_TARGET,s.ANIMATION,s.MATERIAL,s.TEXTURE,s.ACCESSOR,s.BUFFER],keepLeaves:!1,keepAttributes:!1,keepIndices:!1,keepSolidTextures:!1,keepExtras:!1};function mw(Z=Dt){let J=d7(Dt,Z),X=new Set(J.propertyTypes),Y=J.keepExtras;return hX(kW,async($)=>{let Q=$.getLogger(),K=$.getRoot(),W=$.getGraph(),G=new rt,V=(z)=>G.dispose(z.target);if(W.addEventListener("node:dispose",V),X.has(s.MESH))for(let z of K.listMeshes()){if(z.listPrimitives().length>0)continue;z.dispose()}if(X.has(s.NODE)){if(!J.keepLeaves)for(let z of K.listScenes())tt(W,z,Y);for(let z of K.listNodes())r9(z,Y)}if(X.has(s.SKIN))for(let z of K.listSkins())r9(z,Y);if(X.has(s.MESH))for(let z of K.listMeshes())r9(z,Y);if(X.has(s.CAMERA))for(let z of K.listCameras())r9(z,Y);if(X.has(s.PRIMITIVE))Pt(W,s.PRIMITIVE,Y);if(X.has(s.PRIMITIVE_TARGET))Pt(W,s.PRIMITIVE_TARGET,Y);if(!J.keepAttributes&&X.has(s.ACCESSOR)){let z=new Map;for(let F of K.listMeshes())for(let H of F.listPrimitives()){let q=H.getMaterial();if(!q)continue;let U=et($,H,q),B=vE1(H,U);Ct(H,B),H.listTargets().forEach((L)=>Ct(L,B)),z.has(q)?z.get(q).add(H):z.set(q,new Set([H]))}for(let[F,H]of z)SE1(F,Array.from(H))}if(!J.keepIndices&&X.has(s.ACCESSOR))for(let z of K.listMeshes())for(let F of z.listPrimitives())_E1(F);if(X.has(s.ANIMATION))for(let z of K.listAnimations()){for(let F of z.listChannels())if(!F.getTargetNode())F.dispose();if(!z.listChannels().length){let F=z.listSamplers();r9(z,Y),F.forEach((H)=>r9(H,Y))}else z.listSamplers().forEach((F)=>r9(F,Y))}if(X.has(s.MATERIAL))K.listMaterials().forEach((z)=>r9(z,Y));if(X.has(s.TEXTURE)){if(K.listTextures().forEach((z)=>r9(z,Y)),!J.keepSolidTextures)await AE1($)}if(X.has(s.ACCESSOR))K.listAccessors().forEach((z)=>r9(z,Y));if(X.has(s.BUFFER))K.listBuffers().forEach((z)=>r9(z,Y));if(W.removeEventListener("node:dispose",V),!G.empty()){let z=G.entries().map(([F,H])=>`${F} (${H})`).join(", ");Q.info(`${kW}: Removed types... ${z}`)}else Q.debug(`${kW}: No unused properties found.`);Q.debug(`${kW}: Complete.`)})}class rt{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 r9(Z,J){let X=Z.listParents().filter(($)=>!($ instanceof _$||$ instanceof k$)),Y=J&&!ut(Z.getExtras());if(!X.length&&!Y)Z.dispose()}function Pt(Z,J,X){for(let Y of Z.listEdges()){let $=Y.getParent();if($.propertyType===J)r9($,X)}}function tt(Z,J,X){if(J.listChildren().forEach((K)=>tt(Z,K,X)),J instanceof FW)return;let Y=Z.listParentEdges(J).some((K)=>{let W=K.getParent().propertyType;return W!==s.ROOT&&W!==s.SCENE&&W!==s.NODE}),$=Z.listChildren(J).length===0,Q=X&&!ut(J.getExtras());if($&&!Y&&!Q)J.dispose()}function Ct(Z,J){for(let X of J)Z.setAttribute(X,null)}function _E1(Z){let J=Z.getIndices(),X=J&&J.getArray(),Y=Z.listAttributes()[0];if(!X||!Y)return;if(J.getCount()!==Y.getCount())return;for(let $=0,Q=X.length;$<Q;$++)if($!==X[$])return;Z.setIndices(null)}function vE1(Z,J){let X=[];for(let Y of Z.listSemantics())if(Y==="NORMAL"&&!J.has(Y))X.push(Y);else if(Y==="TANGENT"&&!J.has(Y))X.push(Y);else if(Y.startsWith("TEXCOORD_")&&!J.has(Y))X.push(Y);else if(Y.startsWith("COLOR_")&&Y!=="COLOR_0")X.push(Y);return X}function et(Z,J,X,Y=new Set){let Q=Z.getGraph().listChildEdges(X),K=new Set;for(let V of Q)if(V.getChild()instanceof I$)K.add(V.getName());for(let V of Q){let z=V.getName(),F=V.getChild();if(F instanceof h5){if(K.has(z.replace(/Info$/,"")))Y.add(`TEXCOORD_${F.getTexCoord()}`)}if(F instanceof I$&&z.match(/normalTexture/i))Y.add("TANGENT");if(F instanceof HW)et(Z,J,F,Y)}let W=X instanceof h7&&!X.getExtension("KHR_materials_unlit"),G=J.getMode()===T8.Mode.POINTS;if(W&&!G)Y.add("NORMAL");return Y}function SE1(Z,J){let X=EE1(Z),Y=new Set(X.map((G)=>G.getTexCoord())),$=Array.from(Y).sort(),Q=new Map($.map((G,V)=>[G,V])),K=new Map($.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((z)=>z.startsWith("TEXCOORD_")).sort();W(G,V),G.listTargets().forEach((z)=>W(z,V))}function W(G,V){for(let z of V){let F=G.getAttribute(z);if(!F)continue;let H=K.get(z);if(H===z)continue;G.setAttribute(H,F),G.setAttribute(z,null)}}}async function AE1(Z){let J=Z.getRoot(),X=Z.getGraph(),Y=Z.getLogger(),Q=J.listTextures().map(async(K)=>{var W;let G=await hE1(K);if(!G)return;if(kE1(K)==="srgb")cT.convertSRGBToLinear(G,G);let V=K.getName()||K.getURI(),z=(W=K.getSize())==null?void 0:W.join("x"),F=IE1(K);for(let H of X.listParentEdges(K)){let q=H.getParent();if(q!==J&&xE1(q,G,H.getName(),Y))H.dispose()}if(K.listParents().length===1)K.dispose(),Y.debug(`${kW}: Removed solid-color texture "${V}" (${z}px ${F.join(", ")})`)});await Promise.all(Q)}function xE1(Z,J,X,Y){if(Z instanceof h7)switch(X){case"baseColorTexture":return Z.setBaseColorFactor(CE1(J,J,Z.getBaseColorFactor())),!0;case"emissiveTexture":return Z.setEmissiveFactor(UE1([0,0,0],J.slice(0,3),Z.getEmissiveFactor())),!0;case"occlusionTexture":return Math.abs(J[0]-1)<=RE;case"metallicRoughnessTexture":return Z.setRoughnessFactor(J[1]*Z.getRoughnessFactor()),Z.setMetallicFactor(J[2]*Z.getMetallicFactor()),!0;case"normalTexture":return ot(st(at(),J,[0.5,0.5,1,1]))<=RE}return Y.warn(`${kW}: Detected single-color ${X} texture. Pruning ${X} not yet supported.`),!1}async function hE1(Z){let J=await fE1(Z);if(!J)return null;let X=[1/0,1/0,1/0,1/0],Y=[-1/0,-1/0,-1/0,-1/0],$=[0,0,0,0],[Q,K]=J.shape;for(let W=0;W<Q;W++){for(let G=0;G<K;G++)for(let V=0;V<4;V++)X[V]=Math.min(X[V],J.get(W,G,V)),Y[V]=Math.max(Y[V],J.get(W,G,V));if(ot(st($,Y,X))/255>RE)return null}return DE1($,NE1($,Y,X),0.00196078431372549)}async function fE1(Z){try{return await mr(Z.getImage(),Z.getMimeType())}catch(J){return null}}var SX=4294967295;class Ze{constructor(Z){this.attributes=[],this.u8=void 0,this.u32=void 0;let J=0;for(let X of kE(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),Y=Z.getElementSize()*Z.getComponentSize(),$=a0.padNumber(Y);return this.attributes.push({u8:X,byteStride:Y,paddedByteStride:$}),$}hash(Z){let J=0;for(let{u8:X,byteStride:Y,paddedByteStride:$}of this.attributes){for(let Q=0;Q<$;Q++)if(Q<Y)this.u8[J+Q]=X[Z*Y+Q];else this.u8[J+Q]=0;J+=$}return yE1(0,this.u32)}equal(Z,J){for(let{u8:X,byteStride:Y}of this.attributes)for(let $=0;$<Y;$++)if(X[Z*Y+$]!==X[J*Y+$])return!1;return!0}}function yE1(Z,J){for(let $=0,Q=J.length;$<Q;$++){let K=J[$];K=Math.imul(K,1540483477)>>>0,K=(K^K>>24)>>>0,K=Math.imul(K,1540483477)>>>0,Z=Math.imul(Z,1540483477)>>>0,Z=(Z^K)>>>0}return Z}function bE1(Z,J,X,Y,$=SX){let Q=J-1,W=X.hash(Y)&Q;for(let G=0;G<=Q;G++){let V=Z[W];if(V===$||X.equal(V,Y))return W;W=W+G+1&Q}throw new Error("Hash table full.")}var R6;(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"})(R6||(R6={}));function xX(Z,J){let X=Z.getAttribute("POSITION"),Y=Z.getIndices();switch(J){case R6.RENDER:return Y?Y.getCount():X.getCount();case R6.RENDER_CACHED:return Y?new Set(Y.getArray()).size:X.getCount();case R6.UPLOAD_NAIVE:case R6.UPLOAD:return X.getCount();case R6.DISTINCT:case R6.DISTINCT_POSITION:return gE1(J);case R6.UNUSED:return Y?X.getCount()-new Set(Y.getArray()).size:0;default:return mE1(J)}}function gE1(Z){throw new Error(`Not implemented: ${Z}`)}function mE1(Z){throw new Error(`Unexpected value: ${Z}`)}function hz(Z,J,X){let Y=y6.fromGraph(Z.getGraph());if(!J||!X)[J,X]=uE1(Z);let $=Z.getIndices(),Q=$?$.getArray():null,K=xX(Z,R6.RENDER),W=Y.createAccessor(),G=K,V=EE(G,X);for(let F=0;F<G;F++)V[F]=J[Q?Q[F]:F];Z.setIndices(W.setArray(V));let z=kE(Z);for(let F of Z.listAttributes()){let H=WJ(Y,F);jE(F,$,J,H,X),Z.swap(F,H)}for(let F of Z.listTargets())for(let H of F.listAttributes()){let q=WJ(Y,H);jE(H,$,J,q,X),F.swap(H,q)}if($&&$.listParents().length===1)$.dispose();for(let F of z)if(F.listParents().length===1)F.dispose();return Z}function jE(Z,J,X,Y,$){let Q=Z.getElementSize(),K=Z.getArray(),W=J?J.getArray():null,G=J?J.getCount():Z.getCount(),V=new K.constructor($*Q),z=new Uint8Array($);for(let F=0;F<G;F++){let H=W?W[F]:F,q=X[H];if(z[q])continue;for(let U=0;U<Q;U++)V[q*Q+U]=K[H*Q+U];z[q]=1}return Y.setArray(V)}function uE1(Z){let J=xX(Z,R6.UPLOAD),X=Z.getIndices(),Y=X?X.getArray():null;if(!X||!Y)return[ek1(J,1e6),J];let $=new Uint32Array(J).fill(SX),Q=0;for(let K=0;K<Y.length;K++){let W=Y[K];if($[W]===SX)$[W]=Q++}return[$,Q]}var DE="weld",hw={overwrite:!0,cleanup:!0};function IE(Z=hw){let J=d7(hw,Z);return hX(DE,async(X)=>{let Y=X.getLogger();for(let $ of X.getRoot().listMeshes()){for(let Q of $.listPrimitives())if(uw(Q,J),xX(Q,R6.RENDER)===0)Q.dispose();if($.listPrimitives().length===0)$.dispose()}if(J.cleanup)await X.transform(mw({propertyTypes:[s.ACCESSOR,s.NODE],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}),it({propertyTypes:[s.ACCESSOR]}));Y.debug(`${DE}: Complete.`)})}function uw(Z,J=hw){let X=Z.getGraph(),$=y6.fromGraph(X).getLogger(),Q=EW({},hw,J);if(Z.getIndices()&&!Q.overwrite)return;if(Z.getMode()===T8.Mode.POINTS)return;let K=Z.getAttribute("POSITION").getCount(),W=Z.getIndices(),G=W==null?void 0:W.getArray(),V=W?W.getCount():K,z=new Ze(Z),F=JE1(K+K/4),H=new Uint32Array(F).fill(SX),q=new Uint32Array(K).fill(SX),U=0;for(let B=0;B<V;B++){let L=G?G[B]:B;if(q[L]!==SX)continue;let w=bE1(H,F,z,L,SX),M=H[w];if(M===SX)H[w]=L,q[L]=U++;else q[L]=q[M]}$.debug(`${DE}: ${bw(K,U)} vertices.`),hz(Z,q,U)}var{FLOAT:dE1}=x0.ComponentType;function Je(Z,J){let X=Z.getAttribute("POSITION");if(X)Tt(J,X);let Y=Z.getAttribute("NORMAL");if(Y)kt(J,Y);let $=Z.getAttribute("TANGENT");if($)Et(J,$);for(let Q of Z.listTargets()){let K=Q.getAttribute("POSITION");if(K)Tt(J,K);let W=Q.getAttribute("NORMAL");if(W)kt(J,W);let G=Q.getAttribute("TANGENT");if(G)Et(J,G)}if(KE1(J)<0)cE1(Z)}function Tt(Z,J){let X=J.getComponentType(),Y=J.getNormalized(),$=J.getArray(),Q=X===dE1?$:new Float32Array($.length),K=gw();for(let W=0,G=J.getCount();W<G;W++){if(Y)K[0]=l0.decodeNormalizedInt($[W*3],X),K[1]=l0.decodeNormalizedInt($[W*3+1],X),K[2]=l0.decodeNormalizedInt($[W*3+2],X);else K[0]=$[W*3],K[1]=$[W*3+1],K[2]=$[W*3+2];FE1(K,K,Z),Q[W*3]=K[0],Q[W*3+1]=K[1],Q[W*3+2]=K[2]}J.setArray(Q).setNormalized(!1)}function kt(Z,J){let X=J.getArray(),Y=J.getNormalized(),$=J.getComponentType(),Q=WE1();GE1(Q,Z),zE1(Q,Q),VE1(Q,Q);let K=gw();for(let W=0,G=J.getCount();W<G;W++){if(Y)K[0]=l0.decodeNormalizedInt(X[W*3],$),K[1]=l0.decodeNormalizedInt(X[W*3+1],$),K[2]=l0.decodeNormalizedInt(X[W*3+2],$);else K[0]=X[W*3],K[1]=X[W*3+1],K[2]=X[W*3+2];if(qE1(K,K,Q),pt(K,K),Y)X[W*3]=l0.decodeNormalizedInt(K[0],$),X[W*3+1]=l0.decodeNormalizedInt(K[1],$),X[W*3+2]=l0.decodeNormalizedInt(K[2],$);else X[W*3]=K[0],X[W*3+1]=K[1],X[W*3+2]=K[2]}}function Et(Z,J){let X=J.getArray(),Y=J.getNormalized(),$=J.getComponentType(),Q=gw();for(let K=0,W=J.getCount();K<W;K++){if(Y)Q[0]=l0.decodeNormalizedInt(X[K*4],$),Q[1]=l0.decodeNormalizedInt(X[K*4+1],$),Q[2]=l0.decodeNormalizedInt(X[K*4+2],$);else Q[0]=X[K*4],Q[1]=X[K*4+1],Q[2]=X[K*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],pt(Q,Q),Y)X[K*4]=l0.decodeNormalizedInt(Q[0],$),X[K*4+1]=l0.decodeNormalizedInt(Q[1],$),X[K*4+2]=l0.decodeNormalizedInt(Q[2],$);else X[K*4]=Q[0],X[K*4+1]=Q[1],X[K*4+2]=Q[2]}}function cE1(Z){if(Z.getMode()!==T8.Mode.TRIANGLES)return;if(!Z.getIndices())uw(Z);let J=Z.getIndices();for(let X=0,Y=J.getCount();X<Y;X+=3){let $=J.getScalar(X),Q=J.getScalar(X+2);J.setScalar(X,Q),J.setScalar(X+2,$)}}function lE1(Z,J){for(let X of Z.listPrimitives()){let Y=pE1(X,Z);if(X!==Y)Z.removePrimitive(X).addPrimitive(Y)}for(let X of Z.listPrimitives())hz(X),Je(X,J)}function pE1(Z,J){if(Z.listParents().some((Y)=>Y instanceof Hz&&Y!==J))Z=Z.clone();for(let Y of Z.listTargets())if(Y.listParents().some((Q)=>Q instanceof T8&&Q!==Z))Z.removeTarget(Y).addTarget(Y.clone());return Z}var It=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function Xe(Z){let J=Z.getMesh(),X=Z.getMatrix();if(J&&!l0.eq(X,It))lE1(J,X);for(let Y of Z.listChildren()){let $=Y.getMatrix();lt($,$,X),Y.setMatrix($)}return Z.setMatrix(It)}var{LINES:iE1,LINE_STRIP:nE1,LINE_LOOP:aE1,TRIANGLES:sE1,TRIANGLE_STRIP:oE1,TRIANGLE_FAN:rE1}=T8.Mode;function tE1(Z){let J=Z.getGraph(),X=y6.fromGraph(J);if(!Z.getIndices())uw(Z);let Y=Z.getIndices(),$=Y.getArray(),Q=mt(Z),W=new jX[Y.getComponentType()](Q*2),G=Z.getMode();if(G===nE1)for(let z=0;z<Q;z++)W[z*2]=$[z],W[z*2+1]=$[z+1];else if(G===aE1)for(let z=0;z<Q;z++)if(z<Q-1)W[z*2]=$[z],W[z*2+1]=$[z+1];else W[z*2]=$[z],W[z*2+1]=$[0];else throw new Error("Only LINE_STRIP and LINE_LOOP may be converted to LINES.");Z.setMode(iE1);let V=X.getRoot();if(Y.listParents().some((z)=>z!==V&&z!==Z))Z.setIndices(WJ(X,Y).setArray(W));else Y.setArray(W)}function Ye(Z){let J=Z.getGraph(),X=y6.fromGraph(J);if(!Z.getIndices())uw(Z);let Y=Z.getIndices(),$=Y.getArray(),Q=mt(Z),W=new jX[Y.getComponentType()](Q*3),G=Z.getMode();if(G===oE1)for(let z=0,F=$.length;z<F-2;z++)if(z%2)W[z*3]=$[z+1],W[z*3+1]=$[z],W[z*3+2]=$[z+2];else W[z*3]=$[z],W[z*3+1]=$[z+1],W[z*3+2]=$[z+2];else if(G===rE1)for(let z=0;z<Q;z++)W[z*3]=$[0],W[z*3+1]=$[z+1],W[z*3+2]=$[z+2];else throw new Error("Only TRIANGLE_STRIP and TRIANGLE_FAN may be converted to TRIANGLES.");Z.setMode(sE1);let V=X.getRoot();if(Y.listParents().some((z)=>z!==V&&z!==Z))Z.setIndices(WJ(X,Y).setArray(W));else Y.setArray(W)}var _t="dequantize",fw={pattern:/^((?!JOINTS_).)*$/};function $e(Z=fw){let J=d7(fw,Z);return hX(_t,(X)=>{let Y=X.getLogger();for(let $ of X.getRoot().listMeshes())for(let Q of $.listPrimitives())eE1(Q,J);X.createExtension(Az).dispose(),Y.debug(`${_t}: Complete.`)})}function eE1(Z,J=fw){let X=d7(fw,J);for(let Y of Z.listSemantics())if(X.pattern.test(Y))PE(Z.getAttribute(Y));for(let Y of Z.listTargets())for(let $ of Y.listSemantics())if(X.pattern.test($))PE(Y.getAttribute($))}function PE(Z){let J=Z.getArray();if(!J)return;let X=yw(J,Z.getComponentType(),Z.getNormalized());Z.setArray(X).setNormalized(!1)}function yw(Z,J,X){let Y=new Float32Array(Z.length);for(let $=0,Q=Z.length;$<Q;$++)if(X)Y[$]=l0.decodeNormalizedInt(Z[$],J);else Y[$]=Z[$];return Y}var{TEXTURE_INFO:Qe,ROOT:Jh6}=s;function Ke(Z){let J=new y6().setLogger(Z.getLogger()),X=_E(J,Z);return ZI1(J,Z,X),J.getRoot().copy(Z.getRoot(),X),J}function ZI1(Z,J,X){X||(X=_E(Z,J));for(let Y of J.getRoot().listExtensionsUsed()){let $=Z.createExtension(Y.constructor);if(Y.isRequired())$.setRequired(!0)}return JI1(Z,J,XI1(J),X)}function JI1(Z,J,X,Y){Y||(Y=_E(Z,J));let $=new Map;for(let Q of X)if(!$.has(Q)&&Q.propertyType!==Qe)$.set(Q,Y(Q));for(let[Q,K]of $.entries())K.copy(Q,Y);return $}function _E(Z,J){let X=new Map([[J.getRoot(),Z.getRoot()]]);return(Y)=>{if(Y.propertyType===Qe)return Y;let $=X.get(Y);if(!$)$=new Y.constructor(Z.getGraph()),X.set(Y,$);return $}}function XI1(Z){let J=new Set;for(let X of Z.getGraph().listEdges())J.add(X.getChild());return Array.from(J)}var OE="flatten",vt={cleanup:!0};function We(Z=vt){let J=d7(vt,Z);return hX(OE,async(X)=>{let Y=X.getRoot(),$=X.getLogger(),Q=new Set;for(let V of Y.listSkins())for(let z of V.listJoints())Q.add(z);let K=new Set;for(let V of Y.listAnimations())for(let z of V.listChannels()){let F=z.getTargetNode();if(F&&z.getTargetPath()!=="weights")K.add(F)}let W=new Set,G=new Set;for(let V of Y.listScenes())V.traverse((z)=>{let F=z.getParentNode();if(!F)return;if(Q.has(F)||W.has(F))W.add(z);if(K.has(F)||G.has(F))G.add(z)});for(let V of Y.listScenes())V.traverse((z)=>{if(K.has(z))return;if(W.has(z))return;if(G.has(z))return;$E1(z)});if(K.size)$.debug(`${OE}: Flattening node hierarchies with TRS animation not yet supported.`);if(J.cleanup)await X.transform(mw({propertyTypes:[s.NODE],keepLeaves:!1}));$.debug(`${OE}: Complete.`)})}function Ge(Z){return dT(Z)}var YI1={skipValidation:!1},St=4294967295,{LINE_STRIP:$I1,LINE_LOOP:QI1,TRIANGLE_STRIP:KI1,TRIANGLE_FAN:WI1}=T8.Mode;function GI1(Z,J={}){let X=d7(YI1,J),Y=Z[0],$=y6.fromGraph(Y.getGraph());if(!X.skipValidation&&new Set(Z.map(dt)).size>1)throw new Error("Requires >=2 Primitives, sharing the same Material and Mode, with compatible vertex attributes and indices.");for(let q of Z)switch(q.getMode()){case $I1:case QI1:tE1(q);break;case KI1:case WI1:Ye(q);break}let Q=[],K=new Uint32Array(Z.length),W=0,G=0;for(let q=0;q<Z.length;q++){let U=Z[q],B=U.getIndices(),L=U.getAttribute("POSITION").getCount(),w=B?B.getArray():null,M=B?B.getCount():L,N=new Uint32Array(L).fill(St);for(let R=0;R<M;R++){let P=w?w[R]:R;if(N[P]===St)N[P]=W++,K[q]++}Q.push(N),G+=M}let V=$.createPrimitive().setMode(Y.getMode()).setMaterial(Y.getMaterial());for(let q of Y.listSemantics()){let U=Y.getAttribute(q),B=jX[U.getComponentType()],L=WJ($,U).setArray(new B(W*U.getElementSize()));V.setAttribute(q,L)}let z=Y.getIndices(),F=z?WJ($,z).setArray(EE(G,W)):null;V.setIndices(F);let H=0;for(let q=0;q<Q.length;q++){let U=Z[q],B=U.getIndices(),L=B?B.getCount():-1,w=Q[q];if(B&&F)zI1(B,w,F,H),H+=L;for(let M of V.listSemantics()){let N=U.getAttribute(M),R=V.getAttribute(M);VI1(N,B,w,R)}}return V}function VI1(Z,J,X,Y){let $=Z.getElementSize(),Q=J?J.getArray():null,K=Z.getCount(),W=Z.getArray(),G=Y.getArray(),V=new Uint8Array(Z.getCount());for(let z=0,F=J?J.getCount():K;z<F;z++){let H=Q?Q[z]:z,q=X[H];if(V[q])continue;for(let U=0;U<$;U++)G[q*$+U]=W[H*$+U];V[q]=1}}function zI1(Z,J,X,Y){let $=Z.getCount(),Q=Z.getArray(),K=X.getArray();for(let W=0;W<$;W++){let G=Q[W],V=J[G];K[Y+W]=V}}var CE="join",{ROOT:HI1,NODE:FI1,MESH:qI1,PRIMITIVE:UI1,ACCESSOR:BI1}=s,ME=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],At={keepMeshes:!1,keepNamed:!1,cleanup:!0};function Ve(Z=At){let J=d7(At,Z);return hX(CE,async(X)=>{let Y=X.getRoot(),$=X.getLogger();for(let Q of Y.listScenes())xt(X,Q,J),Q.traverse((K)=>xt(X,K,J));if(J.cleanup)await X.transform(mw({propertyTypes:[FI1,qI1,UI1,BI1],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}));$.debug(`${CE}: Complete.`)})}function xt(Z,J,X){let Y=Z.getLogger(),$={},Q=J.listChildren();for(let G=0;G<Q.length;G++){let V=Q[G];if(V.listParents().some((H)=>H instanceof k$))continue;let F=V.getMesh();if(!F)continue;if(V.getExtension("EXT_mesh_gpu_instancing"))continue;if(V.getSkin())continue;for(let H of F.listPrimitives()){if(H.listTargets().length>0)continue;let q=H.getMaterial();if(q&&q.getExtension("KHR_materials_volume"))continue;hz(H),wI1(H);let U=dt(H),B=F.getName()||V.getName();if(X.keepMeshes||X.keepNamed&&B)U+=`|${G}`;if(!(U in $))$[U]={prims:[],primMeshes:[],primNodes:[],dstNode:V,dstMesh:void 0};let L=$[U];L.prims.push(H),L.primNodes.push(V)}}let K=Object.values($).filter(({prims:G})=>G.length>1),W=new Set(K.flatMap((G)=>G.primNodes));for(let G of W){let V=G.getMesh();if(V.listParents().some((F)=>{return F.propertyType!==HI1&&G!==F}))G.setMesh(V.clone())}for(let G of K){let{dstNode:V,primNodes:z}=G;G.dstMesh=V.getMesh(),G.primMeshes=z.map((F)=>F.getMesh())}for(let G of K){let{prims:V,primNodes:z,primMeshes:F,dstNode:H,dstMesh:q}=G,U=H.getMatrix();for(let w=0;w<V.length;w++){let M=z[w],N=F[w],R=V[w];if(N.removePrimitive(R),ZE1(R))R=V[w]=LI1(V[w]);if(M!==H)lt(ME,QE1(ME,U),M.getMatrix()),Je(R,ME)}let B=GI1(V),L=B.listAttributes()[0].getCount();q.addPrimitive(B),Y.debug(`${CE}: Joined Primitives (${V.length}) containing ${NE(L)} vertices under Node "${H.getName()}".`)}}function LI1(Z){let J=Z.clone();for(let Y of J.listSemantics())J.setAttribute(Y,J.getAttribute(Y).clone());let X=J.getIndices();if(X)J.setIndices(X.clone());return J}function wI1(Z){for(let J of["POSITION","NORMAL","TANGENT"]){let X=Z.getAttribute(J);if(X)PE(X)}}var{TRANSLATION:Xh6,ROTATION:Yh6,SCALE:$h6,WEIGHTS:Qh6}=k$.TargetPath;var OI1={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12,normalizeWeights:!0,cleanup:!0};var Kh6=EW({level:"high"},OI1);var MI1="unweld";function NI1(Z,J=new Map){let X=Z.getIndices();if(!X)return;let Y=Z.getGraph(),$=y6.fromGraph(Y),Q=$.getLogger(),K=Z.getAttribute("POSITION").getCount();for(let G of Z.listAttributes())if(Z.swap(G,ht($,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,ht($,V,X,J)),V.listParents().length===1)V.dispose();let W=Z.getAttribute("POSITION").getCount();if(Q.debug(`${MI1}: ${bw(K,W)} vertices.`),Z.setIndices(null),X.listParents().length===1)X.dispose()}function ht(Z,J,X,Y){if(Y.has(J)&&Y.get(J).has(X))return Y.get(J).get(X);let $=J.getArray(),K=new $.constructor(X.getCount()*J.getElementSize()),W=X.getArray(),G=J.getElementSize();for(let z=0,F=X.getCount();z<F;z++)for(let H=0;H<G;H++)K[z*G+H]=$[W[z]*G+H];if(!Y.has(J))Y.set(J,new Map);let V=WJ(Z,J).setArray(K);return Y.get(J).set(X,V),V}var ft;(function(Z){Z[Z.STEP=0]="STEP",Z[Z.LERP=1]="LERP",Z[Z.SLERP=2]="SLERP"})(ft||(ft={}));var RI1=0.000001;function jI1(Z,J,X,Y=0.0001){let $=J.length/Z.length,Q=new Array($).fill(0),K=new Array($).fill(0),W=new Array($).fill(0),G=new Array($).fill(0),V=Z.length-1,z=1;for(let F=1;F<V;++F){let H=Z[z-1],q=Z[F],U=Z[F+1],B=(q-H)/(U-H),L=!1;if(q!==U&&(F!==1||q!==Z[0])){if(xz(J,z-1,G),xz(J,F,K),xz(J,F+1,W),X==="slerp"){let w=CI1(Q,G,W,B),M=bt(G,K)+bt(K,W);L=!xw(K,w,Y)||M+Number.EPSILON>=Math.PI}else if(X==="lerp"){let w=PI1(Q,G,W,B);L=!xw(K,w,Y)}else if(X==="step")L=!xw(K,G)||!xw(K,W)}if(L){if(F!==z)Z[z]=Z[F],yt(J,z,xz(J,F,Q));z++}}if(V>0)Z[z]=Z[V],yt(J,z,xz(J,V,Q)),z++;return z}function xz(Z,J,X){for(let Y=0,$=X.length;Y<$;Y++)X[Y]=Z[J*$+Y];return X}function yt(Z,J,X){for(let Y=0,$=X.length;Y<$;Y++)Z[J*$+Y]=X[Y]}function xw(Z,J,X=0){if(Z.length!==J.length)return!1;for(let Y=0;Y<Z.length;Y++)if(Math.abs(Z[Y]-J[Y])>X)return!1;return!0}function DI1(Z,J,X){return Z*(1-X)+J*X}function PI1(Z,J,X,Y){for(let $=0;$<J.length;$++)Z[$]=DI1(J[$],X[$],Y);return Z}function CI1(Z,J,X,Y){let $=J[0],Q=J[1],K=J[2],W=J[3],G=X[0],V=X[1],z=X[2],F=X[3],H,q,U,B,L;if(q=$*G+Q*V+K*z+W*F,q<0)q=-q,G=-G,V=-V,z=-z,F=-F;if(1-q>RI1)H=Math.acos(q),U=Math.sin(H),B=Math.sin((1-Y)*H)/U,L=Math.sin(Y*H)/U;else B=1-Y,L=Y;return Z[0]=B*$+L*G,Z[1]=B*Q+L*V,Z[2]=B*K+L*z,Z[3]=B*W+L*F,Z}function bt(Z,J){let X=TI1(Z,J);return Math.acos(2*X*X-1)}function TI1(Z,J){return Z[0]*J[0]+Z[1]*J[1]+Z[2]*J[2]+Z[3]*J[3]}var Wh6=new Float32Array(0),Gh6={ready:Promise.resolve(),resample:jI1,tolerance:0.0001,cleanup:!0};var h$="simplify",{POINTS:ze,LINES:kI1,LINE_STRIP:EI1,LINE_LOOP:II1,TRIANGLES:_I1,TRIANGLE_STRIP:He,TRIANGLE_FAN:Fe}=T8.Mode,qe={ratio:0,error:0.0001,lockBorder:!1,cleanup:!0};function Ue(Z){let J=d7(qe,Z),X=J.simplifier;if(!X)throw new Error(`${h$}: simplifier dependency required — install "meshoptimizer".`);return hX(h$,async(Y)=>{let $=Y.getLogger();await X.ready,await Y.transform(IE({overwrite:!1,cleanup:J.cleanup}));let Q=0;for(let K of Y.getRoot().listMeshes()){for(let W of K.listPrimitives()){let G=W.getMode();if(G===_I1||G===He||G===Fe){if(gt(W,J),xX(W,R6.RENDER)===0)W.dispose()}else if(W.getMode()===ze&&!!X.simplifyPoints){if(gt(W,J),xX(W,R6.RENDER)===0)W.dispose()}else Q++}if(K.listPrimitives().length===0)K.dispose()}if(Q>0)$.warn(`${h$}: Skipping simplification of ${Q} primitives: Unsupported draw mode.`);if(J.cleanup)await Y.transform(mw({propertyTypes:[s.ACCESSOR,s.NODE],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}),it({propertyTypes:[s.ACCESSOR]}));$.debug(`${h$}: Complete.`)})}function gt(Z,J){let X=EW({},qe,J),Y=X.simplifier,$=Z.getGraph(),Q=y6.fromGraph($),K=Q.getLogger();switch(Z.getMode()){case ze:return vI1(Q,Z,X);case kI1:case EI1:case II1:return K.warn(`${h$}: Skipping primitive simplification: Unsupported draw mode.`),Z;case He:case Fe:Ye(Z);break}let W=xX(Z,R6.UPLOAD),G=xX(Z,R6.RENDER);if(G<W/2)hz(Z);let V=Z.getAttribute("POSITION"),z=Z.getIndices(),F=V.getArray(),H=z.getArray();if(!(F instanceof Float32Array))F=yw(F,V.getComponentType(),V.getNormalized());if(!(H instanceof Uint32Array))H=new Uint32Array(H);let q=Math.floor(X.ratio*G/3)*3,U=X.lockBorder?["LockBorder"]:[],[B,L]=Y.simplify(H,F,3,q,X.error,U);if(Z.setIndices(WJ(Q,z).setArray(B)),z.listParents().length===1)z.dispose();hz(Z);let w=xX(Z,R6.UPLOAD);if(w<=65534)Z.getIndices().setArray(new Uint16Array(Z.getIndices().getArray()));return K.debug(`${h$}: ${bw(W,w)} vertices, error: ${L.toFixed(4)}.`),Z}function vI1(Z,J,X){let Y=X.simplifier,$=Z.getLogger();if(J.getIndices())NI1(J);let K=J.getAttribute("POSITION"),W=J.getAttribute("COLOR_0"),G=K.getCount(),V=K.getArray(),z=W?W.getArray():void 0,F=W?W.getComponentSize():void 0;if(!(V instanceof Float32Array))V=yw(V,K.getComponentType(),K.getNormalized());if(z&&!(z instanceof Float32Array))z=yw(z,K.getComponentType(),K.getNormalized());Y.useExperimentalFeatures=!0;let H=Math.floor(X.ratio*G),q=Y.simplifyPoints(V,3,H,z,F);Y.useExperimentalFeatures=!1;let[U,B]=Y.compactMesh(q);$.debug(`${h$}: ${bw(K.getCount(),B)} vertices.`);for(let L of kE(J)){let w=WJ(Z,L);if(jE(L,null,U,w,B),rk1(J,L,w),L.listParents().length===1)L.dispose()}return J}var TE;(function(Z){Z.LANCZOS3="lanczos3",Z.LANCZOS2="lanczos2"})(TE||(TE={}));var Vh6={resizeFilter:TE.LANCZOS3,pattern:void 0,formats:void 0,slots:void 0,quality:void 0,effort:void 0,lossless:!1,nearLossless:!1,limitInputPixels:!0};var Re=r(Ne(),1);var _W={OPTIMIZED_DIR:".optimized",CHECKSUM_EXT:".md5",DIRECTORIES:[(()=>{try{return H9.dirname(m.resolve("@hytopia.com/assets"))}catch{return null}})(),H9.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 g5{static instance=new g5;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)c.fatalError(`ModelRegistry.getAnimationNames(): Model ${Z} not found!`);return J.getRoot().listAnimations().map((Y)=>Y.getName())}getBoundingBox(Z){let J=this._modelUriBoundingBoxes.get(Z);if(!J)c.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)c.fatalError(`ModelRegistry.getNodeNames(): Model ${Z} not found!`);return J}getTrimesh(Z,J=1){let X=this._modelUriTrimeshes.get(Z);if(!X){c.error(`ModelRegistry.getTrimesh(): Model ${Z} not found!`);return}let Y=X.vertices;if(J!==1){Y=new Float32Array(Y.length);for(let $=0;$<Y.length;$++)Y[$]=X.vertices[$]*J}return{vertices:Y,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)c.fatalError(`ModelRegistry.modelHasNode(): Model ${Z} not found!`);return X.includes(J)}_absoluteModelPathToModelUri(Z){let J=H9.normalize(Z);for(let X of _W.DIRECTORIES){let Y=H9.normalize(X);if(J.startsWith(Y))return H9.relative(Y,J).replace(/\\/g,"/")}return H9.basename(J)}async _getAbsoluteModelPaths(){let Z=[];for(let J of _W.DIRECTORIES){let X=H9.resolve(process.cwd(),J);if(!fX.existsSync(X))continue;let Y=await EL("**/*.{gltf,glb}",{cwd:X,follow:!0});for(let $ of Y)Z.push(H9.join(X,$))}return Z}async _loadModelData(Z){let J=await new aT().read(Z),X=Ge(J.getRoot().listScenes()[0]),Y=J.getRoot().listNodes().map((Q)=>Q.getName()),$=this._absoluteModelPathToModelUri(Z);this._modelUriDocuments.set($,J),this._modelUriBoundingBoxes.set($,{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($,await this._buildTrimesh($))}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)}${_W.CHECKSUM_EXT}`;if(!fX.existsSync(J))return!1;let X=this._calculateChecksum(Z),Y=fX.readFileSync(J,"utf8");return X===Y}_calculateChecksum(Z){if(!fX.existsSync(Z))return"";let J=fX.readFileSync(Z);return fI1.createHash("sha256").update(J.toString("base64")).digest("hex")}_buildOptimizedModelPath(Z){let J=H9.basename(Z),X=J.replace(/\.[^/.]+$/,""),Y=H9.dirname(Z),$=H9.join(Y,_W.OPTIMIZED_DIR,X);return H9.join($,J)}async _buildTrimesh(Z,J=1,X=0.001){let Y=this._modelUriDocuments.get(Z);if(!Y)c.fatalError(`ModelRegistry._buildTrimesh(): Model ${Z} not found!`);let $=Ke(Y);$.setLogger(new f5(Vz.WARN)),await $.transform(ct({pivot:"center"}),We(),Ve(),IE(),Ue({simplifier:Re.MeshoptSimplifier,ratio:J,error:X}),$e());for(let V of $.getRoot().listScenes())for(let z of V.listChildren())Xe(z);let Q=$.getRoot().listMeshes()[0];if(!Q){c.error(`ModelRegistry._buildTrimesh(): Model ${Z} has no root mesh!`);return}let K=Q.listPrimitives()[0];if(!K){c.error(`ModelRegistry._buildTrimesh(): Model ${Z} has no root primitive!`);return}let W=K.getAttribute("POSITION"),G=K.getIndices();if(!W||!G){c.error(`ModelRegistry._buildTrimesh(): Model ${Z} missing required geometry data!`);return}return{vertices:W.getArray(),indices:G.getArray()}}async _optimizeModel(Z,J){let X=H9.dirname(J);fX.rmSync(X,{recursive:!0,force:!0}),fX.mkdirSync(X,{recursive:!0}),console.log(`ModelRegistry: Optimizing model ${this._absoluteModelPathToModelUri(Z)}...`);for(let Y of _W.OPTIMIZER_RUNS){let $=J.replace(/(\.[^/.]+)$/,`${Y.suffix}$1`),{stderr:Q}=await vn("npx",["@gltf-transform/cli","optimize",Z,$,...Y.options]);if(Q)return c.warning(`ModelRegistry._optimizeModel(): Error optimizing model ${this._absoluteModelPathToModelUri(Z)}, defaulting to unoptimized model. Error: ${Q}`),Z}return fX.writeFileSync(`${J}${_W.CHECKSUM_EXT}`,this._calculateChecksum(Z)),J}}var GJ=r(_V(),1);var mz;(($)=>{$.DYNAMIC="dynamic";$.FIXED="fixed";$.KINEMATIC_POSITION="kinematic_position";$.KINEMATIC_VELOCITY="kinematic_velocity"})(mz||={});var hE=0.001,je="dynamic";class f$ extends O0{_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??=je,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:Y}=this.rotation;return{x:-2*(Z*X+Y*J),y:-2*(J*X-Y*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:Y,principalAngularInertiaLocalFrame:$}=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"]:GJ.default.RigidBodyType.Dynamic,["fixed"]:GJ.default.RigidBodyType.Fixed,["kinematic_position"]:GJ.default.RigidBodyType.KinematicPositionBased,["kinematic_velocity"]:GJ.default.RigidBodyType.KinematicVelocityBased}[Z];if(X===void 0)return c.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 c.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 F9({...Z,parentRigidBody:this,simulation:this._simulation}):this._createAndAddPendingChildCollider(Z)}createAndAddChildColliders(Z){let J=[];return Z.forEach((X)=>{let Y=this.createAndAddChildCollider(X);if(Y)J.push(Y)}),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 c.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 c.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 c.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,Y])=>{if(X in Z)Y(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 F9(Z);return this._colliders.add(J),J}_createAndAddPendingChildColliders(Z){let J=[];return Z.forEach((X)=>{let Y=this._createAndAddPendingChildCollider(X);if(Y)J.push(Y)}),J}_createRigidBodyDesc(Z){let J=Z.type??je;return{["dynamic"]:()=>GJ.default.RigidBodyDesc.dynamic(),["fixed"]:()=>GJ.default.RigidBodyDesc.fixed(),["kinematic_position"]:()=>GJ.default.RigidBodyDesc.kinematicPositionBased(),["kinematic_velocity"]:()=>GJ.default.RigidBodyDesc.kinematicVelocityBased()}[J]()}_requireCreated(Z){if(!this._rigidBody||!this._simulation)c.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)c.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)c.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)c.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)c.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)c.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)<hE&&Math.abs(Z.y)<hE&&Math.abs(Z.z)<hE}}var fE;(($)=>{$[$.Average=0]="Average";$[$.Min=1]="Min";$[$.Multiply=2]="Multiply";$[$.Max=3]="Max"})(fE||={});var uz;((z)=>{z.NONE="none";z.BALL="ball";z.BLOCK="block";z.CAPSULE="capsule";z.CONE="cone";z.CYLINDER="cylinder";z.ROUND_CYLINDER="round-cylinder";z.TRIMESH="trimesh";z.VOXELS="voxels";z.WEDGE="wedge"})(uz||={});class F9 extends O0{_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 Y=g5.instance.getBoundingBox(Z),$=Y.max.x-Y.min.x,Q=Y.max.y-Y.min.y,K=Y.max.z-Y.min.z,W=Math.max($,K),G=Math.min($,K),V=W/G,z=W/Q,F=W*J/2,H=(M)=>Math.max(0.01,M),q=()=>({shape:"block",halfExtents:{x:H($*J/2),y:H(Q*J/2),z:H(K*J/2)}}),U=()=>({shape:"round-cylinder",radius:H(F),halfHeight:H(Q*J/2),borderRadius:H(F*0.1)}),B=()=>{let M=g5.instance.getTrimesh(Z,J);if(!M)return;return{shape:"trimesh",vertices:M.vertices,indices:M.indices}},L=()=>({shape:"wedge",extents:{x:$*J,y:Q*J,z:K*J}}),w=()=>({shape:"capsule",radius:H(F),halfHeight:H(Q*J/2-F)});if(X)switch(X){case"block":return q();case"capsule":return w();case"round-cylinder":return U();case"trimesh":{let M=B();if(!M){c.error(`Collider.optionsFromModelUri(): Failed to create trimesh options for model ${Z}, falling back to generic shape!`);break}return M}case"wedge":return L();default:c.warning(`Collider.optionsFromModelUri(): Preferred shape ${X} is not yet supported with Collider.optionsFromModelUri(), defaulting to generic shape!`)}if(V>2)return q();if(z>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?g4.decodeRawCollisionGroups(this._collider.collisionGroups()):g4.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=g4.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 c.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 c.error("Collider.addToSimulation(): Rigid body must be simulated before adding a collider to it!");if(J.type==="dynamic"&&this.shape==="trimesh")c.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 c.error("Collider.combineVoxelStates(): Other collider is not simulated!");if(this.shape!=="voxels")return c.error("Collider.combineVoxelStates(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return c.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|n8.default.ActiveEvents.COLLISION_EVENTS:J&~n8.default.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|n8.default.ActiveEvents.CONTACT_FORCE_EVENTS:J&~n8.default.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 c.error("Collider.propagateVoxelChange(): Other collider is not simulated!");if(this.shape!=="voxels")return c.error("Collider.propagateVoxelChange(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return c.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":{c.error("Collider.setScale(): Trimesh colliders cannot be scaled!");return}case"voxels":{c.error("Collider.setScale(): Voxels colliders cannot be scaled!");return}case"wedge":{c.error("Collider.setScale(): Wedge colliders cannot be scaled!");return}default:c.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,Y])=>{if(Z[X]!==void 0)Y.call(this,Z[X])})}_autoAddToSimulation(Z){if(Z.simulation)this.addToSimulation(Z.simulation,Z.parentRigidBody)}_buildWedgeConvexHullVertices(Z){let{x:J,y:X,z:Y}=Z,$=J/2,Q=Y/2,K=X/2;return new Float32Array([-$,0-K,-Q,$,0-K,-Q,$,0-K,Q,-$,0-K,Q,-$,X-K,-Q,$,X-K,-Q])}_createColliderDesc(Z){let{shape:J,flags:X}=Z;switch(J){case"ball":{if(!Z.radius)c.fatalError("Ball collider must have a radius!");return n8.default.ColliderDesc.ball(Z.radius)}case"block":{if(!Z.halfExtents)c.fatalError("Block collider must have halfExtents!");return n8.default.ColliderDesc.cuboid(Z.halfExtents.x,Z.halfExtents.y,Z.halfExtents.z)}case"capsule":{if(!Z.halfHeight||!Z.radius)c.fatalError("Capsule collider must have halfHeight and radius!");return n8.default.ColliderDesc.capsule(Z.halfHeight,Z.radius)}case"cone":{if(!Z.radius||!Z.halfHeight)c.fatalError("Cone collider must have radius and halfHeight!");return n8.default.ColliderDesc.cone(Z.halfHeight,Z.radius)}case"cylinder":{if(!Z.radius||!Z.halfHeight)c.fatalError("Cylinder collider must have radius and halfHeight!");return n8.default.ColliderDesc.cylinder(Z.halfHeight,Z.radius)}case"round-cylinder":{if(!Z.radius||!Z.halfHeight||!Z.borderRadius)c.fatalError("Round cylinder collider must have radius, halfHeight, and borderRadius!");return n8.default.ColliderDesc.roundCylinder(Z.halfHeight,Z.radius,Z.borderRadius)}case"trimesh":{if(!Z.indices||!Z.vertices)c.fatalError("Trimesh collider must have vertices and indices!");return n8.default.ColliderDesc.trimesh(Z.vertices,Z.indices,X)}case"voxels":{if(!Z.coordinates||!Z.size)c.fatalError("Voxels collider must have coordinates and size!");return n8.default.ColliderDesc.voxels(this._coordinatesToInt32Array(Z.coordinates),Z.size)}case"wedge":{if(!Z.extents)c.fatalError("Wedge collider must have extents!");let Y=this._buildWedgeConvexHullVertices(Z.extents),$=n8.default.ColliderDesc.convexHull(Y);if(!$)throw c.fatalError("Failed to create convex hull for wedge collider!"),new Error("Convex hull creation failed");return $}default:c.fatalError(`Collider._createColliderDesc(): ${J} is not a valid collider shape!`)}}_requireSimulated(Z){if(!this.isSimulated)c.error(`Collider._requireSimulated(): Collider is not simulated, invoked method: ${Z}()`);return this.isSimulated}_requireUnsimulated(Z){if(this.isSimulated)c.error(`Collider._requireUnsimulated(): Collider is already simulated, invoked method: ${Z}()`);return!this.isSimulated}_requireNotRemoved(Z){if(this.isRemoved)c.error(`Collider._requireNotRemoved(): Collider is removed, invoked method: ${Z}()`);return!this.isRemoved}_setActiveCollisionTypes(){(this._collider??this._colliderDesc).setActiveCollisionTypes(n8.default.ActiveCollisionTypes.DYNAMIC_DYNAMIC|n8.default.ActiveCollisionTypes.DYNAMIC_KINEMATIC|n8.default.ActiveCollisionTypes.DYNAMIC_FIXED|n8.default.ActiveCollisionTypes.KINEMATIC_KINEMATIC|n8.default.ActiveCollisionTypes.KINEMATIC_FIXED)}_coordinatesToInt32Array(Z){let J=new Int32Array(Z.length*3);for(let X=0;X<Z.length;X++){let Y=Z[X],$=X*3;J[$]=Math.floor(Y.x),J[$+1]=Math.floor(Y.y),J[$+2]=Math.floor(Y.z)}return J}}var yI1={shape:"voxels"},yE;((X)=>{X.ENTITY_COLLISION="BLOCK_TYPE.ENTITY_COLLISION";X.ENTITY_CONTACT_FORCE="BLOCK_TYPE.ENTITY_CONTACT_FORCE"})(yE||={});class q9 extends O0{_id;_customColliderOptions;_halfExtents;_isLiquid;_name;_textureUri;constructor(Z={id:-1,textureUri:"textures/missing.png",name:"Unknown"}){if(Z.id<0)c.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}get id(){return this._id}get colliderOptions(){return{...this._customColliderOptions,...yI1}}get halfExtents(){return this._halfExtents}get isLiquid(){return this._isLiquid}get isMeshable(){return!this._customColliderOptions}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 F9({...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(g4.isDefaultCollisionGroups(J.collisionGroups))J.setCollisionGroups({belongsTo:[1],collidesWith:[65535&~1]});return J}serialize(){return k0.serializeBlockType(this)}}var bE;((J)=>J.REGISTER_BLOCK_TYPE="BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE")(bE||={});class dz extends O0{_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)c.fatalError(`BlockTypeRegistry.getBlockType(): BlockType with id ${Z} not found.`);return J}registerGenericBlockType(Z){let X=new class extends q9{constructor(Y=Z){super(Y)}};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 k0.serializeBlockTypeRegistry(this)}}var B_={};EK(B_,{worldSchema:()=>U_,worldPacketDefinition:()=>B50,vectorSchema:()=>z1,vectorBooleanSchema:()=>hy1,uiSchema:()=>F_,uiPacketDefinition:()=>q50,uiDatasSchema:()=>q_,uiDatasPacketDefinition:()=>U50,uiDataSendPacketDefinition:()=>t60,uiDataSchema:()=>FH,syncResponseSchema:()=>H_,syncResponsePacketDefinition:()=>F50,syncRequestSchema:()=>gI,syncRequestPacketDefinition:()=>r60,stateRequestSchema:()=>bI,stateRequestPacketDefinition:()=>o60,sceneUIsSchema:()=>z_,sceneUIsPacketDefinition:()=>H50,sceneUISchema:()=>V_,rgbColorSchema:()=>c6,registeredPackets:()=>vO,quaternionSchema:()=>rI,playersSchema:()=>G_,playersPacketDefinition:()=>z50,playerSchema:()=>W_,physicsDebugRenderSchema:()=>K_,physicsDebugRenderPacketDefinition:()=>G50,physicsDebugRaycastsSchema:()=>Q_,physicsDebugRaycastsPacketDefinition:()=>V50,physicsDebugRaycastSchema:()=>$_,particleEmittersSchema:()=>Y_,particleEmittersPacketDefinition:()=>W50,particleEmitterSchema:()=>X_,outboundPackets:()=>_O,modelNodeOverrideSchema:()=>oI,lightsSchema:()=>J_,lightsPacketDefinition:()=>K50,lightSchema:()=>Z_,isValidPacket:()=>yy1,inputSchema:()=>yI,inputPacketDefinition:()=>s60,inboundPackets:()=>IO,hexColorSchema:()=>hI,heartbeatSchema:()=>xI,heartbeatPacketDefinition:()=>i60,entitySchema:()=>tI,entitiesSchema:()=>eI,entitiesPacketDefinition:()=>Q50,definePacket:()=>_0,debugConfigSchema:()=>fI,debugConfigPacketDefinition:()=>a60,createPacket:()=>Cy1,connectionSchema:()=>AI,connectionPacketDefinition:()=>p60,chunksSchema:()=>sI,chunksPacketDefinition:()=>$50,chunkSchema:()=>aI,chatMessagesSchema:()=>nI,chatMessagesPacketDefinition:()=>Y50,chatMessageSendPacketDefinition:()=>n60,chatMessageSchema:()=>HH,cameraSchema:()=>iI,cameraPacketDefinition:()=>X50,blocksSchema:()=>cI,blocksPacketDefinition:()=>Z50,blockTypesSchema:()=>pI,blockTypesPacketDefinition:()=>J50,blockTypeSchema:()=>lI,blockSchema:()=>dI,bidirectionalPackets:()=>EO,audiosSchema:()=>uI,audiosPacketDefinition:()=>e60,audioSchema:()=>mI,PacketId:()=>A1});var EO={};EK(EO,{heartbeatPacketDefinition:()=>i60,connectionPacketDefinition:()=>p60});var vI=r(c60(),1);class SI extends vI.default{static instance=new vI.default}var A1;((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"})(A1||={});function Cy1(Z,J,X){if(!Z.validate(J))throw new Error(`Invalid payload for packet with id ${Z.id}. Error: ${SI.instance.errorsText(Z.validate.errors)}`);let Y=[Z.id,J];if(typeof X==="number")Y.push(X);return Y}function _0(Z,J){return{id:Z,schema:J,validate:SI.instance.compile(J)}}var Ty1={type:"object",properties:{i:{type:"string"}},required:["i"],additionalProperties:!1},l60={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},ky1={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},Ey1={type:"object",properties:{usernameFragment:{type:"string"},password:{type:"string"},iceLite:{type:"boolean",nullable:!0}},required:["usernameFragment","password"],additionalProperties:!1},Iy1={type:"object",properties:{i:{type:"string"},l:{type:"string"}},required:["i","l"],additionalProperties:!1},_y1={type:"object",properties:{port:{type:"number"},OS:{type:"number"},MIS:{type:"number"},maxMessageSize:{type:"number"}},required:["port","OS","MIS","maxMessageSize"],additionalProperties:!0},vy1={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},Sy1={type:"object",properties:{i:{type:"string"},f:{type:"string",enum:["cs","sc"]},ip:Ey1,ic:{type:"array",items:ky1},d:l60,s:_y1},required:["i","f","ip","ic","d","s"],additionalProperties:!1},Ay1={type:"object",properties:{i:{type:"string"},d:l60},required:["i","d"],additionalProperties:!1},xy1={type:"object",properties:{i:{type:"string",nullable:!0},pi:{type:"string",nullable:!0},l:{type:"string"},s:vy1},required:["l","s"],additionalProperties:!1},AI={type:"object",properties:{i:{type:"string",nullable:!0},k:{type:"boolean",nullable:!0},c:{...Ay1,nullable:!0},ca:{...Ty1,nullable:!0},d:{type:"array",items:{...xy1},nullable:!0},pa:{...Iy1,nullable:!0},t:{type:"array",items:{...Sy1},nullable:!0}},additionalProperties:!1};var p60=_0(116,AI);var xI={type:"null",nullable:!0};var i60=_0(117,xI);var IO={};EK(IO,{uiDataSendPacketDefinition:()=>t60,syncRequestPacketDefinition:()=>r60,stateRequestPacketDefinition:()=>o60,inputPacketDefinition:()=>s60,debugConfigPacketDefinition:()=>a60,chatMessageSendPacketDefinition:()=>n60});var hI={type:"string",pattern:"^[0-9A-Fa-f]{6}$"};var HH={type:"object",properties:{m:{type:"string"},c:{...hI,nullable:!0},p:{type:"string",nullable:!0}},required:["m"],additionalProperties:!1};var n60=_0(3,HH);var fI={type:"object",properties:{pdr:{type:"boolean",nullable:!0}},additionalProperties:!1};var a60=_0(128,fI);var yI={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 s60=_0(1,yI);var bI={type:"object",properties:{},additionalProperties:!1};var o60=_0(2,bI);var gI={type:"null",nullable:!0};var r60=_0(0,gI);var FH={type:"object",properties:{},additionalProperties:!0};var t60=_0(4,FH);var _O={};EK(_O,{worldPacketDefinition:()=>B50,uiPacketDefinition:()=>q50,uiDatasPacketDefinition:()=>U50,syncResponsePacketDefinition:()=>F50,sceneUIsPacketDefinition:()=>H50,playersPacketDefinition:()=>z50,physicsDebugRenderPacketDefinition:()=>G50,physicsDebugRaycastsPacketDefinition:()=>V50,particleEmittersPacketDefinition:()=>W50,lightsPacketDefinition:()=>K50,entitiesPacketDefinition:()=>Q50,chunksPacketDefinition:()=>$50,chatMessagesPacketDefinition:()=>Y50,cameraPacketDefinition:()=>X50,blocksPacketDefinition:()=>Z50,blockTypesPacketDefinition:()=>J50,audiosPacketDefinition:()=>e60});var z1={type:"array",items:[{type:"number"},{type:"number"},{type:"number"}],minItems:3,maxItems:3};var mI={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:{...z1,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 uI={type:"array",items:{...mI}};var e60=_0(33,uI);var dI={type:"object",properties:{i:{type:"number"},c:z1},required:["i","c"],additionalProperties:!1};var cI={type:"array",items:{...dI}};var Z50=_0(34,cI);var lI={type:"object",properties:{i:{type:"number"},l:{type:"boolean",nullable:!0},n:{type:"string",nullable:!0},t:{type:"string",nullable:!0}},required:["i"],additionalProperties:!1};var pI={type:"array",items:{...lI}};var J50=_0(35,pI);var iI={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:{...z1,nullable:!0},p:{...z1,nullable:!0},pt:{...z1,nullable:!0},pl:{...z1,nullable:!0},s:{type:"array",items:{type:"string"},nullable:!0},sa:{type:"number",nullable:!0},z:{type:"number",nullable:!0}},additionalProperties:!1};var nI={type:"array",items:{...HH}};var aI={type:"object",properties:{c:z1,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 sI={type:"array",items:{...aI}};var c6={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 oI={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:{...c6,nullable:!0}},required:["n"],additionalProperties:!1};var rI={type:"array",items:[{type:"number"},{type:"number"},{type:"number"},{type:"number"}],minItems:4,maxItems:4};var tI={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:{...z1,nullable:!0},bt:{type:"string",nullable:!0},h:{type:"array",items:{type:"string"},nullable:!0},m:{type:"string",nullable:!0},mo:{type:"array",items:{...oI},nullable:!0},mt:{type:"string",nullable:!0},n:{type:"string",nullable:!0},o:{type:"number",nullable:!0},p:{...z1,nullable:!0},pe:{type:"number",nullable:!0},pn:{type:"string",nullable:!0},r:{...rI,nullable:!0},rm:{type:"boolean",nullable:!0},s:{type:"number",nullable:!0},sn:{type:"array",items:{type:"string"},nullable:!0},t:{...c6,nullable:!0}},required:["i"],additionalProperties:!1};var eI={type:"array",items:{...tI}};var Z_={type:"object",properties:{i:{type:"number"},a:{type:"number",nullable:!0},e:{type:"number",nullable:!0},c:{...c6,nullable:!0},d:{type:"number",nullable:!0},n:{type:"number",nullable:!0},o:{...z1,nullable:!0},p:{...z1,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:{...z1,nullable:!0}},required:["i"],additionalProperties:!1};var J_={type:"array",items:{...Z_}};var X_={type:"object",properties:{i:{type:"number"},at:{type:"number",nullable:!0},b:{type:"number",nullable:!0},ce:{...c6,nullable:!0},cev:{...c6,nullable:!0},cs:{...c6,nullable:!0},csv:{...c6,nullable:!0},e:{type:"number",nullable:!0},en:{type:"string",nullable:!0},g:{...z1,nullable:!0},l:{type:"number",nullable:!0},lv:{type:"number",nullable:!0},mp:{type:"number",nullable:!0},o:{...z1,nullable:!0},oe:{type:"number",nullable:!0},oev:{type:"number",nullable:!0},os:{type:"number",nullable:!0},osv:{type:"number",nullable:!0},p:{...z1,nullable:!0},pa:{type:"boolean",nullable:!0},pv:{...z1,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:{...z1,nullable:!0},vv:{...z1,nullable:!0}},required:["i"],additionalProperties:!1};var Y_={type:"array",items:{...X_}};var $_={type:"object",properties:{o:{...z1},d:{...z1},l:{type:"number"},h:{type:"boolean"}},required:["o","d","l","h"],additionalProperties:!1};var Q_={type:"array",items:{...$_}};var K_={type:"object",properties:{v:{type:"array",items:{type:"number"}},c:{type:"array",items:{type:"number"}}},required:["v","c"],additionalProperties:!1};var W_={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 G_={type:"array",items:{...W_}};var V_={type:"object",properties:{i:{type:"number"},e:{type:"number",nullable:!0},o:{...z1,nullable:!0},p:{...z1,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 z_={type:"array",items:{...V_}};var H_={type:"object",properties:{r:{type:"number"},s:{type:"number"},p:{type:"number"},n:{type:"number"}},required:["r","s","p","n"],additionalProperties:!1};var F_={type:"object",properties:{p:{type:"boolean",nullable:!0},u:{type:"string",nullable:!0}},additionalProperties:!1};var q_={type:"array",items:{...FH}};var hy1={type:"array",items:[{type:"boolean"},{type:"boolean"},{type:"boolean"}],minItems:3,maxItems:3};var U_={type:"object",properties:{i:{type:"number"},ac:{...c6,nullable:!0},ai:{type:"number",nullable:!0},dc:{...c6,nullable:!0},di:{type:"number",nullable:!0},dp:{...z1,nullable:!0},fc:{...c6,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 X50=_0(40,iI);var Y50=_0(36,nI);var $50=_0(37,sI);var Q50=_0(38,eI);var K50=_0(44,J_);var W50=_0(46,Y_);var G50=_0(192,K_);var V50=_0(193,Q_);var z50=_0(45,G_);var H50=_0(43,z_);var F50=_0(32,H_);var q50=_0(41,F_);var U50=_0(42,q_);var B50=_0(39,U_);var vO=new Map,fy1={...EO,...IO,..._O};for(let Z of Object.values(fy1))if("id"in Z&&"schema"in Z){let J=Z;if(vO.has(J.id))throw new Error(`Packet with id ${J.id} is already registered.`);vO.set(J.id,J)}function yy1(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=vO.get(Z[0]);return!!J&&J.validate(Z[1])}var Q0=B_;var m50=r(b50(),1);import c$ from"fs";import g50 from"path";var UH="./dev/persistence";class p7{static instance=new p7;gameId=process.env.HYTOPIA_GAME_ID;lobbyId=process.env.HYTOPIA_LOBBY_ID;_creativeGateway;constructor(){try{this._creativeGateway=new m50.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(`
412
+ >>> no match, partial?`,Z,F,J,H),F===W)return!0}return!1}let U;if(typeof V==="string")U=z===V,this.debug("string match",V,z,U);else U=V.test(z),this.debug("pattern match",V,z,U);if(!U)return!1}if(Q===W&&K===G)return!0;else if(Q===W)return X;else if(K===G)return Q===W-1&&Z[Q]==="";else throw new Error("wtf?")}braceExpand(){return on(this.pattern,this.options)}parse(Z){iV(Z);let J=this.options;if(Z==="**")return M6;if(Z==="")return"";let X,Y=null;if(X=Z.match(ON1))Y=J.dot?NN1:MN1;else if(X=Z.match(GN1))Y=(J.nocase?J.dot?FN1:HN1:J.dot?zN1:VN1)(X[1]);else if(X=Z.match(RN1))Y=(J.nocase?J.dot?DN1:jN1:J.dot?PN1:CN1)(X);else if(X=Z.match(qN1))Y=J.dot?BN1:UN1;else if(X=Z.match(LN1))Y=wN1;let $=O6.fromGlob(Z,this.options).toMMPattern();if(Y&&typeof $==="object")Reflect.defineProperty($,"test",{value:Y});return $}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?EN1:J.dot?IN1:_N1,Y=new Set(J.nocase?["i"]:[]),$=Z.map((W)=>{let G=W.map((V)=>{if(V instanceof RegExp)for(let z of V.flags.split(""))Y.add(z);return typeof V==="string"?hN1(V):V===M6?M6:V._src});return G.forEach((V,z)=>{let F=G[z+1],H=G[z-1];if(V!==M6||H===M6)return;if(H===void 0)if(F!==void 0&&F!==M6)G[z+1]="(?:\\/|"+X+"\\/)?"+F;else G[z]=X;else if(F===void 0)G[z-1]=H+"(?:\\/|"+X+")?";else if(F!==M6)G[z-1]=H+"(?:\\/|\\/"+X+"\\/)"+F,G[z+1]=M6}),G.filter((V)=>V!==M6).join("/")}).join("|"),[Q,K]=Z.length>1?["(?:",")"]:["",""];if($="^"+Q+$+K+"$",this.negate)$="^(?!"+$+").+$";try{this.regexp=new RegExp($,[...Y].join(""))}catch(W){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 Y=this.slashSplit(Z);this.debug(this.pattern,"split",Y);let $=this.set;this.debug(this.pattern,"set",$);let Q=Y[Y.length-1];if(!Q)for(let K=Y.length-2;!Q&&K>=0;K--)Q=Y[K];for(let K=0;K<$.length;K++){let W=$[K],G=Y;if(X.matchBase&&W.length===1)G=[Q];if(this.matchOne(G,W,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return Y5.defaults(Z).Minimatch}}Y5.AST=O6;Y5.Minimatch=d9;Y5.escape=XW;Y5.unescape=c4;import{fileURLToPath as qR1}from"node:url";var YW=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,tn=new Set,NT=typeof process==="object"&&!!process?process:{},en=(Z,J,X,Y)=>{typeof NT.emitWarning==="function"?NT.emitWarning(Z,J,X,Y):console.error(`[${X}] ${J}: ${Z}`)},UL=globalThis.AbortController,rn=globalThis.AbortSignal;if(typeof UL==="undefined"){rn=class X{onabort;_onabort=[];reason;aborted=!1;addEventListener(Y,$){this._onabort.push($)}},UL=class X{constructor(){J()}signal=new rn;abort(Y){if(this.signal.aborted)return;this.signal.reason=Y,this.signal.aborted=!0;for(let $ of this.signal._onabort)$(Y);this.signal.onabort?.(Y)}};let Z=NT.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",J=()=>{if(!Z)return;Z=!1,en("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 fN1=(Z)=>!tn.has(Z),lS6=Symbol("type"),OX=(Z)=>Z&&Z===Math.floor(Z)&&Z>0&&isFinite(Z),Za=(Z)=>!OX(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?aV:null;class aV extends Array{constructor(Z){super(Z);this.fill(0)}}class $W{heap;length;static#Z=!1;static create(Z){let J=Za(Z);if(!J)return[];$W.#Z=!0;let X=new $W(Z,J);return $W.#Z=!1,X}constructor(Z,J){if(!$W.#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 sV{#Z;#J;#Y;#X;#$;#z;#F;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#W;#G;#V;#H;#Q;#U;#L;#B;#O;#k;#M;#E;#j;#R;#N;#C;#w;#_;static unsafeExposeInternals(Z){return{starts:Z.#j,ttls:Z.#R,sizes:Z.#E,keyMap:Z.#V,keyList:Z.#H,valList:Z.#Q,next:Z.#U,prev:Z.#L,get head(){return Z.#B},get tail(){return Z.#O},free:Z.#k,isBackgroundFetch:(J)=>Z.#q(J),backgroundFetch:(J,X,Y,$)=>Z.#h(J,X,Y,$),moveToTail:(J)=>Z.#b(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.#J}get calculatedSize(){return this.#G}get size(){return this.#W}get fetchMethod(){return this.#z}get memoMethod(){return this.#F}get dispose(){return this.#Y}get onInsert(){return this.#X}get disposeAfter(){return this.#$}constructor(Z){let{max:J=0,ttl:X,ttlResolution:Y=1,ttlAutopurge:$,updateAgeOnGet:Q,updateAgeOnHas:K,allowStale:W,dispose:G,onInsert:V,disposeAfter:z,noDisposeOnSet:F,noUpdateTTL:H,maxSize:q=0,maxEntrySize:U=0,sizeCalculation:B,fetchMethod:L,memoMethod:w,noDeleteOnFetchRejection:M,noDeleteOnStaleGet:N,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:P,ignoreFetchAbort:D}=Z;if(J!==0&&!OX(J))throw new TypeError("max option must be a nonnegative integer");let C=J?Za(J):Array;if(!C)throw new Error("invalid max value: "+J);if(this.#Z=J,this.#J=q,this.maxEntrySize=U||this.#J,this.sizeCalculation=B,this.sizeCalculation){if(!this.#J&&!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.#F=w,L!==void 0&&typeof L!=="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#z=L,this.#C=!!L,this.#V=new Map,this.#H=new Array(J).fill(void 0),this.#Q=new Array(J).fill(void 0),this.#U=new C(J),this.#L=new C(J),this.#B=0,this.#O=0,this.#k=$W.create(J),this.#W=0,this.#G=0,typeof G==="function")this.#Y=G;if(typeof V==="function")this.#X=V;if(typeof z==="function")this.#$=z,this.#M=[];else this.#$=void 0,this.#M=void 0;if(this.#N=!!this.#Y,this.#_=!!this.#X,this.#w=!!this.#$,this.noDisposeOnSet=!!F,this.noUpdateTTL=!!H,this.noDeleteOnFetchRejection=!!M,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!P,this.ignoreFetchAbort=!!D,this.maxEntrySize!==0){if(this.#J!==0){if(!OX(this.#J))throw new TypeError("maxSize must be a positive integer if specified")}if(!OX(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#m()}if(this.allowStale=!!W,this.noDeleteOnStaleGet=!!N,this.updateAgeOnGet=!!Q,this.updateAgeOnHas=!!K,this.ttlResolution=OX(Y)||Y===0?Y:1,this.ttlAutopurge=!!$,this.ttl=X||0,this.ttl){if(!OX(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#K()}if(this.#Z===0&&this.ttl===0&&this.#J===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#Z&&!this.#J){if(fN1("LRU_CACHE_UNBOUNDED"))tn.add("LRU_CACHE_UNBOUNDED"),en("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",sV)}}getRemainingTTL(Z){return this.#V.has(Z)?1/0:0}#K(){let Z=new aV(this.#Z),J=new aV(this.#Z);this.#R=Z,this.#j=J,this.#v=($,Q,K=YW.now())=>{if(J[$]=Q!==0?K:0,Z[$]=Q,Q!==0&&this.ttlAutopurge){let W=setTimeout(()=>{if(this.#P($))this.#S(this.#H[$],"expire")},Q+1);if(W.unref)W.unref()}},this.#A=($)=>{J[$]=Z[$]!==0?YW.now():0},this.#D=($,Q)=>{if(Z[Q]){let K=Z[Q],W=J[Q];if(!K||!W)return;$.ttl=K,$.start=W,$.now=X||Y();let G=$.now-W;$.remainingTTL=K-G}};let X=0,Y=()=>{let $=YW.now();if(this.ttlResolution>0){X=$;let Q=setTimeout(()=>X=0,this.ttlResolution);if(Q.unref)Q.unref()}return $};this.getRemainingTTL=($)=>{let Q=this.#V.get($);if(Q===void 0)return 0;let K=Z[Q],W=J[Q];if(!K||!W)return 1/0;let G=(X||Y())-W;return K-G},this.#P=($)=>{let Q=J[$],K=Z[$];return!!K&&!!Q&&(X||Y())-Q>K}}#A=()=>{};#D=()=>{};#v=()=>{};#P=()=>!1;#m(){let Z=new aV(this.#Z);this.#G=0,this.#E=Z,this.#x=(J)=>{this.#G-=Z[J],Z[J]=0},this.#u=(J,X,Y,$)=>{if(this.#q(X))return 0;if(!OX(Y))if($){if(typeof $!=="function")throw new TypeError("sizeCalculation must be a function");if(Y=$(X,J),!OX(Y))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 Y},this.#f=(J,X,Y)=>{if(Z[J]=X,this.#J){let $=this.#J-Z[J];while(this.#G>$)this.#y(!0)}if(this.#G+=Z[J],Y)Y.entrySize=X,Y.totalCalculatedSize=this.#G}}#x=(Z)=>{};#f=(Z,J,X)=>{};#u=(Z,J,X,Y)=>{if(X||Y)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#T({allowStale:Z=this.allowStale}={}){if(this.#W)for(let J=this.#O;;){if(!this.#d(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.#W)for(let J=this.#B;;){if(!this.#d(J))break;if(Z||!this.#P(J))yield J;if(J===this.#O)break;else J=this.#U[J]}}#d(Z){return Z!==void 0&&this.#V.get(this.#H[Z])===Z}*entries(){for(let Z of this.#T())if(this.#Q[Z]!==void 0&&this.#H[Z]!==void 0&&!this.#q(this.#Q[Z]))yield[this.#H[Z],this.#Q[Z]]}*rentries(){for(let Z of this.#I())if(this.#Q[Z]!==void 0&&this.#H[Z]!==void 0&&!this.#q(this.#Q[Z]))yield[this.#H[Z],this.#Q[Z]]}*keys(){for(let Z of this.#T()){let J=this.#H[Z];if(J!==void 0&&!this.#q(this.#Q[Z]))yield J}}*rkeys(){for(let Z of this.#I()){let J=this.#H[Z];if(J!==void 0&&!this.#q(this.#Q[Z]))yield J}}*values(){for(let Z of this.#T())if(this.#Q[Z]!==void 0&&!this.#q(this.#Q[Z]))yield this.#Q[Z]}*rvalues(){for(let Z of this.#I())if(this.#Q[Z]!==void 0&&!this.#q(this.#Q[Z]))yield this.#Q[Z]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(Z,J={}){for(let X of this.#T()){let Y=this.#Q[X],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0)continue;if(Z($,this.#H[X],this))return this.get(this.#H[X],J)}}forEach(Z,J=this){for(let X of this.#T()){let Y=this.#Q[X],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0)continue;Z.call(J,$,this.#H[X],this)}}rforEach(Z,J=this){for(let X of this.#I()){let Y=this.#Q[X],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0)continue;Z.call(J,$,this.#H[X],this)}}purgeStale(){let Z=!1;for(let J of this.#I({allowStale:!0}))if(this.#P(J))this.#S(this.#H[J],"expire"),Z=!0;return Z}info(Z){let J=this.#V.get(Z);if(J===void 0)return;let X=this.#Q[J],Y=this.#q(X)?X.__staleWhileFetching:X;if(Y===void 0)return;let $={value:Y};if(this.#R&&this.#j){let Q=this.#R[J],K=this.#j[J];if(Q&&K){let W=Q-(YW.now()-K);$.ttl=W,$.start=Date.now()}}if(this.#E)$.size=this.#E[J];return $}dump(){let Z=[];for(let J of this.#T({allowStale:!0})){let X=this.#H[J],Y=this.#Q[J],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0||X===void 0)continue;let Q={value:$};if(this.#R&&this.#j){Q.ttl=this.#R[J];let K=YW.now()-this.#j[J];Q.start=Math.floor(Date.now()-K)}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 Y=Date.now()-X.start;X.start=YW.now()-Y}this.set(J,X.value,X)}}set(Z,J,X={}){if(J===void 0)return this.delete(Z),this;let{ttl:Y=this.ttl,start:$,noDisposeOnSet:Q=this.noDisposeOnSet,sizeCalculation:K=this.sizeCalculation,status:W}=X,{noUpdateTTL:G=this.noUpdateTTL}=X,V=this.#u(Z,J,X.size||0,K);if(this.maxEntrySize&&V>this.maxEntrySize){if(W)W.set="miss",W.maxEntrySizeExceeded=!0;return this.#S(Z,"set"),this}let z=this.#W===0?void 0:this.#V.get(Z);if(z===void 0){if(z=this.#W===0?this.#O:this.#k.length!==0?this.#k.pop():this.#W===this.#Z?this.#y(!1):this.#W,this.#H[z]=Z,this.#Q[z]=J,this.#V.set(Z,z),this.#U[this.#O]=z,this.#L[z]=this.#O,this.#O=z,this.#W++,this.#f(z,V,W),W)W.set="add";if(G=!1,this.#_)this.#X?.(J,Z,"add")}else{this.#b(z);let F=this.#Q[z];if(J!==F){if(this.#C&&this.#q(F)){F.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:H}=F;if(H!==void 0&&!Q){if(this.#N)this.#Y?.(H,Z,"set");if(this.#w)this.#M?.push([H,Z,"set"])}}else if(!Q){if(this.#N)this.#Y?.(F,Z,"set");if(this.#w)this.#M?.push([F,Z,"set"])}if(this.#x(z),this.#f(z,V,W),this.#Q[z]=J,W){W.set="replace";let H=F&&this.#q(F)?F.__staleWhileFetching:F;if(H!==void 0)W.oldValue=H}}else if(W)W.set="update";if(this.#_)this.onInsert?.(J,Z,J===F?"update":"replace")}if(Y!==0&&!this.#R)this.#K();if(this.#R){if(!G)this.#v(z,Y,$);if(W)this.#D(W,z)}if(!Q&&this.#w&&this.#M){let F=this.#M,H;while(H=F?.shift())this.#$?.(...H)}return this}pop(){try{while(this.#W){let Z=this.#Q[this.#B];if(this.#y(!0),this.#q(Z)){if(Z.__staleWhileFetching)return Z.__staleWhileFetching}else if(Z!==void 0)return Z}}finally{if(this.#w&&this.#M){let Z=this.#M,J;while(J=Z?.shift())this.#$?.(...J)}}}#y(Z){let J=this.#B,X=this.#H[J],Y=this.#Q[J];if(this.#C&&this.#q(Y))Y.__abortController.abort(new Error("evicted"));else if(this.#N||this.#w){if(this.#N)this.#Y?.(Y,X,"evict");if(this.#w)this.#M?.push([Y,X,"evict"])}if(this.#x(J),Z)this.#H[J]=void 0,this.#Q[J]=void 0,this.#k.push(J);if(this.#W===1)this.#B=this.#O=0,this.#k.length=0;else this.#B=this.#U[J];return this.#V.delete(X),this.#W--,J}has(Z,J={}){let{updateAgeOnHas:X=this.updateAgeOnHas,status:Y}=J,$=this.#V.get(Z);if($!==void 0){let Q=this.#Q[$];if(this.#q(Q)&&Q.__staleWhileFetching===void 0)return!1;if(!this.#P($)){if(X)this.#A($);if(Y)Y.has="hit",this.#D(Y,$);return!0}else if(Y)Y.has="stale",this.#D(Y,$)}else if(Y)Y.has="miss";return!1}peek(Z,J={}){let{allowStale:X=this.allowStale}=J,Y=this.#V.get(Z);if(Y===void 0||!X&&this.#P(Y))return;let $=this.#Q[Y];return this.#q($)?$.__staleWhileFetching:$}#h(Z,J,X,Y){let $=J===void 0?void 0:this.#Q[J];if(this.#q($))return $;let Q=new UL,{signal:K}=X;K?.addEventListener("abort",()=>Q.abort(K.reason),{signal:Q.signal});let W={signal:Q.signal,options:X,context:Y},G=(U,B=!1)=>{let{aborted:L}=Q.signal,w=X.ignoreFetchAbort&&U!==void 0;if(X.status)if(L&&!B){if(X.status.fetchAborted=!0,X.status.fetchError=Q.signal.reason,w)X.status.fetchAbortIgnored=!0}else X.status.fetchResolved=!0;if(L&&!w&&!B)return z(Q.signal.reason);let M=H;if(this.#Q[J]===H)if(U===void 0)if(M.__staleWhileFetching)this.#Q[J]=M.__staleWhileFetching;else this.#S(Z,"fetch");else{if(X.status)X.status.fetchUpdated=!0;this.set(Z,U,W.options)}return U},V=(U)=>{if(X.status)X.status.fetchRejected=!0,X.status.fetchError=U;return z(U)},z=(U)=>{let{aborted:B}=Q.signal,L=B&&X.allowStaleOnFetchAbort,w=L||X.allowStaleOnFetchRejection,M=w||X.noDeleteOnFetchRejection,N=H;if(this.#Q[J]===H){if(!M||N.__staleWhileFetching===void 0)this.#S(Z,"fetch");else if(!L)this.#Q[J]=N.__staleWhileFetching}if(w){if(X.status&&N.__staleWhileFetching!==void 0)X.status.returnedStale=!0;return N.__staleWhileFetching}else if(N.__returned===N)throw U},F=(U,B)=>{let L=this.#z?.(Z,$,W);if(L&&L instanceof Promise)L.then((w)=>U(w===void 0?void 0:w),B);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 H=new Promise(F).then(G,V),q=Object.assign(H,{__abortController:Q,__staleWhileFetching:$,__returned:void 0});if(J===void 0)this.set(Z,q,{...W.options,status:void 0}),J=this.#V.get(Z);else this.#Q[J]=q;return q}#q(Z){if(!this.#C)return!1;let J=Z;return!!J&&J instanceof Promise&&J.hasOwnProperty("__staleWhileFetching")&&J.__abortController instanceof UL}async fetch(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:Y=this.updateAgeOnGet,noDeleteOnStaleGet:$=this.noDeleteOnStaleGet,ttl:Q=this.ttl,noDisposeOnSet:K=this.noDisposeOnSet,size:W=0,sizeCalculation:G=this.sizeCalculation,noUpdateTTL:V=this.noUpdateTTL,noDeleteOnFetchRejection:z=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:F=this.allowStaleOnFetchRejection,ignoreFetchAbort:H=this.ignoreFetchAbort,allowStaleOnFetchAbort:q=this.allowStaleOnFetchAbort,context:U,forceRefresh:B=!1,status:L,signal:w}=J;if(!this.#C){if(L)L.fetch="get";return this.get(Z,{allowStale:X,updateAgeOnGet:Y,noDeleteOnStaleGet:$,status:L})}let M={allowStale:X,updateAgeOnGet:Y,noDeleteOnStaleGet:$,ttl:Q,noDisposeOnSet:K,size:W,sizeCalculation:G,noUpdateTTL:V,noDeleteOnFetchRejection:z,allowStaleOnFetchRejection:F,allowStaleOnFetchAbort:q,ignoreFetchAbort:H,status:L,signal:w},N=this.#V.get(Z);if(N===void 0){if(L)L.fetch="miss";let R=this.#h(Z,N,M,U);return R.__returned=R}else{let R=this.#Q[N];if(this.#q(R)){let k=X&&R.__staleWhileFetching!==void 0;if(L){if(L.fetch="inflight",k)L.returnedStale=!0}return k?R.__staleWhileFetching:R.__returned=R}let P=this.#P(N);if(!B&&!P){if(L)L.fetch="hit";if(this.#b(N),Y)this.#A(N);if(L)this.#D(L,N);return R}let D=this.#h(Z,N,M,U),T=D.__staleWhileFetching!==void 0&&X;if(L){if(L.fetch=P?"stale":"refresh",T&&P)L.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.#F;if(!X)throw new Error("no memoMethod provided to constructor");let{context:Y,forceRefresh:$,...Q}=J,K=this.get(Z,Q);if(!$&&K!==void 0)return K;let W=X(Z,K,{options:Q,context:Y});return this.set(Z,W,Q),W}get(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:Y=this.updateAgeOnGet,noDeleteOnStaleGet:$=this.noDeleteOnStaleGet,status:Q}=J,K=this.#V.get(Z);if(K!==void 0){let W=this.#Q[K],G=this.#q(W);if(Q)this.#D(Q,K);if(this.#P(K)){if(Q)Q.get="stale";if(!G){if(!$)this.#S(Z,"expire");if(Q&&X)Q.returnedStale=!0;return X?W:void 0}else{if(Q&&X&&W.__staleWhileFetching!==void 0)Q.returnedStale=!0;return X?W.__staleWhileFetching:void 0}}else{if(Q)Q.get="hit";if(G)return W.__staleWhileFetching;if(this.#b(K),Y)this.#A(K);return W}}else if(Q)Q.get="miss"}#c(Z,J){this.#L[J]=Z,this.#U[Z]=J}#b(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.#S(Z,"delete")}#S(Z,J){let X=!1;if(this.#W!==0){let Y=this.#V.get(Z);if(Y!==void 0)if(X=!0,this.#W===1)this.#g(J);else{this.#x(Y);let $=this.#Q[Y];if(this.#q($))$.__abortController.abort(new Error("deleted"));else if(this.#N||this.#w){if(this.#N)this.#Y?.($,Z,J);if(this.#w)this.#M?.push([$,Z,J])}if(this.#V.delete(Z),this.#H[Y]=void 0,this.#Q[Y]=void 0,Y===this.#O)this.#O=this.#L[Y];else if(Y===this.#B)this.#B=this.#U[Y];else{let Q=this.#L[Y];this.#U[Q]=this.#U[Y];let K=this.#U[Y];this.#L[K]=this.#L[Y]}this.#W--,this.#k.push(Y)}}if(this.#w&&this.#M?.length){let Y=this.#M,$;while($=Y?.shift())this.#$?.(...$)}return X}clear(){return this.#g("delete")}#g(Z){for(let J of this.#I({allowStale:!0})){let X=this.#Q[J];if(this.#q(X))X.__abortController.abort(new Error("deleted"));else{let Y=this.#H[J];if(this.#N)this.#Y?.(X,Y,Z);if(this.#w)this.#M?.push([X,Y,Z])}}if(this.#V.clear(),this.#Q.fill(void 0),this.#H.fill(void 0),this.#R&&this.#j)this.#R.fill(0),this.#j.fill(0);if(this.#E)this.#E.fill(0);if(this.#B=0,this.#O=0,this.#k.length=0,this.#G=0,this.#W=0,this.#w&&this.#M){let J=this.#M,X;while(X=J?.shift())this.#$?.(...X)}}}import{posix as nN1,win32 as _T}from"node:path";import{fileURLToPath as aN1}from"node:url";import{lstatSync as sN1,readdir as oN1,readdirSync as rN1,readlinkSync as tN1,realpathSync as eN1}from"fs";import*as ZR1 from"node:fs";import{lstat as XR1,readdir as YR1,readlink as $R1,realpath as QR1}from"node:fs/promises";import{EventEmitter as TT}from"node:events";import Qa from"node:stream";import{StringDecoder as yN1}from"node:string_decoder";var Ja=typeof process==="object"&&process?process:{stdout:null,stderr:null},bN1=(Z)=>!!Z&&typeof Z==="object"&&(Z instanceof P$||Z instanceof Qa||gN1(Z)||mN1(Z)),gN1=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof TT&&typeof Z.pipe==="function"&&Z.pipe!==Qa.Writable.prototype.pipe,mN1=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof TT&&typeof Z.write==="function"&&typeof Z.end==="function",gZ=Symbol("EOF"),mZ=Symbol("maybeEmitEnd"),MX=Symbol("emittedEnd"),BL=Symbol("emittingEnd"),oV=Symbol("emittedError"),LL=Symbol("closed"),Xa=Symbol("read"),wL=Symbol("flush"),Ya=Symbol("flushChunk"),l4=Symbol("encoding"),QW=Symbol("decoder"),Z6=Symbol("flowing"),rV=Symbol("paused"),KW=Symbol("resume"),J6=Symbol("buffer"),$5=Symbol("pipes"),X6=Symbol("bufferLength"),RT=Symbol("bufferPush"),OL=Symbol("bufferShift"),h6=Symbol("objectMode"),C8=Symbol("destroyed"),jT=Symbol("error"),DT=Symbol("emitData"),$a=Symbol("emitEnd"),PT=Symbol("emitEnd2"),S7=Symbol("async"),CT=Symbol("abort"),ML=Symbol("aborted"),tV=Symbol("signal"),D$=Symbol("dataListeners"),Q9=Symbol("discarded"),eV=(Z)=>Promise.resolve().then(Z),uN1=(Z)=>Z(),dN1=(Z)=>Z==="end"||Z==="finish"||Z==="prefinish",cN1=(Z)=>Z instanceof ArrayBuffer||!!Z&&typeof Z==="object"&&Z.constructor&&Z.constructor.name==="ArrayBuffer"&&Z.byteLength>=0,lN1=(Z)=>!Buffer.isBuffer(Z)&&ArrayBuffer.isView(Z);class kT{src;dest;opts;ondrain;constructor(Z,J,X){this.src=Z,this.dest=J,this.opts=X,this.ondrain=()=>Z[KW](),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 Ka extends kT{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(Z,J,X){super(Z,J,X);this.proxyErrors=(Y)=>J.emit("error",Y),Z.on("error",this.proxyErrors)}}var pN1=(Z)=>!!Z.objectMode,iN1=(Z)=>!Z.objectMode&&!!Z.encoding&&Z.encoding!=="buffer";class P$ extends TT{[Z6]=!1;[rV]=!1;[$5]=[];[J6]=[];[h6];[l4];[S7];[QW];[gZ]=!1;[MX]=!1;[BL]=!1;[LL]=!1;[oV]=null;[X6]=0;[C8]=!1;[tV];[ML]=!1;[D$]=0;[Q9]=!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(pN1(J))this[h6]=!0,this[l4]=null;else if(iN1(J))this[l4]=J.encoding,this[h6]=!1;else this[h6]=!1,this[l4]=null;if(this[S7]=!!J.async,this[QW]=this[l4]?new yN1(this[l4]):null,J&&J.debugExposeBuffer===!0)Object.defineProperty(this,"buffer",{get:()=>this[J6]});if(J&&J.debugExposePipes===!0)Object.defineProperty(this,"pipes",{get:()=>this[$5]});let{signal:X}=J;if(X)if(this[tV]=X,X.aborted)this[CT]();else X.addEventListener("abort",()=>this[CT]())}get bufferLength(){return this[X6]}get encoding(){return this[l4]}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[h6]}set objectMode(Z){throw new Error("objectMode must be set at instantiation time")}get["async"](){return this[S7]}set["async"](Z){this[S7]=this[S7]||!!Z}[CT](){this[ML]=!0,this.emit("abort",this[tV]?.reason),this.destroy(this[tV]?.reason)}get aborted(){return this[ML]}set aborted(Z){}write(Z,J,X){if(this[ML])return!1;if(this[gZ])throw new Error("write after end");if(this[C8])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 Y=this[S7]?eV:uN1;if(!this[h6]&&!Buffer.isBuffer(Z)){if(lN1(Z))Z=Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength);else if(cN1(Z))Z=Buffer.from(Z);else if(typeof Z!=="string")throw new Error("Non-contiguous data written to non-objectMode stream")}if(this[h6]){if(this[Z6]&&this[X6]!==0)this[wL](!0);if(this[Z6])this.emit("data",Z);else this[RT](Z);if(this[X6]!==0)this.emit("readable");if(X)Y(X);return this[Z6]}if(!Z.length){if(this[X6]!==0)this.emit("readable");if(X)Y(X);return this[Z6]}if(typeof Z==="string"&&!(J===this[l4]&&!this[QW]?.lastNeed))Z=Buffer.from(Z,J);if(Buffer.isBuffer(Z)&&this[l4])Z=this[QW].write(Z);if(this[Z6]&&this[X6]!==0)this[wL](!0);if(this[Z6])this.emit("data",Z);else this[RT](Z);if(this[X6]!==0)this.emit("readable");if(X)Y(X);return this[Z6]}read(Z){if(this[C8])return null;if(this[Q9]=!1,this[X6]===0||Z===0||Z&&Z>this[X6])return this[mZ](),null;if(this[h6])Z=null;if(this[J6].length>1&&!this[h6])this[J6]=[this[l4]?this[J6].join(""):Buffer.concat(this[J6],this[X6])];let J=this[Xa](Z||null,this[J6][0]);return this[mZ](),J}[Xa](Z,J){if(this[h6])this[OL]();else{let X=J;if(Z===X.length||Z===null)this[OL]();else if(typeof X==="string")this[J6][0]=X.slice(Z),J=X.slice(0,Z),this[X6]-=Z;else this[J6][0]=X.subarray(Z),J=X.subarray(0,Z),this[X6]-=Z}if(this.emit("data",J),!this[J6].length&&!this[gZ])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[gZ]=!0,this.writable=!1,this[Z6]||!this[rV])this[mZ]();return this}[KW](){if(this[C8])return;if(!this[D$]&&!this[$5].length)this[Q9]=!0;if(this[rV]=!1,this[Z6]=!0,this.emit("resume"),this[J6].length)this[wL]();else if(this[gZ])this[mZ]();else this.emit("drain")}resume(){return this[KW]()}pause(){this[Z6]=!1,this[rV]=!0,this[Q9]=!1}get destroyed(){return this[C8]}get flowing(){return this[Z6]}get paused(){return this[rV]}[RT](Z){if(this[h6])this[X6]+=1;else this[X6]+=Z.length;this[J6].push(Z)}[OL](){if(this[h6])this[X6]-=1;else this[X6]-=this[J6][0].length;return this[J6].shift()}[wL](Z=!1){do;while(this[Ya](this[OL]())&&this[J6].length);if(!Z&&!this[J6].length&&!this[gZ])this.emit("drain")}[Ya](Z){return this.emit("data",Z),this[Z6]}pipe(Z,J){if(this[C8])return Z;this[Q9]=!1;let X=this[MX];if(J=J||{},Z===Ja.stdout||Z===Ja.stderr)J.end=!1;else J.end=J.end!==!1;if(J.proxyErrors=!!J.proxyErrors,X){if(J.end)Z.end()}else if(this[$5].push(!J.proxyErrors?new kT(this,Z,J):new Ka(this,Z,J)),this[S7])eV(()=>this[KW]());else this[KW]();return Z}unpipe(Z){let J=this[$5].find((X)=>X.dest===Z);if(J){if(this[$5].length===1){if(this[Z6]&&this[D$]===0)this[Z6]=!1;this[$5]=[]}else this[$5].splice(this[$5].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[Q9]=!1,this[D$]++,!this[$5].length&&!this[Z6])this[KW]()}else if(Z==="readable"&&this[X6]!==0)super.emit("readable");else if(dN1(Z)&&this[MX])super.emit(Z),this.removeAllListeners(Z);else if(Z==="error"&&this[oV]){let Y=J;if(this[S7])eV(()=>Y.call(this,this[oV]));else Y.call(this,this[oV])}return X}removeListener(Z,J){return this.off(Z,J)}off(Z,J){let X=super.off(Z,J);if(Z==="data"){if(this[D$]=this.listeners("data").length,this[D$]===0&&!this[Q9]&&!this[$5].length)this[Z6]=!1}return X}removeAllListeners(Z){let J=super.removeAllListeners(Z);if(Z==="data"||Z===void 0){if(this[D$]=0,!this[Q9]&&!this[$5].length)this[Z6]=!1}return J}get emittedEnd(){return this[MX]}[mZ](){if(!this[BL]&&!this[MX]&&!this[C8]&&this[J6].length===0&&this[gZ]){if(this[BL]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[LL])this.emit("close");this[BL]=!1}}emit(Z,...J){let X=J[0];if(Z!=="error"&&Z!=="close"&&Z!==C8&&this[C8])return!1;else if(Z==="data")return!this[h6]&&!X?!1:this[S7]?(eV(()=>this[DT](X)),!0):this[DT](X);else if(Z==="end")return this[$a]();else if(Z==="close"){if(this[LL]=!0,!this[MX]&&!this[C8])return!1;let $=super.emit("close");return this.removeAllListeners("close"),$}else if(Z==="error"){this[oV]=X,super.emit(jT,X);let $=!this[tV]||this.listeners("error").length?super.emit("error",X):!1;return this[mZ](),$}else if(Z==="resume"){let $=super.emit("resume");return this[mZ](),$}else if(Z==="finish"||Z==="prefinish"){let $=super.emit(Z);return this.removeAllListeners(Z),$}let Y=super.emit(Z,...J);return this[mZ](),Y}[DT](Z){for(let X of this[$5])if(X.dest.write(Z)===!1)this.pause();let J=this[Q9]?!1:super.emit("data",Z);return this[mZ](),J}[$a](){if(this[MX])return!1;return this[MX]=!0,this.readable=!1,this[S7]?(eV(()=>this[PT]()),!0):this[PT]()}[PT](){if(this[QW]){let J=this[QW].end();if(J){for(let X of this[$5])X.dest.write(J);if(!this[Q9])super.emit("data",J)}}for(let J of this[$5])J.end();let Z=super.emit("end");return this.removeAllListeners("end"),Z}async collect(){let Z=Object.assign([],{dataLength:0});if(!this[h6])Z.dataLength=0;let J=this.promise();return this.on("data",(X)=>{if(Z.push(X),!this[h6])Z.dataLength+=X.length}),await J,Z}async concat(){if(this[h6])throw new Error("cannot concat in objectMode");let Z=await this.collect();return this[l4]?Z.join(""):Buffer.concat(Z,Z.dataLength)}async promise(){return new Promise((Z,J)=>{this.on(C8,()=>J(new Error("stream destroyed"))),this.on("error",(X)=>J(X)),this.on("end",()=>Z())})}[Symbol.asyncIterator](){this[Q9]=!1;let Z=!1,J=async()=>{return this.pause(),Z=!0,{value:void 0,done:!0}};return{next:()=>{if(Z)return J();let Y=this.read();if(Y!==null)return Promise.resolve({done:!1,value:Y});if(this[gZ])return J();let $,Q,K=(z)=>{this.off("data",W),this.off("end",G),this.off(C8,V),J(),Q(z)},W=(z)=>{this.off("error",K),this.off("end",G),this.off(C8,V),this.pause(),$({value:z,done:!!this[gZ]})},G=()=>{this.off("error",K),this.off("data",W),this.off(C8,V),J(),$({done:!0,value:void 0})},V=()=>K(new Error("stream destroyed"));return new Promise((z,F)=>{Q=F,$=z,this.once(C8,V),this.once("error",K),this.once("end",G),this.once("data",W)})},throw:J,return:J,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Q9]=!1;let Z=!1,J=()=>{return this.pause(),this.off(jT,J),this.off(C8,J),this.off("end",J),Z=!0,{done:!0,value:void 0}},X=()=>{if(Z)return J();let Y=this.read();return Y===null?J():{done:!1,value:Y}};return this.once("end",J),this.once(jT,J),this.once(C8,J),{next:X,throw:J,return:J,[Symbol.iterator](){return this}}}destroy(Z){if(this[C8]){if(Z)this.emit("error",Z);else this.emit(C8);return this}this[C8]=!0,this[Q9]=!0,this[J6].length=0,this[X6]=0;let J=this;if(typeof J.close==="function"&&!this[LL])J.close();if(Z)this.emit("error",Z);else this.emit(C8);return this}static get isStream(){return bN1}}var JR1=eN1.native,Jz={lstatSync:sN1,readdir:oN1,readdirSync:rN1,readlinkSync:tN1,realpathSync:JR1,promises:{lstat:XR1,readdir:YR1,readlink:$R1,realpath:QR1}},Ha=(Z)=>!Z||Z===Jz||Z===ZR1?Jz:{...Jz,...Z,promises:{...Jz.promises,...Z.promises||{}}},Fa=/^\\\\\?\\([a-z]:)\\?$/i,KR1=(Z)=>Z.replace(/\//g,"\\").replace(Fa,"$1\\"),WR1=/[\\\/]/,l9=0,qa=1,Ua=2,A7=4,Ba=6,La=8,C$=10,wa=12,c9=15,Zz=~c9,ET=16,Wa=32,Xz=64,p4=128,NL=256,jL=512,Ga=Xz|p4|jL,GR1=1023,IT=(Z)=>Z.isFile()?La:Z.isDirectory()?A7:Z.isSymbolicLink()?C$:Z.isCharacterDevice()?Ua:Z.isBlockDevice()?Ba:Z.isSocket()?wa:Z.isFIFO()?qa:l9,Va=new Map,Yz=(Z)=>{let J=Va.get(Z);if(J)return J;let X=Z.normalize("NFKD");return Va.set(Z,X),X},za=new Map,RL=(Z)=>{let J=za.get(Z);if(J)return J;let X=Yz(Z.toLowerCase());return za.set(Z,X),X};class vT extends sV{constructor(){super({max:256})}}class Oa extends sV{constructor(Z=16384){super({maxSize:Z,sizeCalculation:(J)=>J.length+1})}}var Ma=Symbol("PathScurry setAsCwd");class Q5{name;root;roots;parent;nocase;isCWD=!1;#Z;#J;get dev(){return this.#J}#Y;get mode(){return this.#Y}#X;get nlink(){return this.#X}#$;get uid(){return this.#$}#z;get gid(){return this.#z}#F;get rdev(){return this.#F}#W;get blksize(){return this.#W}#G;get ino(){return this.#G}#V;get size(){return this.#V}#H;get blocks(){return this.#H}#Q;get atimeMs(){return this.#Q}#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}#M;get ctime(){return this.#M}#E;get birthtime(){return this.#E}#j;#R;#N;#C;#w;#_;#K;#A;#D;#v;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(Z,J=l9,X,Y,$,Q,K){if(this.name=Z,this.#j=$?RL(Z):Yz(Z),this.#K=J&GR1,this.nocase=$,this.roots=Y,this.root=X||this,this.#A=Q,this.#N=K.fullpath,this.#w=K.relative,this.#_=K.relativePosix,this.parent=K.parent,this.parent)this.#Z=this.parent.#Z;else this.#Z=Ha(K.fs)}depth(){if(this.#R!==void 0)return this.#R;if(!this.parent)return this.#R=0;return this.#R=this.parent.depth()+1}childrenCache(){return this.#A}resolve(Z){if(!Z)return this;let J=this.getRootString(Z),Y=Z.substring(J.length).split(this.splitSep);return J?this.getRoot(J).#P(Y):this.#P(Y)}#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.#K&=~ET,J}child(Z,J){if(Z===""||Z===".")return this;if(Z==="..")return this.parent||this;let X=this.children(),Y=this.nocase?RL(Z):Yz(Z);for(let W of X)if(W.#j===Y)return W;let $=this.parent?this.sep:"",Q=this.#N?this.#N+$+Z:void 0,K=this.newChild(Z,l9,{...J,parent:this,fullpath:Q});if(!this.canReaddir())K.#K|=p4;return X.push(K),K}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.#_!==void 0)return this.#_;let Z=this.name,J=this.parent;if(!J)return this.#_=this.fullpathPosix();let X=J.relativePosix();return X+(!X||!J.parent?"":"/")+Z}fullpath(){if(this.#N!==void 0)return this.#N;let Z=this.name,J=this.parent;if(!J)return this.#N=this.name;let Y=J.fullpath()+(!J.parent?"":this.sep)+Z;return this.#N=Y}fullpathPosix(){if(this.#C!==void 0)return this.#C;if(this.sep==="/")return this.#C=this.fullpath();if(!this.parent){let Y=this.fullpath().replace(/\\/g,"/");if(/^[a-z]:\//i.test(Y))return this.#C=`//?/${Y}`;else return this.#C=Y}let Z=this.parent,J=Z.fullpathPosix(),X=J+(!J||!Z.parent?"":"/")+this.name;return this.#C=X}isUnknown(){return(this.#K&c9)===l9}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.#K&c9)===La}isDirectory(){return(this.#K&c9)===A7}isCharacterDevice(){return(this.#K&c9)===Ua}isBlockDevice(){return(this.#K&c9)===Ba}isFIFO(){return(this.#K&c9)===qa}isSocket(){return(this.#K&c9)===wa}isSymbolicLink(){return(this.#K&C$)===C$}lstatCached(){return this.#K&Wa?this:void 0}readlinkCached(){return this.#D}realpathCached(){return this.#v}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.#K&c9;return!(Z!==l9&&Z!==C$||this.#K&NL||this.#K&p4)}calledReaddir(){return!!(this.#K&ET)}isENOENT(){return!!(this.#K&p4)}isNamed(Z){return!this.nocase?this.#j===Yz(Z):this.#j===RL(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.#y(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.#y(J.code);return}}#m(Z){this.#K|=ET;for(let J=Z.provisional;J<Z.length;J++){let X=Z[J];if(X)X.#x()}}#x(){if(this.#K&p4)return;this.#K=(this.#K|p4)&Zz,this.#f()}#f(){let Z=this.children();Z.provisional=0;for(let J of Z)J.#x()}#u(){this.#K|=jL,this.#T()}#T(){if(this.#K&Xz)return;let Z=this.#K;if((Z&c9)===A7)Z&=Zz;this.#K=Z|Xz,this.#f()}#I(Z=""){if(Z==="ENOTDIR"||Z==="EPERM")this.#T();else if(Z==="ENOENT")this.#x();else this.children().provisional=0}#d(Z=""){if(Z==="ENOTDIR")this.parent.#T();else if(Z==="ENOENT")this.#x()}#y(Z=""){let J=this.#K;if(J|=NL,Z==="ENOENT")J|=p4;if(Z==="EINVAL"||Z==="UNKNOWN")J&=Zz;if(this.#K=J,Z==="ENOTDIR"&&this.parent)this.parent.#T()}#h(Z,J){return this.#c(Z,J)||this.#q(Z,J)}#q(Z,J){let X=IT(Z),Y=this.newChild(Z.name,X,{parent:this}),$=Y.#K&c9;if($!==A7&&$!==C$&&$!==l9)Y.#K|=Xz;return J.unshift(Y),J.provisional++,Y}#c(Z,J){for(let X=J.provisional;X<J.length;X++){let Y=J[X];if((this.nocase?RL(Z.name):Yz(Z.name))!==Y.#j)continue;return this.#b(Z,Y,X,J)}}#b(Z,J,X,Y){let $=J.name;if(J.#K=J.#K&Zz|IT(Z),$!==Z.name)J.name=Z.name;if(X!==Y.provisional){if(X===Y.length-1)Y.pop();else Y.splice(X,1);Y.unshift(J)}return Y.provisional++,J}async lstat(){if((this.#K&p4)===0)try{return this.#S(await this.#Z.promises.lstat(this.fullpath())),this}catch(Z){this.#d(Z.code)}}lstatSync(){if((this.#K&p4)===0)try{return this.#S(this.#Z.lstatSync(this.fullpath())),this}catch(Z){this.#d(Z.code)}}#S(Z){let{atime:J,atimeMs:X,birthtime:Y,birthtimeMs:$,blksize:Q,blocks:K,ctime:W,ctimeMs:G,dev:V,gid:z,ino:F,mode:H,mtime:q,mtimeMs:U,nlink:B,rdev:L,size:w,uid:M}=Z;this.#O=J,this.#Q=X,this.#E=Y,this.#B=$,this.#W=Q,this.#H=K,this.#M=W,this.#L=G,this.#J=V,this.#z=z,this.#G=F,this.#Y=H,this.#k=q,this.#U=U,this.#X=B,this.#F=L,this.#V=w,this.#$=M;let N=IT(Z);if(this.#K=this.#K&Zz|N|Wa,N!==l9&&N!==A7&&N!==C$)this.#K|=Xz}#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 $=X.slice(0,X.provisional);if(J)Z(null,$);else queueMicrotask(()=>Z(null,$));return}if(this.#g.push(Z),this.#p)return;this.#p=!0;let Y=this.fullpath();this.#Z.readdir(Y,{withFileTypes:!0},($,Q)=>{if($)this.#I($.code),X.provisional=0;else{for(let K of Q)this.#h(K,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((Y)=>X=Y);try{for(let Y of await this.#Z.promises.readdir(J,{withFileTypes:!0}))this.#h(Y,Z);this.#m(Z)}catch(Y){this.#I(Y.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.#h(X,Z);this.#m(Z)}catch(X){this.#I(X.code),Z.provisional=0}return Z.slice(0,Z.provisional)}canReaddir(){if(this.#K&Ga)return!1;let Z=c9&this.#K;if(!(Z===l9||Z===A7||Z===C$))return!1;return!0}shouldWalk(Z,J){return(this.#K&A7)===A7&&!(this.#K&Ga)&&!Z.has(this)&&(!J||J(this))}async realpath(){if(this.#v)return this.#v;if((jL|NL|p4)&this.#K)return;try{let Z=await this.#Z.promises.realpath(this.fullpath());return this.#v=this.resolve(Z)}catch(Z){this.#u()}}realpathSync(){if(this.#v)return this.#v;if((jL|NL|p4)&this.#K)return;try{let Z=this.#Z.realpathSync(this.fullpath());return this.#v=this.resolve(Z)}catch(Z){this.#u()}}[Ma](Z){if(Z===this)return;Z.isCWD=!1,this.isCWD=!0;let J=new Set([]),X=[],Y=this;while(Y&&Y.parent)J.add(Y),Y.#w=X.join(this.sep),Y.#_=X.join("/"),Y=Y.parent,X.push("..");Y=Z;while(Y&&Y.parent&&!J.has(Y))Y.#w=void 0,Y.#_=void 0,Y=Y.parent}}class DL extends Q5{sep="\\";splitSep=WR1;constructor(Z,J=l9,X,Y,$,Q,K){super(Z,J,X,Y,$,Q,K)}newChild(Z,J=l9,X={}){return new DL(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}getRootString(Z){return _T.parse(Z).root}getRoot(Z){if(Z=KR1(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 $z(Z,this).root}sameRoot(Z,J=this.root.name){return Z=Z.toUpperCase().replace(/\//g,"\\").replace(Fa,"$1\\"),Z===J}}class PL extends Q5{splitSep="/";sep="/";constructor(Z,J=l9,X,Y,$,Q,K){super(Z,J,X,Y,$,Q,K)}getRootString(Z){return Z.startsWith("/")?"/":""}getRoot(Z){return this.root}newChild(Z,J=l9,X={}){return new PL(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}}class ST{root;rootPath;roots;cwd;#Z;#J;#Y;nocase;#X;constructor(Z=process.cwd(),J,X,{nocase:Y,childrenCacheSize:$=16384,fs:Q=Jz}={}){if(this.#X=Ha(Q),Z instanceof URL||Z.startsWith("file://"))Z=aN1(Z);let K=J.resolve(Z);this.roots=Object.create(null),this.rootPath=this.parseRootPath(K),this.#Z=new vT,this.#J=new vT,this.#Y=new Oa($);let W=K.substring(this.rootPath.length).split(X);if(W.length===1&&!W[0])W.pop();if(Y===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=Y,this.root=this.newRoot(this.#X),this.roots[this.rootPath]=this.root;let G=this.root,V=W.length-1,z=J.sep,F=this.rootPath,H=!1;for(let q of W){let U=V--;G=G.child(q,{relative:new Array(U).fill("..").join(z),relativePosix:new Array(U).fill("..").join("/"),fullpath:F+=(H?"":z)+q}),H=!0}this.cwd=G}depth(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.depth()}childrenCache(){return this.#Y}resolve(...Z){let J="";for(let $=Z.length-1;$>=0;$--){let Q=Z[$];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 Y=this.cwd.resolve(J).fullpath();return this.#Z.set(J,Y),Y}resolvePosix(...Z){let J="";for(let $=Z.length-1;$>=0;$--){let Q=Z[$];if(!Q||Q===".")continue;if(J=J?`${Q}/${J}`:Q,this.isAbsolute(Q))break}let X=this.#J.get(J);if(X!==void 0)return X;let Y=this.cwd.resolve(J).fullpathPosix();return this.#J.set(J,Y),Y}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 Q5))J=Z,Z=this.cwd;let{withFileTypes:X}=J;if(!Z.canReaddir())return[];else{let Y=await Z.readdir();return X?Y:Y.map(($)=>$.name)}}readdirSync(Z=this.cwd,J={withFileTypes:!0}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof Q5))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((Y)=>Y.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 Q5))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 Q5))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 Q5))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 Q5))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 Q5))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=[];if(!$||$(Z))K.push(X?Z:Z.fullpath());let W=new Set,G=(z,F)=>{W.add(z),z.readdirCB((H,q)=>{if(H)return F(H);let U=q.length;if(!U)return F();let B=()=>{if(--U===0)F()};for(let L of q){if(!$||$(L))K.push(X?L:L.fullpath());if(Y&&L.isSymbolicLink())L.realpath().then((w)=>w?.isUnknown()?w.lstat():w).then((w)=>w?.shouldWalk(W,Q)?G(w,B):B());else if(L.shouldWalk(W,Q))G(L,B);else B()}},!0)},V=Z;return new Promise((z,F)=>{G(V,(H)=>{if(H)return F(H);z(K)})})}walkSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof Q5))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=[];if(!$||$(Z))K.push(X?Z:Z.fullpath());let W=new Set([Z]);for(let G of W){let V=G.readdirSync();for(let z of V){if(!$||$(z))K.push(X?z:z.fullpath());let F=z;if(z.isSymbolicLink()){if(!(Y&&(F=z.realpathSync())))continue;if(F.isUnknown())F.lstatSync()}if(F.shouldWalk(W,Q))W.add(F)}}return K}[Symbol.asyncIterator](){return this.iterate()}iterate(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof Q5))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 Q5))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J;if(!$||$(Z))yield X?Z:Z.fullpath();let K=new Set([Z]);for(let W of K){let G=W.readdirSync();for(let V of G){if(!$||$(V))yield X?V:V.fullpath();let z=V;if(V.isSymbolicLink()){if(!(Y&&(z=V.realpathSync())))continue;if(z.isUnknown())z.lstatSync()}if(z.shouldWalk(K,Q))K.add(z)}}}stream(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof Q5))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=new P$({objectMode:!0});if(!$||$(Z))K.write(X?Z:Z.fullpath());let W=new Set,G=[Z],V=0,z=()=>{let F=!1;while(!F){let H=G.shift();if(!H){if(V===0)K.end();return}V++,W.add(H);let q=(B,L,w=!1)=>{if(B)return K.emit("error",B);if(Y&&!w){let M=[];for(let N of L)if(N.isSymbolicLink())M.push(N.realpath().then((R)=>R?.isUnknown()?R.lstat():R));if(M.length){Promise.all(M).then(()=>q(null,L,!0));return}}for(let M of L)if(M&&(!$||$(M))){if(!K.write(X?M:M.fullpath()))F=!0}V--;for(let M of L){let N=M.realpathCached()||M;if(N.shouldWalk(W,Q))G.push(N)}if(F&&!K.flowing)K.once("drain",z);else if(!U)z()},U=!0;H.readdirCB(q,!0),U=!1}};return z(),K}streamSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof Q5))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=new P$({objectMode:!0}),W=new Set;if(!$||$(Z))K.write(X?Z:Z.fullpath());let G=[Z],V=0,z=()=>{let F=!1;while(!F){let H=G.shift();if(!H){if(V===0)K.end();return}V++,W.add(H);let q=H.readdirSync();for(let U of q)if(!$||$(U)){if(!K.write(X?U:U.fullpath()))F=!0}V--;for(let U of q){let B=U;if(U.isSymbolicLink()){if(!(Y&&(B=U.realpathSync())))continue;if(B.isUnknown())B.lstatSync()}if(B.shouldWalk(W,Q))G.push(B)}}if(F&&!K.flowing)K.once("drain",z)};return z(),K}chdir(Z=this.cwd){let J=this.cwd;this.cwd=typeof Z==="string"?this.cwd.resolve(Z):Z,this.cwd[Ma](J)}}class $z extends ST{sep="\\";constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,_T,"\\",{...J,nocase:X});this.nocase=X;for(let Y=this.cwd;Y;Y=Y.parent)Y.nocase=this.nocase}parseRootPath(Z){return _T.parse(Z).root.toUpperCase()}newRoot(Z){return new DL(this.rootPath,A7,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")||Z.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(Z)}}class Qz extends ST{sep="/";constructor(Z=process.cwd(),J={}){let{nocase:X=!1}=J;super(Z,nN1,"/",{...J,nocase:X});this.nocase=X}parseRootPath(Z){return"/"}newRoot(Z){return new PL(this.rootPath,A7,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")}}class CL extends Qz{constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,{...J,nocase:X})}}var XA6=process.platform==="win32"?DL:PL,Na=process.platform==="win32"?$z:process.platform==="darwin"?CL:Qz;var VR1=(Z)=>Z.length>=1,zR1=(Z)=>Z.length>=1;class WW{#Z;#J;#Y;length;#X;#$;#z;#F;#W;#G;#V=!0;constructor(Z,J,X,Y){if(!VR1(Z))throw new TypeError("empty pattern list");if(!zR1(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.#J=J,this.#Y=X,this.#X=Y,this.#Y===0){if(this.isUNC()){let[$,Q,K,W,...G]=this.#Z,[V,z,F,H,...q]=this.#J;if(G[0]==="")G.shift(),q.shift();let U=[$,Q,K,W,""].join("/"),B=[V,z,F,H,""].join("/");this.#Z=[U,...G],this.#J=[B,...q],this.length=this.#Z.length}else if(this.isDrive()||this.isAbsolute()){let[$,...Q]=this.#Z,[K,...W]=this.#J;if(Q[0]==="")Q.shift(),W.shift();let G=$+"/",V=K+"/";this.#Z=[G,...Q],this.#J=[V,...W],this.length=this.#Z.length}}}pattern(){return this.#Z[this.#Y]}isString(){return typeof this.#Z[this.#Y]==="string"}isGlobstar(){return this.#Z[this.#Y]===M6}isRegExp(){return this.#Z[this.#Y]instanceof RegExp}globString(){return this.#z=this.#z||(this.#Y===0?this.isAbsolute()?this.#J[0]+this.#J.slice(1).join("/"):this.#J.join("/"):this.#J.slice(this.#Y).join("/"))}hasMore(){return this.length>this.#Y+1}rest(){if(this.#$!==void 0)return this.#$;if(!this.hasMore())return this.#$=null;return this.#$=new WW(this.#Z,this.#J,this.#Y+1,this.#X),this.#$.#G=this.#G,this.#$.#W=this.#W,this.#$.#F=this.#F,this.#$}isUNC(){let Z=this.#Z;return this.#W!==void 0?this.#W:this.#W=this.#X==="win32"&&this.#Y===0&&Z[0]===""&&Z[1]===""&&typeof Z[2]==="string"&&!!Z[2]&&typeof Z[3]==="string"&&!!Z[3]}isDrive(){let Z=this.#Z;return this.#F!==void 0?this.#F:this.#F=this.#X==="win32"&&this.#Y===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.#Y===0?Z:""}checkFollowGlobstar(){return!(this.#Y===0||!this.isGlobstar()||!this.#V)}markFollowGlobstar(){if(this.#Y===0||!this.isGlobstar()||!this.#V)return!1;return this.#V=!1,!0}}var HR1=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class Kz{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(Z,{nobrace:J,nocase:X,noext:Y,noglobstar:$,platform:Q=HR1}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=Q,this.mmopts={dot:!0,nobrace:J,nocase:X,noext:Y,noglobstar:$,optimizationLevel:2,platform:Q,nocomment:!0,nonegate:!0};for(let K of Z)this.add(K)}add(Z){let J=new d9(Z,this.mmopts);for(let X=0;X<J.set.length;X++){let Y=J.set[X],$=J.globParts[X];if(!Y||!$)throw new Error("invalid pattern object");while(Y[0]==="."&&$[0]===".")Y.shift(),$.shift();let Q=new WW(Y,$,0,this.platform),K=new d9(Q.globString(),this.mmopts),W=$[$.length-1]==="**",G=Q.isAbsolute();if(G)this.absolute.push(K);else this.relative.push(K);if(W)if(G)this.absoluteChildren.push(K);else this.relativeChildren.push(K)}}ignored(Z){let J=Z.fullpath(),X=`${J}/`,Y=Z.relative()||".",$=`${Y}/`;for(let Q of this.relative)if(Q.match(Y)||Q.match($))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 Y of this.relativeChildren)if(Y.match(X))return!0;for(let Y of this.absoluteChildren)if(Y.match(J))return!0;return!1}}class AT{store;constructor(Z=new Map){this.store=Z}copy(){return new AT(new Map(this.store))}hasWalked(Z,J){return this.store.get(Z.fullpath())?.has(J.globString())}storeWalked(Z,J){let X=Z.fullpath(),Y=this.store.get(X);if(Y)Y.add(J.globString());else this.store.set(X,new Set([J.globString()]))}}class Ra{store=new Map;add(Z,J,X){let Y=(J?2:0)|(X?1:0),$=this.store.get(Z);this.store.set(Z,$===void 0?Y:Y&$)}entries(){return[...this.store.entries()].map(([Z,J])=>[Z,!!(J&2),!!(J&1)])}}class ja{store=new Map;add(Z,J){if(!Z.canReaddir())return;let X=this.store.get(Z);if(X){if(!X.find((Y)=>Y.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 Wz{hasWalkedCache;matches=new Ra;subwalks=new ja;patterns;follow;dot;opts;constructor(Z,J){this.opts=Z,this.follow=!!Z.follow,this.dot=!!Z.dot,this.hasWalkedCache=J?J.copy():new AT}processPatterns(Z,J){this.patterns=J;let X=J.map((Y)=>[Z,Y]);for(let[Y,$]of X){this.hasWalkedCache.storeWalked(Y,$);let Q=$.root(),K=$.isAbsolute()&&this.opts.absolute!==!1;if(Q){Y=Y.resolve(Q==="/"&&this.opts.root!==void 0?this.opts.root:Q);let z=$.rest();if(!z){this.matches.add(Y,!0,!1);continue}else $=z}if(Y.isENOENT())continue;let W,G,V=!1;while(typeof(W=$.pattern())==="string"&&(G=$.rest()))Y=Y.resolve(W),$=G,V=!0;if(W=$.pattern(),G=$.rest(),V){if(this.hasWalkedCache.hasWalked(Y,$))continue;this.hasWalkedCache.storeWalked(Y,$)}if(typeof W==="string"){let z=W===".."||W===""||W===".";this.matches.add(Y.resolve(W),K,z);continue}else if(W===M6){if(!Y.isSymbolicLink()||this.follow||$.checkFollowGlobstar())this.subwalks.add(Y,$);let z=G?.pattern(),F=G?.rest();if(!G||(z===""||z===".")&&!F)this.matches.add(Y,K,z===""||z===".");else if(z===".."){let H=Y.parent||Y;if(!F)this.matches.add(H,K,!0);else if(!this.hasWalkedCache.hasWalked(H,F))this.subwalks.add(H,F)}}else if(W instanceof RegExp)this.subwalks.add(Y,$)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new Wz(this.opts,this.hasWalkedCache)}filterEntries(Z,J){let X=this.subwalks.get(Z),Y=this.child();for(let $ of J)for(let Q of X){let K=Q.isAbsolute(),W=Q.pattern(),G=Q.rest();if(W===M6)Y.testGlobstar($,Q,G,K);else if(W instanceof RegExp)Y.testRegExp($,W,G,K);else Y.testString($,W,G,K)}return Y}testGlobstar(Z,J,X,Y){if(this.dot||!Z.name.startsWith(".")){if(!J.hasMore())this.matches.add(Z,Y,!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 $=X.pattern();if(typeof $==="string"&&$!==".."&&$!==""&&$!==".")this.testString(Z,$,X.rest(),Y);else if($===".."){let Q=Z.parent||Z;this.subwalks.add(Q,X)}else if($ instanceof RegExp)this.testRegExp(Z,$,X.rest(),Y)}}testRegExp(Z,J,X,Y){if(!J.test(Z.name))return;if(!X)this.matches.add(Z,Y,!1);else this.subwalks.add(Z,X)}testString(Z,J,X,Y){if(!Z.isNamed(J))return;if(!X)this.matches.add(Z,Y,!1);else this.subwalks.add(Z,X)}}var FR1=(Z,J)=>typeof Z==="string"?new Kz([Z],J):Array.isArray(Z)?new Kz(Z,J):Z;class xT{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#Z=[];#J;#Y;signal;maxDepth;includeChildMatches;constructor(Z,J,X){if(this.patterns=Z,this.path=J,this.opts=X,this.#Y=!X.posix&&X.platform==="win32"?"\\":"/",this.includeChildMatches=X.includeChildMatches!==!1,X.ignore||!this.includeChildMatches){if(this.#J=FR1(X.ignore??[],X),!this.includeChildMatches&&typeof this.#J.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})}#X(Z){return this.seen.has(Z)||!!this.#J?.ignored?.(Z)}#$(Z){return!!this.#J?.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 $=Z.isUnknown()||this.opts.stat?await Z.lstat():Z;if(this.opts.follow&&this.opts.nodir&&$?.isSymbolicLink()){let Q=await $.realpath();if(Q&&(Q.isUnknown()||this.opts.stat))await Q.lstat()}return this.matchCheckTest($,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.#X(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 $=Z.isUnknown()||this.opts.stat?Z.lstatSync():Z;if(this.opts.follow&&this.opts.nodir&&$?.isSymbolicLink()){let Q=$.realpathSync();if(Q&&(Q?.isUnknown()||this.opts.stat))Q.lstatSync()}return this.matchCheckTest($,J)}matchFinish(Z,J){if(this.#X(Z))return;if(!this.includeChildMatches&&this.#J?.add){let $=`${Z.relativePosix()}/**`;this.#J.add($)}let X=this.opts.absolute===void 0?J:this.opts.absolute;this.seen.add(Z);let Y=this.opts.mark&&Z.isDirectory()?this.#Y:"";if(this.opts.withFileTypes)this.matchEmit(Z);else if(X){let $=this.opts.posix?Z.fullpathPosix():Z.fullpath();this.matchEmit($+Y)}else{let $=this.opts.posix?Z.relativePosix():Z.relative(),Q=this.opts.dotRelative&&!$.startsWith(".."+this.#Y)?"."+this.#Y:"";this.matchEmit(!$?"."+Y:Q+$+Y)}}async match(Z,J,X){let Y=await this.matchCheck(Z,X);if(Y)this.matchFinish(Y,J)}matchSync(Z,J,X){let Y=this.matchCheckSync(Z,X);if(Y)this.matchFinish(Y,J)}walkCB(Z,J,X){if(this.signal?.aborted)X();this.walkCB2(Z,J,new Wz(this.opts),X)}walkCB2(Z,J,X,Y){if(this.#$(Z))return Y();if(this.signal?.aborted)Y();if(this.paused){this.onResume(()=>this.walkCB2(Z,J,X,Y));return}X.processPatterns(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;$++,this.match(K,W,G).then(()=>Q())}for(let K of X.subwalkTargets()){if(this.maxDepth!==1/0&&K.depth()>=this.maxDepth)continue;$++;let W=K.readdirCached();if(K.calledReaddir())this.walkCB3(K,W,X,Q);else K.readdirCB((G,V)=>this.walkCB3(K,V,X,Q),!0)}Q()}walkCB3(Z,J,X,Y){X=X.filterEntries(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;$++,this.match(K,W,G).then(()=>Q())}for(let[K,W]of X.subwalks.entries())$++,this.walkCB2(K,W,X.child(),Q);Q()}walkCBSync(Z,J,X){if(this.signal?.aborted)X();this.walkCB2Sync(Z,J,new Wz(this.opts),X)}walkCB2Sync(Z,J,X,Y){if(this.#$(Z))return Y();if(this.signal?.aborted)Y();if(this.paused){this.onResume(()=>this.walkCB2Sync(Z,J,X,Y));return}X.processPatterns(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;this.matchSync(K,W,G)}for(let K of X.subwalkTargets()){if(this.maxDepth!==1/0&&K.depth()>=this.maxDepth)continue;$++;let W=K.readdirSync();this.walkCB3Sync(K,W,X,Q)}Q()}walkCB3Sync(Z,J,X,Y){X=X.filterEntries(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;this.matchSync(K,W,G)}for(let[K,W]of X.subwalks.entries())$++,this.walkCB2Sync(K,W,X.child(),Q);Q()}}class TL extends xT{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 kL extends xT{results;constructor(Z,J,X){super(Z,J,X);this.results=new P$({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 UR1=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class x7{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=qR1(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((W)=>W.replace(/\\/g,"/"));if(this.matchBase){if(J.noglobstar)throw new TypeError("base matching requires globstar");Z=Z.map((W)=>W.includes("/")?W:`./**/${W}`)}if(this.pattern=Z,this.platform=J.platform||UR1,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 W=J.platform==="win32"?$z:J.platform==="darwin"?CL:J.platform?Qz:Na;this.scurry=new W(this.cwd,{nocase:J.nocase,fs:J.fs})}this.nocase=this.scurry.nocase;let X=this.platform==="darwin"||this.platform==="win32",Y={...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},$=this.pattern.map((W)=>new d9(W,Y)),[Q,K]=$.reduce((W,G)=>{return W[0].push(...G.set),W[1].push(...G.globParts),W},[[],[]]);this.patterns=Q.map((W,G)=>{let V=K[G];if(!V)throw new Error("invalid pattern object");return new WW(W,V,0,this.platform)})}async walk(){return[...await new TL(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 TL(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 kL(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 kL(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 hT=(Z,J={})=>{if(!Array.isArray(Z))Z=[Z];for(let X of Z)if(new d9(X,J).hasMagic())return!0;return!1};function IL(Z,J={}){return new x7(Z,J).streamSync()}function Pa(Z,J={}){return new x7(Z,J).stream()}function Ca(Z,J={}){return new x7(Z,J).walkSync()}async function Da(Z,J={}){return new x7(Z,J).walk()}function _L(Z,J={}){return new x7(Z,J).iterateSync()}function Ta(Z,J={}){return new x7(Z,J).iterate()}var BR1=IL,LR1=Object.assign(Pa,{sync:IL}),wR1=_L,OR1=Object.assign(Ta,{sync:_L}),MR1=Object.assign(Ca,{stream:IL,iterate:_L}),EL=Object.assign(Da,{glob:Da,globSync:Ca,sync:MR1,globStream:Pa,stream:LR1,globStreamSync:IL,streamSync:BR1,globIterate:Ta,iterate:OR1,globIterateSync:_L,iterateSync:wR1,Glob:x7,hasMagic:hT,escape:XW,unescape:c4});EL.glob=EL;class fT{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 Y=this._listeners[Z];if(Y!==void 0){let $=Y.indexOf(J);if($!==-1)Y.splice($,1)}return this}dispatchEvent(Z){let X=this._listeners[Z.type];if(X!==void 0){let Y=X.slice(0);for(let $=0,Q=Y.length;$<Q;$++)Y[$].call(this,Z)}return this}dispose(){for(let Z in this._listeners)delete this._listeners[Z]}}class x5{constructor(Z,J,X,Y={}){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=Y,!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 GW extends fT{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,Y){let $=new x5(Z,J,X,Y);this._edges.add($);let Q=$.getParent();if(!this._parentEdges.has(Q))this._parentEdges.set(Q,new Set);this._parentEdges.get(Q).add($);let K=$.getChild();if(!this._childEdges.has(K))this._childEdges.set(K,new Set);return this._childEdges.get(K).add($),$}_destroyEdge(Z){return this._edges.delete(Z),this._parentEdges.get(Z.getParent()).delete(Z),this._childEdges.get(Z.getChild()).delete(Z),this}}function Gz(){return Gz=Object.assign||function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))Z[Y]=X[Y]}return Z},Gz.apply(this,arguments)}class f6{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 Y8{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 b0=Symbol("attributes"),i4=Symbol("immutableKeys");class VW extends fT{constructor(Z){super();this._disposed=!1,this.graph=void 0,this[b0]=void 0,this[i4]=void 0,this.graph=Z,this[i4]=new Set,this[b0]=this._createAttributes()}getDefaults(){return{}}_createAttributes(){let Z=this.getDefaults(),J={};for(let X in Z){let Y=Z[X];if(Y instanceof VW){let $=this.graph._createEdge(X,this,Y);this[i4].add(X),J[X]=$}else J[X]=Y}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[b0]){let Y=this[b0][X];if(Y instanceof x5){let $=Y;if($.getChild()===Z)this.setRef(X,J,$.getAttributes())}else if(Y instanceof f6)for(let $ of Y.listRefsByChild(Z)){let Q=$.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}else if(Y instanceof I0){let $=Y.getRefByChild(Z);if($){let Q=$.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}}else if(Y instanceof Y8)for(let $ of Y.keys()){let Q=Y.get($);if(Q.getChild()===Z)this.setRefMap(X,$,J,Q.getAttributes())}}return this}get(Z){return this[b0][Z]}set(Z,J){return this[b0][Z]=J,this.dispatchEvent({type:"change",attribute:Z})}getRef(Z){let J=this[b0][Z];return J?J.getChild():null}setRef(Z,J,X){if(this[i4].has(Z))throw new Error(`Cannot overwrite immutable attribute, "${Z}".`);let Y=this[b0][Z];if(Y)Y.dispose();if(!J)return this;let $=this.graph._createEdge(Z,this,J,X);return this[b0][Z]=$,this.dispatchEvent({type:"change",attribute:Z})}listRefs(Z){return this.assertRefList(Z).values().map((X)=>X.getChild())}addRef(Z,J,X){let Y=this.graph._createEdge(Z,this,J,X);return this.assertRefList(Z).add(Y),this.dispatchEvent({type:"change",attribute:Z})}removeRef(Z,J){let X=this.assertRefList(Z);if(X instanceof f6)for(let Y of X.listRefsByChild(J))Y.dispose();else{let Y=X.getRefByChild(J);if(Y)Y.dispose()}return this}assertRefList(Z){let J=this[b0][Z];if(J instanceof f6||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 Y=this.assertRefMap(Z).get(J);return Y?Y.getChild():null}setRefMap(Z,J,X,Y){let $=this.assertRefMap(Z),Q=$.get(J);if(Q)Q.dispose();if(!X)return this;Y=Object.assign(Y||{},{key:J});let K=this.graph._createEdge(Z,this,X,Gz({},Y,{key:J}));return $.set(J,K),this.dispatchEvent({type:"change",attribute:Z,key:J})}assertRefMap(Z){let J=this[b0][Z];if(J instanceof Y8)return J;throw new Error(`Expected RefMap for attribute "${Z}"`)}dispatchEvent(Z){return super.dispatchEvent(Gz({},Z,{target:this})),this.graph.dispatchEvent(Gz({},Z,{target:this,type:`node:${Z.type}`})),this}_destroyRef(Z){let J=Z.getName();if(this[b0][J]===Z){if(this[b0][J]=null,this[i4].has(J))Z.getChild().dispose()}else if(this[b0][J]instanceof f6)this[b0][J].remove(Z);else if(this[b0][J]instanceof I0)this[b0][J].remove(Z);else if(this[b0][J]instanceof Y8){let X=this[b0][J];for(let Y of X.keys())if(X.get(Y)===Z)X.delete(Y)}else return;this.graph._destroyEdge(Z),this.dispatchEvent({type:"change",attribute:J})}}var Aa="v4.1.1",fL="@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 yL;(function(Z){Z.INTERLEAVED="interleaved",Z.SEPARATE="separate"})(yL||(yL={}));var K9;(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"})(K9||(K9={}));var bL;(function(Z){Z[Z.R=4096]="R",Z[Z.G=256]="G",Z[Z.B=16]="B",Z[Z.A=1]="A"})(bL||(bL={}));var uZ;(function(Z){Z.GLTF="GLTF",Z.GLB="GLB"})(uZ||(uZ={}));var jX={"5120":Int8Array,"5121":Uint8Array,"5122":Int16Array,"5123":Uint16Array,"5125":Uint32Array,"5126":Float32Array},bT=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 NR1(){var Z=new bT(3);if(bT!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function yT(Z){var J=Z[0],X=Z[1],Y=Z[2];return Math.hypot(J,X,Y)}function RR1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=X[3]*Y+X[7]*$+X[11]*Q+X[15];return K=K||1,Z[0]=(X[0]*Y+X[4]*$+X[8]*Q+X[12])/K,Z[1]=(X[1]*Y+X[5]*$+X[9]*Q+X[13])/K,Z[2]=(X[2]*Y+X[6]*$+X[10]*Q+X[14])/K,Z}(function(){var Z=NR1();return function(J,X,Y,$,Q,K){var W,G;if(!X)X=3;if(!Y)Y=0;if($)G=Math.min($*X+Y,J.length);else G=J.length;for(W=Y;W<G;W+=X)Z[0]=J[W],Z[1]=J[W+1],Z[2]=J[W+2],Q(Z,Z,K),J[W]=Z[0],J[W+1]=Z[1],J[W+2]=Z[2];return J}})();function dT(Z){let J=xa(),X=Z.propertyType===s.NODE?[Z]:Z.listChildren();for(let Y of X)Y.traverse(($)=>{let Q=$.getMesh();if(!Q)return;let K=jR1(Q,$.getWorldMatrix());if(K.min.every(isFinite)&&K.max.every(isFinite))gT(K.min,J),gT(K.max,J)});return J}function jR1(Z,J){let X=xa();for(let Y of Z.listPrimitives()){let $=Y.getAttribute("POSITION"),Q=Y.getIndices();if(!$)continue;let K=[0,0,0],W=[0,0,0];for(let G=0,V=Q?Q.getCount():$.getCount();G<V;G++){let z=Q?Q.getScalar(G):G;K=$.getElement(z,K),W=RR1(W,K,J),gT(W,X)}}return X}function gT(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 xa(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}class a0{static createBufferFromDataURI(Z){if(typeof Buffer==="undefined"){let J=atob(Z.split(",")[1]),X=new Uint8Array(J.length);for(let Y=0;Y<J.length;Y++)X[Y]=J.charCodeAt(Y);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 $ of Z)J+=$.byteLength;let X=new Uint8Array(J),Y=0;for(let $ 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 Y=new Uint8Array(X);if(Y.set(Z),J!==0)for(let $=Z.byteLength;$<X;$++)Y[$]=J;return Y}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 cT{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^Y*255<<8^$*255<<0}static convertSRGBToLinear(Z,J){let X=Z,Y=J;for(let $=0;$<3;$++)Y[$]=X[$]<0.04045?X[$]*0.0773993808:Math.pow(X[$]*0.9478672986+0.0521327014,2.4);return J}static convertLinearToSRGB(Z,J){let X=Z,Y=J;for(let $=0;$<3;$++)Y[$]=X[$]<0.0031308?X[$]*12.92:1.055*Math.pow(X[$],0.41666)-0.055;return J}}class ha{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,Y;while(J.byteLength){if(X=J.getUint16(0,!1),DR1(J,X),Y=J.getUint8(X+1),Y===192||Y===193||Y===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 uL{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(a0.decodeText(Z.slice(12,16))===uL.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}}uL.PNG_FRIED_CHUNK_NAME="CgBI";class dZ{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,Y=4,$=this.getSize(Z,J);if(!$)return null;while($[0]>1||$[1]>1)X+=$[0]*$[1]*Y,$[0]=Math.max(Math.floor($[0]/2),1),$[1]=Math.max(Math.floor($[1]/2),1);return X+=1*Y,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}`}}dZ.impls={"image/jpeg":new ha,"image/png":new uL};function DR1(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 cZ{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 dZ.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 ka(Z){return Object.prototype.toString.call(Z)==="[object Object]"}function T$(Z){if(ka(Z)===!1)return!1;let J=Z.constructor;if(J===void 0)return!0;let X=J.prototype;if(ka(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}var mT,Vz;(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"})(Vz||(Vz={}));class f5{constructor(Z){this.verbosity=void 0,this.verbosity=Z}debug(Z){if(this.verbosity<=f5.Verbosity.DEBUG)console.debug(Z)}info(Z){if(this.verbosity<=f5.Verbosity.INFO)console.info(Z)}warn(Z){if(this.verbosity<=f5.Verbosity.WARN)console.warn(Z)}error(Z){if(this.verbosity<=f5.Verbosity.ERROR)console.error(Z)}}mT=f5;f5.Verbosity=Vz;f5.DEFAULT_INSTANCE=new mT(mT.Verbosity.INFO);function PR1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3],Q=Z[4],K=Z[5],W=Z[6],G=Z[7],V=Z[8],z=Z[9],F=Z[10],H=Z[11],q=Z[12],U=Z[13],B=Z[14],L=Z[15],w=J*K-X*Q,M=J*W-Y*Q,N=J*G-$*Q,R=X*W-Y*K,P=X*G-$*K,D=Y*G-$*W,C=V*U-z*q,T=V*B-F*q,k=V*L-H*q,A=z*B-F*U,v=z*L-H*U,x=F*L-H*B;return w*x-M*v+N*A+R*k-P*T+D*C}function CR1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=J[3],W=J[4],G=J[5],V=J[6],z=J[7],F=J[8],H=J[9],q=J[10],U=J[11],B=J[12],L=J[13],w=J[14],M=J[15],N=X[0],R=X[1],P=X[2],D=X[3];return Z[0]=N*Y+R*W+P*F+D*B,Z[1]=N*$+R*G+P*H+D*L,Z[2]=N*Q+R*V+P*q+D*w,Z[3]=N*K+R*z+P*U+D*M,N=X[4],R=X[5],P=X[6],D=X[7],Z[4]=N*Y+R*W+P*F+D*B,Z[5]=N*$+R*G+P*H+D*L,Z[6]=N*Q+R*V+P*q+D*w,Z[7]=N*K+R*z+P*U+D*M,N=X[8],R=X[9],P=X[10],D=X[11],Z[8]=N*Y+R*W+P*F+D*B,Z[9]=N*$+R*G+P*H+D*L,Z[10]=N*Q+R*V+P*q+D*w,Z[11]=N*K+R*z+P*U+D*M,N=X[12],R=X[13],P=X[14],D=X[15],Z[12]=N*Y+R*W+P*F+D*B,Z[13]=N*$+R*G+P*H+D*L,Z[14]=N*Q+R*V+P*q+D*w,Z[15]=N*K+R*z+P*U+D*M,Z}function TR1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[4],K=J[5],W=J[6],G=J[8],V=J[9],z=J[10];return Z[0]=Math.hypot(X,Y,$),Z[1]=Math.hypot(Q,K,W),Z[2]=Math.hypot(G,V,z),Z}function kR1(Z,J){var X=new bT(3);TR1(X,J);var Y=1/X[0],$=1/X[1],Q=1/X[2],K=J[0]*Y,W=J[1]*$,G=J[2]*Q,V=J[4]*Y,z=J[5]*$,F=J[6]*Q,H=J[8]*Y,q=J[9]*$,U=J[10]*Q,B=K+z+U,L=0;if(B>0)L=Math.sqrt(B+1)*2,Z[3]=0.25*L,Z[0]=(F-q)/L,Z[1]=(H-G)/L,Z[2]=(W-V)/L;else if(K>z&&K>U)L=Math.sqrt(1+K-z-U)*2,Z[3]=(F-q)/L,Z[0]=0.25*L,Z[1]=(W+V)/L,Z[2]=(H+G)/L;else if(z>U)L=Math.sqrt(1+z-K-U)*2,Z[3]=(H-G)/L,Z[0]=(W+V)/L,Z[1]=0.25*L,Z[2]=(F+q)/L;else L=Math.sqrt(1+U-K-z)*2,Z[3]=(W-V)/L,Z[0]=(H+G)/L,Z[1]=(F+q)/L,Z[2]=0.25*L;return Z}class l0{static identity(Z){return Z}static eq(Z,J,X=0.00001){if(Z.length!==J.length)return!1;for(let Y=0;Y<Z.length;Y++)if(Math.abs(Z[Y]-J[Y])>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(l0.clamp(Z,0,1)*65535);case 5121:return Math.round(l0.clamp(Z,0,1)*255);case 5122:return Math.round(l0.clamp(Z,-1,1)*32767);case 5120:return Math.round(l0.clamp(Z,-1,1)*127);default:throw new Error("Invalid component type.")}}static decompose(Z,J,X,Y){let $=yT([Z[0],Z[1],Z[2]]),Q=yT([Z[4],Z[5],Z[6]]),K=yT([Z[8],Z[9],Z[10]]);if(PR1(Z)<0)$=-$;J[0]=Z[12],J[1]=Z[13],J[2]=Z[14];let G=Z.slice(),V=1/$,z=1/Q,F=1/K;G[0]*=V,G[1]*=V,G[2]*=V,G[4]*=z,G[5]*=z,G[6]*=z,G[8]*=F,G[9]*=F,G[10]*=F,kR1(X,G),Y[0]=$,Y[1]=Q,Y[2]=K}static compose(Z,J,X,Y){let $=Y,Q=J[0],K=J[1],W=J[2],G=J[3],V=Q+Q,z=K+K,F=W+W,H=Q*V,q=Q*z,U=Q*F,B=K*z,L=K*F,w=W*F,M=G*V,N=G*z,R=G*F,P=X[0],D=X[1],C=X[2];return $[0]=(1-(B+w))*P,$[1]=(q+R)*P,$[2]=(U-N)*P,$[3]=0,$[4]=(q-R)*D,$[5]=(1-(H+w))*D,$[6]=(L+M)*D,$[7]=0,$[8]=(U+N)*C,$[9]=(L-M)*C,$[10]=(1-(H+B))*C,$[11]=0,$[12]=Z[0],$[13]=Z[1],$[14]=Z[2],$[15]=1,$}}function ER1(Z,J){if(!!Z!==!!J)return!1;let X=Z.getChild(),Y=J.getChild();return X===Y||X.equals(Y)}function IR1(Z,J){if(!!Z!==!!J)return!1;let X=Z.values(),Y=J.values();if(X.length!==Y.length)return!1;for(let $=0;$<X.length;$++){let Q=X[$],K=Y[$];if(Q.getChild()===K.getChild())continue;if(!Q.getChild().equals(K.getChild()))return!1}return!0}function _R1(Z,J){if(!!Z!==!!J)return!1;let X=Z.keys(),Y=J.keys();if(X.length!==Y.length)return!1;for(let $ of X){let Q=Z.get($),K=J.get($);if(!!Q!==!!K)return!1;let W=Q.getChild(),G=K.getChild();if(W===G)continue;if(!W.equals(G))return!1}return!0}function fa(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 ya(Z,J){if(Z===J)return!0;if(!!Z!==!!J)return!1;if(!T$(Z)||!T$(J))return Z===J;let X=Z,Y=J,$=0,Q=0,K;for(K in X)$++;for(K in Y)Q++;if($!==Q)return!1;for(K in X){let W=X[K],G=Y[K];if(gL(W)&&gL(G)){if(!fa(W,G))return!1}else if(T$(W)&&T$(G)){if(!ya(W,G))return!1}else if(W!==G)return!1}return!0}function gL(Z){return Array.isArray(Z)||ArrayBuffer.isView(Z)}var Ea="23456789abdegjkmnpqrvwxyzABDEGJKMNPQRVWXYZ",vR1=999,SR1=6,Ia=new Set,AR1=function Z(){let J="";for(let X=0;X<SR1;X++)J+=Ea.charAt(Math.floor(Math.random()*Ea.length));return J},ba=function Z(){for(let J=0;J<vR1;J++){let X=AR1();if(!Ia.has(X))return Ia.add(X),X}return""},_a="https://null.example";class p9{static dirname(Z){let J=Z.lastIndexOf("/");if(J===-1)return"./";return Z.substring(0,J+1)}static basename(Z){return cZ.basename(new URL(Z,_a).pathname)}static extension(Z){return cZ.extension(new URL(Z,_a).pathname)}static resolve(Z,J){if(!this.isRelativePath(J))return J;let X=Z.split("/"),Y=J.split("/");X.pop();for(let $=0;$<Y.length;$++){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)}}p9.DEFAULT_INIT={};p9.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;var RX=(Z)=>Z,xR1=new Set;class dL extends VW{constructor(Z,J=""){super(Z);this[b0].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,RX)}copy(Z,J=RX){for(let X in this[b0]){let Y=this[b0][X];if(Y instanceof x5){if(!this[i4].has(X))Y.dispose()}else if(Y instanceof f6||Y instanceof I0)for(let $ of Y.values())$.dispose();else if(Y instanceof Y8)for(let $ of Y.values())$.dispose()}for(let X in Z[b0]){let Y=this[b0][X],$=Z[b0][X];if($ instanceof x5)if(this[i4].has(X))Y.getChild().copy(J($.getChild()),J);else this.setRef(X,J($.getChild()),$.getAttributes());else if($ instanceof I0||$ instanceof f6)for(let Q of $.values())this.addRef(X,J(Q.getChild()),Q.getAttributes());else if($ instanceof Y8)for(let Q of $.keys()){let K=$.get(Q);this.setRefMap(X,Q,J(K.getChild()),K.getAttributes())}else if(T$($))this[b0][X]=JSON.parse(JSON.stringify($));else if(Array.isArray($)||$ instanceof ArrayBuffer||ArrayBuffer.isView($))this[b0][X]=$.slice();else this[b0][X]=$}return this}equals(Z,J=xR1){if(this===Z)return!0;if(this.propertyType!==Z.propertyType)return!1;for(let X in this[b0]){if(J.has(X))continue;let Y=this[b0][X],$=Z[b0][X];if(Y instanceof x5||$ instanceof x5){if(!ER1(Y,$))return!1}else if(Y instanceof I0||$ instanceof I0||Y instanceof f6||$ instanceof f6){if(!IR1(Y,$))return!1}else if(Y instanceof Y8||$ instanceof Y8){if(!_R1(Y,$))return!1}else if(T$(Y)||T$($)){if(!ya(Y,$))return!1}else if(gL(Y)||gL($)){if(!fa(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 b6 extends dL{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new Y8})}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 x0 extends b6{init(){this.propertyType=s.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:x0.Type.SCALAR,componentType:x0.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(Z){switch(Z){case x0.Type.SCALAR:return 1;case x0.Type.VEC2:return 2;case x0.Type.VEC3:return 3;case x0.Type.VEC4:return 4;case x0.Type.MAT2:return 4;case x0.Type.MAT3:return 9;case x0.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+Z)}}static getComponentSize(Z){switch(Z){case x0.ComponentType.BYTE:return 1;case x0.ComponentType.UNSIGNED_BYTE:return 1;case x0.ComponentType.SHORT:return 2;case x0.ComponentType.UNSIGNED_SHORT:return 2;case x0.ComponentType.UNSIGNED_INT:return 4;case x0.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+Z)}}getMinNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMin(Z),J)for(let $=0;$<X;$++)Z[$]=l0.decodeNormalizedInt(Z[$],Y);return Z}getMin(Z){let J=this.getArray(),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.min(Z[Q],K)}return Z}getMaxNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMax(Z),J)for(let $=0;$<X;$++)Z[$]=l0.decodeNormalizedInt(Z[$],Y);return Z}getMax(Z){let J=this.get("array"),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=-1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.max(Z[Q],K)}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 x0.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(),Y=this.getArray();if(this.getNormalized())return l0.decodeNormalizedInt(Y[Z*J],X);return Y[Z*J]}setScalar(Z,J){let X=this.getElementSize(),Y=this.getComponentType(),$=this.getArray();if(this.getNormalized())$[Z*X]=l0.encodeNormalizedInt(J,Y);else $[Z*X]=J;return this}getElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)J[K]=l0.decodeNormalizedInt(Q[Z*Y+K],$);else J[K]=Q[Z*Y+K];return J}setElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)Q[Z*Y+K]=l0.encodeNormalizedInt(J[K],$);else Q[Z*Y+K]=J[K];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?hR1(Z):x0.ComponentType.FLOAT),this.set("array",Z),this}getByteLength(){let Z=this.get("array");return Z?Z.byteLength:0}}x0.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};x0.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};function hR1(Z){switch(Z.constructor){case Float32Array:return x0.ComponentType.FLOAT;case Uint32Array:return x0.ComponentType.UNSIGNED_INT;case Uint16Array:return x0.ComponentType.UNSIGNED_SHORT;case Uint8Array:return x0.ComponentType.UNSIGNED_BYTE;case Int16Array:return x0.ComponentType.SHORT;case Int8Array:return x0.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}class lT extends b6{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 k$ extends b6{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)}}k$.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class zW extends b6{init(){this.propertyType=s.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:zW.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:K9.OTHER})}getOutput(){return this.getRef("output")}setOutput(Z){return this.setRef("output",Z,{usage:K9.OTHER})}}zW.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class pT extends b6{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 E$ extends b6{init(){this.propertyType=s.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:E$.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)}}E$.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class HW extends dL{_validateParent(Z){if(!this.parentTypes.includes(Z.propertyType))throw new Error(`Parent "${Z.propertyType}" invalid for child "${this.propertyType}".`)}}HW.EXTENSION_NAME=void 0;class h5 extends b6{init(){this.propertyType=s.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:h5.WrapMode.REPEAT,wrapT:h5.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)}}h5.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};h5.MagFilter={NEAREST:9728,LINEAR:9729};h5.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};var{R:vL,G:SL,B:AL,A:fR1}=bL;class h7 extends b6{init(){this.propertyType=s.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:h7.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new h5(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new h5(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new h5(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new h5(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new h5(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:vL|SL|AL|fR1,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:vL|SL|AL,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:vL|SL|AL})}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:vL})}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:SL|AL})}}h7.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class Hz extends b6{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 cL extends b6{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=RX){if(J===RX)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 l0.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(Z){let J=this.get("translation").slice(),X=this.get("rotation").slice(),Y=this.get("scale").slice();return l0.decompose(Z,J,X,Y),this.set("translation",J).set("rotation",X).set("scale",Y)}getWorldTranslation(){let Z=[0,0,0];return l0.decompose(this.getWorldMatrix(),Z,[0,0,0,1],[1,1,1]),Z}getWorldRotation(){let Z=[0,0,0,1];return l0.decompose(this.getWorldMatrix(),[0,0,0],Z,[1,1,1]),Z}getWorldScale(){let Z=[1,1,1];return l0.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],Z),Z}getWorldMatrix(){let Z=[];for(let Y=this;Y!=null;Y=Y.getParentNode())Z.push(Y);let J,X=Z.pop().getMatrix();while(J=Z.pop())CR1(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 T8 extends b6{init(){this.propertyType=s.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:T8.Mode.TRIANGLES,material:null,indices:null,attributes:new Y8,targets:new I0})}getIndices(){return this.getRef("indices")}setIndices(Z){return this.setRef("indices",Z,{usage:K9.ELEMENT_ARRAY_BUFFER})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:K9.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)}}T8.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class iT extends dL{init(){this.propertyType=s.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new Y8})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:K9.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function K5(){return K5=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},K5.apply(null,arguments)}class FW extends b6{init(){this.propertyType=s.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:new I0})}copy(Z,J=RX){if(J===RX)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 nT extends b6{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:K9.INVERSE_BIND_MATRICES})}addJoint(Z){return this.addRef("joints",Z)}removeJoint(Z){return this.removeRef("joints",Z)}listJoints(){return this.listRefs("joints")}}class I$ extends b6{init(){this.propertyType=s.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||dZ.extensionToMimeType(cZ.extension(this.get("uri")))}setMimeType(Z){return this.set("mimeType",Z)}getURI(){return this.get("uri")}setURI(Z){this.set("uri",Z);let J=dZ.extensionToMimeType(cZ.extension(Z));if(J)this.set("mimeType",J);return this}getImage(){return this.get("image")}setImage(Z){return this.set("image",a0.assertView(Z))}getSize(){let Z=this.get("image");if(!Z)return null;return dZ.getSize(Z,this.getMimeType())}}class _$ extends b6{init(){this.propertyType=s.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${Aa}`,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=RX){if(J===RX)throw new Error("Root cannot be copied.");this.set("asset",K5({},Z.get("asset"))),this.setName(Z.getName()),this.setExtras(K5({},Z.getExtras())),this.setDefaultScene(Z.getDefaultScene()?J(Z.getDefaultScene()):null);for(let X of Z.listRefMapKeys("extensions")){let Y=Z.getExtension(X);this.setExtension(X,J(Y))}return this}_addChildOfRoot(Z){if(Z instanceof FW)this.addRef("scenes",Z);else if(Z instanceof cL)this.addRef("nodes",Z);else if(Z instanceof E$)this.addRef("cameras",Z);else if(Z instanceof nT)this.addRef("skins",Z);else if(Z instanceof Hz)this.addRef("meshes",Z);else if(Z instanceof h7)this.addRef("materials",Z);else if(Z instanceof I$)this.addRef("textures",Z);else if(Z instanceof lT)this.addRef("animations",Z);else if(Z instanceof x0)this.addRef("accessors",Z);else if(Z instanceof pT)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 y6{static fromGraph(Z){return y6._GRAPH_DOCUMENTS.get(Z)||null}constructor(){this._graph=new GW,this._root=new _$(this._graph),this._logger=f5.DEFAULT_INSTANCE,y6._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((Y)=>Y.extensionName===J)||new Z(this)}createScene(Z=""){return new FW(this._graph,Z)}createNode(Z=""){return new cL(this._graph,Z)}createCamera(Z=""){return new E$(this._graph,Z)}createSkin(Z=""){return new nT(this._graph,Z)}createMesh(Z=""){return new Hz(this._graph,Z)}createPrimitive(){return new T8(this._graph)}createPrimitiveTarget(Z=""){return new iT(this._graph,Z)}createMaterial(Z=""){return new h7(this._graph,Z)}createTexture(Z=""){return new I$(this._graph,Z)}createAnimation(Z=""){return new lT(this._graph,Z)}createAnimationChannel(Z=""){return new k$(this._graph,Z)}createAnimationSampler(Z=""){return new zW(this._graph,Z)}createAccessor(Z="",J=null){if(!J)J=this.getRoot().listBuffers()[0];return new x0(this._graph,Z).setBuffer(J)}createBuffer(Z=""){return new pT(this._graph,Z)}}y6._GRAPH_DOCUMENTS=new WeakMap;class ga{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 Y=X,$=Y.target;if($ instanceof HW&&$.extensionName===this.extensionName){if(Y.type==="node:create")this._addExtensionProperty($);if(Y.type==="node:dispose")this._removeExtensionProperty($)}};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}}ga.EXTENSION_NAME=void 0;class ma{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 Y=this.jsonDoc.json.samplers[X.sampler];if(Y.magFilter!==void 0)Z.setMagFilter(Y.magFilter);if(Y.minFilter!==void 0)Z.setMinFilter(Y.minFilter);if(Y.wrapS!==void 0)Z.setWrapS(Y.wrapS);if(Y.wrapT!==void 0)Z.setWrapT(Y.wrapT)}}var va={logger:f5.DEFAULT_INSTANCE,extensions:[],dependencies:{}},yR1=new Set([s.BUFFER,s.TEXTURE,s.MATERIAL,s.MESH,s.PRIMITIVE,s.NODE,s.SCENE]);class ua{static read(Z,J=va){let X=K5({},va,J),{json:Y}=Z,$=new y6().setLogger(X.logger);this.validate(Z,X);let Q=new ma(Z),K=Y.asset,W=$.getRoot().getAsset();if(K.copyright)W.copyright=K.copyright;if(K.extras)W.extras=K.extras;if(Y.extras!==void 0)$.getRoot().setExtras(K5({},Y.extras));let G=Y.extensionsUsed||[],V=Y.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=$.createExtension(D).setRequired(V.includes(D.EXTENSION_NAME)),T=C.prereadTypes.filter((k)=>!yR1.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 z=Y.buffers||[];$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.BUFFER)).forEach((D)=>D.preread(Q,s.BUFFER)),Q.buffers=z.map((D)=>{let C=$.createBuffer(D.name);if(D.extras)C.setExtras(D.extras);if(D.uri&&D.uri.indexOf("__")!==0)C.setURI(D.uri);return C});let F=Y.bufferViews||[];Q.bufferViewBuffers=F.map((D,C)=>{if(!Q.bufferViews[C]){let T=Z.json.buffers[D.buffer],k=T.uri?Z.resources[T.uri]:Z.resources[fL],A=D.byteOffset||0;Q.bufferViews[C]=a0.toView(k,A,D.byteLength)}return Q.buffers[D.buffer]});let H=Y.accessors||[];Q.accessors=H.map((D)=>{let C=Q.bufferViewBuffers[D.bufferView],T=$.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(hL(D,Q)),T});let q=Y.images||[],U=Y.textures||[];$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.TEXTURE)).forEach((D)=>D.preread(Q,s.TEXTURE)),Q.textures=q.map((D)=>{let C=$.createTexture(D.name);if(D.extras)C.setExtras(D.extras);if(D.bufferView!==void 0){let T=Y.bufferViews[D.bufferView],k=Z.json.buffers[T.buffer],A=k.uri?Z.resources[k.uri]:Z.resources[fL],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=cZ.extension(D.uri);C.setMimeType(dZ.extensionToMimeType(T))}return C}),$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.MATERIAL)).forEach((D)=>D.preread(Q,s.MATERIAL));let B=Y.materials||[];Q.materials=B.map((D)=>{let C=$.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}),$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.MESH)).forEach((D)=>D.preread(Q,s.MESH));let L=Y.meshes||[];$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.PRIMITIVE)).forEach((D)=>D.preread(Q,s.PRIMITIVE)),Q.meshes=L.map((D)=>{let C=$.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=$.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,_]of Object.entries(k.attributes||{}))A.setAttribute(I,Q.accessors[_]);if(k.indices!==void 0)A.setIndices(Q.accessors[k.indices]);let v=D.extras&&D.extras.targetNames||[];(k.targets||[]).forEach((I,_)=>{let b=v[_]||_.toString(),u=$.createPrimitiveTarget(b);for(let[i,e]of Object.entries(I))u.setAttribute(i,Q.accessors[e]);A.addTarget(u)}),C.addPrimitive(A)}),C});let w=Y.cameras||[];Q.cameras=w.map((D)=>{let C=$.createCamera(D.name).setType(D.type);if(D.extras)C.setExtras(D.extras);if(D.type===E$.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 M=Y.nodes||[];$.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.NODE)).forEach((D)=>D.preread(Q,s.NODE)),Q.nodes=M.map((D)=>{let C=$.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];l0.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 N=Y.skins||[];Q.skins=N.map((D)=>{let C=$.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}),M.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 R=Y.animations||[];Q.animations=R.map((D)=>{let C=$.createAnimation(D.name);if(D.extras)C.setExtras(D.extras);let k=(D.samplers||[]).map((v)=>{let x=$.createAnimationSampler().setInput(Q.accessors[v.input]).setOutput(Q.accessors[v.output]).setInterpolation(v.interpolation||zW.Interpolation.LINEAR);if(v.extras)x.setExtras(v.extras);return C.addSampler(x),x});return(D.channels||[]).forEach((v)=>{let x=$.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=Y.scenes||[];if($.getRoot().listExtensionsUsed().filter((D)=>D.prereadTypes.includes(s.SCENE)).forEach((D)=>D.preread(Q,s.SCENE)),Q.scenes=P.map((D)=>{let C=$.createScene(D.name);if(D.extras)C.setExtras(D.extras);return(D.nodes||[]).map((k)=>Q.nodes[k]).forEach((k)=>C.addChild(k)),C}),Y.scene!==void 0)$.getRoot().setDefaultScene(Q.scenes[Y.scene]);return $.getRoot().listExtensionsUsed().forEach((D)=>D.read(Q)),H.forEach((D,C)=>{let T=Q.accessors[C],k=!!D.sparse,A=!D.bufferView&&!T.getArray();if(k||A)T.setSparse(!0).setArray(gR1(D,Q))}),$}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 Y of X.extensionsRequired)if(!J.extensions.find(($)=>$.EXTENSION_NAME===Y))throw new Error(`Missing required extension, "${Y}".`)}if(X.extensionsUsed){for(let Y of X.extensionsUsed)if(!J.extensions.find(($)=>$.EXTENSION_NAME===Y))J.logger.warn(`Missing optional extension, "${Y}".`)}}}function bR1(Z,J){let X=J.jsonDoc,Y=J.bufferViews[Z.bufferView],$=X.json.bufferViews[Z.bufferView],Q=jX[Z.componentType],K=x0.getElementSize(Z.type),W=Q.BYTES_PER_ELEMENT,G=Z.byteOffset||0,V=new Q(Z.count*K),z=new DataView(Y.buffer,Y.byteOffset,Y.byteLength),F=$.byteStride;for(let H=0;H<Z.count;H++)for(let q=0;q<K;q++){let U=G+H*F+q*W,B;switch(Z.componentType){case x0.ComponentType.FLOAT:B=z.getFloat32(U,!0);break;case x0.ComponentType.UNSIGNED_INT:B=z.getUint32(U,!0);break;case x0.ComponentType.UNSIGNED_SHORT:B=z.getUint16(U,!0);break;case x0.ComponentType.UNSIGNED_BYTE:B=z.getUint8(U);break;case x0.ComponentType.SHORT:B=z.getInt16(U,!0);break;case x0.ComponentType.BYTE:B=z.getInt8(U);break;default:throw new Error(`Unexpected componentType "${Z.componentType}".`)}V[H*K+q]=B}return V}function hL(Z,J){let X=J.jsonDoc,Y=J.bufferViews[Z.bufferView],$=X.json.bufferViews[Z.bufferView],Q=jX[Z.componentType],K=x0.getElementSize(Z.type),W=Q.BYTES_PER_ELEMENT,G=K*W;if($.byteStride!==void 0&&$.byteStride!==G)return bR1(Z,J);let V=Y.byteOffset+(Z.byteOffset||0),z=Z.count*K*W;return new Q(Y.buffer.slice(V,V+z))}function gR1(Z,J){let X=jX[Z.componentType],Y=x0.getElementSize(Z.type),$;if(Z.bufferView!==void 0)$=hL(Z,J);else $=new X(Z.count*Y);let Q=Z.sparse;if(!Q)return $;let K=Q.count,W=K5({},Z,Q.indices,{count:K,type:"SCALAR"}),G=K5({},Z,Q.values,{count:K}),V=hL(W,J),z=hL(G,J);for(let F=0;F<W.count;F++)for(let H=0;H<Y;H++)$[V[F]*Y+H]=z[F*Y+H];return $}var zz;(function(Z){Z[Z.ARRAY_BUFFER=34962]="ARRAY_BUFFER",Z[Z.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"})(zz||(zz={}));class NX{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 Y=Z.getRoot(),$=Y.listBuffers().length,Q=Y.listTextures().length;this.bufferURIGenerator=new uT($>1,()=>X.basename||"buffer"),this.imageURIGenerator=new uT(Q>1,(K)=>mR1(Z,K)||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()},Y=JSON.stringify(X);if(!this.samplerDefIndexMap.has(Y))this.samplerDefIndexMap.set(Y,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(X);let $={source:this.imageIndexMap.get(Z),sampler:this.samplerDefIndexMap.get(Y)},Q=JSON.stringify($);if(!this.textureDefIndexMap.has(Q))this.textureDefIndexMap.set(Q,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push($);let K={index:this.textureDefIndexMap.get(Q)};if(J.getTexCoord()!==0)K.texCoord=J.getTexCoord();if(Object.keys(J.getExtras()).length>0)K.extras=J.getExtras();return this.textureInfoDefMap.set(J,K),K}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((Y)=>Y.getName()==="attributes"&&Y.getAttributes().key==="POSITION"||Y.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===uZ.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 Y=dZ.mimeTypeToExtension(X.getMimeType());Z.uri=this.imageURIGenerator.createURI(X,Y),this.assignResourceURI(Z.uri,J,!1)}}assignResourceURI(Z,J,X){let Y=this.jsonDoc.resources;if(!(Z in Y)){Y[Z]=J;return}if(J===Y[Z]){this.logger.warn(`Duplicate resource URI, "${Z}".`);return}let $=`Resource URI "${Z}" already assigned to different data.`;if(!X){this.logger.warn($);return}throw new Error($)}getAccessorUsage(Z){let J=this._accessorUsageMap.get(Z);if(J)return J;if(Z.getSparse())return K9.SPARSE;for(let X of this._doc.getGraph().listParentEdges(Z)){let{usage:Y}=X.getAttributes();if(Y)return Y;if(X.getParent().propertyType!==s.ROOT)this.logger.warn(`Missing attribute ".usage" on edge, "${X.getName()}".`)}return K9.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}}NX.BufferViewTarget=zz;NX.BufferViewUsage=K9;NX.USAGE_TO_TARGET={[K9.ARRAY_BUFFER]:zz.ARRAY_BUFFER,[K9.ELEMENT_ARRAY_BUFFER]:zz.ELEMENT_ARRAY_BUFFER};class uT{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 mR1(Z,J){let X=Z.getGraph().listParentEdges(J).find((Y)=>Y.getParent()!==Z.getRoot());return X?X.getName().replace(/texture$/i,""):""}var{BufferViewUsage:xL}=NX,{UNSIGNED_INT:uR1,UNSIGNED_SHORT:dR1,UNSIGNED_BYTE:cR1}=x0.ComponentType,lR1=new Set([s.ACCESSOR,s.BUFFER,s.MATERIAL,s.MESH]);class da{static write(Z,J){let X=Z.getGraph(),Y=Z.getRoot(),$={asset:K5({generator:`glTF-Transform ${Aa}`},Y.getAsset()),extras:K5({},Y.getExtras())},Q={json:$,resources:{}},K=new NX(Z,Q,J),W=J.logger||f5.DEFAULT_INSTANCE,G=new Set(J.extensions.map((L)=>L.EXTENSION_NAME)),V=Z.getRoot().listExtensionsUsed().filter((L)=>G.has(L.extensionName)).sort((L,w)=>L.extensionName>w.extensionName?1:-1),z=Z.getRoot().listExtensionsRequired().filter((L)=>G.has(L.extensionName)).sort((L,w)=>L.extensionName>w.extensionName?1:-1);if(V.length<Z.getRoot().listExtensionsUsed().length)W.warn("Some extensions were not registered for I/O, and will not be written.");for(let L of V){let w=L.prewriteTypes.filter((M)=>!lR1.has(M));if(w.length)W.warn(`Prewrite hooks for some types (${w.join()}), requested by extension ${L.extensionName}, are unsupported. Please file an issue or a PR.`);for(let M of L.writeDependencies)L.install(M,J.dependencies[M])}function F(L,w,M,N){let R=[],P=0;for(let T of L){let k=K.createAccessorDef(T);k.bufferView=$.bufferViews.length;let A=T.getArray(),v=a0.pad(a0.toView(A));k.byteOffset=P,P+=v.byteLength,R.push(v),K.accessorIndexMap.set(T,$.accessors.length),$.accessors.push(k)}let D=a0.concat(R),C={buffer:w,byteOffset:M,byteLength:D.byteLength};if(N)C.target=N;return $.bufferViews.push(C),{buffers:R,byteLength:P}}function H(L,w,M){let N=L[0].getCount(),R=0;for(let k of L){let A=K.createAccessorDef(k);A.bufferView=$.bufferViews.length,A.byteOffset=R;let v=k.getElementSize(),x=k.getComponentSize();R+=a0.padNumber(v*x),K.accessorIndexMap.set(k,$.accessors.length),$.accessors.push(A)}let P=N*R,D=new ArrayBuffer(P),C=new DataView(D);for(let k=0;k<N;k++){let A=0;for(let v of L){let x=v.getElementSize(),I=v.getComponentSize(),_=v.getComponentType(),b=v.getArray();for(let u=0;u<x;u++){let i=k*R+A+u*I,e=b[k*x+u];switch(_){case x0.ComponentType.FLOAT:C.setFloat32(i,e,!0);break;case x0.ComponentType.BYTE:C.setInt8(i,e);break;case x0.ComponentType.SHORT:C.setInt16(i,e,!0);break;case x0.ComponentType.UNSIGNED_BYTE:C.setUint8(i,e);break;case x0.ComponentType.UNSIGNED_SHORT:C.setUint16(i,e,!0);break;case x0.ComponentType.UNSIGNED_INT:C.setUint32(i,e,!0);break;default:throw new Error("Unexpected component type: "+_)}}A+=a0.padNumber(x*I)}}let T={buffer:w,byteOffset:M,byteLength:P,byteStride:R,target:NX.BufferViewTarget.ARRAY_BUFFER};return $.bufferViews.push(T),{byteLength:P,buffers:[new Uint8Array(D)]}}function q(L,w,M){let N=[],R=0,P=new Map,D=-1/0,C=!1;for(let _ of L){let b=K.createAccessorDef(_);$.accessors.push(b),K.accessorIndexMap.set(_,$.accessors.length-1);let u=[],i=[],e=[],Z0=new Array(_.getElementSize()).fill(0);for(let s0=0,x8=_.getCount();s0<x8;s0++){if(_.getElement(s0,e),l0.eq(e,Z0,0))continue;D=Math.max(s0,D),u.push(s0);for(let J8=0;J8<e.length;J8++)i.push(e[J8])}let K0=u.length,S0={accessorDef:b,count:K0};if(P.set(_,S0),K0===0)continue;if(K0>_.getCount()/2)C=!0;let A0=jX[_.getComponentType()];S0.indices=u,S0.values=new A0(i)}if(!Number.isFinite(D))return{buffers:N,byteLength:R};if(C)W.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?cR1:D<65535?dR1:uR1,A={buffer:w,byteOffset:M+R,byteLength:0};for(let _ of L){let b=P.get(_);if(b.count===0)continue;b.indicesByteOffset=A.byteLength;let u=a0.pad(a0.toView(new T(b.indices)));N.push(u),R+=u.byteLength,A.byteLength+=u.byteLength}$.bufferViews.push(A);let v=$.bufferViews.length-1,x={buffer:w,byteOffset:M+R,byteLength:0};for(let _ of L){let b=P.get(_);if(b.count===0)continue;b.valuesByteOffset=x.byteLength;let u=a0.pad(a0.toView(b.values));N.push(u),R+=u.byteLength,x.byteLength+=u.byteLength}$.bufferViews.push(x);let I=$.bufferViews.length-1;for(let _ of L){let b=P.get(_);if(b.count===0)continue;b.accessorDef.sparse={count:b.count,indices:{bufferView:v,byteOffset:b.indicesByteOffset,componentType:k},values:{bufferView:I,byteOffset:b.valuesByteOffset}}}return{buffers:N,byteLength:R}}if($.accessors=[],$.bufferViews=[],$.samplers=[],$.textures=[],$.images=Y.listTextures().map((L,w)=>{let M=K.createPropertyDef(L);if(L.getMimeType())M.mimeType=L.getMimeType();let N=L.getImage();if(N)K.createImageData(M,N,L);return K.imageIndexMap.set(L,w),M}),V.filter((L)=>L.prewriteTypes.includes(s.ACCESSOR)).forEach((L)=>L.prewrite(K,s.ACCESSOR)),Y.listAccessors().forEach((L)=>{let{accessorUsageGroupedByParent:w,accessorParents:M}=K;if(K.accessorIndexMap.has(L))return;let N=K.getAccessorUsage(L);if(K.addAccessorToUsageGroup(L,N),w.has(N)){let R=X.listParents(L).find((P)=>P.propertyType!==s.ROOT);M.set(L,R)}}),V.filter((L)=>L.prewriteTypes.includes(s.BUFFER)).forEach((L)=>L.prewrite(K,s.BUFFER)),(Y.listAccessors().length>0||K.otherBufferViews.size>0||Y.listTextures().length>0&&J.format===uZ.GLB)&&Y.listBuffers().length===0)throw new Error("Buffer required for Document resources, but none was found.");if($.buffers=[],Y.listBuffers().forEach((L,w)=>{let M=K.createPropertyDef(L),N=K.accessorUsageGroupedByParent,R=L.listParents().filter((x)=>x instanceof x0),P=new Set(R.map((x)=>K.accessorParents.get(x))),D=new Map(Array.from(P).map((x,I)=>[x,I])),C={};for(let x of R){var T;if(K.accessorIndexMap.has(x))continue;let I=K.getAccessorUsage(x),_=I;if(N.has(I)){let b=K.accessorParents.get(x);_+=`:${D.get(b)}`}C[T=_]||(C[T]={usage:I,accessors:[]}),C[_].accessors.push(x)}let k=[],A=$.buffers.length,v=0;for(let{usage:x,accessors:I}of Object.values(C))if(x===xL.ARRAY_BUFFER&&J.vertexLayout===yL.INTERLEAVED){let _=H(I,A,v);v+=_.byteLength;for(let b of _.buffers)k.push(b)}else if(x===xL.ARRAY_BUFFER)for(let _ of I){let b=H([_],A,v);v+=b.byteLength;for(let u of b.buffers)k.push(u)}else if(x===xL.SPARSE){let _=q(I,A,v);v+=_.byteLength;for(let b of _.buffers)k.push(b)}else if(x===xL.ELEMENT_ARRAY_BUFFER){let _=NX.BufferViewTarget.ELEMENT_ARRAY_BUFFER,b=F(I,A,v,_);v+=b.byteLength;for(let u of b.buffers)k.push(u)}else{let _=F(I,A,v);v+=_.byteLength;for(let b of _.buffers)k.push(b)}if(K.imageBufferViews.length&&w===0){for(let x=0;x<K.imageBufferViews.length;x++)if($.bufferViews[$.images[x].bufferView].byteOffset=v,v+=K.imageBufferViews[x].byteLength,k.push(K.imageBufferViews[x]),v%8){let I=8-v%8;v+=I,k.push(new Uint8Array(I))}}if(K.otherBufferViews.has(L))for(let x of K.otherBufferViews.get(L))$.bufferViews.push({buffer:A,byteOffset:v,byteLength:x.byteLength}),K.otherBufferViewsIndexMap.set(x,$.bufferViews.length-1),v+=x.byteLength,k.push(x);if(v){let x;if(J.format===uZ.GLB)x=fL;else x=K.bufferURIGenerator.createURI(L,"bin"),M.uri=x;M.byteLength=v,K.assignResourceURI(x,a0.concat(k),!0)}$.buffers.push(M),K.bufferIndexMap.set(L,w)}),Y.listAccessors().find((L)=>!L.getBuffer()))W.warn("Skipped writing one or more Accessors: no Buffer assigned.");V.filter((L)=>L.prewriteTypes.includes(s.MATERIAL)).forEach((L)=>L.prewrite(K,s.MATERIAL)),$.materials=Y.listMaterials().map((L,w)=>{let M=K.createPropertyDef(L);if(L.getAlphaMode()!==h7.AlphaMode.OPAQUE)M.alphaMode=L.getAlphaMode();if(L.getAlphaMode()===h7.AlphaMode.MASK)M.alphaCutoff=L.getAlphaCutoff();if(L.getDoubleSided())M.doubleSided=!0;if(M.pbrMetallicRoughness={},!l0.eq(L.getBaseColorFactor(),[1,1,1,1]))M.pbrMetallicRoughness.baseColorFactor=L.getBaseColorFactor();if(!l0.eq(L.getEmissiveFactor(),[0,0,0]))M.emissiveFactor=L.getEmissiveFactor();if(L.getRoughnessFactor()!==1)M.pbrMetallicRoughness.roughnessFactor=L.getRoughnessFactor();if(L.getMetallicFactor()!==1)M.pbrMetallicRoughness.metallicFactor=L.getMetallicFactor();if(L.getBaseColorTexture()){let N=L.getBaseColorTexture(),R=L.getBaseColorTextureInfo();M.pbrMetallicRoughness.baseColorTexture=K.createTextureInfoDef(N,R)}if(L.getEmissiveTexture()){let N=L.getEmissiveTexture(),R=L.getEmissiveTextureInfo();M.emissiveTexture=K.createTextureInfoDef(N,R)}if(L.getNormalTexture()){let N=L.getNormalTexture(),R=L.getNormalTextureInfo(),P=K.createTextureInfoDef(N,R);if(L.getNormalScale()!==1)P.scale=L.getNormalScale();M.normalTexture=P}if(L.getOcclusionTexture()){let N=L.getOcclusionTexture(),R=L.getOcclusionTextureInfo(),P=K.createTextureInfoDef(N,R);if(L.getOcclusionStrength()!==1)P.strength=L.getOcclusionStrength();M.occlusionTexture=P}if(L.getMetallicRoughnessTexture()){let N=L.getMetallicRoughnessTexture(),R=L.getMetallicRoughnessTextureInfo();M.pbrMetallicRoughness.metallicRoughnessTexture=K.createTextureInfoDef(N,R)}return K.materialIndexMap.set(L,w),M}),V.filter((L)=>L.prewriteTypes.includes(s.MESH)).forEach((L)=>L.prewrite(K,s.MESH)),$.meshes=Y.listMeshes().map((L,w)=>{let M=K.createPropertyDef(L),N=null;if(M.primitives=L.listPrimitives().map((R)=>{let P={attributes:{}};P.mode=R.getMode();let D=R.getMaterial();if(D)P.material=K.materialIndexMap.get(D);if(Object.keys(R.getExtras()).length)P.extras=R.getExtras();let C=R.getIndices();if(C)P.indices=K.accessorIndexMap.get(C);for(let T of R.listSemantics())P.attributes[T]=K.accessorIndexMap.get(R.getAttribute(T));for(let T of R.listTargets()){let k={};for(let A of T.listSemantics())k[A]=K.accessorIndexMap.get(T.getAttribute(A));P.targets=P.targets||[],P.targets.push(k)}if(R.listTargets().length&&!N)N=R.listTargets().map((T)=>T.getName());return P}),L.getWeights().length)M.weights=L.getWeights();if(N)M.extras=M.extras||{},M.extras.targetNames=N;return K.meshIndexMap.set(L,w),M}),$.cameras=Y.listCameras().map((L,w)=>{let M=K.createPropertyDef(L);if(M.type=L.getType(),M.type===E$.Type.PERSPECTIVE){M.perspective={znear:L.getZNear(),zfar:L.getZFar(),yfov:L.getYFov()};let N=L.getAspectRatio();if(N!==null)M.perspective.aspectRatio=N}else M.orthographic={znear:L.getZNear(),zfar:L.getZFar(),xmag:L.getXMag(),ymag:L.getYMag()};return K.cameraIndexMap.set(L,w),M}),$.nodes=Y.listNodes().map((L,w)=>{let M=K.createPropertyDef(L);if(!l0.eq(L.getTranslation(),[0,0,0]))M.translation=L.getTranslation();if(!l0.eq(L.getRotation(),[0,0,0,1]))M.rotation=L.getRotation();if(!l0.eq(L.getScale(),[1,1,1]))M.scale=L.getScale();if(L.getWeights().length)M.weights=L.getWeights();return K.nodeIndexMap.set(L,w),M}),$.skins=Y.listSkins().map((L,w)=>{let M=K.createPropertyDef(L),N=L.getInverseBindMatrices();if(N)M.inverseBindMatrices=K.accessorIndexMap.get(N);let R=L.getSkeleton();if(R)M.skeleton=K.nodeIndexMap.get(R);return M.joints=L.listJoints().map((P)=>K.nodeIndexMap.get(P)),K.skinIndexMap.set(L,w),M}),Y.listNodes().forEach((L,w)=>{let M=$.nodes[w],N=L.getMesh();if(N)M.mesh=K.meshIndexMap.get(N);let R=L.getCamera();if(R)M.camera=K.cameraIndexMap.get(R);let P=L.getSkin();if(P)M.skin=K.skinIndexMap.get(P);if(L.listChildren().length>0)M.children=L.listChildren().map((D)=>K.nodeIndexMap.get(D))}),$.animations=Y.listAnimations().map((L,w)=>{let M=K.createPropertyDef(L),N=new Map;return M.samplers=L.listSamplers().map((R,P)=>{let D=K.createPropertyDef(R);return D.input=K.accessorIndexMap.get(R.getInput()),D.output=K.accessorIndexMap.get(R.getOutput()),D.interpolation=R.getInterpolation(),N.set(R,P),D}),M.channels=L.listChannels().map((R)=>{let P=K.createPropertyDef(R);return P.sampler=N.get(R.getSampler()),P.target={node:K.nodeIndexMap.get(R.getTargetNode()),path:R.getTargetPath()},P}),K.animationIndexMap.set(L,w),M}),$.scenes=Y.listScenes().map((L,w)=>{let M=K.createPropertyDef(L);return M.nodes=L.listChildren().map((N)=>K.nodeIndexMap.get(N)),K.sceneIndexMap.set(L,w),M});let B=Y.getDefaultScene();if(B)$.scene=Y.listScenes().indexOf(B);return $.extensionsUsed=V.map((L)=>L.extensionName),$.extensionsRequired=z.map((L)=>L.extensionName),V.forEach((L)=>L.write(K)),pR1($),Q}}function pR1(Z){let J=[];for(let X in Z){let Y=Z[X];if(Array.isArray(Y)&&Y.length===0)J.push(X);else if(Y===null||Y==="")J.push(X);else if(Y&&typeof Y==="object"&&Object.keys(Y).length===0)J.push(X)}for(let X of J)delete Z[X]}var mL;(function(Z){Z[Z.JSON=1313821514]="JSON",Z[Z.BIN=5130562]="BIN"})(mL||(mL={}));class ca{constructor(){this._logger=f5.DEFAULT_INSTANCE,this._extensions=new Set,this._dependencies={},this._vertexLayout=yL.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=Sa(J)?this._binaryToJSON(J):{json:JSON.parse(a0.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),ua.read(Z,{extensions:Array.from(this._extensions),dependencies:this._dependencies,logger:this._logger})}async binaryToJSON(Z){let J=this._binaryToJSON(a0.assertView(Z));this._readResourcesInternal(J);let X=J.json;if(X.buffers&&X.buffers.some((Y)=>iR1(J,Y)))throw new Error("Cannot resolve external buffers with binaryToJSON().");else if(X.images&&X.images.some((Y)=>nR1(J,Y)))throw new Error("Cannot resolve external images with binaryToJSON().");return J}async readBinary(Z){return this.readJSON(await this.binaryToJSON(a0.assertView(Z)))}async writeJSON(Z,J={}){if(J.format===uZ.GLB&&Z.getRoot().listBuffers().length>1)throw new Error("GLB must have 0–1 buffers.");return da.write(Z,{format:J.format||uZ.GLTF,basename:J.basename||"",logger:this._logger,vertexLayout:this._vertexLayout,dependencies:K5({},this._dependencies),extensions:Array.from(this._extensions)})}async writeBinary(Z){let{json:J,resources:X}=await this.writeJSON(Z,{format:uZ.GLB}),Y=new Uint32Array([1179937895,2,12]),$=JSON.stringify(J),Q=a0.pad(a0.encodeText($),32),K=a0.toView(new Uint32Array([Q.byteLength,1313821514])),W=a0.concat([K,Q]);Y[Y.length-1]+=W.byteLength;let G=Object.values(X)[0];if(!G||!G.byteLength)return a0.concat([a0.toView(Y),W]);let V=a0.pad(G,0),z=a0.toView(new Uint32Array([V.byteLength,5130562])),F=a0.concat([z,V]);return Y[Y.length-1]+=F.byteLength,a0.concat([a0.toView(Y),W,F])}async _readResourcesExternal(Z,J){var X=this;let Y=Z.json.images||[],$=Z.json.buffers||[],Q=[...Y,...$].map(async function(K){let W=K.uri;if(!W||W.match(/data:/))return Promise.resolve();Z.resources[W]=await X.readURI(X.resolve(J,W),"view"),X.lastReadBytes+=Z.resources[W].byteLength});await Promise.all(Q)}_readResourcesInternal(Z){function J($){if(!$.uri)return;if($.uri in Z.resources){a0.assertView(Z.resources[$.uri]);return}if($.uri.match(/data:/)){let Q=`__${ba()}.${cZ.extension($.uri)}`;Z.resources[Q]=a0.createBufferFromDataURI($.uri),$.uri=Q}}(Z.json.images||[]).forEach(($)=>{if($.bufferView===void 0&&$.uri===void 0)throw new Error("Missing resource URI or buffer view.");J($)}),(Z.json.buffers||[]).forEach(J)}_copyJSON(Z){let{images:J,buffers:X}=Z.json;if(Z={json:K5({},Z.json),resources:K5({},Z.resources)},J)Z.json.images=J.map((Y)=>K5({},Y));if(X)Z.json.buffers=X.map((Y)=>K5({},Y));return Z}_binaryToJSON(Z){if(!Sa(Z))throw new Error("Invalid glTF 2.0 binary.");let J=new Uint32Array(Z.buffer,Z.byteOffset+12,2);if(J[1]!==mL.JSON)throw new Error("Missing required GLB JSON chunk.");let X=20,Y=J[0],$=a0.decodeText(a0.toView(Z,X,Y)),Q=JSON.parse($),K=X+Y;if(Z.byteLength<=K)return{json:Q,resources:{}};let W=new Uint32Array(Z.buffer,Z.byteOffset+K,2);if(W[1]!==mL.BIN)return{json:Q,resources:{}};let G=W[0],V=a0.toView(Z,K+8,G);return{json:Q,resources:{[fL]:V}}}}function iR1(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)}function nR1(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)&&J.bufferView===void 0}function Sa(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 aT extends ca{constructor(Z=null,J=p9.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(),p9.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(p9.isAbsoluteURL(Z)||p9.isAbsoluteURL(J))return p9.resolve(Z,J);return this._path.resolve(Z,decodeURIComponent(J))}dirname(Z){if(p9.isAbsoluteURL(Z))return p9.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:Y,resources:$}=await this.writeJSON(J,{format:uZ.GLTF,basename:cZ.basename(Z)}),{_fs:Q,_path:K}=this,W=K.dirname(Z),G=JSON.stringify(Y,null,2);await Q.writeFile(Z,G),this.lastWriteBytes+=G.length;for(let V of aR1(Object.keys($),10))await Promise.all(V.map(async function(z){if(p9.isAbsoluteURL(z)){if(p9.extension(z)==="bin")throw new Error(`Cannot write buffer to path "${z}".`);return}let F=K.join(W,decodeURIComponent(z));await Q.mkdir(K.dirname(F),{recursive:!0}),await Q.writeFile(F,$[z]),X.lastWriteBytes+=$[z].byteLength}))}async _writeGLB(Z,J){let X=await this.writeBinary(J);await this._fs.writeFile(Z,X),this.lastWriteBytes=X.byteLength}}function aR1(Z,J){let X=[];for(let Y=0,$=Z.length;Y<$;Y+=J){let Q=[];for(let K=0;K<J&&Y+K<$;K++)Q.push(Z[Y+K]);X.push(Q)}return X}var br=r(sT(),1),gr=r(Rr(),1),gT1=r(yr(),1);async function mT1(Z,J){if(!(Z instanceof Uint8Array))throw new Error("[ndarray-pixels] Input must be Uint8Array or Buffer.");let{data:X,info:Y}=await gr.default(Z).ensureAlpha().raw().toBuffer({resolveWithObject:!0});return br.default(new Uint8Array(X),[Y.width,Y.height,4],[4,4*Y.width|0,1],0)}async function mr(Z,J){return mT1(Z)}var uT1="v4.2.1",kk="@glb.bin",o;(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"})(o||(o={}));var ur;(function(Z){Z.INTERLEAVED="interleaved",Z.SEPARATE="separate"})(ur||(ur={}));var V9;(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"})(V9||(V9={}));var z9;(function(Z){Z[Z.R=4096]="R",Z[Z.G=256]="G",Z[Z.B=16]="B",Z[Z.A=1]="A"})(z9||(z9={}));var Rk;(function(Z){Z.GLTF="GLTF",Z.GLB="GLB"})(Rk||(Rk={}));class g6{static createBufferFromDataURI(Z){if(typeof Buffer==="undefined"){let J=atob(Z.split(",")[1]),X=new Uint8Array(J.length);for(let Y=0;Y<J.length;Y++)X[Y]=J.charCodeAt(Y);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 $ of Z)J+=$.byteLength;let X=new Uint8Array(J),Y=0;for(let $ 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 Y=new Uint8Array(X);if(Y.set(Z),J!==0)for(let $=Z.byteLength;$<X;$++)Y[$]=J;return Y}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 pr{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,Y;while(J.byteLength){if(X=J.getUint16(0,!1),dT1(J,X),Y=J.getUint8(X+1),Y===192||Y===193||Y===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 Mw{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(g6.decodeText(Z.slice(12,16))===Mw.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}}Mw.PNG_FRIED_CHUNK_NAME="CgBI";class a4{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,Y=4,$=this.getSize(Z,J);if(!$)return null;while($[0]>1||$[1]>1)X+=$[0]*$[1]*Y,$[0]=Math.max(Math.floor($[0]/2),1),$[1]=Math.max(Math.floor($[1]/2),1);return X+=1*Y,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}`}}a4.impls={"image/jpeg":new pr,"image/png":new Mw};function dT1(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 Rz{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 a4.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()}}var jk=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 cT1(){var Z=new jk(3);if(jk!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function Nk(Z){var J=Z[0],X=Z[1],Y=Z[2];return Math.hypot(J,X,Y)}function lT1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=X[3]*Y+X[7]*$+X[11]*Q+X[15];return K=K||1,Z[0]=(X[0]*Y+X[4]*$+X[8]*Q+X[12])/K,Z[1]=(X[1]*Y+X[5]*$+X[9]*Q+X[13])/K,Z[2]=(X[2]*Y+X[6]*$+X[10]*Q+X[14])/K,Z}(function(){var Z=cT1();return function(J,X,Y,$,Q,K){var W,G;if(!X)X=3;if(!Y)Y=0;if($)G=Math.min($*X+Y,J.length);else G=J.length;for(W=Y;W<G;W+=X)Z[0]=J[W],Z[1]=J[W+1],Z[2]=J[W+2],Q(Z,Z,K),J[W]=Z[0],J[W+1]=Z[1],J[W+2]=Z[2];return J}})();function ir(Z){let J=nr(),X=Z.propertyType===o.NODE?[Z]:Z.listChildren();for(let Y of X)Y.traverse(($)=>{let Q=$.getMesh();if(!Q)return;let K=pT1(Q,$.getWorldMatrix());if(K.min.every(isFinite)&&K.max.every(isFinite))Dk(K.min,J),Dk(K.max,J)});return J}function pT1(Z,J){let X=nr();for(let Y of Z.listPrimitives()){let $=Y.getAttribute("POSITION"),Q=Y.getIndices();if(!$)continue;let K=[0,0,0],W=[0,0,0];for(let G=0,V=Q?Q.getCount():$.getCount();G<V;G++){let z=Q?Q.getScalar(G):G;K=$.getElement(z,K),W=lT1(W,K,J),Dk(W,X)}}return X}function Dk(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 nr(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}var dr="https://null.example";class Ek{static dirname(Z){let J=Z.lastIndexOf("/");if(J===-1)return"./";return Z.substring(0,J+1)}static basename(Z){return Rz.basename(new URL(Z,dr).pathname)}static extension(Z){return Rz.extension(new URL(Z,dr).pathname)}static resolve(Z,J){if(!this.isRelativePath(J))return J;let X=Z.split("/"),Y=J.split("/");X.pop();for(let $=0;$<Y.length;$++){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)}}Ek.DEFAULT_INIT={};Ek.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;function cr(Z){return Object.prototype.toString.call(Z)==="[object Object]"}function x$(Z){if(cr(Z)===!1)return!1;let J=Z.constructor;if(J===void 0)return!0;let X=J.prototype;if(cr(X)===!1)return!1;if(Object.hasOwn(X,"isPrototypeOf")===!1)return!1;return!0}var Pk,Ck;(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"})(Ck||(Ck={}));class u7{constructor(Z){this.verbosity=void 0,this.verbosity=Z}debug(Z){if(this.verbosity<=u7.Verbosity.DEBUG)console.debug(Z)}info(Z){if(this.verbosity<=u7.Verbosity.INFO)console.info(Z)}warn(Z){if(this.verbosity<=u7.Verbosity.WARN)console.warn(Z)}error(Z){if(this.verbosity<=u7.Verbosity.ERROR)console.error(Z)}}Pk=u7;u7.Verbosity=Ck;u7.DEFAULT_INSTANCE=new Pk(Pk.Verbosity.INFO);function iT1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3],Q=Z[4],K=Z[5],W=Z[6],G=Z[7],V=Z[8],z=Z[9],F=Z[10],H=Z[11],q=Z[12],U=Z[13],B=Z[14],L=Z[15],w=J*K-X*Q,M=J*W-Y*Q,N=J*G-$*Q,R=X*W-Y*K,P=X*G-$*K,D=Y*G-$*W,C=V*U-z*q,T=V*B-F*q,k=V*L-H*q,A=z*B-F*U,v=z*L-H*U,x=F*L-H*B;return w*x-M*v+N*A+R*k-P*T+D*C}function nT1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=J[3],W=J[4],G=J[5],V=J[6],z=J[7],F=J[8],H=J[9],q=J[10],U=J[11],B=J[12],L=J[13],w=J[14],M=J[15],N=X[0],R=X[1],P=X[2],D=X[3];return Z[0]=N*Y+R*W+P*F+D*B,Z[1]=N*$+R*G+P*H+D*L,Z[2]=N*Q+R*V+P*q+D*w,Z[3]=N*K+R*z+P*U+D*M,N=X[4],R=X[5],P=X[6],D=X[7],Z[4]=N*Y+R*W+P*F+D*B,Z[5]=N*$+R*G+P*H+D*L,Z[6]=N*Q+R*V+P*q+D*w,Z[7]=N*K+R*z+P*U+D*M,N=X[8],R=X[9],P=X[10],D=X[11],Z[8]=N*Y+R*W+P*F+D*B,Z[9]=N*$+R*G+P*H+D*L,Z[10]=N*Q+R*V+P*q+D*w,Z[11]=N*K+R*z+P*U+D*M,N=X[12],R=X[13],P=X[14],D=X[15],Z[12]=N*Y+R*W+P*F+D*B,Z[13]=N*$+R*G+P*H+D*L,Z[14]=N*Q+R*V+P*q+D*w,Z[15]=N*K+R*z+P*U+D*M,Z}function aT1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[4],K=J[5],W=J[6],G=J[8],V=J[9],z=J[10];return Z[0]=Math.hypot(X,Y,$),Z[1]=Math.hypot(Q,K,W),Z[2]=Math.hypot(G,V,z),Z}function sT1(Z,J){var X=new jk(3);aT1(X,J);var Y=1/X[0],$=1/X[1],Q=1/X[2],K=J[0]*Y,W=J[1]*$,G=J[2]*Q,V=J[4]*Y,z=J[5]*$,F=J[6]*Q,H=J[8]*Y,q=J[9]*$,U=J[10]*Q,B=K+z+U,L=0;if(B>0)L=Math.sqrt(B+1)*2,Z[3]=0.25*L,Z[0]=(F-q)/L,Z[1]=(H-G)/L,Z[2]=(W-V)/L;else if(K>z&&K>U)L=Math.sqrt(1+K-z-U)*2,Z[3]=(F-q)/L,Z[0]=0.25*L,Z[1]=(W+V)/L,Z[2]=(H+G)/L;else if(z>U)L=Math.sqrt(1+z-K-U)*2,Z[3]=(H-G)/L,Z[0]=(W+V)/L,Z[1]=0.25*L,Z[2]=(F+q)/L;else L=Math.sqrt(1+U-K-z)*2,Z[3]=(W-V)/L,Z[0]=(H+G)/L,Z[1]=(F+q)/L,Z[2]=0.25*L;return Z}class U8{static identity(Z){return Z}static eq(Z,J,X=0.00001){if(Z.length!==J.length)return!1;for(let Y=0;Y<Z.length;Y++)if(Math.abs(Z[Y]-J[Y])>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(U8.clamp(Z,0,1)*65535);case 5121:return Math.round(U8.clamp(Z,0,1)*255);case 5122:return Math.round(U8.clamp(Z,-1,1)*32767);case 5120:return Math.round(U8.clamp(Z,-1,1)*127);default:throw new Error("Invalid component type.")}}static decompose(Z,J,X,Y){let $=Nk([Z[0],Z[1],Z[2]]),Q=Nk([Z[4],Z[5],Z[6]]),K=Nk([Z[8],Z[9],Z[10]]);if(iT1(Z)<0)$=-$;J[0]=Z[12],J[1]=Z[13],J[2]=Z[14];let G=Z.slice(),V=1/$,z=1/Q,F=1/K;G[0]*=V,G[1]*=V,G[2]*=V,G[4]*=z,G[5]*=z,G[6]*=z,G[8]*=F,G[9]*=F,G[10]*=F,sT1(X,G),Y[0]=$,Y[1]=Q,Y[2]=K}static compose(Z,J,X,Y){let $=Y,Q=J[0],K=J[1],W=J[2],G=J[3],V=Q+Q,z=K+K,F=W+W,H=Q*V,q=Q*z,U=Q*F,B=K*z,L=K*F,w=W*F,M=G*V,N=G*z,R=G*F,P=X[0],D=X[1],C=X[2];return $[0]=(1-(B+w))*P,$[1]=(q+R)*P,$[2]=(U-N)*P,$[3]=0,$[4]=(q-R)*D,$[5]=(1-(H+w))*D,$[6]=(L+M)*D,$[7]=0,$[8]=(U+N)*C,$[9]=(L-M)*C,$[10]=(1-(H+B))*C,$[11]=0,$[12]=Z[0],$[13]=Z[1],$[14]=Z[2],$[15]=1,$}}function oT1(Z,J){if(!!Z!==!!J)return!1;let X=Z.getChild(),Y=J.getChild();return X===Y||X.equals(Y)}function rT1(Z,J){if(!!Z!==!!J)return!1;let X=Z.values(),Y=J.values();if(X.length!==Y.length)return!1;for(let $=0;$<X.length;$++){let Q=X[$],K=Y[$];if(Q.getChild()===K.getChild())continue;if(!Q.getChild().equals(K.getChild()))return!1}return!0}function tT1(Z,J){if(!!Z!==!!J)return!1;let X=Z.keys(),Y=J.keys();if(X.length!==Y.length)return!1;for(let $ of X){let Q=Z.get($),K=J.get($);if(!!Q!==!!K)return!1;let W=Q.getChild(),G=K.getChild();if(W===G)continue;if(!W.equals(G))return!1}return!0}function ar(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 sr(Z,J){if(Z===J)return!0;if(!!Z!==!!J)return!1;if(!x$(Z)||!x$(J))return Z===J;let X=Z,Y=J,$=0,Q=0,K;for(K in X)$++;for(K in Y)Q++;if($!==Q)return!1;for(K in X){let W=X[K],G=Y[K];if(Lw(W)&&Lw(G)){if(!ar(W,G))return!1}else if(x$(W)&&x$(G)){if(!sr(W,G))return!1}else if(W!==G)return!1}return!0}function Lw(Z){return Array.isArray(Z)||ArrayBuffer.isView(Z)}var EX=(Z)=>Z,eT1=new Set;class Nw extends VW{constructor(Z,J=""){super(Z);this[b0].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,EX)}copy(Z,J=EX){for(let X in this[b0]){let Y=this[b0][X];if(Y instanceof x5){if(!this[i4].has(X))Y.dispose()}else if(Y instanceof f6||Y instanceof I0)for(let $ of Y.values())$.dispose();else if(Y instanceof Y8)for(let $ of Y.values())$.dispose()}for(let X in Z[b0]){let Y=this[b0][X],$=Z[b0][X];if($ instanceof x5)if(this[i4].has(X))Y.getChild().copy(J($.getChild()),J);else this.setRef(X,J($.getChild()),$.getAttributes());else if($ instanceof I0||$ instanceof f6)for(let Q of $.values())this.addRef(X,J(Q.getChild()),Q.getAttributes());else if($ instanceof Y8)for(let Q of $.keys()){let K=$.get(Q);this.setRefMap(X,Q,J(K.getChild()),K.getAttributes())}else if(x$($))this[b0][X]=JSON.parse(JSON.stringify($));else if(Array.isArray($)||$ instanceof ArrayBuffer||ArrayBuffer.isView($))this[b0][X]=$.slice();else this[b0][X]=$}return this}equals(Z,J=eT1){if(this===Z)return!0;if(this.propertyType!==Z.propertyType)return!1;for(let X in this[b0]){if(J.has(X))continue;let Y=this[b0][X],$=Z[b0][X];if(Y instanceof x5||$ instanceof x5){if(!oT1(Y,$))return!1}else if(Y instanceof I0||$ instanceof I0||Y instanceof f6||$ instanceof f6){if(!rT1(Y,$))return!1}else if(Y instanceof Y8||$ instanceof Y8){if(!tT1(Y,$))return!1}else if(x$(Y)||x$($)){if(!sr(Y,$))return!1}else if(Lw(Y)||Lw($)){if(!ar(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 m6 extends Nw{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new Y8})}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 C0 extends m6{init(){this.propertyType=o.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:C0.Type.SCALAR,componentType:C0.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(Z){switch(Z){case C0.Type.SCALAR:return 1;case C0.Type.VEC2:return 2;case C0.Type.VEC3:return 3;case C0.Type.VEC4:return 4;case C0.Type.MAT2:return 4;case C0.Type.MAT3:return 9;case C0.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+Z)}}static getComponentSize(Z){switch(Z){case C0.ComponentType.BYTE:return 1;case C0.ComponentType.UNSIGNED_BYTE:return 1;case C0.ComponentType.SHORT:return 2;case C0.ComponentType.UNSIGNED_SHORT:return 2;case C0.ComponentType.UNSIGNED_INT:return 4;case C0.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+Z)}}getMinNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMin(Z),J)for(let $=0;$<X;$++)Z[$]=U8.decodeNormalizedInt(Z[$],Y);return Z}getMin(Z){let J=this.getArray(),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.min(Z[Q],K)}return Z}getMaxNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMax(Z),J)for(let $=0;$<X;$++)Z[$]=U8.decodeNormalizedInt(Z[$],Y);return Z}getMax(Z){let J=this.get("array"),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=-1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.max(Z[Q],K)}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 C0.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(),Y=this.getArray();if(this.getNormalized())return U8.decodeNormalizedInt(Y[Z*J],X);return Y[Z*J]}setScalar(Z,J){let X=this.getElementSize(),Y=this.getComponentType(),$=this.getArray();if(this.getNormalized())$[Z*X]=U8.encodeNormalizedInt(J,Y);else $[Z*X]=J;return this}getElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)J[K]=U8.decodeNormalizedInt(Q[Z*Y+K],$);else J[K]=Q[Z*Y+K];return J}setElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)Q[Z*Y+K]=U8.encodeNormalizedInt(J[K],$);else Q[Z*Y+K]=J[K];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?Zk1(Z):C0.ComponentType.FLOAT),this.set("array",Z),this}getByteLength(){let Z=this.get("array");return Z?Z.byteLength:0}}C0.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};C0.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};function Zk1(Z){switch(Z.constructor){case Float32Array:return C0.ComponentType.FLOAT;case Uint32Array:return C0.ComponentType.UNSIGNED_INT;case Uint16Array:return C0.ComponentType.UNSIGNED_SHORT;case Uint8Array:return C0.ComponentType.UNSIGNED_BYTE;case Int16Array:return C0.ComponentType.SHORT;case Int8Array:return C0.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}class Ik extends m6{init(){this.propertyType=o.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 Dz extends m6{init(){this.propertyType=o.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)}}Dz.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class jW extends m6{init(){this.propertyType=o.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:jW.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:V9.OTHER})}getOutput(){return this.getRef("output")}setOutput(Z){return this.setRef("output",Z,{usage:V9.OTHER})}}jW.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class _k extends m6{init(){this.propertyType=o.BUFFER}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(Z){return this.set("uri",Z)}}class Pz extends m6{init(){this.propertyType=o.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:Pz.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)}}Pz.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class t1 extends Nw{_validateParent(Z){if(!this.parentTypes.includes(Z.propertyType))throw new Error(`Parent "${Z.propertyType}" invalid for child "${this.propertyType}".`)}}t1.EXTENSION_NAME=void 0;class E1 extends m6{init(){this.propertyType=o.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:E1.WrapMode.REPEAT,wrapT:E1.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)}}E1.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};E1.MagFilter={NEAREST:9728,LINEAR:9729};E1.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};var{R:qw,G:Uw,B:Bw,A:Jk1}=z9;class Cz extends m6{init(){this.propertyType=o.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:Cz.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new E1(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new E1(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new E1(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new E1(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new E1(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:qw|Uw|Bw|Jk1,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:qw|Uw|Bw,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:qw|Uw|Bw})}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:qw})}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:Uw|Bw})}}Cz.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class vk extends m6{init(){this.propertyType=o.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 Sk extends m6{init(){this.propertyType=o.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=EX){if(J===EX)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 U8.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(Z){let J=this.get("translation").slice(),X=this.get("rotation").slice(),Y=this.get("scale").slice();return U8.decompose(Z,J,X,Y),this.set("translation",J).set("rotation",X).set("scale",Y)}getWorldTranslation(){let Z=[0,0,0];return U8.decompose(this.getWorldMatrix(),Z,[0,0,0,1],[1,1,1]),Z}getWorldRotation(){let Z=[0,0,0,1];return U8.decompose(this.getWorldMatrix(),[0,0,0],Z,[1,1,1]),Z}getWorldScale(){let Z=[1,1,1];return U8.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],Z),Z}getWorldMatrix(){let Z=[];for(let Y=this;Y!=null;Y=Y.getParentNode())Z.push(Y);let J,X=Z.pop().getMatrix();while(J=Z.pop())nT1(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===o.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===o.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 IX extends m6{init(){this.propertyType=o.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:IX.Mode.TRIANGLES,material:null,indices:null,attributes:new Y8,targets:new I0})}getIndices(){return this.getRef("indices")}setIndices(Z){return this.setRef("indices",Z,{usage:V9.ELEMENT_ARRAY_BUFFER})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:V9.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)}}IX.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class or extends Nw{init(){this.propertyType=o.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new Y8})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:V9.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function ww(){return ww=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},ww.apply(null,arguments)}class Ak extends m6{init(){this.propertyType=o.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:new I0})}copy(Z,J=EX){if(J===EX)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 xk extends m6{init(){this.propertyType=o.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:V9.INVERSE_BIND_MATRICES})}addJoint(Z){return this.addRef("joints",Z)}removeJoint(Z){return this.removeRef("joints",Z)}listJoints(){return this.listRefs("joints")}}class hk extends m6{init(){this.propertyType=o.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||a4.extensionToMimeType(Rz.extension(this.get("uri")))}setMimeType(Z){return this.set("mimeType",Z)}getURI(){return this.get("uri")}setURI(Z){this.set("uri",Z);let J=a4.extensionToMimeType(Rz.extension(Z));if(J)this.set("mimeType",J);return this}getImage(){return this.get("image")}setImage(Z){return this.set("image",g6.assertView(Z))}getSize(){let Z=this.get("image");if(!Z)return null;return a4.getSize(Z,this.getMimeType())}}class Rw extends m6{init(){this.propertyType=o.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${uT1}`,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=EX){if(J===EX)throw new Error("Root cannot be copied.");this.set("asset",ww({},Z.get("asset"))),this.setName(Z.getName()),this.setExtras(ww({},Z.getExtras())),this.setDefaultScene(Z.getDefaultScene()?J(Z.getDefaultScene()):null);for(let X of Z.listRefMapKeys("extensions")){let Y=Z.getExtension(X);this.setExtension(X,J(Y))}return this}_addChildOfRoot(Z){if(Z instanceof Ak)this.addRef("scenes",Z);else if(Z instanceof Sk)this.addRef("nodes",Z);else if(Z instanceof Pz)this.addRef("cameras",Z);else if(Z instanceof xk)this.addRef("skins",Z);else if(Z instanceof vk)this.addRef("meshes",Z);else if(Z instanceof Cz)this.addRef("materials",Z);else if(Z instanceof hk)this.addRef("textures",Z);else if(Z instanceof Ik)this.addRef("animations",Z);else if(Z instanceof C0)this.addRef("accessors",Z);else if(Z instanceof _k)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 Ow{static fromGraph(Z){return Ow._GRAPH_DOCUMENTS.get(Z)||null}constructor(){this._graph=new GW,this._root=new Rw(this._graph),this._logger=u7.DEFAULT_INSTANCE,Ow._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((Y)=>Y.extensionName===J)||new Z(this)}createScene(Z=""){return new Ak(this._graph,Z)}createNode(Z=""){return new Sk(this._graph,Z)}createCamera(Z=""){return new Pz(this._graph,Z)}createSkin(Z=""){return new xk(this._graph,Z)}createMesh(Z=""){return new vk(this._graph,Z)}createPrimitive(){return new IX(this._graph)}createPrimitiveTarget(Z=""){return new or(this._graph,Z)}createMaterial(Z=""){return new Cz(this._graph,Z)}createTexture(Z=""){return new hk(this._graph,Z)}createAnimation(Z=""){return new Ik(this._graph,Z)}createAnimationChannel(Z=""){return new Dz(this._graph,Z)}createAnimationSampler(Z=""){return new jW(this._graph,Z)}createAccessor(Z="",J=null){if(!J)J=this.getRoot().listBuffers()[0];return new C0(this._graph,Z).setBuffer(J)}createBuffer(Z=""){return new _k(this._graph,Z)}}Ow._GRAPH_DOCUMENTS=new WeakMap;class v1{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 Y=X,$=Y.target;if($ instanceof t1&&$.extensionName===this.extensionName){if(Y.type==="node:create")this._addExtensionProperty($);if(Y.type==="node:dispose")this._removeExtensionProperty($)}};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}}v1.EXTENSION_NAME=void 0;var yx6={logger:u7.DEFAULT_INSTANCE,extensions:[],dependencies:{}},bx6=new Set([o.BUFFER,o.TEXTURE,o.MATERIAL,o.MESH,o.PRIMITIVE,o.NODE,o.SCENE]);var jz;(function(Z){Z[Z.ARRAY_BUFFER=34962]="ARRAY_BUFFER",Z[Z.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"})(jz||(jz={}));class _X{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 Y=Z.getRoot(),$=Y.listBuffers().length,Q=Y.listTextures().length;this.bufferURIGenerator=new Tk($>1,()=>X.basename||"buffer"),this.imageURIGenerator=new Tk(Q>1,(K)=>Xk1(Z,K)||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()},Y=JSON.stringify(X);if(!this.samplerDefIndexMap.has(Y))this.samplerDefIndexMap.set(Y,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(X);let $={source:this.imageIndexMap.get(Z),sampler:this.samplerDefIndexMap.get(Y)},Q=JSON.stringify($);if(!this.textureDefIndexMap.has(Q))this.textureDefIndexMap.set(Q,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push($);let K={index:this.textureDefIndexMap.get(Q)};if(J.getTexCoord()!==0)K.texCoord=J.getTexCoord();if(Object.keys(J.getExtras()).length>0)K.extras=J.getExtras();return this.textureInfoDefMap.set(J,K),K}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((Y)=>Y.getName()==="attributes"&&Y.getAttributes().key==="POSITION"||Y.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===Rk.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 Y=a4.mimeTypeToExtension(X.getMimeType());Z.uri=this.imageURIGenerator.createURI(X,Y),this.assignResourceURI(Z.uri,J,!1)}}assignResourceURI(Z,J,X){let Y=this.jsonDoc.resources;if(!(Z in Y)){Y[Z]=J;return}if(J===Y[Z]){this.logger.warn(`Duplicate resource URI, "${Z}".`);return}let $=`Resource URI "${Z}" already assigned to different data.`;if(!X){this.logger.warn($);return}throw new Error($)}getAccessorUsage(Z){let J=this._accessorUsageMap.get(Z);if(J)return J;if(Z.getSparse())return V9.SPARSE;for(let X of this._doc.getGraph().listParentEdges(Z)){let{usage:Y}=X.getAttributes();if(Y)return Y;if(X.getParent().propertyType!==o.ROOT)this.logger.warn(`Missing attribute ".usage" on edge, "${X.getName()}".`)}return V9.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}}_X.BufferViewTarget=jz;_X.BufferViewUsage=V9;_X.USAGE_TO_TARGET={[V9.ARRAY_BUFFER]:jz.ARRAY_BUFFER,[V9.ELEMENT_ARRAY_BUFFER]:jz.ELEMENT_ARRAY_BUFFER};class Tk{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 Xk1(Z,J){let X=Z.getGraph().listParentEdges(J).find((Y)=>Y.getParent()!==Z.getRoot());return X?X.getName().replace(/texture$/i,""):""}var{UNSIGNED_INT:gx6,UNSIGNED_SHORT:mx6,UNSIGNED_BYTE:ux6}=C0.ComponentType,dx6=new Set([o.ACCESSOR,o.BUFFER,o.MATERIAL,o.MESH]);var lr;(function(Z){Z[Z.JSON=1313821514]="JSON",Z[Z.BIN=5130562]="BIN"})(lr||(lr={}));var tr=163,er=166;function Yk1(){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 DW{constructor(Z,J,X,Y){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(Z.buffer,Z.byteOffset+J,X),this._littleEndian=Y,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,Y=0;while(this._dataView.getUint8(this._offset)!==J&&Y<Z)Y++,this._offset++;if(Y<Z)this._offset++;return new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+X,Y)}}var px6=new Uint8Array([0]),z5=[171,75,84,88,32,50,48,187,13,10,26,10];function rr(Z){return new TextDecoder().decode(Z)}function jw(Z){let J=new Uint8Array(Z.buffer,Z.byteOffset,z5.length);if(J[0]!==z5[0]||J[1]!==z5[1]||J[2]!==z5[2]||J[3]!==z5[3]||J[4]!==z5[4]||J[5]!==z5[5]||J[6]!==z5[6]||J[7]!==z5[7]||J[8]!==z5[8]||J[9]!==z5[9]||J[10]!==z5[10]||J[11]!==z5[11])throw new Error("Missing KTX 2.0 identifier.");let X=Yk1(),Y=17*Uint32Array.BYTES_PER_ELEMENT,$=new DW(Z,z5.length,Y,!0);X.vkFormat=$._nextUint32(),X.typeSize=$._nextUint32(),X.pixelWidth=$._nextUint32(),X.pixelHeight=$._nextUint32(),X.pixelDepth=$._nextUint32(),X.layerCount=$._nextUint32(),X.faceCount=$._nextUint32();let Q=$._nextUint32();X.supercompressionScheme=$._nextUint32();let K=$._nextUint32(),W=$._nextUint32(),G=$._nextUint32(),V=$._nextUint32(),z=$._nextUint64(),F=$._nextUint64(),H=Q*3*8,q=new DW(Z,z5.length+Y,H,!0);for(let L6=0;L6<Q;L6++)X.levels.push({levelData:new Uint8Array(Z.buffer,Z.byteOffset+q._nextUint64(),q._nextUint64()),uncompressedByteLength:q._nextUint64()});let U=new DW(Z,K,W,!0);U._skip(4);let B=U._nextUint16(),L=U._nextUint16(),w=U._nextUint16(),M=U._nextUint16(),N=U._nextUint8(),R=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:B,descriptorType:L,versionNumber:w,colorModel:N,colorPrimaries:R,transferFunction:P,flags:D,texelBlockDimension:C,bytesPlane:T,samples:[]},v=6,x=4,I=(M/4-v)/x;for(let L6=0;L6<I;L6++){let EZ={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(EZ.channelType&64)EZ.sampleLower=U._nextInt32(),EZ.sampleUpper=U._nextInt32();else EZ.sampleLower=U._nextUint32(),EZ.sampleUpper=U._nextUint32();A.samples[L6]=EZ}X.dataFormatDescriptor.length=0,X.dataFormatDescriptor.push(A);let _=new DW(Z,G,V,!0);while(_._offset<V){let L6=_._nextUint32(),EZ=_._scan(L6),G2=rr(EZ);if(X.keyValue[G2]=_._nextUint8Array(L6-EZ.byteLength-1),G2.match(/^ktx/i)){let Iu=rr(X.keyValue[G2]);X.keyValue[G2]=Iu.substring(0,Iu.lastIndexOf("\x00"))}let rF1=L6%4?4-L6%4:0;_._skip(rF1)}if(F<=0)return X;let b=new DW(Z,z,F,!0),u=b._nextUint16(),i=b._nextUint16(),e=b._nextUint32(),Z0=b._nextUint32(),K0=b._nextUint32(),S0=b._nextUint32(),A0=[];for(let L6=0;L6<Q;L6++)A0.push({imageFlags:b._nextUint32(),rgbSliceByteOffset:b._nextUint32(),rgbSliceByteLength:b._nextUint32(),alphaSliceByteOffset:b._nextUint32(),alphaSliceByteLength:b._nextUint32()});let s0=z+b._offset,x8=s0+e,J8=x8+Z0,C7=J8+K0,h4=new Uint8Array(Z.buffer,Z.byteOffset+s0,e),TK=new Uint8Array(Z.buffer,Z.byteOffset+x8,Z0),kK=new Uint8Array(Z.buffer,Z.byteOffset+J8,K0),G$=new Uint8Array(Z.buffer,Z.byteOffset+C7,S0);return X.globalData={endpointCount:u,selectorCount:i,imageDescs:A0,endpointsData:h4,selectorsData:TK,tablesData:kK,extendedData:G$},X}var iZ="EXT_mesh_gpu_instancing",N6="EXT_meshopt_compression",Tz="EXT_texture_webp",kz="EXT_texture_avif",Q8="KHR_draco_mesh_compression",a9="KHR_lights_punctual",nZ="KHR_materials_anisotropy",aZ="KHR_materials_clearcoat",sZ="KHR_materials_diffuse_transmission",oZ="KHR_materials_dispersion",rZ="KHR_materials_emissive_strength",tZ="KHR_materials_ior",eZ="KHR_materials_iridescence",ZJ="KHR_materials_pbrSpecularGlossiness",JJ="KHR_materials_sheen",XJ="KHR_materials_specular",YJ="KHR_materials_transmission",vX="KHR_materials_unlit",$J="KHR_materials_volume",u6="KHR_materials_variants",Ft="KHR_mesh_quantization",Ez="KHR_texture_basisu",QJ="KHR_texture_transform",s9="KHR_xmp_json_ld",yk="INSTANCE_ATTRIBUTE";class gk extends t1{init(){this.extensionName=iZ,this.propertyType="InstancedMesh",this.parentTypes=[o.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new Y8})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:yk})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}gk.EXTENSION_NAME=iZ;class Cw extends v1{constructor(...Z){super(...Z);this.extensionName=iZ,this.provideTypes=[o.NODE],this.prewriteTypes=[o.ACCESSOR]}createInstancedMesh(){return new gk(this.document.getGraph())}read(Z){return(Z.jsonDoc.json.nodes||[]).forEach((Y,$)=>{if(!Y.extensions||!Y.extensions[iZ])return;let Q=Y.extensions[iZ],K=this.createInstancedMesh();for(let W in Q.attributes)K.setAttribute(W,Z.accessors[Q.attributes[W]]);Z.nodes[$].setExtension(iZ,K)}),this}prewrite(Z){Z.accessorUsageGroupedByParent.add(yk);for(let J of this.properties)for(let X of J.listAttributes())Z.addAccessorToUsageGroup(X,yk);return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listNodes().forEach((X)=>{let Y=X.getExtension(iZ);if(Y){let $=Z.nodeIndexMap.get(X),Q=J.json.nodes[$],K={attributes:{}};Y.listSemantics().forEach((W)=>{let G=Y.getAttribute(W);K.attributes[W]=Z.accessorIndexMap.get(G)}),Q.extensions=Q.extensions||{},Q.extensions[iZ]=K}}),this}}Cw.EXTENSION_NAME=iZ;function KJ(){return KJ=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},KJ.apply(null,arguments)}var Iz;(function(Z){Z.QUANTIZE="quantize",Z.FILTER="filter"})(Iz||(Iz={}));var PW;(function(Z){Z.ATTRIBUTES="ATTRIBUTES",Z.TRIANGLES="TRIANGLES",Z.INDICES="INDICES"})(PW||(PW={}));var B8;(function(Z){Z.NONE="NONE",Z.OCTAHEDRAL="OCTAHEDRAL",Z.QUATERNION="QUATERNION",Z.EXPONENTIAL="EXPONENTIAL"})(B8||(B8={}));function $k1(Z){if(!Z.extensions||!Z.extensions[N6])return!1;return!!Z.extensions[N6].fallback}var{BYTE:Qk1,SHORT:Zt,FLOAT:Kk1}=C0.ComponentType,{encodeNormalizedInt:Jt,decodeNormalizedInt:bk}=U8;function Wk1(Z,J,X,Y){let{filter:$,bits:Q}=Y,K={array:Z.getArray(),byteStride:Z.getElementSize()*Z.getComponentSize(),componentType:Z.getComponentType(),normalized:Z.getNormalized()};if(X!==PW.ATTRIBUTES)return K;if($!==B8.NONE){let W=Z.getNormalized()?Gk1(Z):new Float32Array(K.array);switch($){case B8.EXPONENTIAL:K.byteStride=Z.getElementSize()*4,K.componentType=Kk1,K.normalized=!1,K.array=J.encodeFilterExp(W,Z.getCount(),K.byteStride,Q);break;case B8.OCTAHEDRAL:K.byteStride=Q>8?8:4,K.componentType=Q>8?Zt:Qk1,K.normalized=!0,W=Z.getElementSize()===3?zk1(W):W,K.array=J.encodeFilterOct(W,Z.getCount(),K.byteStride,Q);break;case B8.QUATERNION:K.byteStride=8,K.componentType=Zt,K.normalized=!0,K.array=J.encodeFilterQuat(W,Z.getCount(),K.byteStride,Q);break;default:throw new Error("Invalid filter.")}if(K.min=Z.getMin([]),K.max=Z.getMax([]),Z.getNormalized())K.min=K.min.map((G)=>bk(G,Z.getComponentType())),K.max=K.max.map((G)=>bk(G,Z.getComponentType()));if(K.normalized)K.min=K.min.map((G)=>Jt(G,K.componentType)),K.max=K.max.map((G)=>Jt(G,K.componentType))}else if(K.byteStride%4)K.array=Vk1(K.array,Z.getElementSize()),K.byteStride=K.array.byteLength/Z.getCount();return K}function Gk1(Z){let J=Z.getComponentType(),X=Z.getArray(),Y=new Float32Array(X.length);for(let $=0;$<X.length;$++)Y[$]=bk(X[$],J);return Y}function Vk1(Z,J){let Y=g6.padNumber(Z.BYTES_PER_ELEMENT*J)/Z.BYTES_PER_ELEMENT,$=Z.length/J,Q=new Z.constructor($*Y);for(let K=0;K*J<Z.length;K++)for(let W=0;W<J;W++)Q[K*Y+W]=Z[K*J+W];return Q}function zk1(Z){let J=new Float32Array(Z.length*4/3);for(let X=0,Y=Z.length/3;X<Y;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 Hk1(Z,J){if(J===_X.BufferViewUsage.ELEMENT_ARRAY_BUFFER)return Z.listParents().some((Y)=>{return Y instanceof IX&&Y.getMode()===IX.Mode.TRIANGLES})?PW.TRIANGLES:PW.INDICES;return PW.ATTRIBUTES}function Fk1(Z,J){let X=J.getGraph().listParentEdges(Z).filter((Y)=>!(Y.getParent()instanceof Rw));for(let Y of X){let $=Y.getName(),Q=Y.getAttributes().key||"",K=Y.getParent().propertyType===o.PRIMITIVE_TARGET;if($==="indices")return{filter:B8.NONE};if($==="attributes"){if(Q==="POSITION")return{filter:B8.NONE};if(Q==="TEXCOORD_0")return{filter:B8.NONE};if(Q.startsWith("JOINTS_"))return{filter:B8.NONE};if(Q.startsWith("WEIGHTS_"))return{filter:B8.NONE};if(Q==="NORMAL"||Q==="TANGENT")return K?{filter:B8.NONE}:{filter:B8.OCTAHEDRAL,bits:8}}if($==="output"){let W=qt(Z);if(W==="rotation")return{filter:B8.QUATERNION,bits:16};if(W==="translation")return{filter:B8.EXPONENTIAL,bits:12};if(W==="scale")return{filter:B8.EXPONENTIAL,bits:12};return{filter:B8.NONE}}if($==="input")return{filter:B8.NONE};if($==="inverseBindMatrices")return{filter:B8.NONE}}return{filter:B8.NONE}}function qt(Z){for(let J of Z.listParents()){if(!(J instanceof jW))continue;for(let X of J.listParents()){if(!(X instanceof Dz))continue;return X.getTargetPath()}}return null}var Xt={method:Iz.QUANTIZE};class vz extends v1{constructor(...Z){super(...Z);this.extensionName=N6,this.prereadTypes=[o.BUFFER,o.PRIMITIVE],this.prewriteTypes=[o.BUFFER,o.ACCESSOR],this.readDependencies=["meshopt.decoder"],this.writeDependencies=["meshopt.encoder"],this._decoder=null,this._decoderFallbackBufferMap=new Map,this._encoder=null,this._encoderOptions=Xt,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=KJ({},Xt,Z),this}preread(Z,J){if(!this._decoder){if(!this.isRequired())return this;throw new Error(`[${N6}] Please install extension dependency, "meshopt.decoder".`)}if(!this._decoder.supported){if(!this.isRequired())return this;throw new Error(`[${N6}]: Missing WASM support.`)}if(J===o.BUFFER)this._prereadBuffers(Z);else if(J===o.PRIMITIVE)this._prereadPrimitives(Z);return this}_prereadBuffers(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach((Y,$)=>{if(!Y.extensions||!Y.extensions[N6])return;let Q=Y.extensions[N6],K=Q.byteOffset||0,W=Q.byteLength||0,G=Q.count,V=Q.byteStride,z=new Uint8Array(G*V),F=J.json.buffers[Q.buffer],H=F.uri?J.resources[F.uri]:J.resources[kk],q=g6.toView(H,K,W);this._decoder.decodeGltfBuffer(z,G,V,q,Q.mode,Q.filter),Z.bufferViews[$]=z})}_prereadPrimitives(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach((Y)=>{if(!Y.extensions||!Y.extensions[N6])return;let $=Y.extensions[N6],Q=Z.buffers[$.buffer],K=Z.buffers[Y.buffer],W=J.json.buffers[Y.buffer];if($k1(W))this._decoderFallbackBufferMap.set(K,Q)})}read(Z){if(!this.isRequired())return this;for(let[J,X]of this._decoderFallbackBufferMap){for(let Y of J.listParents())if(Y instanceof C0)Y.swap(J,X);J.dispose()}return this}prewrite(Z,J){if(J===o.ACCESSOR)this._prewriteAccessors(Z);else if(J===o.BUFFER)this._prewriteBuffers(Z);return this}_prewriteAccessors(Z){let J=Z.jsonDoc.json,X=this._encoder,Y=this._encoderOptions,$=this.document.getGraph(),Q=this.document.createBuffer(),K=this.document.getRoot().listBuffers().indexOf(Q),W=1,G=new Map,V=(z)=>{for(let F of $.listParents(z)){if(F.propertyType===o.ROOT)continue;let H=G.get(z);if(H===void 0)G.set(z,H=W++);return H}return-1};this._encoderFallbackBuffer=Q,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={};for(let z of this.document.getRoot().listAccessors()){if(qt(z)==="weights")continue;if(z.getSparse())continue;let F=Z.getAccessorUsage(z),H=Z.accessorUsageGroupedByParent.has(F)?V(z):null,q=Hk1(z,F),U=Y.method===Iz.FILTER?Fk1(z,this.document):{filter:B8.NONE},B=Wk1(z,X,q,U),{array:L,byteStride:w}=B,M=z.getBuffer();if(!M)throw new Error(`${N6}: Missing buffer for accessor.`);let N=this.document.getRoot().listBuffers().indexOf(M),R=[F,H,q,U.filter,w,N].join(":"),P=this._encoderBufferViews[R],D=this._encoderBufferViewData[R],C=this._encoderBufferViewAccessors[R];if(!P||!D)C=this._encoderBufferViewAccessors[R]=[],D=this._encoderBufferViewData[R]=[],P=this._encoderBufferViews[R]={buffer:K,target:_X.USAGE_TO_TARGET[F],byteOffset:0,byteLength:0,byteStride:F===_X.BufferViewUsage.ARRAY_BUFFER?w:void 0,extensions:{[N6]:{buffer:N,byteOffset:0,byteLength:0,mode:q,filter:U.filter!==B8.NONE?U.filter:void 0,byteStride:w,count:0}}};let T=Z.createAccessorDef(z);if(T.componentType=B.componentType,T.normalized=B.normalized,T.byteOffset=P.byteLength,T.min&&B.min)T.min=B.min;if(T.max&&B.max)T.max=B.max;Z.accessorIndexMap.set(z,J.accessors.length),J.accessors.push(T),C.push(T),D.push(new Uint8Array(L.buffer,L.byteOffset,L.byteLength)),P.byteLength+=L.byteLength,P.extensions.EXT_meshopt_compression.count+=z.getCount()}}_prewriteBuffers(Z){let J=this._encoder;for(let X in this._encoderBufferViews){let Y=this._encoderBufferViews[X],$=this._encoderBufferViewData[X],Q=this.document.getRoot().listBuffers()[Y.extensions[N6].buffer],K=Z.otherBufferViews.get(Q)||[],{count:W,byteStride:G,mode:V}=Y.extensions[N6],z=g6.concat($),F=J.encodeGltfBuffer(z,W,G,V),H=g6.pad(F);Y.extensions[N6].byteLength=F.byteLength,$.length=0,$.push(H),K.push(H),Z.otherBufferViews.set(Q,K)}}write(Z){let J=0;for(let Q in this._encoderBufferViews){let K=this._encoderBufferViews[Q],W=this._encoderBufferViewData[Q][0],G=Z.otherBufferViewsIndexMap.get(W),V=this._encoderBufferViewAccessors[Q];for(let q of V)q.bufferView=G;let z=Z.jsonDoc.json.bufferViews[G],F=z.byteOffset||0;Object.assign(z,K),z.byteOffset=J;let H=z.extensions[N6];H.byteOffset=F,J+=g6.padNumber(K.byteLength)}let X=this._encoderFallbackBuffer,Y=Z.bufferIndexMap.get(X),$=Z.jsonDoc.json.buffers[Y];return $.byteLength=J,$.extensions={[N6]:{fallback:!0}},X.dispose(),this}}vz.EXTENSION_NAME=N6;vz.EncoderMethod=Iz;class Ut{match(Z){return Z.length>=12&&g6.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=Yt(J,0);if(!X)return null;let Y=X.end;while(X=Yt(J,Y))if(X.type==="meta")Y=X.start+4;else if(X.type==="iprp"||X.type==="ipco")Y=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 Y=X.end;return null}getChannels(Z){return 4}}class Tw extends v1{constructor(...Z){super(...Z);this.extensionName=kz,this.prereadTypes=[o.TEXTURE]}static register(){a4.registerFormat("image/avif",new Ut)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[kz])X.source=X.extensions[kz].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 Y=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===Y)Q.extensions=Q.extensions||{},Q.extensions[kz]={source:Q.source},delete Q.source})}}),this}}Tw.EXTENSION_NAME=kz;function Yt(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:g6.decodeText(new Uint8Array(Z.buffer,Z.byteOffset+J+4,4)),start:J+8,end:J+X}}class Bt{match(Z){return Z.length>=12&&Z[8]===87&&Z[9]===69&&Z[10]===66&&Z[11]===80}getSize(Z){let J=g6.decodeText(Z.slice(0,4)),X=g6.decodeText(Z.slice(8,12));if(J!=="RIFF"||X!=="WEBP")return null;let Y=new DataView(Z.buffer,Z.byteOffset),$=12;while($<Y.byteLength){let Q=g6.decodeText(new Uint8Array([Y.getUint8($),Y.getUint8($+1),Y.getUint8($+2),Y.getUint8($+3)])),K=Y.getUint32($+4,!0);if(Q==="VP8 "){let W=Y.getInt16($+14,!0)&16383,G=Y.getInt16($+16,!0)&16383;return[W,G]}else if(Q==="VP8L"){let W=Y.getUint8($+9),G=Y.getUint8($+10),V=Y.getUint8($+11),z=Y.getUint8($+12),F=1+((G&63)<<8|W),H=1+((z&15)<<10|V<<2|(G&192)>>6);return[F,H]}$+=8+K+K%2}return null}getChannels(Z){return 4}}class kw extends v1{constructor(...Z){super(...Z);this.extensionName=Tz,this.prereadTypes=[o.TEXTURE]}static register(){a4.registerFormat("image/webp",new Bt)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[Tz])X.source=X.extensions[Tz].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 Y=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===Y)Q.extensions=Q.extensions||{},Q.extensions[Tz]={source:Q.source},delete Q.source})}}),this}}kw.EXTENSION_NAME=Tz;var i8,Lt,wt;function qk1(Z,J){let X=new i8.DecoderBuffer;try{if(X.Init(J,J.length),Z.GetEncodedGeometryType(X)!==i8.TRIANGULAR_MESH)throw new Error(`[${Q8}] Unknown geometry type.`);let $=new i8.Mesh;if(!Z.DecodeBufferToMesh(X,$).ok()||$.ptr===0)throw new Error(`[${Q8}] Decoding failure.`);return $}finally{i8.destroy(X)}}function Uk1(Z,J){let Y=J.num_faces()*3,$,Q;if(J.num_points()<=65534){let K=Y*Uint16Array.BYTES_PER_ELEMENT;$=i8._malloc(K),Z.GetTrianglesUInt16Array(J,K,$),Q=new Uint16Array(i8.HEAPU16.buffer,$,Y).slice()}else{let K=Y*Uint32Array.BYTES_PER_ELEMENT;$=i8._malloc(K),Z.GetTrianglesUInt32Array(J,K,$),Q=new Uint32Array(i8.HEAPU32.buffer,$,Y).slice()}return i8._free($),Q}function Bk1(Z,J,X,Y){let $=wt[Y.componentType],Q=Lt[Y.componentType],K=X.num_components(),G=J.num_points()*K,V=G*Q.BYTES_PER_ELEMENT,z=i8._malloc(V);Z.GetAttributeDataArrayForAllPoints(J,X,$,V,z);let F=new Q(i8.HEAPF32.buffer,z,G).slice();return i8._free(z),F}function Lk1(Z){i8=Z,Lt={[C0.ComponentType.FLOAT]:Float32Array,[C0.ComponentType.UNSIGNED_INT]:Uint32Array,[C0.ComponentType.UNSIGNED_SHORT]:Uint16Array,[C0.ComponentType.UNSIGNED_BYTE]:Uint8Array,[C0.ComponentType.SHORT]:Int16Array,[C0.ComponentType.BYTE]:Int8Array},wt={[C0.ComponentType.FLOAT]:i8.DT_FLOAT32,[C0.ComponentType.UNSIGNED_INT]:i8.DT_UINT32,[C0.ComponentType.UNSIGNED_SHORT]:i8.DT_UINT16,[C0.ComponentType.UNSIGNED_BYTE]:i8.DT_UINT8,[C0.ComponentType.SHORT]:i8.DT_INT16,[C0.ComponentType.BYTE]:i8.DT_INT8}}var n9,_z;(function(Z){Z[Z.EDGEBREAKER=1]="EDGEBREAKER",Z[Z.SEQUENTIAL=0]="SEQUENTIAL"})(_z||(_z={}));var o9;(function(Z){Z.POSITION="POSITION",Z.NORMAL="NORMAL",Z.COLOR="COLOR",Z.TEX_COORD="TEX_COORD",Z.GENERIC="GENERIC"})(o9||(o9={}));var Ot={[o9.POSITION]:14,[o9.NORMAL]:10,[o9.COLOR]:8,[o9.TEX_COORD]:12,[o9.GENERIC]:12},$t={decodeSpeed:5,encodeSpeed:5,method:_z.EDGEBREAKER,quantizationBits:Ot,quantizationVolume:"mesh"};function wk1(Z){n9=Z}function Ok1(Z,J=$t){let X=KJ({},$t,J);X.quantizationBits=KJ({},Ot,J.quantizationBits);let Y=new n9.MeshBuilder,$=new n9.Mesh,Q=new n9.ExpertEncoder($),K={},W=new n9.DracoInt8Array,G=Z.listTargets().length>0,V=!1;for(let B of Z.listSemantics()){let L=Z.getAttribute(B);if(L.getSparse()){V=!0;continue}let w=Mk1(B),M=Nk1(Y,L.getComponentType(),$,n9[w],L.getCount(),L.getElementSize(),L.getArray());if(M===-1)throw new Error(`Error compressing "${B}" attribute.`);if(K[B]=M,X.quantizationVolume==="mesh"||B!=="POSITION")Q.SetAttributeQuantization(M,X.quantizationBits[w]);else if(typeof X.quantizationVolume==="object"){let{quantizationVolume:N}=X,R=Math.max(N.max[0]-N.min[0],N.max[1]-N.min[1],N.max[2]-N.min[2]);Q.SetAttributeExplicitQuantization(M,X.quantizationBits[w],L.getElementSize(),N.min,R)}else throw new Error("Invalid quantization volume state.")}let z=Z.getIndices();if(!z)throw new Dw("Primitive must have indices.");if(Y.AddFacesToMesh($,z.getCount()/3,z.getArray()),Q.SetSpeedOptions(X.encodeSpeed,X.decodeSpeed),Q.SetTrackEncodedProperties(!0),X.method===_z.SEQUENTIAL||G||V)Q.SetEncodingMethod(n9.MESH_SEQUENTIAL_ENCODING);else Q.SetEncodingMethod(n9.MESH_EDGEBREAKER_ENCODING);let F=Q.EncodeToDracoBuffer(!(G||V),W);if(F<=0)throw new Dw("Error applying Draco compression.");let H=new Uint8Array(F);for(let B=0;B<F;++B)H[B]=W.GetValue(B);let q=Q.GetNumberOfEncodedPoints(),U=Q.GetNumberOfEncodedFaces()*3;return n9.destroy(W),n9.destroy($),n9.destroy(Y),n9.destroy(Q),{numVertices:q,numIndices:U,data:H,attributeIDs:K}}function Mk1(Z){if(Z==="POSITION")return o9.POSITION;else if(Z==="NORMAL")return o9.NORMAL;else if(Z.startsWith("COLOR_"))return o9.COLOR;else if(Z.startsWith("TEXCOORD_"))return o9.TEX_COORD;return o9.GENERIC}function Nk1(Z,J,X,Y,$,Q,K){switch(J){case C0.ComponentType.UNSIGNED_BYTE:return Z.AddUInt8Attribute(X,Y,$,Q,K);case C0.ComponentType.BYTE:return Z.AddInt8Attribute(X,Y,$,Q,K);case C0.ComponentType.UNSIGNED_SHORT:return Z.AddUInt16Attribute(X,Y,$,Q,K);case C0.ComponentType.SHORT:return Z.AddInt16Attribute(X,Y,$,Q,K);case C0.ComponentType.UNSIGNED_INT:return Z.AddUInt32Attribute(X,Y,$,Q,K);case C0.ComponentType.FLOAT:return Z.AddFloatAttribute(X,Y,$,Q,K);default:throw new Error(`Unexpected component type, "${J}".`)}}class Dw extends Error{}class Sz extends v1{constructor(...Z){super(...Z);this.extensionName=Q8,this.prereadTypes=[o.PRIMITIVE],this.prewriteTypes=[o.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,Lk1(this._decoderModule);if(Z==="draco3d.encoder")this._encoderModule=J,wk1(this._encoderModule);return this}setEncoderOptions(Z){return this._encoderOptions=Z,this}preread(Z){if(!this._decoderModule)throw new Error(`[${Q8}] Please install extension dependency, "draco3d.decoder".`);let J=this.document.getLogger(),X=Z.jsonDoc,Y=new Map;try{let $=X.json.meshes||[];for(let Q of $)for(let K of Q.primitives){if(!K.extensions||!K.extensions[Q8])continue;let W=K.extensions[Q8],[G,V]=Y.get(W.bufferView)||[];if(!V||!G){let z=X.json.bufferViews[W.bufferView],F=X.json.buffers[z.buffer],H=F.uri?X.resources[F.uri]:X.resources[kk],q=z.byteOffset||0,U=z.byteLength,B=g6.toView(H,q,U);G=new this._decoderModule.Decoder,V=qk1(G,B),Y.set(W.bufferView,[G,V]),J.debug(`[${Q8}] Decompressed ${B.byteLength} bytes.`)}for(let z in W.attributes){let F=Z.jsonDoc.json.accessors[K.attributes[z]],H=G.GetAttributeByUniqueId(V,W.attributes[z]),q=Bk1(G,V,H,F);Z.accessors[K.attributes[z]].setArray(q)}if(K.indices!==void 0)Z.accessors[K.indices].setArray(Uk1(G,V))}}finally{for(let[$,Q]of Array.from(Y.values()))this._decoderModule.destroy($),this._decoderModule.destroy(Q)}return this}read(Z){return this}prewrite(Z,J){if(!this._encoderModule)throw new Error(`[${Q8}] Please install extension dependency, "draco3d.encoder".`);let X=this.document.getLogger();X.debug(`[${Q8}] Compression options: ${JSON.stringify(this._encoderOptions)}`);let Y=Rk1(this.document),$=new Map,Q="mesh";if(this._encoderOptions.quantizationVolume==="scene")if(this.document.getRoot().listScenes().length!==1)X.warn(`[${Q8}]: quantizationVolume=scene requires exactly 1 scene.`);else Q=ir(this.document.getRoot().listScenes().pop());for(let K of Array.from(Y.keys())){let W=Y.get(K);if(!W)throw new Error("Unexpected primitive.");if($.has(W)){$.set(W,$.get(W));continue}let G=K.getIndices(),V=Z.jsonDoc.json.accessors,z;try{z=Ok1(K,KJ({},this._encoderOptions,{quantizationVolume:Q}))}catch(q){if(q instanceof Dw){X.warn(`[${Q8}]: ${q.message} Skipping primitive compression.`);continue}throw q}$.set(W,z);let F=Z.createAccessorDef(G);if(F.count=z.numIndices,Z.accessorIndexMap.set(G,V.length),V.push(F),z.numVertices>65534&&C0.getComponentSize(F.componentType)<=2)F.componentType=C0.ComponentType.UNSIGNED_INT;else if(z.numVertices>254&&C0.getComponentSize(F.componentType)<=1)F.componentType=C0.ComponentType.UNSIGNED_SHORT;for(let q of K.listSemantics()){let U=K.getAttribute(q);if(z.attributeIDs[q]===void 0)continue;let B=Z.createAccessorDef(U);B.count=z.numVertices,Z.accessorIndexMap.set(U,V.length),V.push(B)}let H=K.getAttribute("POSITION").getBuffer()||this.document.getRoot().listBuffers()[0];if(!Z.otherBufferViews.has(H))Z.otherBufferViews.set(H,[]);Z.otherBufferViews.get(H).push(z.data)}return X.debug(`[${Q8}] Compressed ${Y.size} primitives.`),Z.extensionData[Q8]={primitiveHashMap:Y,primitiveEncodingMap:$},this}write(Z){let J=Z.extensionData[Q8];for(let X of this.document.getRoot().listMeshes()){let Y=Z.jsonDoc.json.meshes[Z.meshIndexMap.get(X)];for(let $=0;$<X.listPrimitives().length;$++){let Q=X.listPrimitives()[$],K=Y.primitives[$],W=J.primitiveHashMap.get(Q);if(!W)continue;let G=J.primitiveEncodingMap.get(W);if(!G)continue;K.extensions=K.extensions||{},K.extensions[Q8]={bufferView:Z.otherBufferViewsIndexMap.get(G.data),attributes:G.attributeIDs}}}if(!J.primitiveHashMap.size){let X=Z.jsonDoc.json;X.extensionsUsed=(X.extensionsUsed||[]).filter((Y)=>Y!==Q8),X.extensionsRequired=(X.extensionsRequired||[]).filter((Y)=>Y!==Q8)}return this}}Sz.EXTENSION_NAME=Q8;Sz.EncoderMethod=_z;function Rk1(Z){let J=Z.getLogger(),X=new Set,Y=new Set,$=0,Q=0;for(let F of Z.getRoot().listMeshes())for(let H of F.listPrimitives())if(!H.getIndices())Y.add(H),$++;else if(H.getMode()!==IX.Mode.TRIANGLES)Y.add(H),Q++;else X.add(H);if($>0)J.warn(`[${Q8}] Skipping Draco compression of ${$} non-indexed primitives.`);if(Q>0)J.warn(`[${Q8}] Skipping Draco compression of ${Q} non-TRIANGLES primitives.`);let K=Z.getRoot().listAccessors(),W=new Map;for(let F=0;F<K.length;F++)W.set(K[F],F);let G=new Map,V=new Set,z=new Map;for(let F of Array.from(X)){let H=Qt(F,W);if(V.has(H)){z.set(F,H);continue}if(G.has(F.getIndices())){let q=F.getIndices(),U=q.clone();W.set(U,Z.getRoot().listAccessors().length-1),F.swap(q,U)}for(let q of F.listAttributes())if(G.has(q)){let U=q.clone();W.set(U,Z.getRoot().listAccessors().length-1),F.swap(q,U)}H=Qt(F,W),V.add(H),z.set(F,H),G.set(F.getIndices(),H);for(let q of F.listAttributes())G.set(q,H)}for(let F of Array.from(G.keys())){let H=new Set(F.listParents().map((q)=>q.propertyType));if(H.size!==2||!H.has(o.PRIMITIVE)||!H.has(o.ROOT))throw new Error(`[${Q8}] Compressed accessors must only be used as indices or vertex attributes.`)}for(let F of Array.from(X)){let H=z.get(F),q=F.getIndices();if(G.get(q)!==H||F.listAttributes().some((U)=>G.get(U)!==H))throw new Error(`[${Q8}] Draco primitives must share all, or no, accessors.`)}for(let F of Array.from(Y)){let H=F.getIndices();if(G.has(H)||F.listAttributes().some((q)=>G.has(q)))throw new Error(`[${Q8}] Accessor cannot be shared by compressed and uncompressed primitives.`)}return z}function Qt(Z,J){let X=[],Y=Z.getIndices();X.push(J.get(Y));for(let $ of Z.listAttributes())X.push(J.get($));return X.sort().join("|")}class CW extends t1{init(){this.extensionName=a9,this.propertyType="Light",this.parentTypes=[o.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{color:[1,1,1],intensity:1,type:CW.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)}}CW.EXTENSION_NAME=a9;CW.Type={POINT:"point",SPOT:"spot",DIRECTIONAL:"directional"};class mk extends v1{constructor(...Z){super(...Z);this.extensionName=a9}createLight(Z=""){return new CW(this.document.getGraph(),Z)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[a9])return this;let $=(J.json.extensions[a9].lights||[]).map((Q)=>{var K,W;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(((K=Q.spot)==null?void 0:K.innerConeAngle)!==void 0)G.setInnerConeAngle(Q.spot.innerConeAngle);if(((W=Q.spot)==null?void 0:W.outerConeAngle)!==void 0)G.setOuterConeAngle(Q.spot.outerConeAngle);return G});return J.json.nodes.forEach((Q,K)=>{if(!Q.extensions||!Q.extensions[a9])return;let W=Q.extensions[a9];Z.nodes[K].setExtension(a9,$[W.light])}),this}write(Z){let J=Z.jsonDoc;if(this.properties.size===0)return this;let X=[],Y=new Map;for(let $ of this.properties){let Q=$,K={type:Q.getType()};if(!U8.eq(Q.getColor(),[1,1,1]))K.color=Q.getColor();if(Q.getIntensity()!==1)K.intensity=Q.getIntensity();if(Q.getRange()!=null)K.range=Q.getRange();if(Q.getName())K.name=Q.getName();if(Q.getType()===CW.Type.SPOT)K.spot={innerConeAngle:Q.getInnerConeAngle(),outerConeAngle:Q.getOuterConeAngle()};X.push(K),Y.set(Q,X.length-1)}return this.document.getRoot().listNodes().forEach(($)=>{let Q=$.getExtension(a9);if(Q){let K=Z.nodeIndexMap.get($),W=J.json.nodes[K];W.extensions=W.extensions||{},W.extensions[a9]={light:Y.get(Q)}}}),J.json.extensions=J.json.extensions||{},J.json.extensions[a9]={lights:X},this}}mk.EXTENSION_NAME=a9;var{R:jk1,G:Dk1,B:Pk1}=z9;class uk extends t1{init(){this.extensionName=nZ,this.propertyType="Anisotropy",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{anisotropyStrength:0,anisotropyRotation:0,anisotropyTexture:null,anisotropyTextureInfo:new E1(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:jk1|Dk1|Pk1})}}uk.EXTENSION_NAME=nZ;class dk extends v1{constructor(...Z){super(...Z);this.extensionName=nZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createAnisotropy(){return new uk(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[nZ]){let K=this.createAnisotropy();Z.materials[Q].setExtension(nZ,K);let W=$.extensions[nZ];if(W.anisotropyStrength!==void 0)K.setAnisotropyStrength(W.anisotropyStrength);if(W.anisotropyRotation!==void 0)K.setAnisotropyRotation(W.anisotropyRotation);if(W.anisotropyTexture!==void 0){let G=W.anisotropyTexture,V=Z.textures[Y[G.index].source];K.setAnisotropyTexture(V),Z.setTextureInfo(K.getAnisotropyTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(nZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[nZ]={};if(Y.getAnisotropyStrength()>0)K.anisotropyStrength=Y.getAnisotropyStrength();if(Y.getAnisotropyRotation()!==0)K.anisotropyRotation=Y.getAnisotropyRotation();if(Y.getAnisotropyTexture()){let W=Y.getAnisotropyTexture(),G=Y.getAnisotropyTextureInfo();K.anisotropyTexture=Z.createTextureInfoDef(W,G)}}}),this}}dk.EXTENSION_NAME=nZ;var{R:Kt,G:Wt,B:Ck1}=z9;class ck extends t1{init(){this.extensionName=aZ,this.propertyType="Clearcoat",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{clearcoatFactor:0,clearcoatTexture:null,clearcoatTextureInfo:new E1(this.graph,"clearcoatTextureInfo"),clearcoatRoughnessFactor:0,clearcoatRoughnessTexture:null,clearcoatRoughnessTextureInfo:new E1(this.graph,"clearcoatRoughnessTextureInfo"),clearcoatNormalScale:1,clearcoatNormalTexture:null,clearcoatNormalTextureInfo:new E1(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:Kt})}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:Wt})}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:Kt|Wt|Ck1})}}ck.EXTENSION_NAME=aZ;class lk extends v1{constructor(...Z){super(...Z);this.extensionName=aZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createClearcoat(){return new ck(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[aZ]){let K=this.createClearcoat();Z.materials[Q].setExtension(aZ,K);let W=$.extensions[aZ];if(W.clearcoatFactor!==void 0)K.setClearcoatFactor(W.clearcoatFactor);if(W.clearcoatRoughnessFactor!==void 0)K.setClearcoatRoughnessFactor(W.clearcoatRoughnessFactor);if(W.clearcoatTexture!==void 0){let G=W.clearcoatTexture,V=Z.textures[Y[G.index].source];K.setClearcoatTexture(V),Z.setTextureInfo(K.getClearcoatTextureInfo(),G)}if(W.clearcoatRoughnessTexture!==void 0){let G=W.clearcoatRoughnessTexture,V=Z.textures[Y[G.index].source];K.setClearcoatRoughnessTexture(V),Z.setTextureInfo(K.getClearcoatRoughnessTextureInfo(),G)}if(W.clearcoatNormalTexture!==void 0){let G=W.clearcoatNormalTexture,V=Z.textures[Y[G.index].source];if(K.setClearcoatNormalTexture(V),Z.setTextureInfo(K.getClearcoatNormalTextureInfo(),G),G.scale!==void 0)K.setClearcoatNormalScale(G.scale)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(aZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[aZ]={clearcoatFactor:Y.getClearcoatFactor(),clearcoatRoughnessFactor:Y.getClearcoatRoughnessFactor()};if(Y.getClearcoatTexture()){let W=Y.getClearcoatTexture(),G=Y.getClearcoatTextureInfo();K.clearcoatTexture=Z.createTextureInfoDef(W,G)}if(Y.getClearcoatRoughnessTexture()){let W=Y.getClearcoatRoughnessTexture(),G=Y.getClearcoatRoughnessTextureInfo();K.clearcoatRoughnessTexture=Z.createTextureInfoDef(W,G)}if(Y.getClearcoatNormalTexture()){let W=Y.getClearcoatNormalTexture(),G=Y.getClearcoatNormalTextureInfo();if(K.clearcoatNormalTexture=Z.createTextureInfoDef(W,G),Y.getClearcoatNormalScale()!==1)K.clearcoatNormalTexture.scale=Y.getClearcoatNormalScale()}}}),this}}lk.EXTENSION_NAME=aZ;var{R:Tk1,G:kk1,B:Ek1,A:Ik1}=z9;class pk extends t1{init(){this.extensionName=sZ,this.propertyType="DiffuseTransmission",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseTransmissionFactor:0,diffuseTransmissionTexture:null,diffuseTransmissionTextureInfo:new E1(this.graph,"diffuseTransmissionTextureInfo"),diffuseTransmissionColorFactor:[1,1,1],diffuseTransmissionColorTexture:null,diffuseTransmissionColorTextureInfo:new E1(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:Ik1})}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:Tk1|kk1|Ek1})}}pk.EXTENSION_NAME=sZ;class ik extends v1{constructor(...Z){super(...Z);this.extensionName=sZ}createDiffuseTransmission(){return new pk(this.document.getGraph())}read(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[sZ]){let K=this.createDiffuseTransmission();Z.materials[Q].setExtension(sZ,K);let W=$.extensions[sZ];if(W.diffuseTransmissionFactor!==void 0)K.setDiffuseTransmissionFactor(W.diffuseTransmissionFactor);if(W.diffuseTransmissionColorFactor!==void 0)K.setDiffuseTransmissionColorFactor(W.diffuseTransmissionColorFactor);if(W.diffuseTransmissionTexture!==void 0){let G=W.diffuseTransmissionTexture,V=Z.textures[Y[G.index].source];K.setDiffuseTransmissionTexture(V),Z.setTextureInfo(K.getDiffuseTransmissionTextureInfo(),G)}if(W.diffuseTransmissionColorTexture!==void 0){let G=W.diffuseTransmissionColorTexture,V=Z.textures[Y[G.index].source];K.setDiffuseTransmissionColorTexture(V),Z.setTextureInfo(K.getDiffuseTransmissionColorTextureInfo(),G)}}}),this}write(Z){let J=Z.jsonDoc;for(let X of this.document.getRoot().listMaterials()){let Y=X.getExtension(sZ);if(!Y)continue;let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[sZ]={diffuseTransmissionFactor:Y.getDiffuseTransmissionFactor(),diffuseTransmissionColorFactor:Y.getDiffuseTransmissionColorFactor()};if(Y.getDiffuseTransmissionTexture()){let W=Y.getDiffuseTransmissionTexture(),G=Y.getDiffuseTransmissionTextureInfo();K.diffuseTransmissionTexture=Z.createTextureInfoDef(W,G)}if(Y.getDiffuseTransmissionColorTexture()){let W=Y.getDiffuseTransmissionColorTexture(),G=Y.getDiffuseTransmissionColorTextureInfo();K.diffuseTransmissionColorTexture=Z.createTextureInfoDef(W,G)}}return this}}ik.EXTENSION_NAME=sZ;class nk extends t1{init(){this.extensionName=oZ,this.propertyType="Dispersion",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{dispersion:0})}getDispersion(){return this.get("dispersion")}setDispersion(Z){return this.set("dispersion",Z)}}nk.EXTENSION_NAME=oZ;class ak extends v1{constructor(...Z){super(...Z);this.extensionName=oZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createDispersion(){return new nk(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((Y,$)=>{if(Y.extensions&&Y.extensions[oZ]){let Q=this.createDispersion();Z.materials[$].setExtension(oZ,Q);let K=Y.extensions[oZ];if(K.dispersion!==void 0)Q.setDispersion(K.dispersion)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(oZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{},Q.extensions[oZ]={dispersion:Y.getDispersion()}}}),this}}ak.EXTENSION_NAME=oZ;class sk extends t1{init(){this.extensionName=rZ,this.propertyType="EmissiveStrength",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{emissiveStrength:1})}getEmissiveStrength(){return this.get("emissiveStrength")}setEmissiveStrength(Z){return this.set("emissiveStrength",Z)}}sk.EXTENSION_NAME=rZ;class ok extends v1{constructor(...Z){super(...Z);this.extensionName=rZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createEmissiveStrength(){return new sk(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((Y,$)=>{if(Y.extensions&&Y.extensions[rZ]){let Q=this.createEmissiveStrength();Z.materials[$].setExtension(rZ,Q);let K=Y.extensions[rZ];if(K.emissiveStrength!==void 0)Q.setEmissiveStrength(K.emissiveStrength)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(rZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{},Q.extensions[rZ]={emissiveStrength:Y.getEmissiveStrength()}}}),this}}ok.EXTENSION_NAME=rZ;class rk extends t1{init(){this.extensionName=tZ,this.propertyType="IOR",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{ior:1.5})}getIOR(){return this.get("ior")}setIOR(Z){return this.set("ior",Z)}}rk.EXTENSION_NAME=tZ;class Ew extends v1{constructor(...Z){super(...Z);this.extensionName=tZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createIOR(){return new rk(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((Y,$)=>{if(Y.extensions&&Y.extensions[tZ]){let Q=this.createIOR();Z.materials[$].setExtension(tZ,Q);let K=Y.extensions[tZ];if(K.ior!==void 0)Q.setIOR(K.ior)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(tZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{},Q.extensions[tZ]={ior:Y.getIOR()}}}),this}}Ew.EXTENSION_NAME=tZ;var{R:_k1,G:vk1}=z9;class tk extends t1{init(){this.extensionName=eZ,this.propertyType="Iridescence",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{iridescenceFactor:0,iridescenceTexture:null,iridescenceTextureInfo:new E1(this.graph,"iridescenceTextureInfo"),iridescenceIOR:1.3,iridescenceThicknessMinimum:100,iridescenceThicknessMaximum:400,iridescenceThicknessTexture:null,iridescenceThicknessTextureInfo:new E1(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:_k1})}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:vk1})}}tk.EXTENSION_NAME=eZ;class ek extends v1{constructor(...Z){super(...Z);this.extensionName=eZ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createIridescence(){return new tk(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[eZ]){let K=this.createIridescence();Z.materials[Q].setExtension(eZ,K);let W=$.extensions[eZ];if(W.iridescenceFactor!==void 0)K.setIridescenceFactor(W.iridescenceFactor);if(W.iridescenceIor!==void 0)K.setIridescenceIOR(W.iridescenceIor);if(W.iridescenceThicknessMinimum!==void 0)K.setIridescenceThicknessMinimum(W.iridescenceThicknessMinimum);if(W.iridescenceThicknessMaximum!==void 0)K.setIridescenceThicknessMaximum(W.iridescenceThicknessMaximum);if(W.iridescenceTexture!==void 0){let G=W.iridescenceTexture,V=Z.textures[Y[G.index].source];K.setIridescenceTexture(V),Z.setTextureInfo(K.getIridescenceTextureInfo(),G)}if(W.iridescenceThicknessTexture!==void 0){let G=W.iridescenceThicknessTexture,V=Z.textures[Y[G.index].source];K.setIridescenceThicknessTexture(V),Z.setTextureInfo(K.getIridescenceThicknessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(eZ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[eZ]={};if(Y.getIridescenceFactor()>0)K.iridescenceFactor=Y.getIridescenceFactor();if(Y.getIridescenceIOR()!==1.3)K.iridescenceIor=Y.getIridescenceIOR();if(Y.getIridescenceThicknessMinimum()!==100)K.iridescenceThicknessMinimum=Y.getIridescenceThicknessMinimum();if(Y.getIridescenceThicknessMaximum()!==400)K.iridescenceThicknessMaximum=Y.getIridescenceThicknessMaximum();if(Y.getIridescenceTexture()){let W=Y.getIridescenceTexture(),G=Y.getIridescenceTextureInfo();K.iridescenceTexture=Z.createTextureInfoDef(W,G)}if(Y.getIridescenceThicknessTexture()){let W=Y.getIridescenceThicknessTexture(),G=Y.getIridescenceThicknessTextureInfo();K.iridescenceThicknessTexture=Z.createTextureInfoDef(W,G)}}}),this}}ek.EXTENSION_NAME=eZ;var{R:Gt,G:Vt,B:zt,A:Ht}=z9;class ZE extends t1{init(){this.extensionName=ZJ,this.propertyType="PBRSpecularGlossiness",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseFactor:[1,1,1,1],diffuseTexture:null,diffuseTextureInfo:new E1(this.graph,"diffuseTextureInfo"),specularFactor:[1,1,1],glossinessFactor:1,specularGlossinessTexture:null,specularGlossinessTextureInfo:new E1(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:Gt|Vt|zt|Ht,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:Gt|Vt|zt|Ht})}}ZE.EXTENSION_NAME=ZJ;class Iw extends v1{constructor(...Z){super(...Z);this.extensionName=ZJ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createPBRSpecularGlossiness(){return new ZE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[ZJ]){let K=this.createPBRSpecularGlossiness();Z.materials[Q].setExtension(ZJ,K);let W=$.extensions[ZJ];if(W.diffuseFactor!==void 0)K.setDiffuseFactor(W.diffuseFactor);if(W.specularFactor!==void 0)K.setSpecularFactor(W.specularFactor);if(W.glossinessFactor!==void 0)K.setGlossinessFactor(W.glossinessFactor);if(W.diffuseTexture!==void 0){let G=W.diffuseTexture,V=Z.textures[Y[G.index].source];K.setDiffuseTexture(V),Z.setTextureInfo(K.getDiffuseTextureInfo(),G)}if(W.specularGlossinessTexture!==void 0){let G=W.specularGlossinessTexture,V=Z.textures[Y[G.index].source];K.setSpecularGlossinessTexture(V),Z.setTextureInfo(K.getSpecularGlossinessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(ZJ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[ZJ]={diffuseFactor:Y.getDiffuseFactor(),specularFactor:Y.getSpecularFactor(),glossinessFactor:Y.getGlossinessFactor()};if(Y.getDiffuseTexture()){let W=Y.getDiffuseTexture(),G=Y.getDiffuseTextureInfo();K.diffuseTexture=Z.createTextureInfoDef(W,G)}if(Y.getSpecularGlossinessTexture()){let W=Y.getSpecularGlossinessTexture(),G=Y.getSpecularGlossinessTextureInfo();K.specularGlossinessTexture=Z.createTextureInfoDef(W,G)}}}),this}}Iw.EXTENSION_NAME=ZJ;var{R:Sk1,G:Ak1,B:xk1,A:hk1}=z9;class JE extends t1{init(){this.extensionName=JJ,this.propertyType="Sheen",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{sheenColorFactor:[0,0,0],sheenColorTexture:null,sheenColorTextureInfo:new E1(this.graph,"sheenColorTextureInfo"),sheenRoughnessFactor:0,sheenRoughnessTexture:null,sheenRoughnessTextureInfo:new E1(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:Sk1|Ak1|xk1,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:hk1})}}JE.EXTENSION_NAME=JJ;class XE extends v1{constructor(...Z){super(...Z);this.extensionName=JJ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createSheen(){return new JE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[JJ]){let K=this.createSheen();Z.materials[Q].setExtension(JJ,K);let W=$.extensions[JJ];if(W.sheenColorFactor!==void 0)K.setSheenColorFactor(W.sheenColorFactor);if(W.sheenRoughnessFactor!==void 0)K.setSheenRoughnessFactor(W.sheenRoughnessFactor);if(W.sheenColorTexture!==void 0){let G=W.sheenColorTexture,V=Z.textures[Y[G.index].source];K.setSheenColorTexture(V),Z.setTextureInfo(K.getSheenColorTextureInfo(),G)}if(W.sheenRoughnessTexture!==void 0){let G=W.sheenRoughnessTexture,V=Z.textures[Y[G.index].source];K.setSheenRoughnessTexture(V),Z.setTextureInfo(K.getSheenRoughnessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(JJ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[JJ]={sheenColorFactor:Y.getSheenColorFactor(),sheenRoughnessFactor:Y.getSheenRoughnessFactor()};if(Y.getSheenColorTexture()){let W=Y.getSheenColorTexture(),G=Y.getSheenColorTextureInfo();K.sheenColorTexture=Z.createTextureInfoDef(W,G)}if(Y.getSheenRoughnessTexture()){let W=Y.getSheenRoughnessTexture(),G=Y.getSheenRoughnessTextureInfo();K.sheenRoughnessTexture=Z.createTextureInfoDef(W,G)}}}),this}}XE.EXTENSION_NAME=JJ;var{R:fk1,G:yk1,B:bk1,A:gk1}=z9;class YE extends t1{init(){this.extensionName=XJ,this.propertyType="Specular",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{specularFactor:1,specularTexture:null,specularTextureInfo:new E1(this.graph,"specularTextureInfo"),specularColorFactor:[1,1,1],specularColorTexture:null,specularColorTextureInfo:new E1(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:gk1})}getSpecularColorTexture(){return this.getRef("specularColorTexture")}getSpecularColorTextureInfo(){return this.getRef("specularColorTexture")?this.getRef("specularColorTextureInfo"):null}setSpecularColorTexture(Z){return this.setRef("specularColorTexture",Z,{channels:fk1|yk1|bk1,isColor:!0})}}YE.EXTENSION_NAME=XJ;class _w extends v1{constructor(...Z){super(...Z);this.extensionName=XJ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createSpecular(){return new YE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[XJ]){let K=this.createSpecular();Z.materials[Q].setExtension(XJ,K);let W=$.extensions[XJ];if(W.specularFactor!==void 0)K.setSpecularFactor(W.specularFactor);if(W.specularColorFactor!==void 0)K.setSpecularColorFactor(W.specularColorFactor);if(W.specularTexture!==void 0){let G=W.specularTexture,V=Z.textures[Y[G.index].source];K.setSpecularTexture(V),Z.setTextureInfo(K.getSpecularTextureInfo(),G)}if(W.specularColorTexture!==void 0){let G=W.specularColorTexture,V=Z.textures[Y[G.index].source];K.setSpecularColorTexture(V),Z.setTextureInfo(K.getSpecularColorTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(XJ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[XJ]={};if(Y.getSpecularFactor()!==1)K.specularFactor=Y.getSpecularFactor();if(!U8.eq(Y.getSpecularColorFactor(),[1,1,1]))K.specularColorFactor=Y.getSpecularColorFactor();if(Y.getSpecularTexture()){let W=Y.getSpecularTexture(),G=Y.getSpecularTextureInfo();K.specularTexture=Z.createTextureInfoDef(W,G)}if(Y.getSpecularColorTexture()){let W=Y.getSpecularColorTexture(),G=Y.getSpecularColorTextureInfo();K.specularColorTexture=Z.createTextureInfoDef(W,G)}}}),this}}_w.EXTENSION_NAME=XJ;var{R:mk1}=z9;class $E extends t1{init(){this.extensionName=YJ,this.propertyType="Transmission",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{transmissionFactor:0,transmissionTexture:null,transmissionTextureInfo:new E1(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:mk1})}}$E.EXTENSION_NAME=YJ;class QE extends v1{constructor(...Z){super(...Z);this.extensionName=YJ,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createTransmission(){return new $E(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[YJ]){let K=this.createTransmission();Z.materials[Q].setExtension(YJ,K);let W=$.extensions[YJ];if(W.transmissionFactor!==void 0)K.setTransmissionFactor(W.transmissionFactor);if(W.transmissionTexture!==void 0){let G=W.transmissionTexture,V=Z.textures[Y[G.index].source];K.setTransmissionTexture(V),Z.setTextureInfo(K.getTransmissionTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(YJ);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[YJ]={transmissionFactor:Y.getTransmissionFactor()};if(Y.getTransmissionTexture()){let W=Y.getTransmissionTexture(),G=Y.getTransmissionTextureInfo();K.transmissionTexture=Z.createTextureInfoDef(W,G)}}}),this}}QE.EXTENSION_NAME=YJ;class KE extends t1{init(){this.extensionName=vX,this.propertyType="Unlit",this.parentTypes=[o.MATERIAL]}}KE.EXTENSION_NAME=vX;class vw extends v1{constructor(...Z){super(...Z);this.extensionName=vX,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createUnlit(){return new KE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((X,Y)=>{if(X.extensions&&X.extensions[vX])Z.materials[Y].setExtension(vX,this.createUnlit())}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{if(X.getExtension(vX)){let Y=Z.materialIndexMap.get(X),$=J.json.materials[Y];$.extensions=$.extensions||{},$.extensions[vX]={}}}),this}}vw.EXTENSION_NAME=vX;class WE extends t1{init(){this.extensionName=u6,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")}}WE.EXTENSION_NAME=u6;class GE extends t1{init(){this.extensionName=u6,this.propertyType="MappingList",this.parentTypes=[o.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")}}GE.EXTENSION_NAME=u6;class Pw extends t1{init(){this.extensionName=u6,this.propertyType="Variant",this.parentTypes=["MappingList"]}}Pw.EXTENSION_NAME=u6;class VE extends v1{constructor(...Z){super(...Z);this.extensionName=u6}createMappingList(){return new GE(this.document.getGraph())}createVariant(Z=""){return new Pw(this.document.getGraph(),Z)}createMapping(){return new WE(this.document.getGraph())}listVariants(){return Array.from(this.properties).filter((Z)=>Z instanceof Pw)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[u6])return this;let $=(J.json.extensions[u6].variants||[]).map((K)=>this.createVariant().setName(K.name||""));return(J.json.meshes||[]).forEach((K,W)=>{let G=Z.meshes[W];(K.primitives||[]).forEach((z,F)=>{if(!z.extensions||!z.extensions[u6])return;let H=this.createMappingList(),q=z.extensions[u6];for(let U of q.mappings){let B=this.createMapping();if(U.material!==void 0)B.setMaterial(Z.materials[U.material]);for(let L of U.variants||[])B.addVariant($[L]);H.addMapping(B)}G.listPrimitives()[F].setExtension(u6,H)})}),this}write(Z){let J=Z.jsonDoc,X=this.listVariants();if(!X.length)return this;let Y=[],$=new Map;for(let Q of X)$.set(Q,Y.length),Y.push(Z.createPropertyDef(Q));for(let Q of this.document.getRoot().listMeshes()){let K=Z.meshIndexMap.get(Q);Q.listPrimitives().forEach((W,G)=>{let V=W.getExtension(u6);if(!V)return;let z=Z.jsonDoc.json.meshes[K].primitives[G],F=V.listMappings().map((H)=>{let q=Z.createPropertyDef(H),U=H.getMaterial();if(U)q.material=Z.materialIndexMap.get(U);return q.variants=H.listVariants().map((B)=>$.get(B)),q});z.extensions=z.extensions||{},z.extensions[u6]={mappings:F}})}return J.json.extensions=J.json.extensions||{},J.json.extensions[u6]={variants:Y},this}}VE.EXTENSION_NAME=u6;var{G:uk1}=z9;class zE extends t1{init(){this.extensionName=$J,this.propertyType="Volume",this.parentTypes=[o.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{thicknessFactor:0,thicknessTexture:null,thicknessTextureInfo:new E1(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:uk1})}getAttenuationDistance(){return this.get("attenuationDistance")}setAttenuationDistance(Z){return this.set("attenuationDistance",Z)}getAttenuationColor(){return this.get("attenuationColor")}setAttenuationColor(Z){return this.set("attenuationColor",Z)}}zE.EXTENSION_NAME=$J;class HE extends v1{constructor(...Z){super(...Z);this.extensionName=$J,this.prereadTypes=[o.MESH],this.prewriteTypes=[o.MESH]}createVolume(){return new zE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[$J]){let K=this.createVolume();Z.materials[Q].setExtension($J,K);let W=$.extensions[$J];if(W.thicknessFactor!==void 0)K.setThicknessFactor(W.thicknessFactor);if(W.attenuationDistance!==void 0)K.setAttenuationDistance(W.attenuationDistance);if(W.attenuationColor!==void 0)K.setAttenuationColor(W.attenuationColor);if(W.thicknessTexture!==void 0){let G=W.thicknessTexture,V=Z.textures[Y[G.index].source];K.setThicknessTexture(V),Z.setTextureInfo(K.getThicknessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension($J);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[$J]={};if(Y.getThicknessFactor()>0)K.thicknessFactor=Y.getThicknessFactor();if(Number.isFinite(Y.getAttenuationDistance()))K.attenuationDistance=Y.getAttenuationDistance();if(!U8.eq(Y.getAttenuationColor(),[1,1,1]))K.attenuationColor=Y.getAttenuationColor();if(Y.getThicknessTexture()){let W=Y.getThicknessTexture(),G=Y.getThicknessTextureInfo();K.thicknessTexture=Z.createTextureInfoDef(W,G)}}}),this}}HE.EXTENSION_NAME=$J;class Az extends v1{constructor(...Z){super(...Z);this.extensionName=Ft}read(Z){return this}write(Z){return this}}Az.EXTENSION_NAME=Ft;class Mt{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=jw(Z);return[J.pixelWidth,J.pixelHeight]}getChannels(Z){let X=jw(Z).dataFormatDescriptor[0];if(X.colorModel===tr)return X.samples.length===2&&(X.samples[1].channelType&15)===15?4:3;else if(X.colorModel===er)return(X.samples[0].channelType&15)===3?4:3;throw new Error(`Unexpected KTX2 colorModel, "${X.colorModel}".`)}getVRAMByteLength(Z){let J=jw(Z),X=this.getChannels(Z)>3,Y=0;for(let $=0;$<J.levels.length;$++){let Q=J.levels[$];if(Q.uncompressedByteLength)Y+=Q.uncompressedByteLength;else{let K=Math.max(1,Math.floor(J.pixelWidth/Math.pow(2,$))),W=Math.max(1,Math.floor(J.pixelHeight/Math.pow(2,$))),G=X?16:8;Y+=K/4*(W/4)*G}}return Y}}class FE extends v1{constructor(...Z){super(...Z);this.extensionName=Ez,this.prereadTypes=[o.TEXTURE]}static register(){a4.registerFormat("image/ktx2",new Mt)}preread(Z){return Z.jsonDoc.json.textures.forEach((J)=>{if(J.extensions&&J.extensions[Ez]){let X=J.extensions[Ez];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 Y=Z.imageIndexMap.get(X);J.json.textures.forEach(($)=>{if($.source===Y)$.extensions=$.extensions||{},$.extensions[Ez]={source:$.source},delete $.source})}}),this}}FE.EXTENSION_NAME=Ez;class qE extends t1{init(){this.extensionName=QJ,this.propertyType="Transform",this.parentTypes=[o.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)}}qE.EXTENSION_NAME=QJ;class UE extends v1{constructor(...Z){super(...Z);this.extensionName=QJ}createTransform(){return new qE(this.document.getGraph())}read(Z){for(let[J,X]of Array.from(Z.textureInfos.entries())){if(!X.extensions||!X.extensions[QJ])continue;let Y=this.createTransform(),$=X.extensions[QJ];if($.offset!==void 0)Y.setOffset($.offset);if($.rotation!==void 0)Y.setRotation($.rotation);if($.scale!==void 0)Y.setScale($.scale);if($.texCoord!==void 0)Y.setTexCoord($.texCoord);J.setExtension(QJ,Y)}return this}write(Z){let J=Array.from(Z.textureInfoDefMap.entries());for(let[X,Y]of J){let $=X.getExtension(QJ);if(!$)continue;Y.extensions=Y.extensions||{};let Q={},K=U8.eq;if(!K($.getOffset(),[0,0]))Q.offset=$.getOffset();if($.getRotation()!==0)Q.rotation=$.getRotation();if(!K($.getScale(),[1,1]))Q.scale=$.getScale();if($.getTexCoord()!=null)Q.texCoord=$.getTexCoord();Y.extensions[QJ]=Q}return this}}UE.EXTENSION_NAME=QJ;var dk1=[o.ROOT,o.SCENE,o.NODE,o.MESH,o.MATERIAL,o.TEXTURE,o.ANIMATION];class BE extends t1{init(){this.extensionName=s9,this.propertyType="Packet",this.parentTypes=dk1}getDefaults(){return Object.assign(super.getDefaults(),{context:{},properties:{}})}getContext(){return this.get("context")}setContext(Z){return this.set("context",KJ({},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=KJ({},this.get("properties"));if(J)X[Z]=J;else delete X[Z];return this.set("properties",X)}toJSONLD(){let Z=fk(this.get("context")),J=fk(this.get("properties"));return KJ({"@context":Z},J)}fromJSONLD(Z){Z=fk(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(`${s9}: Missing context for term, "${Z}".`)}}BE.EXTENSION_NAME=s9;function fk(Z){return JSON.parse(JSON.stringify(Z))}class LE extends v1{constructor(...Z){super(...Z);this.extensionName=s9}createPacket(){return new BE(this.document.getGraph())}listPackets(){return Array.from(this.properties)}read(Z){var J;let X=(J=Z.jsonDoc.json.extensions)==null?void 0:J[s9];if(!X||!X.packets)return this;let Y=Z.jsonDoc.json,$=this.document.getRoot(),Q=X.packets.map((G)=>this.createPacket().fromJSONLD(G)),K=[[Y.asset],Y.scenes,Y.nodes,Y.meshes,Y.materials,Y.images,Y.animations],W=[[$],$.listScenes(),$.listNodes(),$.listMeshes(),$.listMaterials(),$.listTextures(),$.listAnimations()];for(let G=0;G<K.length;G++){let V=K[G]||[];for(let z=0;z<V.length;z++){let F=V[z];if(F.extensions&&F.extensions[s9]){let H=F.extensions[s9];W[G][z].setExtension(s9,Q[H.packet])}}}return this}write(Z){let{json:J}=Z.jsonDoc,X=[];for(let Y of this.properties){X.push(Y.toJSONLD());for(let $ of Y.listParents()){let Q;switch($.propertyType){case o.ROOT:Q=J.asset;break;case o.SCENE:Q=J.scenes[Z.sceneIndexMap.get($)];break;case o.NODE:Q=J.nodes[Z.nodeIndexMap.get($)];break;case o.MESH:Q=J.meshes[Z.meshIndexMap.get($)];break;case o.MATERIAL:Q=J.materials[Z.materialIndexMap.get($)];break;case o.TEXTURE:Q=J.images[Z.imageIndexMap.get($)];break;case o.ANIMATION:Q=J.animations[Z.animationIndexMap.get($)];break;default:Q=null,this.document.getLogger().warn(`[${s9}]: Unsupported parent property, "${$.propertyType}"`);break}if(!Q)continue;Q.extensions=Q.extensions||{},Q.extensions[s9]={packet:X.length-1}}}if(X.length>0)J.extensions=J.extensions||{},J.extensions[s9]={packets:X};return this}}LE.EXTENSION_NAME=s9;var ck1=[Sz,mk,dk,lk,ik,ak,ok,Ew,ek,Iw,_w,XE,QE,vw,VE,HE,Az,FE,UE,LE],sx6=[Cw,vz,Tw,kw,...ck1];var lk1=r(sT(),1);function EW(){return EW=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},EW.apply(null,arguments)}var{POINTS:Nt,LINES:Sw,LINE_STRIP:pk1,LINE_LOOP:ik1,TRIANGLES:Aw,TRIANGLE_STRIP:nk1,TRIANGLE_FAN:ak1}=T8.Mode;function hX(Z,J){return Object.defineProperty(J,"name",{value:Z}),J}function d7(Z,J){let X=EW({},Z);for(let Y in J)if(J[Y]!==void 0)X[Y]=J[Y];return X}function mt(Z){let J=Z.getIndices(),X=Z.getAttribute("POSITION");switch(Z.getMode()){case T8.Mode.POINTS:return J?J.getCount():X.getCount();case T8.Mode.LINES:return J?J.getCount()/2:X.getCount()/2;case T8.Mode.LINE_LOOP:return J?J.getCount():X.getCount();case T8.Mode.LINE_STRIP:return J?J.getCount()-1:X.getCount()-1;case T8.Mode.TRIANGLES:return J?J.getCount()/3:X.getCount()/3;case T8.Mode.TRIANGLE_STRIP:case T8.Mode.TRIANGLE_FAN:return J?J.getCount()-2:X.getCount()-2;default:throw new Error("Unexpected mode: "+Z.getMode())}}var sk1=new Intl.NumberFormat(void 0,{maximumFractionDigits:0});function NE(Z){return sk1.format(Z)}function ok1(Z,J,X=2){let Y=Z>J?"–":"+",$="%";return Y+(Math.abs(Z-J)/Z*100).toFixed(X)+"%"}function bw(Z,J){return`${NE(Z)} → ${NE(J)} (${ok1(Z,J)})`}function kE(Z){let J=[];for(let X of Z.listAttributes())J.push(X);for(let X of Z.listTargets())for(let Y of X.listAttributes())J.push(Y);return Array.from(new Set(J))}function rk1(Z,J,X){Z.swap(J,X);for(let Y of Z.listTargets())Y.swap(J,X)}function tk1(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 WJ(Z,J){return Z.createAccessor(J.getName()).setArray(J.getArray()).setType(J.getType()).setBuffer(J.getBuffer()).setNormalized(J.getNormalized()).setSparse(J.getSparse())}function ek1(Z,J=Z){let X=EE(Z,J);for(let Y=0;Y<X.length;Y++)X[Y]=Y;return X}function EE(Z,J=Z){return J<=65534?new Uint16Array(Z):new Uint32Array(Z)}function ZE1(Z){return Z.listParents().some((J)=>J.propertyType!==s.ROOT)}function ut(Z){for(let J in Z)return!1;return!0}function dt(Z){let J=y6.fromGraph(Z.getGraph()),X=Z.getMaterial(),Y=J.getRoot().listMaterials().indexOf(X),$=XE1[Z.getMode()],Q=!!Z.getIndices(),K=Z.listSemantics().sort().map((G)=>{let V=Z.getAttribute(G),z=V.getElementSize(),F=V.getComponentType();return`${G}:${z}:${F}`}).join("+"),W=Z.listTargets().map((G)=>{return G.listSemantics().sort().map((V)=>{let z=Z.getAttribute(V),F=z.getElementSize(),H=z.getComponentType();return`${V}:${F}:${H}`}).join("+")}).join("~");return`${Y}|${$}|${Q}|${K}|${W}`}function JE1(Z){return Math.pow(2,Math.ceil(Math.log(Z)/Math.LN2))}var XE1={[Nt]:Nt,[Sw]:Sw,[pk1]:Sw,[ik1]:Sw,[Aw]:Aw,[nk1]:Aw,[ak1]:Aw},TW="center",Rt={pivot:"center"};function ct(Z=Rt){let J=d7(Rt,Z);return hX(TW,(X)=>{let Y=X.getLogger(),$=X.getRoot(),Q=$.listAnimations().length>0||$.listSkins().length>0;X.getRoot().listScenes().forEach((K,W)=>{Y.debug(`${TW}: Scene ${W+1} / ${$.listScenes().length}.`);let G;if(typeof J.pivot==="string"){let z=dT(K);if(G=[(z.max[0]-z.min[0])/2+z.min[0],(z.max[1]-z.min[1])/2+z.min[1],(z.max[2]-z.min[2])/2+z.min[2]],J.pivot==="above")G[1]=z.max[1];if(J.pivot==="below")G[1]=z.min[1]}else G=J.pivot;Y.debug(`${TW}: Pivot "${G.join(", ")}".`);let V=[-1*G[0],-1*G[1],-1*G[2]];if(Q){Y.debug(`${TW}: Model contains animation or skin. Adding a wrapper node.`);let z=X.createNode("Pivot").setTranslation(V);K.listChildren().forEach((F)=>z.addChild(F)),K.addChild(z)}else Y.debug(`${TW}: Skipping wrapper, offsetting all root nodes.`),K.listChildren().forEach((z)=>{let F=z.getTranslation();z.setTranslation([F[0]+V[0],F[1]+V[1],F[2]+V[2]])})}),Y.debug(`${TW}: Complete.`)})}function YE1(Z){let J=new Set,X=Z,Y;while(Y=X.getParentNode()){if(J.has(Y))throw new Error("Circular dependency in scene graph.");J.add(Y),X=Y}return X.listParents().filter(($)=>$ instanceof FW)}function $E1(Z){let J=YE1(Z),X=Z.getParentNode();if(!X)return Z;Z.setMatrix(Z.getWorldMatrix()),X.removeChild(Z);for(let Y of J)Y.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 QE1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[3],K=J[4],W=J[5],G=J[6],V=J[7],z=J[8],F=J[9],H=J[10],q=J[11],U=J[12],B=J[13],L=J[14],w=J[15],M=X*W-Y*K,N=X*G-$*K,R=X*V-Q*K,P=Y*G-$*W,D=Y*V-Q*W,C=$*V-Q*G,T=z*B-F*U,k=z*L-H*U,A=z*w-q*U,v=F*L-H*B,x=F*w-q*B,I=H*w-q*L,_=M*I-N*x+R*v+P*A-D*k+C*T;if(!_)return null;return _=1/_,Z[0]=(W*I-G*x+V*v)*_,Z[1]=($*x-Y*I-Q*v)*_,Z[2]=(B*C-L*D+w*P)*_,Z[3]=(H*D-F*C-q*P)*_,Z[4]=(G*A-K*I-V*k)*_,Z[5]=(X*I-$*A+Q*k)*_,Z[6]=(L*R-U*C-w*N)*_,Z[7]=(z*C-H*R+q*N)*_,Z[8]=(K*x-W*A+V*T)*_,Z[9]=(Y*A-X*x-Q*T)*_,Z[10]=(U*D-B*R+w*M)*_,Z[11]=(F*R-z*D-q*M)*_,Z[12]=(W*k-K*v-G*T)*_,Z[13]=(X*v-Y*k+$*T)*_,Z[14]=(B*N-U*P-L*M)*_,Z[15]=(z*P-F*N+H*M)*_,Z}function KE1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3],Q=Z[4],K=Z[5],W=Z[6],G=Z[7],V=Z[8],z=Z[9],F=Z[10],H=Z[11],q=Z[12],U=Z[13],B=Z[14],L=Z[15],w=J*K-X*Q,M=J*W-Y*Q,N=J*G-$*Q,R=X*W-Y*K,P=X*G-$*K,D=Y*G-$*W,C=V*U-z*q,T=V*B-F*q,k=V*L-H*q,A=z*B-F*U,v=z*L-H*U,x=F*L-H*B;return w*x-M*v+N*A+R*k-P*T+D*C}function lt(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=J[3],W=J[4],G=J[5],V=J[6],z=J[7],F=J[8],H=J[9],q=J[10],U=J[11],B=J[12],L=J[13],w=J[14],M=J[15],N=X[0],R=X[1],P=X[2],D=X[3];return Z[0]=N*Y+R*W+P*F+D*B,Z[1]=N*$+R*G+P*H+D*L,Z[2]=N*Q+R*V+P*q+D*w,Z[3]=N*K+R*z+P*U+D*M,N=X[4],R=X[5],P=X[6],D=X[7],Z[4]=N*Y+R*W+P*F+D*B,Z[5]=N*$+R*G+P*H+D*L,Z[6]=N*Q+R*V+P*q+D*w,Z[7]=N*K+R*z+P*U+D*M,N=X[8],R=X[9],P=X[10],D=X[11],Z[8]=N*Y+R*W+P*F+D*B,Z[9]=N*$+R*G+P*H+D*L,Z[10]=N*Q+R*V+P*q+D*w,Z[11]=N*K+R*z+P*U+D*M,N=X[12],R=X[13],P=X[14],D=X[15],Z[12]=N*Y+R*W+P*F+D*B,Z[13]=N*$+R*G+P*H+D*L,Z[14]=N*Q+R*V+P*q+D*w,Z[15]=N*K+R*z+P*U+D*M,Z}function WE1(){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 GE1(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 VE1(Z,J){if(Z===J){var X=J[1],Y=J[2],$=J[5];Z[1]=J[3],Z[2]=J[6],Z[3]=X,Z[5]=J[7],Z[6]=Y,Z[7]=$}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 zE1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[3],K=J[4],W=J[5],G=J[6],V=J[7],z=J[8],F=z*K-W*V,H=-z*Q+W*G,q=V*Q-K*G,U=X*F+Y*H+$*q;if(!U)return null;return U=1/U,Z[0]=F*U,Z[1]=(-z*Y+$*V)*U,Z[2]=(W*Y-$*K)*U,Z[3]=H*U,Z[4]=(z*X-$*G)*U,Z[5]=(-W*X+$*Q)*U,Z[6]=q*U,Z[7]=(-V*X+Y*G)*U,Z[8]=(K*X-Y*Q)*U,Z}function gw(){var Z=new IW(3);if(IW!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function HE1(Z,J,X){return Z[0]=J[0]*X[0],Z[1]=J[1]*X[1],Z[2]=J[2]*X[2],Z}function pt(Z,J){var X=J[0],Y=J[1],$=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 FE1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=X[3]*Y+X[7]*$+X[11]*Q+X[15];return K=K||1,Z[0]=(X[0]*Y+X[4]*$+X[8]*Q+X[12])/K,Z[1]=(X[1]*Y+X[5]*$+X[9]*Q+X[13])/K,Z[2]=(X[2]*Y+X[6]*$+X[10]*Q+X[14])/K,Z}function qE1(Z,J,X){var Y=J[0],$=J[1],Q=J[2];return Z[0]=Y*X[0]+$*X[3]+Q*X[6],Z[1]=Y*X[1]+$*X[4]+Q*X[7],Z[2]=Y*X[2]+$*X[5]+Q*X[8],Z}var UE1=HE1;(function(){var Z=gw();return function(J,X,Y,$,Q,K){var W,G;if(!X)X=3;if(!Y)Y=0;if($)G=Math.min($*X+Y,J.length);else G=J.length;for(W=Y;W<G;W+=X)Z[0]=J[W],Z[1]=J[W+1],Z[2]=J[W+2],Q(Z,Z,K),J[W]=Z[0],J[W+1]=Z[1],J[W+2]=Z[2];return J}})();var AX="dedup",wE={keepUniqueNames:!1,propertyTypes:[s.ACCESSOR,s.MESH,s.TEXTURE,s.MATERIAL,s.SKIN]};function it(Z=wE){let J=d7(wE,Z),X=new Set(J.propertyTypes);for(let Y of J.propertyTypes)if(!wE.propertyTypes.includes(Y))throw new Error(`${AX}: Unsupported deduplication on type "${Y}".`);return hX(AX,(Y)=>{let $=Y.getLogger();if(X.has(s.ACCESSOR))BE1(Y);if(X.has(s.TEXTURE))wE1(Y,J);if(X.has(s.MATERIAL))OE1(Y,J);if(X.has(s.MESH))LE1(Y,J);if(X.has(s.SKIN))ME1(Y,J);$.debug(`${AX}: Complete.`)})}function BE1(Z){let J=Z.getLogger(),X=new Map,Y=new Map,$=new Map,Q=new Map,K=Z.getRoot().listMeshes();K.forEach((F)=>{F.listPrimitives().forEach((H)=>{H.listAttributes().forEach((q)=>W(q,Y)),W(H.getIndices(),X)})});for(let F of Z.getRoot().listAnimations())for(let H of F.listSamplers())W(H.getInput(),$),W(H.getOutput(),Q);function W(F,H){if(!F)return;let q=[F.getCount(),F.getType(),F.getComponentType(),F.getNormalized(),F.getSparse()].join(":"),U=H.get(q);if(!U)H.set(q,U=new Set);U.add(F)}function G(F,H){for(let q=0;q<F.length;q++){let U=F[q],B=a0.toView(U.getArray());if(H.has(U))continue;for(let L=q+1;L<F.length;L++){let w=F[L];if(H.has(w))continue;if(a0.equals(B,a0.toView(w.getArray())))H.set(w,U)}}}let V=0,z=new Map;for(let F of[Y,X,$,Q])for(let H of F.values())V+=H.size,G(Array.from(H),z);J.debug(`${AX}: Merged ${z.size} of ${V} accessors.`),K.forEach((F)=>{F.listPrimitives().forEach((H)=>{H.listAttributes().forEach((U)=>{if(z.has(U))H.swap(U,z.get(U))});let q=H.getIndices();if(q&&z.has(q))H.swap(q,z.get(q))})});for(let F of Z.getRoot().listAnimations())for(let H of F.listSamplers()){let q=H.getInput(),U=H.getOutput();if(q&&z.has(q))H.swap(q,z.get(q));if(U&&z.has(U))H.swap(U,z.get(U))}Array.from(z.keys()).forEach((F)=>F.dispose())}function LE1(Z,J){let X=Z.getLogger(),Y=Z.getRoot(),$=new Map;Y.listAccessors().forEach((W,G)=>$.set(W,G)),Y.listMaterials().forEach((W,G)=>$.set(W,G));let Q=Y.listMeshes().length,K=new Map;for(let W of Y.listMeshes()){let G=[];for(let z of W.listPrimitives())G.push(nt(z,$));let V="";if(J.keepUniqueNames)V+=W.getName()+";";if(V+=G.join(";"),K.has(V)){let z=K.get(V);W.listParents().forEach((F)=>{if(F.propertyType!==s.ROOT)F.swap(W,z)}),W.dispose()}else K.set(V,W)}X.debug(`${AX}: Merged ${Q-K.size} of ${Q} meshes.`)}function wE1(Z,J){let X=Z.getLogger(),Y=Z.getRoot(),$=Y.listTextures(),Q=new Map;for(let K=0;K<$.length;K++){let W=$[K],G=W.getImage();if(Q.has(W))continue;for(let V=K+1;V<$.length;V++){let z=$[V],F=z.getImage();if(Q.has(z))continue;if(W.getMimeType()!==z.getMimeType())continue;if(J.keepUniqueNames&&W.getName()!==z.getName())continue;let H=W.getSize(),q=z.getSize();if(!H||!q)continue;if(H[0]!==q[0])continue;if(H[1]!==q[1])continue;if(!G||!F)continue;if(a0.equals(G,F))Q.set(z,W)}}X.debug(`${AX}: Merged ${Q.size} of ${Y.listTextures().length} textures.`),Array.from(Q.entries()).forEach(([K,W])=>{K.listParents().forEach((G)=>{if(!(G instanceof _$))G.swap(K,W)}),K.dispose()})}function OE1(Z,J){let X=Z.getLogger(),$=Z.getRoot().listMaterials(),Q=new Map,K=new Map,W=new Set;if(!J.keepUniqueNames)W.add("name");for(let G=0;G<$.length;G++){let V=$[G];if(Q.has(V))continue;if(jt(V,K))continue;for(let z=G+1;z<$.length;z++){let F=$[z];if(Q.has(F))continue;if(jt(F,K))continue;if(V.equals(F,W))Q.set(F,V)}}X.debug(`${AX}: Merged ${Q.size} of ${$.length} materials.`),Array.from(Q.entries()).forEach(([G,V])=>{G.listParents().forEach((z)=>{if(!(z instanceof _$))z.swap(G,V)}),G.dispose()})}function ME1(Z,J){let X=Z.getLogger(),$=Z.getRoot().listSkins(),Q=new Map,K=new Set(["joints"]);if(!J.keepUniqueNames)K.add("name");for(let W=0;W<$.length;W++){let G=$[W];if(Q.has(G))continue;for(let V=W+1;V<$.length;V++){let z=$[V];if(Q.has(z))continue;if(G.equals(z,K)&&tk1(G.listJoints(),z.listJoints()))Q.set(z,G)}}X.debug(`${AX}: Merged ${Q.size} of ${$.length} skins.`),Array.from(Q.entries()).forEach(([W,G])=>{W.listParents().forEach((V)=>{if(!(V instanceof _$))V.swap(W,G)}),W.dispose()})}function nt(Z,J){let X=[];for(let Y of Z.listSemantics()){let $=Z.getAttribute(Y);X.push(Y+":"+J.get($))}if(Z instanceof T8){let Y=Z.getIndices();if(Y)X.push("indices:"+J.get(Y));let $=Z.getMaterial();if($)X.push("material:"+J.get($));X.push("mode:"+Z.getMode());for(let Q of Z.listTargets())X.push("target:"+nt(Q,J))}return X.join(",")}function jt(Z,J){if(J.has(Z))return J.get(Z);let X=Z.getGraph(),Y=new Set,$=X.listParentEdges(Z);while($.length>0){let Q=$.pop();if(Q.getAttributes().modifyChild===!0)return J.set(Z,!0),!0;let K=Q.getChild();if(Y.has(K))continue;for(let W of X.listChildEdges(K))$.push(W)}return J.set(Z,!1),!1}function at(){var Z=new IW(4);if(IW!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0,Z[3]=0;return Z}function NE1(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 RE1(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 jE1(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 DE1(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 PE1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3];return Math.hypot(J,X,Y,$)}var st=RE1,CE1=jE1,ot=PE1;(function(){var Z=at();return function(J,X,Y,$,Q,K){var W,G;if(!X)X=4;if(!Y)Y=0;if($)G=Math.min($*X+Y,J.length);else G=J.length;for(W=Y;W<G;W+=X)Z[0]=J[W],Z[1]=J[W+1],Z[2]=J[W+2],Z[3]=J[W+3],Q(Z,Z,K),J[W]=Z[0],J[W+1]=Z[1],J[W+2]=Z[2],J[W+3]=Z[3];return J}})();var TE1=/color|emissive|diffuse/i;function kE1(Z){return Z.getGraph().listParentEdges(Z).some(($)=>{return $.getAttributes().isColor||TE1.test($.getName())})?"srgb":null}function EE1(Z){let J=Z.getGraph(),X=new Set,Y=new Set;function $(Q){let K=new Set;for(let W of J.listChildEdges(Q))if(W.getChild()instanceof I$)K.add(W.getName()+"Info");for(let W of J.listChildEdges(Q)){let G=W.getChild();if(X.has(G))continue;if(X.add(G),G instanceof h5&&K.has(W.getName()))Y.add(G);else if(G instanceof HW)$(G)}}return $(Z),Array.from(Y)}function IE1(Z){let X=y6.fromGraph(Z.getGraph()).getRoot(),Y=Z.getGraph().listParentEdges(Z).filter(($)=>$.getParent()!==X).map(($)=>$.getName());return Array.from(new Set(Y))}var kW="prune",RE=0.011764705882352941,Dt={propertyTypes:[s.NODE,s.SKIN,s.MESH,s.CAMERA,s.PRIMITIVE,s.PRIMITIVE_TARGET,s.ANIMATION,s.MATERIAL,s.TEXTURE,s.ACCESSOR,s.BUFFER],keepLeaves:!1,keepAttributes:!1,keepIndices:!1,keepSolidTextures:!1,keepExtras:!1};function mw(Z=Dt){let J=d7(Dt,Z),X=new Set(J.propertyTypes),Y=J.keepExtras;return hX(kW,async($)=>{let Q=$.getLogger(),K=$.getRoot(),W=$.getGraph(),G=new rt,V=(z)=>G.dispose(z.target);if(W.addEventListener("node:dispose",V),X.has(s.MESH))for(let z of K.listMeshes()){if(z.listPrimitives().length>0)continue;z.dispose()}if(X.has(s.NODE)){if(!J.keepLeaves)for(let z of K.listScenes())tt(W,z,Y);for(let z of K.listNodes())r9(z,Y)}if(X.has(s.SKIN))for(let z of K.listSkins())r9(z,Y);if(X.has(s.MESH))for(let z of K.listMeshes())r9(z,Y);if(X.has(s.CAMERA))for(let z of K.listCameras())r9(z,Y);if(X.has(s.PRIMITIVE))Pt(W,s.PRIMITIVE,Y);if(X.has(s.PRIMITIVE_TARGET))Pt(W,s.PRIMITIVE_TARGET,Y);if(!J.keepAttributes&&X.has(s.ACCESSOR)){let z=new Map;for(let F of K.listMeshes())for(let H of F.listPrimitives()){let q=H.getMaterial();if(!q)continue;let U=et($,H,q),B=vE1(H,U);Ct(H,B),H.listTargets().forEach((L)=>Ct(L,B)),z.has(q)?z.get(q).add(H):z.set(q,new Set([H]))}for(let[F,H]of z)SE1(F,Array.from(H))}if(!J.keepIndices&&X.has(s.ACCESSOR))for(let z of K.listMeshes())for(let F of z.listPrimitives())_E1(F);if(X.has(s.ANIMATION))for(let z of K.listAnimations()){for(let F of z.listChannels())if(!F.getTargetNode())F.dispose();if(!z.listChannels().length){let F=z.listSamplers();r9(z,Y),F.forEach((H)=>r9(H,Y))}else z.listSamplers().forEach((F)=>r9(F,Y))}if(X.has(s.MATERIAL))K.listMaterials().forEach((z)=>r9(z,Y));if(X.has(s.TEXTURE)){if(K.listTextures().forEach((z)=>r9(z,Y)),!J.keepSolidTextures)await AE1($)}if(X.has(s.ACCESSOR))K.listAccessors().forEach((z)=>r9(z,Y));if(X.has(s.BUFFER))K.listBuffers().forEach((z)=>r9(z,Y));if(W.removeEventListener("node:dispose",V),!G.empty()){let z=G.entries().map(([F,H])=>`${F} (${H})`).join(", ");Q.info(`${kW}: Removed types... ${z}`)}else Q.debug(`${kW}: No unused properties found.`);Q.debug(`${kW}: Complete.`)})}class rt{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 r9(Z,J){let X=Z.listParents().filter(($)=>!($ instanceof _$||$ instanceof k$)),Y=J&&!ut(Z.getExtras());if(!X.length&&!Y)Z.dispose()}function Pt(Z,J,X){for(let Y of Z.listEdges()){let $=Y.getParent();if($.propertyType===J)r9($,X)}}function tt(Z,J,X){if(J.listChildren().forEach((K)=>tt(Z,K,X)),J instanceof FW)return;let Y=Z.listParentEdges(J).some((K)=>{let W=K.getParent().propertyType;return W!==s.ROOT&&W!==s.SCENE&&W!==s.NODE}),$=Z.listChildren(J).length===0,Q=X&&!ut(J.getExtras());if($&&!Y&&!Q)J.dispose()}function Ct(Z,J){for(let X of J)Z.setAttribute(X,null)}function _E1(Z){let J=Z.getIndices(),X=J&&J.getArray(),Y=Z.listAttributes()[0];if(!X||!Y)return;if(J.getCount()!==Y.getCount())return;for(let $=0,Q=X.length;$<Q;$++)if($!==X[$])return;Z.setIndices(null)}function vE1(Z,J){let X=[];for(let Y of Z.listSemantics())if(Y==="NORMAL"&&!J.has(Y))X.push(Y);else if(Y==="TANGENT"&&!J.has(Y))X.push(Y);else if(Y.startsWith("TEXCOORD_")&&!J.has(Y))X.push(Y);else if(Y.startsWith("COLOR_")&&Y!=="COLOR_0")X.push(Y);return X}function et(Z,J,X,Y=new Set){let Q=Z.getGraph().listChildEdges(X),K=new Set;for(let V of Q)if(V.getChild()instanceof I$)K.add(V.getName());for(let V of Q){let z=V.getName(),F=V.getChild();if(F instanceof h5){if(K.has(z.replace(/Info$/,"")))Y.add(`TEXCOORD_${F.getTexCoord()}`)}if(F instanceof I$&&z.match(/normalTexture/i))Y.add("TANGENT");if(F instanceof HW)et(Z,J,F,Y)}let W=X instanceof h7&&!X.getExtension("KHR_materials_unlit"),G=J.getMode()===T8.Mode.POINTS;if(W&&!G)Y.add("NORMAL");return Y}function SE1(Z,J){let X=EE1(Z),Y=new Set(X.map((G)=>G.getTexCoord())),$=Array.from(Y).sort(),Q=new Map($.map((G,V)=>[G,V])),K=new Map($.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((z)=>z.startsWith("TEXCOORD_")).sort();W(G,V),G.listTargets().forEach((z)=>W(z,V))}function W(G,V){for(let z of V){let F=G.getAttribute(z);if(!F)continue;let H=K.get(z);if(H===z)continue;G.setAttribute(H,F),G.setAttribute(z,null)}}}async function AE1(Z){let J=Z.getRoot(),X=Z.getGraph(),Y=Z.getLogger(),Q=J.listTextures().map(async(K)=>{var W;let G=await hE1(K);if(!G)return;if(kE1(K)==="srgb")cT.convertSRGBToLinear(G,G);let V=K.getName()||K.getURI(),z=(W=K.getSize())==null?void 0:W.join("x"),F=IE1(K);for(let H of X.listParentEdges(K)){let q=H.getParent();if(q!==J&&xE1(q,G,H.getName(),Y))H.dispose()}if(K.listParents().length===1)K.dispose(),Y.debug(`${kW}: Removed solid-color texture "${V}" (${z}px ${F.join(", ")})`)});await Promise.all(Q)}function xE1(Z,J,X,Y){if(Z instanceof h7)switch(X){case"baseColorTexture":return Z.setBaseColorFactor(CE1(J,J,Z.getBaseColorFactor())),!0;case"emissiveTexture":return Z.setEmissiveFactor(UE1([0,0,0],J.slice(0,3),Z.getEmissiveFactor())),!0;case"occlusionTexture":return Math.abs(J[0]-1)<=RE;case"metallicRoughnessTexture":return Z.setRoughnessFactor(J[1]*Z.getRoughnessFactor()),Z.setMetallicFactor(J[2]*Z.getMetallicFactor()),!0;case"normalTexture":return ot(st(at(),J,[0.5,0.5,1,1]))<=RE}return Y.warn(`${kW}: Detected single-color ${X} texture. Pruning ${X} not yet supported.`),!1}async function hE1(Z){let J=await fE1(Z);if(!J)return null;let X=[1/0,1/0,1/0,1/0],Y=[-1/0,-1/0,-1/0,-1/0],$=[0,0,0,0],[Q,K]=J.shape;for(let W=0;W<Q;W++){for(let G=0;G<K;G++)for(let V=0;V<4;V++)X[V]=Math.min(X[V],J.get(W,G,V)),Y[V]=Math.max(Y[V],J.get(W,G,V));if(ot(st($,Y,X))/255>RE)return null}return DE1($,NE1($,Y,X),0.00196078431372549)}async function fE1(Z){try{return await mr(Z.getImage(),Z.getMimeType())}catch(J){return null}}var SX=4294967295;class Ze{constructor(Z){this.attributes=[],this.u8=void 0,this.u32=void 0;let J=0;for(let X of kE(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),Y=Z.getElementSize()*Z.getComponentSize(),$=a0.padNumber(Y);return this.attributes.push({u8:X,byteStride:Y,paddedByteStride:$}),$}hash(Z){let J=0;for(let{u8:X,byteStride:Y,paddedByteStride:$}of this.attributes){for(let Q=0;Q<$;Q++)if(Q<Y)this.u8[J+Q]=X[Z*Y+Q];else this.u8[J+Q]=0;J+=$}return yE1(0,this.u32)}equal(Z,J){for(let{u8:X,byteStride:Y}of this.attributes)for(let $=0;$<Y;$++)if(X[Z*Y+$]!==X[J*Y+$])return!1;return!0}}function yE1(Z,J){for(let $=0,Q=J.length;$<Q;$++){let K=J[$];K=Math.imul(K,1540483477)>>>0,K=(K^K>>24)>>>0,K=Math.imul(K,1540483477)>>>0,Z=Math.imul(Z,1540483477)>>>0,Z=(Z^K)>>>0}return Z}function bE1(Z,J,X,Y,$=SX){let Q=J-1,W=X.hash(Y)&Q;for(let G=0;G<=Q;G++){let V=Z[W];if(V===$||X.equal(V,Y))return W;W=W+G+1&Q}throw new Error("Hash table full.")}var R6;(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"})(R6||(R6={}));function xX(Z,J){let X=Z.getAttribute("POSITION"),Y=Z.getIndices();switch(J){case R6.RENDER:return Y?Y.getCount():X.getCount();case R6.RENDER_CACHED:return Y?new Set(Y.getArray()).size:X.getCount();case R6.UPLOAD_NAIVE:case R6.UPLOAD:return X.getCount();case R6.DISTINCT:case R6.DISTINCT_POSITION:return gE1(J);case R6.UNUSED:return Y?X.getCount()-new Set(Y.getArray()).size:0;default:return mE1(J)}}function gE1(Z){throw new Error(`Not implemented: ${Z}`)}function mE1(Z){throw new Error(`Unexpected value: ${Z}`)}function hz(Z,J,X){let Y=y6.fromGraph(Z.getGraph());if(!J||!X)[J,X]=uE1(Z);let $=Z.getIndices(),Q=$?$.getArray():null,K=xX(Z,R6.RENDER),W=Y.createAccessor(),G=K,V=EE(G,X);for(let F=0;F<G;F++)V[F]=J[Q?Q[F]:F];Z.setIndices(W.setArray(V));let z=kE(Z);for(let F of Z.listAttributes()){let H=WJ(Y,F);jE(F,$,J,H,X),Z.swap(F,H)}for(let F of Z.listTargets())for(let H of F.listAttributes()){let q=WJ(Y,H);jE(H,$,J,q,X),F.swap(H,q)}if($&&$.listParents().length===1)$.dispose();for(let F of z)if(F.listParents().length===1)F.dispose();return Z}function jE(Z,J,X,Y,$){let Q=Z.getElementSize(),K=Z.getArray(),W=J?J.getArray():null,G=J?J.getCount():Z.getCount(),V=new K.constructor($*Q),z=new Uint8Array($);for(let F=0;F<G;F++){let H=W?W[F]:F,q=X[H];if(z[q])continue;for(let U=0;U<Q;U++)V[q*Q+U]=K[H*Q+U];z[q]=1}return Y.setArray(V)}function uE1(Z){let J=xX(Z,R6.UPLOAD),X=Z.getIndices(),Y=X?X.getArray():null;if(!X||!Y)return[ek1(J,1e6),J];let $=new Uint32Array(J).fill(SX),Q=0;for(let K=0;K<Y.length;K++){let W=Y[K];if($[W]===SX)$[W]=Q++}return[$,Q]}var DE="weld",hw={overwrite:!0,cleanup:!0};function IE(Z=hw){let J=d7(hw,Z);return hX(DE,async(X)=>{let Y=X.getLogger();for(let $ of X.getRoot().listMeshes()){for(let Q of $.listPrimitives())if(uw(Q,J),xX(Q,R6.RENDER)===0)Q.dispose();if($.listPrimitives().length===0)$.dispose()}if(J.cleanup)await X.transform(mw({propertyTypes:[s.ACCESSOR,s.NODE],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}),it({propertyTypes:[s.ACCESSOR]}));Y.debug(`${DE}: Complete.`)})}function uw(Z,J=hw){let X=Z.getGraph(),$=y6.fromGraph(X).getLogger(),Q=EW({},hw,J);if(Z.getIndices()&&!Q.overwrite)return;if(Z.getMode()===T8.Mode.POINTS)return;let K=Z.getAttribute("POSITION").getCount(),W=Z.getIndices(),G=W==null?void 0:W.getArray(),V=W?W.getCount():K,z=new Ze(Z),F=JE1(K+K/4),H=new Uint32Array(F).fill(SX),q=new Uint32Array(K).fill(SX),U=0;for(let B=0;B<V;B++){let L=G?G[B]:B;if(q[L]!==SX)continue;let w=bE1(H,F,z,L,SX),M=H[w];if(M===SX)H[w]=L,q[L]=U++;else q[L]=q[M]}$.debug(`${DE}: ${bw(K,U)} vertices.`),hz(Z,q,U)}var{FLOAT:dE1}=x0.ComponentType;function Je(Z,J){let X=Z.getAttribute("POSITION");if(X)Tt(J,X);let Y=Z.getAttribute("NORMAL");if(Y)kt(J,Y);let $=Z.getAttribute("TANGENT");if($)Et(J,$);for(let Q of Z.listTargets()){let K=Q.getAttribute("POSITION");if(K)Tt(J,K);let W=Q.getAttribute("NORMAL");if(W)kt(J,W);let G=Q.getAttribute("TANGENT");if(G)Et(J,G)}if(KE1(J)<0)cE1(Z)}function Tt(Z,J){let X=J.getComponentType(),Y=J.getNormalized(),$=J.getArray(),Q=X===dE1?$:new Float32Array($.length),K=gw();for(let W=0,G=J.getCount();W<G;W++){if(Y)K[0]=l0.decodeNormalizedInt($[W*3],X),K[1]=l0.decodeNormalizedInt($[W*3+1],X),K[2]=l0.decodeNormalizedInt($[W*3+2],X);else K[0]=$[W*3],K[1]=$[W*3+1],K[2]=$[W*3+2];FE1(K,K,Z),Q[W*3]=K[0],Q[W*3+1]=K[1],Q[W*3+2]=K[2]}J.setArray(Q).setNormalized(!1)}function kt(Z,J){let X=J.getArray(),Y=J.getNormalized(),$=J.getComponentType(),Q=WE1();GE1(Q,Z),zE1(Q,Q),VE1(Q,Q);let K=gw();for(let W=0,G=J.getCount();W<G;W++){if(Y)K[0]=l0.decodeNormalizedInt(X[W*3],$),K[1]=l0.decodeNormalizedInt(X[W*3+1],$),K[2]=l0.decodeNormalizedInt(X[W*3+2],$);else K[0]=X[W*3],K[1]=X[W*3+1],K[2]=X[W*3+2];if(qE1(K,K,Q),pt(K,K),Y)X[W*3]=l0.decodeNormalizedInt(K[0],$),X[W*3+1]=l0.decodeNormalizedInt(K[1],$),X[W*3+2]=l0.decodeNormalizedInt(K[2],$);else X[W*3]=K[0],X[W*3+1]=K[1],X[W*3+2]=K[2]}}function Et(Z,J){let X=J.getArray(),Y=J.getNormalized(),$=J.getComponentType(),Q=gw();for(let K=0,W=J.getCount();K<W;K++){if(Y)Q[0]=l0.decodeNormalizedInt(X[K*4],$),Q[1]=l0.decodeNormalizedInt(X[K*4+1],$),Q[2]=l0.decodeNormalizedInt(X[K*4+2],$);else Q[0]=X[K*4],Q[1]=X[K*4+1],Q[2]=X[K*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],pt(Q,Q),Y)X[K*4]=l0.decodeNormalizedInt(Q[0],$),X[K*4+1]=l0.decodeNormalizedInt(Q[1],$),X[K*4+2]=l0.decodeNormalizedInt(Q[2],$);else X[K*4]=Q[0],X[K*4+1]=Q[1],X[K*4+2]=Q[2]}}function cE1(Z){if(Z.getMode()!==T8.Mode.TRIANGLES)return;if(!Z.getIndices())uw(Z);let J=Z.getIndices();for(let X=0,Y=J.getCount();X<Y;X+=3){let $=J.getScalar(X),Q=J.getScalar(X+2);J.setScalar(X,Q),J.setScalar(X+2,$)}}function lE1(Z,J){for(let X of Z.listPrimitives()){let Y=pE1(X,Z);if(X!==Y)Z.removePrimitive(X).addPrimitive(Y)}for(let X of Z.listPrimitives())hz(X),Je(X,J)}function pE1(Z,J){if(Z.listParents().some((Y)=>Y instanceof Hz&&Y!==J))Z=Z.clone();for(let Y of Z.listTargets())if(Y.listParents().some((Q)=>Q instanceof T8&&Q!==Z))Z.removeTarget(Y).addTarget(Y.clone());return Z}var It=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function Xe(Z){let J=Z.getMesh(),X=Z.getMatrix();if(J&&!l0.eq(X,It))lE1(J,X);for(let Y of Z.listChildren()){let $=Y.getMatrix();lt($,$,X),Y.setMatrix($)}return Z.setMatrix(It)}var{LINES:iE1,LINE_STRIP:nE1,LINE_LOOP:aE1,TRIANGLES:sE1,TRIANGLE_STRIP:oE1,TRIANGLE_FAN:rE1}=T8.Mode;function tE1(Z){let J=Z.getGraph(),X=y6.fromGraph(J);if(!Z.getIndices())uw(Z);let Y=Z.getIndices(),$=Y.getArray(),Q=mt(Z),W=new jX[Y.getComponentType()](Q*2),G=Z.getMode();if(G===nE1)for(let z=0;z<Q;z++)W[z*2]=$[z],W[z*2+1]=$[z+1];else if(G===aE1)for(let z=0;z<Q;z++)if(z<Q-1)W[z*2]=$[z],W[z*2+1]=$[z+1];else W[z*2]=$[z],W[z*2+1]=$[0];else throw new Error("Only LINE_STRIP and LINE_LOOP may be converted to LINES.");Z.setMode(iE1);let V=X.getRoot();if(Y.listParents().some((z)=>z!==V&&z!==Z))Z.setIndices(WJ(X,Y).setArray(W));else Y.setArray(W)}function Ye(Z){let J=Z.getGraph(),X=y6.fromGraph(J);if(!Z.getIndices())uw(Z);let Y=Z.getIndices(),$=Y.getArray(),Q=mt(Z),W=new jX[Y.getComponentType()](Q*3),G=Z.getMode();if(G===oE1)for(let z=0,F=$.length;z<F-2;z++)if(z%2)W[z*3]=$[z+1],W[z*3+1]=$[z],W[z*3+2]=$[z+2];else W[z*3]=$[z],W[z*3+1]=$[z+1],W[z*3+2]=$[z+2];else if(G===rE1)for(let z=0;z<Q;z++)W[z*3]=$[0],W[z*3+1]=$[z+1],W[z*3+2]=$[z+2];else throw new Error("Only TRIANGLE_STRIP and TRIANGLE_FAN may be converted to TRIANGLES.");Z.setMode(sE1);let V=X.getRoot();if(Y.listParents().some((z)=>z!==V&&z!==Z))Z.setIndices(WJ(X,Y).setArray(W));else Y.setArray(W)}var _t="dequantize",fw={pattern:/^((?!JOINTS_).)*$/};function $e(Z=fw){let J=d7(fw,Z);return hX(_t,(X)=>{let Y=X.getLogger();for(let $ of X.getRoot().listMeshes())for(let Q of $.listPrimitives())eE1(Q,J);X.createExtension(Az).dispose(),Y.debug(`${_t}: Complete.`)})}function eE1(Z,J=fw){let X=d7(fw,J);for(let Y of Z.listSemantics())if(X.pattern.test(Y))PE(Z.getAttribute(Y));for(let Y of Z.listTargets())for(let $ of Y.listSemantics())if(X.pattern.test($))PE(Y.getAttribute($))}function PE(Z){let J=Z.getArray();if(!J)return;let X=yw(J,Z.getComponentType(),Z.getNormalized());Z.setArray(X).setNormalized(!1)}function yw(Z,J,X){let Y=new Float32Array(Z.length);for(let $=0,Q=Z.length;$<Q;$++)if(X)Y[$]=l0.decodeNormalizedInt(Z[$],J);else Y[$]=Z[$];return Y}var{TEXTURE_INFO:Qe,ROOT:Jh6}=s;function Ke(Z){let J=new y6().setLogger(Z.getLogger()),X=_E(J,Z);return ZI1(J,Z,X),J.getRoot().copy(Z.getRoot(),X),J}function ZI1(Z,J,X){X||(X=_E(Z,J));for(let Y of J.getRoot().listExtensionsUsed()){let $=Z.createExtension(Y.constructor);if(Y.isRequired())$.setRequired(!0)}return JI1(Z,J,XI1(J),X)}function JI1(Z,J,X,Y){Y||(Y=_E(Z,J));let $=new Map;for(let Q of X)if(!$.has(Q)&&Q.propertyType!==Qe)$.set(Q,Y(Q));for(let[Q,K]of $.entries())K.copy(Q,Y);return $}function _E(Z,J){let X=new Map([[J.getRoot(),Z.getRoot()]]);return(Y)=>{if(Y.propertyType===Qe)return Y;let $=X.get(Y);if(!$)$=new Y.constructor(Z.getGraph()),X.set(Y,$);return $}}function XI1(Z){let J=new Set;for(let X of Z.getGraph().listEdges())J.add(X.getChild());return Array.from(J)}var OE="flatten",vt={cleanup:!0};function We(Z=vt){let J=d7(vt,Z);return hX(OE,async(X)=>{let Y=X.getRoot(),$=X.getLogger(),Q=new Set;for(let V of Y.listSkins())for(let z of V.listJoints())Q.add(z);let K=new Set;for(let V of Y.listAnimations())for(let z of V.listChannels()){let F=z.getTargetNode();if(F&&z.getTargetPath()!=="weights")K.add(F)}let W=new Set,G=new Set;for(let V of Y.listScenes())V.traverse((z)=>{let F=z.getParentNode();if(!F)return;if(Q.has(F)||W.has(F))W.add(z);if(K.has(F)||G.has(F))G.add(z)});for(let V of Y.listScenes())V.traverse((z)=>{if(K.has(z))return;if(W.has(z))return;if(G.has(z))return;$E1(z)});if(K.size)$.debug(`${OE}: Flattening node hierarchies with TRS animation not yet supported.`);if(J.cleanup)await X.transform(mw({propertyTypes:[s.NODE],keepLeaves:!1}));$.debug(`${OE}: Complete.`)})}function Ge(Z){return dT(Z)}var YI1={skipValidation:!1},St=4294967295,{LINE_STRIP:$I1,LINE_LOOP:QI1,TRIANGLE_STRIP:KI1,TRIANGLE_FAN:WI1}=T8.Mode;function GI1(Z,J={}){let X=d7(YI1,J),Y=Z[0],$=y6.fromGraph(Y.getGraph());if(!X.skipValidation&&new Set(Z.map(dt)).size>1)throw new Error("Requires >=2 Primitives, sharing the same Material and Mode, with compatible vertex attributes and indices.");for(let q of Z)switch(q.getMode()){case $I1:case QI1:tE1(q);break;case KI1:case WI1:Ye(q);break}let Q=[],K=new Uint32Array(Z.length),W=0,G=0;for(let q=0;q<Z.length;q++){let U=Z[q],B=U.getIndices(),L=U.getAttribute("POSITION").getCount(),w=B?B.getArray():null,M=B?B.getCount():L,N=new Uint32Array(L).fill(St);for(let R=0;R<M;R++){let P=w?w[R]:R;if(N[P]===St)N[P]=W++,K[q]++}Q.push(N),G+=M}let V=$.createPrimitive().setMode(Y.getMode()).setMaterial(Y.getMaterial());for(let q of Y.listSemantics()){let U=Y.getAttribute(q),B=jX[U.getComponentType()],L=WJ($,U).setArray(new B(W*U.getElementSize()));V.setAttribute(q,L)}let z=Y.getIndices(),F=z?WJ($,z).setArray(EE(G,W)):null;V.setIndices(F);let H=0;for(let q=0;q<Q.length;q++){let U=Z[q],B=U.getIndices(),L=B?B.getCount():-1,w=Q[q];if(B&&F)zI1(B,w,F,H),H+=L;for(let M of V.listSemantics()){let N=U.getAttribute(M),R=V.getAttribute(M);VI1(N,B,w,R)}}return V}function VI1(Z,J,X,Y){let $=Z.getElementSize(),Q=J?J.getArray():null,K=Z.getCount(),W=Z.getArray(),G=Y.getArray(),V=new Uint8Array(Z.getCount());for(let z=0,F=J?J.getCount():K;z<F;z++){let H=Q?Q[z]:z,q=X[H];if(V[q])continue;for(let U=0;U<$;U++)G[q*$+U]=W[H*$+U];V[q]=1}}function zI1(Z,J,X,Y){let $=Z.getCount(),Q=Z.getArray(),K=X.getArray();for(let W=0;W<$;W++){let G=Q[W],V=J[G];K[Y+W]=V}}var CE="join",{ROOT:HI1,NODE:FI1,MESH:qI1,PRIMITIVE:UI1,ACCESSOR:BI1}=s,ME=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],At={keepMeshes:!1,keepNamed:!1,cleanup:!0};function Ve(Z=At){let J=d7(At,Z);return hX(CE,async(X)=>{let Y=X.getRoot(),$=X.getLogger();for(let Q of Y.listScenes())xt(X,Q,J),Q.traverse((K)=>xt(X,K,J));if(J.cleanup)await X.transform(mw({propertyTypes:[FI1,qI1,UI1,BI1],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}));$.debug(`${CE}: Complete.`)})}function xt(Z,J,X){let Y=Z.getLogger(),$={},Q=J.listChildren();for(let G=0;G<Q.length;G++){let V=Q[G];if(V.listParents().some((H)=>H instanceof k$))continue;let F=V.getMesh();if(!F)continue;if(V.getExtension("EXT_mesh_gpu_instancing"))continue;if(V.getSkin())continue;for(let H of F.listPrimitives()){if(H.listTargets().length>0)continue;let q=H.getMaterial();if(q&&q.getExtension("KHR_materials_volume"))continue;hz(H),wI1(H);let U=dt(H),B=F.getName()||V.getName();if(X.keepMeshes||X.keepNamed&&B)U+=`|${G}`;if(!(U in $))$[U]={prims:[],primMeshes:[],primNodes:[],dstNode:V,dstMesh:void 0};let L=$[U];L.prims.push(H),L.primNodes.push(V)}}let K=Object.values($).filter(({prims:G})=>G.length>1),W=new Set(K.flatMap((G)=>G.primNodes));for(let G of W){let V=G.getMesh();if(V.listParents().some((F)=>{return F.propertyType!==HI1&&G!==F}))G.setMesh(V.clone())}for(let G of K){let{dstNode:V,primNodes:z}=G;G.dstMesh=V.getMesh(),G.primMeshes=z.map((F)=>F.getMesh())}for(let G of K){let{prims:V,primNodes:z,primMeshes:F,dstNode:H,dstMesh:q}=G,U=H.getMatrix();for(let w=0;w<V.length;w++){let M=z[w],N=F[w],R=V[w];if(N.removePrimitive(R),ZE1(R))R=V[w]=LI1(V[w]);if(M!==H)lt(ME,QE1(ME,U),M.getMatrix()),Je(R,ME)}let B=GI1(V),L=B.listAttributes()[0].getCount();q.addPrimitive(B),Y.debug(`${CE}: Joined Primitives (${V.length}) containing ${NE(L)} vertices under Node "${H.getName()}".`)}}function LI1(Z){let J=Z.clone();for(let Y of J.listSemantics())J.setAttribute(Y,J.getAttribute(Y).clone());let X=J.getIndices();if(X)J.setIndices(X.clone());return J}function wI1(Z){for(let J of["POSITION","NORMAL","TANGENT"]){let X=Z.getAttribute(J);if(X)PE(X)}}var{TRANSLATION:Xh6,ROTATION:Yh6,SCALE:$h6,WEIGHTS:Qh6}=k$.TargetPath;var OI1={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12,normalizeWeights:!0,cleanup:!0};var Kh6=EW({level:"high"},OI1);var MI1="unweld";function NI1(Z,J=new Map){let X=Z.getIndices();if(!X)return;let Y=Z.getGraph(),$=y6.fromGraph(Y),Q=$.getLogger(),K=Z.getAttribute("POSITION").getCount();for(let G of Z.listAttributes())if(Z.swap(G,ht($,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,ht($,V,X,J)),V.listParents().length===1)V.dispose();let W=Z.getAttribute("POSITION").getCount();if(Q.debug(`${MI1}: ${bw(K,W)} vertices.`),Z.setIndices(null),X.listParents().length===1)X.dispose()}function ht(Z,J,X,Y){if(Y.has(J)&&Y.get(J).has(X))return Y.get(J).get(X);let $=J.getArray(),K=new $.constructor(X.getCount()*J.getElementSize()),W=X.getArray(),G=J.getElementSize();for(let z=0,F=X.getCount();z<F;z++)for(let H=0;H<G;H++)K[z*G+H]=$[W[z]*G+H];if(!Y.has(J))Y.set(J,new Map);let V=WJ(Z,J).setArray(K);return Y.get(J).set(X,V),V}var ft;(function(Z){Z[Z.STEP=0]="STEP",Z[Z.LERP=1]="LERP",Z[Z.SLERP=2]="SLERP"})(ft||(ft={}));var RI1=0.000001;function jI1(Z,J,X,Y=0.0001){let $=J.length/Z.length,Q=new Array($).fill(0),K=new Array($).fill(0),W=new Array($).fill(0),G=new Array($).fill(0),V=Z.length-1,z=1;for(let F=1;F<V;++F){let H=Z[z-1],q=Z[F],U=Z[F+1],B=(q-H)/(U-H),L=!1;if(q!==U&&(F!==1||q!==Z[0])){if(xz(J,z-1,G),xz(J,F,K),xz(J,F+1,W),X==="slerp"){let w=CI1(Q,G,W,B),M=bt(G,K)+bt(K,W);L=!xw(K,w,Y)||M+Number.EPSILON>=Math.PI}else if(X==="lerp"){let w=PI1(Q,G,W,B);L=!xw(K,w,Y)}else if(X==="step")L=!xw(K,G)||!xw(K,W)}if(L){if(F!==z)Z[z]=Z[F],yt(J,z,xz(J,F,Q));z++}}if(V>0)Z[z]=Z[V],yt(J,z,xz(J,V,Q)),z++;return z}function xz(Z,J,X){for(let Y=0,$=X.length;Y<$;Y++)X[Y]=Z[J*$+Y];return X}function yt(Z,J,X){for(let Y=0,$=X.length;Y<$;Y++)Z[J*$+Y]=X[Y]}function xw(Z,J,X=0){if(Z.length!==J.length)return!1;for(let Y=0;Y<Z.length;Y++)if(Math.abs(Z[Y]-J[Y])>X)return!1;return!0}function DI1(Z,J,X){return Z*(1-X)+J*X}function PI1(Z,J,X,Y){for(let $=0;$<J.length;$++)Z[$]=DI1(J[$],X[$],Y);return Z}function CI1(Z,J,X,Y){let $=J[0],Q=J[1],K=J[2],W=J[3],G=X[0],V=X[1],z=X[2],F=X[3],H,q,U,B,L;if(q=$*G+Q*V+K*z+W*F,q<0)q=-q,G=-G,V=-V,z=-z,F=-F;if(1-q>RI1)H=Math.acos(q),U=Math.sin(H),B=Math.sin((1-Y)*H)/U,L=Math.sin(Y*H)/U;else B=1-Y,L=Y;return Z[0]=B*$+L*G,Z[1]=B*Q+L*V,Z[2]=B*K+L*z,Z[3]=B*W+L*F,Z}function bt(Z,J){let X=TI1(Z,J);return Math.acos(2*X*X-1)}function TI1(Z,J){return Z[0]*J[0]+Z[1]*J[1]+Z[2]*J[2]+Z[3]*J[3]}var Wh6=new Float32Array(0),Gh6={ready:Promise.resolve(),resample:jI1,tolerance:0.0001,cleanup:!0};var h$="simplify",{POINTS:ze,LINES:kI1,LINE_STRIP:EI1,LINE_LOOP:II1,TRIANGLES:_I1,TRIANGLE_STRIP:He,TRIANGLE_FAN:Fe}=T8.Mode,qe={ratio:0,error:0.0001,lockBorder:!1,cleanup:!0};function Ue(Z){let J=d7(qe,Z),X=J.simplifier;if(!X)throw new Error(`${h$}: simplifier dependency required — install "meshoptimizer".`);return hX(h$,async(Y)=>{let $=Y.getLogger();await X.ready,await Y.transform(IE({overwrite:!1,cleanup:J.cleanup}));let Q=0;for(let K of Y.getRoot().listMeshes()){for(let W of K.listPrimitives()){let G=W.getMode();if(G===_I1||G===He||G===Fe){if(gt(W,J),xX(W,R6.RENDER)===0)W.dispose()}else if(W.getMode()===ze&&!!X.simplifyPoints){if(gt(W,J),xX(W,R6.RENDER)===0)W.dispose()}else Q++}if(K.listPrimitives().length===0)K.dispose()}if(Q>0)$.warn(`${h$}: Skipping simplification of ${Q} primitives: Unsupported draw mode.`);if(J.cleanup)await Y.transform(mw({propertyTypes:[s.ACCESSOR,s.NODE],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}),it({propertyTypes:[s.ACCESSOR]}));$.debug(`${h$}: Complete.`)})}function gt(Z,J){let X=EW({},qe,J),Y=X.simplifier,$=Z.getGraph(),Q=y6.fromGraph($),K=Q.getLogger();switch(Z.getMode()){case ze:return vI1(Q,Z,X);case kI1:case EI1:case II1:return K.warn(`${h$}: Skipping primitive simplification: Unsupported draw mode.`),Z;case He:case Fe:Ye(Z);break}let W=xX(Z,R6.UPLOAD),G=xX(Z,R6.RENDER);if(G<W/2)hz(Z);let V=Z.getAttribute("POSITION"),z=Z.getIndices(),F=V.getArray(),H=z.getArray();if(!(F instanceof Float32Array))F=yw(F,V.getComponentType(),V.getNormalized());if(!(H instanceof Uint32Array))H=new Uint32Array(H);let q=Math.floor(X.ratio*G/3)*3,U=X.lockBorder?["LockBorder"]:[],[B,L]=Y.simplify(H,F,3,q,X.error,U);if(Z.setIndices(WJ(Q,z).setArray(B)),z.listParents().length===1)z.dispose();hz(Z);let w=xX(Z,R6.UPLOAD);if(w<=65534)Z.getIndices().setArray(new Uint16Array(Z.getIndices().getArray()));return K.debug(`${h$}: ${bw(W,w)} vertices, error: ${L.toFixed(4)}.`),Z}function vI1(Z,J,X){let Y=X.simplifier,$=Z.getLogger();if(J.getIndices())NI1(J);let K=J.getAttribute("POSITION"),W=J.getAttribute("COLOR_0"),G=K.getCount(),V=K.getArray(),z=W?W.getArray():void 0,F=W?W.getComponentSize():void 0;if(!(V instanceof Float32Array))V=yw(V,K.getComponentType(),K.getNormalized());if(z&&!(z instanceof Float32Array))z=yw(z,K.getComponentType(),K.getNormalized());Y.useExperimentalFeatures=!0;let H=Math.floor(X.ratio*G),q=Y.simplifyPoints(V,3,H,z,F);Y.useExperimentalFeatures=!1;let[U,B]=Y.compactMesh(q);$.debug(`${h$}: ${bw(K.getCount(),B)} vertices.`);for(let L of kE(J)){let w=WJ(Z,L);if(jE(L,null,U,w,B),rk1(J,L,w),L.listParents().length===1)L.dispose()}return J}var TE;(function(Z){Z.LANCZOS3="lanczos3",Z.LANCZOS2="lanczos2"})(TE||(TE={}));var Vh6={resizeFilter:TE.LANCZOS3,pattern:void 0,formats:void 0,slots:void 0,quality:void 0,effort:void 0,lossless:!1,nearLossless:!1,limitInputPixels:!0};var Re=r(Ne(),1);var _W={OPTIMIZED_DIR:".optimized",CHECKSUM_EXT:".md5",DIRECTORIES:[(()=>{try{return H9.dirname(m.resolve("@hytopia.com/assets"))}catch{return null}})(),H9.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 g5{static instance=new g5;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)c.fatalError(`ModelRegistry.getAnimationNames(): Model ${Z} not found!`);return J.getRoot().listAnimations().map((Y)=>Y.getName())}getBoundingBox(Z){let J=this._modelUriBoundingBoxes.get(Z);if(!J)c.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)c.fatalError(`ModelRegistry.getNodeNames(): Model ${Z} not found!`);return J}getTrimesh(Z,J=1){let X=this._modelUriTrimeshes.get(Z);if(!X){c.error(`ModelRegistry.getTrimesh(): Model ${Z} not found!`);return}let Y=X.vertices;if(J!==1){Y=new Float32Array(Y.length);for(let $=0;$<Y.length;$++)Y[$]=X.vertices[$]*J}return{vertices:Y,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)c.fatalError(`ModelRegistry.modelHasNode(): Model ${Z} not found!`);return X.includes(J)}_absoluteModelPathToModelUri(Z){let J=H9.normalize(Z);for(let X of _W.DIRECTORIES){let Y=H9.normalize(X);if(J.startsWith(Y))return H9.relative(Y,J).replace(/\\/g,"/")}return H9.basename(J)}async _getAbsoluteModelPaths(){let Z=[];for(let J of _W.DIRECTORIES){let X=H9.resolve(process.cwd(),J);if(!fX.existsSync(X))continue;let Y=await EL("**/*.{gltf,glb}",{cwd:X,follow:!0});for(let $ of Y)Z.push(H9.join(X,$))}return Z}async _loadModelData(Z){let J=await new aT().read(Z),X=Ge(J.getRoot().listScenes()[0]),Y=J.getRoot().listNodes().map((Q)=>Q.getName()),$=this._absoluteModelPathToModelUri(Z);this._modelUriDocuments.set($,J),this._modelUriBoundingBoxes.set($,{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($,await this._buildTrimesh($))}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)}${_W.CHECKSUM_EXT}`;if(!fX.existsSync(J))return!1;let X=this._calculateChecksum(Z),Y=fX.readFileSync(J,"utf8");return X===Y}_calculateChecksum(Z){if(!fX.existsSync(Z))return"";let J=fX.readFileSync(Z);return fI1.createHash("sha256").update(J.toString("base64")).digest("hex")}_buildOptimizedModelPath(Z){let J=H9.basename(Z),X=J.replace(/\.[^/.]+$/,""),Y=H9.dirname(Z),$=H9.join(Y,_W.OPTIMIZED_DIR,X);return H9.join($,J)}async _buildTrimesh(Z,J=1,X=0.001){let Y=this._modelUriDocuments.get(Z);if(!Y)c.fatalError(`ModelRegistry._buildTrimesh(): Model ${Z} not found!`);let $=Ke(Y);$.setLogger(new f5(Vz.WARN)),await $.transform(ct({pivot:"center"}),We(),Ve(),IE(),Ue({simplifier:Re.MeshoptSimplifier,ratio:J,error:X}),$e());for(let V of $.getRoot().listScenes())for(let z of V.listChildren())Xe(z);let Q=$.getRoot().listMeshes()[0];if(!Q){c.error(`ModelRegistry._buildTrimesh(): Model ${Z} has no root mesh!`);return}let K=Q.listPrimitives()[0];if(!K){c.error(`ModelRegistry._buildTrimesh(): Model ${Z} has no root primitive!`);return}let W=K.getAttribute("POSITION"),G=K.getIndices();if(!W||!G){c.error(`ModelRegistry._buildTrimesh(): Model ${Z} missing required geometry data!`);return}return{vertices:W.getArray(),indices:G.getArray()}}async _optimizeModel(Z,J){let X=H9.dirname(J);fX.rmSync(X,{recursive:!0,force:!0}),fX.mkdirSync(X,{recursive:!0}),console.log(`ModelRegistry: Optimizing model ${this._absoluteModelPathToModelUri(Z)}...`);for(let Y of _W.OPTIMIZER_RUNS){let $=J.replace(/(\.[^/.]+)$/,`${Y.suffix}$1`),{stderr:Q}=await vn("npx",["@gltf-transform/cli","optimize",Z,$,...Y.options]);if(Q)return c.warning(`ModelRegistry._optimizeModel(): Error optimizing model ${this._absoluteModelPathToModelUri(Z)}, defaulting to unoptimized model. Error: ${Q}`),Z}return fX.writeFileSync(`${J}${_W.CHECKSUM_EXT}`,this._calculateChecksum(Z)),J}}var GJ=r(_V(),1);var mz;(($)=>{$.DYNAMIC="dynamic";$.FIXED="fixed";$.KINEMATIC_POSITION="kinematic_position";$.KINEMATIC_VELOCITY="kinematic_velocity"})(mz||={});var hE=0.001,je="dynamic";class f$ extends O0{_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??=je,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:Y}=this.rotation;return{x:-2*(Z*X+Y*J),y:-2*(J*X-Y*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:Y,principalAngularInertiaLocalFrame:$}=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"]:GJ.default.RigidBodyType.Dynamic,["fixed"]:GJ.default.RigidBodyType.Fixed,["kinematic_position"]:GJ.default.RigidBodyType.KinematicPositionBased,["kinematic_velocity"]:GJ.default.RigidBodyType.KinematicVelocityBased}[Z];if(X===void 0)return c.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 c.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 F9({...Z,parentRigidBody:this,simulation:this._simulation}):this._createAndAddPendingChildCollider(Z)}createAndAddChildColliders(Z){let J=[];return Z.forEach((X)=>{let Y=this.createAndAddChildCollider(X);if(Y)J.push(Y)}),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 c.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 c.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 c.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,Y])=>{if(X in Z)Y(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 F9(Z);return this._colliders.add(J),J}_createAndAddPendingChildColliders(Z){let J=[];return Z.forEach((X)=>{let Y=this._createAndAddPendingChildCollider(X);if(Y)J.push(Y)}),J}_createRigidBodyDesc(Z){let J=Z.type??je;return{["dynamic"]:()=>GJ.default.RigidBodyDesc.dynamic(),["fixed"]:()=>GJ.default.RigidBodyDesc.fixed(),["kinematic_position"]:()=>GJ.default.RigidBodyDesc.kinematicPositionBased(),["kinematic_velocity"]:()=>GJ.default.RigidBodyDesc.kinematicVelocityBased()}[J]()}_requireCreated(Z){if(!this._rigidBody||!this._simulation)c.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)c.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)c.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)c.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)c.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)c.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)<hE&&Math.abs(Z.y)<hE&&Math.abs(Z.z)<hE}}var fE;(($)=>{$[$.Average=0]="Average";$[$.Min=1]="Min";$[$.Multiply=2]="Multiply";$[$.Max=3]="Max"})(fE||={});var uz;((z)=>{z.NONE="none";z.BALL="ball";z.BLOCK="block";z.CAPSULE="capsule";z.CONE="cone";z.CYLINDER="cylinder";z.ROUND_CYLINDER="round-cylinder";z.TRIMESH="trimesh";z.VOXELS="voxels";z.WEDGE="wedge"})(uz||={});class F9 extends O0{_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 Y=g5.instance.getBoundingBox(Z),$=Y.max.x-Y.min.x,Q=Y.max.y-Y.min.y,K=Y.max.z-Y.min.z,W=Math.max($,K),G=Math.min($,K),V=W/G,z=W/Q,F=W*J/2,H=(M)=>Math.max(0.01,M),q=()=>({shape:"block",halfExtents:{x:H($*J/2),y:H(Q*J/2),z:H(K*J/2)}}),U=()=>({shape:"round-cylinder",radius:H(F),halfHeight:H(Q*J/2),borderRadius:H(F*0.1)}),B=()=>{let M=g5.instance.getTrimesh(Z,J);if(!M)return;return{shape:"trimesh",vertices:M.vertices,indices:M.indices}},L=()=>({shape:"wedge",extents:{x:$*J,y:Q*J,z:K*J}}),w=()=>({shape:"capsule",radius:H(F),halfHeight:H(Q*J/2-F)});if(X)switch(X){case"block":return q();case"capsule":return w();case"round-cylinder":return U();case"trimesh":{let M=B();if(!M){c.error(`Collider.optionsFromModelUri(): Failed to create trimesh options for model ${Z}, falling back to generic shape!`);break}return M}case"wedge":return L();default:c.warning(`Collider.optionsFromModelUri(): Preferred shape ${X} is not yet supported with Collider.optionsFromModelUri(), defaulting to generic shape!`)}if(V>2)return q();if(z>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?g4.decodeRawCollisionGroups(this._collider.collisionGroups()):g4.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=g4.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 c.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 c.error("Collider.addToSimulation(): Rigid body must be simulated before adding a collider to it!");if(J.type==="dynamic"&&this.shape==="trimesh")c.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 c.error("Collider.combineVoxelStates(): Other collider is not simulated!");if(this.shape!=="voxels")return c.error("Collider.combineVoxelStates(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return c.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|n8.default.ActiveEvents.COLLISION_EVENTS:J&~n8.default.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|n8.default.ActiveEvents.CONTACT_FORCE_EVENTS:J&~n8.default.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 c.error("Collider.propagateVoxelChange(): Other collider is not simulated!");if(this.shape!=="voxels")return c.error("Collider.propagateVoxelChange(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return c.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":{c.error("Collider.setScale(): Trimesh colliders cannot be scaled!");return}case"voxels":{c.error("Collider.setScale(): Voxels colliders cannot be scaled!");return}case"wedge":{c.error("Collider.setScale(): Wedge colliders cannot be scaled!");return}default:c.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,Y])=>{if(Z[X]!==void 0)Y.call(this,Z[X])})}_autoAddToSimulation(Z){if(Z.simulation)this.addToSimulation(Z.simulation,Z.parentRigidBody)}_buildWedgeConvexHullVertices(Z){let{x:J,y:X,z:Y}=Z,$=J/2,Q=Y/2,K=X/2;return new Float32Array([-$,0-K,-Q,$,0-K,-Q,$,0-K,Q,-$,0-K,Q,-$,X-K,-Q,$,X-K,-Q])}_createColliderDesc(Z){let{shape:J,flags:X}=Z;switch(J){case"ball":{if(!Z.radius)c.fatalError("Ball collider must have a radius!");return n8.default.ColliderDesc.ball(Z.radius)}case"block":{if(!Z.halfExtents)c.fatalError("Block collider must have halfExtents!");return n8.default.ColliderDesc.cuboid(Z.halfExtents.x,Z.halfExtents.y,Z.halfExtents.z)}case"capsule":{if(!Z.halfHeight||!Z.radius)c.fatalError("Capsule collider must have halfHeight and radius!");return n8.default.ColliderDesc.capsule(Z.halfHeight,Z.radius)}case"cone":{if(!Z.radius||!Z.halfHeight)c.fatalError("Cone collider must have radius and halfHeight!");return n8.default.ColliderDesc.cone(Z.halfHeight,Z.radius)}case"cylinder":{if(!Z.radius||!Z.halfHeight)c.fatalError("Cylinder collider must have radius and halfHeight!");return n8.default.ColliderDesc.cylinder(Z.halfHeight,Z.radius)}case"round-cylinder":{if(!Z.radius||!Z.halfHeight||!Z.borderRadius)c.fatalError("Round cylinder collider must have radius, halfHeight, and borderRadius!");return n8.default.ColliderDesc.roundCylinder(Z.halfHeight,Z.radius,Z.borderRadius)}case"trimesh":{if(!Z.indices||!Z.vertices)c.fatalError("Trimesh collider must have vertices and indices!");return n8.default.ColliderDesc.trimesh(Z.vertices,Z.indices,X)}case"voxels":{if(!Z.coordinates||!Z.size)c.fatalError("Voxels collider must have coordinates and size!");return n8.default.ColliderDesc.voxels(this._coordinatesToInt32Array(Z.coordinates),Z.size)}case"wedge":{if(!Z.extents)c.fatalError("Wedge collider must have extents!");let Y=this._buildWedgeConvexHullVertices(Z.extents),$=n8.default.ColliderDesc.convexHull(Y);if(!$)throw c.fatalError("Failed to create convex hull for wedge collider!"),new Error("Convex hull creation failed");return $}default:c.fatalError(`Collider._createColliderDesc(): ${J} is not a valid collider shape!`)}}_requireSimulated(Z){if(!this.isSimulated)c.error(`Collider._requireSimulated(): Collider is not simulated, invoked method: ${Z}()`);return this.isSimulated}_requireUnsimulated(Z){if(this.isSimulated)c.error(`Collider._requireUnsimulated(): Collider is already simulated, invoked method: ${Z}()`);return!this.isSimulated}_requireNotRemoved(Z){if(this.isRemoved)c.error(`Collider._requireNotRemoved(): Collider is removed, invoked method: ${Z}()`);return!this.isRemoved}_setActiveCollisionTypes(){(this._collider??this._colliderDesc).setActiveCollisionTypes(n8.default.ActiveCollisionTypes.DYNAMIC_DYNAMIC|n8.default.ActiveCollisionTypes.DYNAMIC_KINEMATIC|n8.default.ActiveCollisionTypes.DYNAMIC_FIXED|n8.default.ActiveCollisionTypes.KINEMATIC_KINEMATIC|n8.default.ActiveCollisionTypes.KINEMATIC_FIXED)}_coordinatesToInt32Array(Z){let J=new Int32Array(Z.length*3);for(let X=0;X<Z.length;X++){let Y=Z[X],$=X*3;J[$]=Math.floor(Y.x),J[$+1]=Math.floor(Y.y),J[$+2]=Math.floor(Y.z)}return J}}var yI1={shape:"voxels"},yE;((X)=>{X.ENTITY_COLLISION="BLOCK_TYPE.ENTITY_COLLISION";X.ENTITY_CONTACT_FORCE="BLOCK_TYPE.ENTITY_CONTACT_FORCE"})(yE||={});class q9 extends O0{_id;_customColliderOptions;_halfExtents;_isLiquid;_name;_textureUri;constructor(Z={id:-1,textureUri:"textures/missing.png",name:"Unknown"}){if(Z.id<0)c.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}get id(){return this._id}get colliderOptions(){return{...this._customColliderOptions,...yI1}}get halfExtents(){return this._halfExtents}get isLiquid(){return this._isLiquid}get isMeshable(){return!this._customColliderOptions}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 F9({...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(g4.isDefaultCollisionGroups(J.collisionGroups))J.setCollisionGroups({belongsTo:[1],collidesWith:[65535&~1]});return J}serialize(){return k0.serializeBlockType(this)}}var bE;((J)=>J.REGISTER_BLOCK_TYPE="BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE")(bE||={});class dz extends O0{_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)c.fatalError(`BlockTypeRegistry.getBlockType(): BlockType with id ${Z} not found.`);return J}registerGenericBlockType(Z){let X=new class extends q9{constructor(Y=Z){super(Y)}};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 k0.serializeBlockTypeRegistry(this)}}var B_={};EK(B_,{worldSchema:()=>U_,worldPacketDefinition:()=>B50,vectorSchema:()=>z1,vectorBooleanSchema:()=>hy1,uiSchema:()=>F_,uiPacketDefinition:()=>q50,uiDatasSchema:()=>q_,uiDatasPacketDefinition:()=>U50,uiDataSendPacketDefinition:()=>t60,uiDataSchema:()=>FH,syncResponseSchema:()=>H_,syncResponsePacketDefinition:()=>F50,syncRequestSchema:()=>gI,syncRequestPacketDefinition:()=>r60,stateRequestSchema:()=>bI,stateRequestPacketDefinition:()=>o60,sceneUIsSchema:()=>z_,sceneUIsPacketDefinition:()=>H50,sceneUISchema:()=>V_,rgbColorSchema:()=>c6,registeredPackets:()=>vO,quaternionSchema:()=>rI,playersSchema:()=>G_,playersPacketDefinition:()=>z50,playerSchema:()=>W_,physicsDebugRenderSchema:()=>K_,physicsDebugRenderPacketDefinition:()=>G50,physicsDebugRaycastsSchema:()=>Q_,physicsDebugRaycastsPacketDefinition:()=>V50,physicsDebugRaycastSchema:()=>$_,particleEmittersSchema:()=>Y_,particleEmittersPacketDefinition:()=>W50,particleEmitterSchema:()=>X_,outboundPackets:()=>_O,modelNodeOverrideSchema:()=>oI,lightsSchema:()=>J_,lightsPacketDefinition:()=>K50,lightSchema:()=>Z_,isValidPacket:()=>yy1,inputSchema:()=>yI,inputPacketDefinition:()=>s60,inboundPackets:()=>IO,hexColorSchema:()=>hI,heartbeatSchema:()=>xI,heartbeatPacketDefinition:()=>i60,entitySchema:()=>tI,entitiesSchema:()=>eI,entitiesPacketDefinition:()=>Q50,definePacket:()=>_0,debugConfigSchema:()=>fI,debugConfigPacketDefinition:()=>a60,createPacket:()=>Cy1,connectionSchema:()=>AI,connectionPacketDefinition:()=>p60,chunksSchema:()=>sI,chunksPacketDefinition:()=>$50,chunkSchema:()=>aI,chatMessagesSchema:()=>nI,chatMessagesPacketDefinition:()=>Y50,chatMessageSendPacketDefinition:()=>n60,chatMessageSchema:()=>HH,cameraSchema:()=>iI,cameraPacketDefinition:()=>X50,blocksSchema:()=>cI,blocksPacketDefinition:()=>Z50,blockTypesSchema:()=>pI,blockTypesPacketDefinition:()=>J50,blockTypeSchema:()=>lI,blockSchema:()=>dI,bidirectionalPackets:()=>EO,audiosSchema:()=>uI,audiosPacketDefinition:()=>e60,audioSchema:()=>mI,PacketId:()=>A1});var EO={};EK(EO,{heartbeatPacketDefinition:()=>i60,connectionPacketDefinition:()=>p60});var vI=r(c60(),1);class SI extends vI.default{static instance=new vI.default}var A1;((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"})(A1||={});function Cy1(Z,J,X,Y){if(!Z.validate(J))throw new Error(`Invalid payload for packet with id ${Z.id}. Error: ${SI.instance.errorsText(Z.validate.errors)}`);let $=Y??[];if($[0]=Z.id,$[1]=J,typeof X==="number")$.push(X);return $}function _0(Z,J){return{id:Z,schema:J,validate:SI.instance.compile(J)}}var Ty1={type:"object",properties:{i:{type:"string"}},required:["i"],additionalProperties:!1},l60={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},ky1={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},Ey1={type:"object",properties:{usernameFragment:{type:"string"},password:{type:"string"},iceLite:{type:"boolean",nullable:!0}},required:["usernameFragment","password"],additionalProperties:!1},Iy1={type:"object",properties:{i:{type:"string"},l:{type:"string"}},required:["i","l"],additionalProperties:!1},_y1={type:"object",properties:{port:{type:"number"},OS:{type:"number"},MIS:{type:"number"},maxMessageSize:{type:"number"}},required:["port","OS","MIS","maxMessageSize"],additionalProperties:!0},vy1={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},Sy1={type:"object",properties:{i:{type:"string"},f:{type:"string",enum:["cs","sc"]},ip:Ey1,ic:{type:"array",items:ky1},d:l60,s:_y1},required:["i","f","ip","ic","d","s"],additionalProperties:!1},Ay1={type:"object",properties:{i:{type:"string"},d:l60},required:["i","d"],additionalProperties:!1},xy1={type:"object",properties:{i:{type:"string",nullable:!0},pi:{type:"string",nullable:!0},l:{type:"string"},s:vy1},required:["l","s"],additionalProperties:!1},AI={type:"object",properties:{i:{type:"string",nullable:!0},k:{type:"boolean",nullable:!0},c:{...Ay1,nullable:!0},ca:{...Ty1,nullable:!0},d:{type:"array",items:{...xy1},nullable:!0},pa:{...Iy1,nullable:!0},t:{type:"array",items:{...Sy1},nullable:!0}},additionalProperties:!1};var p60=_0(116,AI);var xI={type:"null",nullable:!0};var i60=_0(117,xI);var IO={};EK(IO,{uiDataSendPacketDefinition:()=>t60,syncRequestPacketDefinition:()=>r60,stateRequestPacketDefinition:()=>o60,inputPacketDefinition:()=>s60,debugConfigPacketDefinition:()=>a60,chatMessageSendPacketDefinition:()=>n60});var hI={type:"string",pattern:"^[0-9A-Fa-f]{6}$"};var HH={type:"object",properties:{m:{type:"string"},c:{...hI,nullable:!0},p:{type:"string",nullable:!0}},required:["m"],additionalProperties:!1};var n60=_0(3,HH);var fI={type:"object",properties:{pdr:{type:"boolean",nullable:!0}},additionalProperties:!1};var a60=_0(128,fI);var yI={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 s60=_0(1,yI);var bI={type:"object",properties:{},additionalProperties:!1};var o60=_0(2,bI);var gI={type:"null",nullable:!0};var r60=_0(0,gI);var FH={type:"object",properties:{},additionalProperties:!0};var t60=_0(4,FH);var _O={};EK(_O,{worldPacketDefinition:()=>B50,uiPacketDefinition:()=>q50,uiDatasPacketDefinition:()=>U50,syncResponsePacketDefinition:()=>F50,sceneUIsPacketDefinition:()=>H50,playersPacketDefinition:()=>z50,physicsDebugRenderPacketDefinition:()=>G50,physicsDebugRaycastsPacketDefinition:()=>V50,particleEmittersPacketDefinition:()=>W50,lightsPacketDefinition:()=>K50,entitiesPacketDefinition:()=>Q50,chunksPacketDefinition:()=>$50,chatMessagesPacketDefinition:()=>Y50,cameraPacketDefinition:()=>X50,blocksPacketDefinition:()=>Z50,blockTypesPacketDefinition:()=>J50,audiosPacketDefinition:()=>e60});var z1={type:"array",items:[{type:"number"},{type:"number"},{type:"number"}],minItems:3,maxItems:3};var mI={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:{...z1,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 uI={type:"array",items:{...mI}};var e60=_0(33,uI);var dI={type:"object",properties:{i:{type:"number"},c:z1},required:["i","c"],additionalProperties:!1};var cI={type:"array",items:{...dI}};var Z50=_0(34,cI);var lI={type:"object",properties:{i:{type:"number"},l:{type:"boolean",nullable:!0},n:{type:"string",nullable:!0},t:{type:"string",nullable:!0}},required:["i"],additionalProperties:!1};var pI={type:"array",items:{...lI}};var J50=_0(35,pI);var iI={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:{...z1,nullable:!0},p:{...z1,nullable:!0},pt:{...z1,nullable:!0},pl:{...z1,nullable:!0},s:{type:"array",items:{type:"string"},nullable:!0},sa:{type:"number",nullable:!0},z:{type:"number",nullable:!0}},additionalProperties:!1};var nI={type:"array",items:{...HH}};var aI={type:"object",properties:{c:z1,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 sI={type:"array",items:{...aI}};var c6={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 oI={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:{...c6,nullable:!0}},required:["n"],additionalProperties:!1};var rI={type:"array",items:[{type:"number"},{type:"number"},{type:"number"},{type:"number"}],minItems:4,maxItems:4};var tI={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:{...z1,nullable:!0},bt:{type:"string",nullable:!0},h:{type:"array",items:{type:"string"},nullable:!0},m:{type:"string",nullable:!0},mo:{type:"array",items:{...oI},nullable:!0},mt:{type:"string",nullable:!0},n:{type:"string",nullable:!0},o:{type:"number",nullable:!0},p:{...z1,nullable:!0},pe:{type:"number",nullable:!0},pn:{type:"string",nullable:!0},r:{...rI,nullable:!0},rm:{type:"boolean",nullable:!0},s:{type:"number",nullable:!0},sn:{type:"array",items:{type:"string"},nullable:!0},t:{...c6,nullable:!0}},required:["i"],additionalProperties:!1};var eI={type:"array",items:{...tI}};var Z_={type:"object",properties:{i:{type:"number"},a:{type:"number",nullable:!0},e:{type:"number",nullable:!0},c:{...c6,nullable:!0},d:{type:"number",nullable:!0},n:{type:"number",nullable:!0},o:{...z1,nullable:!0},p:{...z1,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:{...z1,nullable:!0}},required:["i"],additionalProperties:!1};var J_={type:"array",items:{...Z_}};var X_={type:"object",properties:{i:{type:"number"},at:{type:"number",nullable:!0},b:{type:"number",nullable:!0},ce:{...c6,nullable:!0},cev:{...c6,nullable:!0},cs:{...c6,nullable:!0},csv:{...c6,nullable:!0},e:{type:"number",nullable:!0},en:{type:"string",nullable:!0},g:{...z1,nullable:!0},l:{type:"number",nullable:!0},lv:{type:"number",nullable:!0},mp:{type:"number",nullable:!0},o:{...z1,nullable:!0},oe:{type:"number",nullable:!0},oev:{type:"number",nullable:!0},os:{type:"number",nullable:!0},osv:{type:"number",nullable:!0},p:{...z1,nullable:!0},pa:{type:"boolean",nullable:!0},pv:{...z1,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:{...z1,nullable:!0},vv:{...z1,nullable:!0}},required:["i"],additionalProperties:!1};var Y_={type:"array",items:{...X_}};var $_={type:"object",properties:{o:{...z1},d:{...z1},l:{type:"number"},h:{type:"boolean"}},required:["o","d","l","h"],additionalProperties:!1};var Q_={type:"array",items:{...$_}};var K_={type:"object",properties:{v:{type:"array",items:{type:"number"}},c:{type:"array",items:{type:"number"}}},required:["v","c"],additionalProperties:!1};var W_={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 G_={type:"array",items:{...W_}};var V_={type:"object",properties:{i:{type:"number"},e:{type:"number",nullable:!0},o:{...z1,nullable:!0},p:{...z1,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 z_={type:"array",items:{...V_}};var H_={type:"object",properties:{r:{type:"number"},s:{type:"number"},p:{type:"number"},n:{type:"number"}},required:["r","s","p","n"],additionalProperties:!1};var F_={type:"object",properties:{p:{type:"boolean",nullable:!0},u:{type:"string",nullable:!0}},additionalProperties:!1};var q_={type:"array",items:{...FH}};var hy1={type:"array",items:[{type:"boolean"},{type:"boolean"},{type:"boolean"}],minItems:3,maxItems:3};var U_={type:"object",properties:{i:{type:"number"},ac:{...c6,nullable:!0},ai:{type:"number",nullable:!0},dc:{...c6,nullable:!0},di:{type:"number",nullable:!0},dp:{...z1,nullable:!0},fc:{...c6,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 X50=_0(40,iI);var Y50=_0(36,nI);var $50=_0(37,sI);var Q50=_0(38,eI);var K50=_0(44,J_);var W50=_0(46,Y_);var G50=_0(192,K_);var V50=_0(193,Q_);var z50=_0(45,G_);var H50=_0(43,z_);var F50=_0(32,H_);var q50=_0(41,F_);var U50=_0(42,q_);var B50=_0(39,U_);var vO=new Map,fy1={...EO,...IO,..._O};for(let Z of Object.values(fy1))if("id"in Z&&"schema"in Z){let J=Z;if(vO.has(J.id))throw new Error(`Packet with id ${J.id} is already registered.`);vO.set(J.id,J)}function yy1(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=vO.get(Z[0]);return!!J&&J.validate(Z[1])}var Q0=B_;var m50=r(b50(),1);import c$ from"fs";import g50 from"path";var UH="./dev/persistence";class p7{static instance=new p7;gameId=process.env.HYTOPIA_GAME_ID;lobbyId=process.env.HYTOPIA_LOBBY_ID;_creativeGateway;constructor(){try{this._creativeGateway=new m50.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(`
413
413
  `))}}get isGatewayAvailable(){return!!this._creativeGateway}async getData(Z){if(!this._creativeGateway&&process.env.NODE_ENV==="production")return c.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 c.warning("PlatformGateway.setData(): Cannot set data with an error property.");if(!this._creativeGateway&&process.env.NODE_ENV==="production")return c.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(!c$.existsSync(UH))return;let J=g50.join(UH,`${Z}.json`);return JSON.parse(c$.readFileSync(J,"utf8"))}catch(J){c.warning(`PlatformGateway._readDevDataLocally(): Failed to read data for key "${Z}": ${J}`)}}_writeDevDataLocally(Z,J){try{if(!c$.existsSync(UH))c$.mkdirSync(UH,{recursive:!0});let X=g50.join(UH,`${Z}.json`),Y={};if(c$.existsSync(X))Y=JSON.parse(c$.readFileSync(X,"utf8"));let $={...Y,...J};c$.writeFileSync(X,JSON.stringify($,null,2),"utf8")}catch(X){c.warning(`PlatformGateway._writeDevDataLocally(): Failed to write data for key "${Z}": ${X}`)}}}class l${static instance=new l$;constructor(){}async getGlobalData(Z){let J=await p7.instance.getData(Z);if(!J||J.error){if(J?.error)c.warning(`PersistenceManager.getGlobalData(): ${J.error.message}`);return}return J}async getPlayerData(Z){let J=await p7.instance.getData(this._getPlayerKey(Z));if(!J||J.error){if(J?.error)c.warning(`PersistenceManager.getPlayerData(): ${J.error.message}`);return}return J}async setGlobalData(Z,J){let X=await p7.instance.setData(Z,J);if(!X||X.error){if(X?.error)c.warning(`PersistenceManager.setGlobalData(): ${X.error.message}`);return}return X}async setPlayerData(Z,J){let X=await p7.instance.setData(this._getPlayerKey(Z),J);if(!X||X.error){if(X?.error)c.warning(`PersistenceManager.setPlayerData(): ${X.error.message}`);return}return X}_getPlayerKey(Z){return`player-${Z.id}`}}var u50;((Y)=>{Y[Y.FIRST_PERSON=0]="FIRST_PERSON";Y[Y.THIRD_PERSON=1]="THIRD_PERSON";Y[Y.SPECTATOR=2]="SPECTATOR"})(u50||={});var w_;((B)=>{B.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";B.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";B.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";B.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";B.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";B.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";B.SET_FOV="PLAYER_CAMERA.SET_FOV";B.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";B.SET_MODEL_SHOWN_NODES="PLAYER_CAMERA.SET_MODEL_SHOWN_NODES";B.SET_MODE="PLAYER_CAMERA.SET_MODE";B.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";B.SET_SHOULDER_ANGLE="PLAYER_CAMERA.SET_SHOULDER_ANGLE";B.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";B.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";B.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(w_||={});class BH extends O0{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),Y=Math.sin(Z),$=Math.cos(J),Q=Math.sin(J);return{x:Y*$,y:X*Q,z:-Y*Q,w:X*$}}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 c.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 k0.serializePlayerCamera(this)}_requirePlayerWorld(Z){if(!this.player.world)c.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world, invoked method: ${Z}()`);return!!this.player.world}}var AO;(($)=>{$.DATA="PLAYER_UI.DATA";$.LOAD="PLAYER_UI.LOAD";$.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";$.SEND_DATA="PLAYER_UI.SEND_DATA"})(AO||={});class LH extends O0{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 d50=["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"],wH;((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"})(wH||={});class uW extends O0{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-${uW._devNextPlayerId++}`,this.username=J?.user.username??this.id,this.profilePictureUrl=J?.user.profilePictureURL??void 0,this.camera=new BH(this),this.connection=Z,this.ui=new LH(this),Z.onPacket(Q0.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),Z.onPacket(Q0.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),Z.onPacket(Q0.PacketId.INPUT,this._onInputPacket),Z.onPacket(Q0.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),Z.onPacket(Q0.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 l$.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},l$.instance.setPlayerData(this,Z).catch((J)=>{}),this._persistedData}serialize(){return k0.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(d50.forEach((X)=>{let Y=X;if(J[Y]!==void 0)this._input[Y]=Boolean(J[Y])}),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 O_;((X)=>{X.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";X.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(O_||={});class OH extends O0{_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[Y];if(Q){Q(J,$,X);return}this._sendBroadcastMessage(J,X)})}_sendBroadcastMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.BROADCAST_MESSAGE",{player:Z,message:J,color:X})}}var U9=16,M_=U9-1,Gb1=U9**3;class B9{_blocks;_originCoordinate;constructor(Z){this._blocks=new Uint8Array(Gb1),this._originCoordinate=Z}get blocks(){return this._blocks}get originCoordinate(){return this._originCoordinate}static blockIndexToLocalCoordinate(Z){return{x:Z%U9,y:(Z/U9|0)%U9,z:Z/(U9*U9)|0}}static globalCoordinateToLocalCoordinate(Z){return{x:Z.x&U9-1,y:Z.y&U9-1,z:Z.z&U9-1}}static globalCoordinateToOriginCoordinate(Z){return{x:Z.x&~(U9-1),y:Z.y&~(U9-1),z:Z.z&~(U9-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 c.error("Chunk.setBlock(): Block local coordinate is out of bounds");let X=this._getIndex(Z);this._blocks[X]=J}serialize(){return k0.serializeChunk(this)}_getIndex(Z){return Z.x+(Z.y<<4)+(Z.z<<8)}_isValidLocalCoordinate(Z){return Z.x>=0&&Z.x<=M_&&Z.y>=0&&Z.y<=M_&&Z.z>=0&&Z.z<=M_}}var N_;((Y)=>{Y.ADD_CHUNK="CHUNK_LATTICE.ADD_CHUNK";Y.REMOVE_CHUNK="CHUNK_LATTICE.REMOVE_CHUNK";Y.SET_BLOCK="CHUNK_LATTICE.SET_BLOCK"})(N_||={});class MH extends O0{_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(B9.globalCoordinateToOriginCoordinate(Z));if(!J)return 0;return J.getBlockId(B9.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(B9.globalCoordinateToOriginCoordinate(Z)))}getOrCreateBlockTypeCollider(Z,J){let X=this._blockTypeColliders.get(Z);if(X)return X;let $=this._world.blockTypeRegistry.getBlockType(Z).createCollider(J);return this._blockTypeColliders.set(Z,$),$}getOrCreateChunk(Z){let J=B9.globalCoordinateToOriginCoordinate(Z),X=this._chunks.get(this._getChunkKey(J));if(X)return X;return X=new B9(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(B9.globalCoordinateToOriginCoordinate(Z));if(!J)return!1;return J.hasBlock(B9.globalCoordinateToLocalCoordinate(Z))}hasChunk(Z){let J=B9.globalCoordinateToOriginCoordinate(Z);return this._chunks.has(this._getChunkKey(J))}setBlock(Z,J){let X=B9.globalCoordinateToLocalCoordinate(Z),Y=this.getOrCreateChunk(Z),$=Y.getBlockId(X);if($===J)return;if(Y.setBlock(X,J),!this._rigidBody)this._rigidBody=new f$({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);if($!==0){let Q=Math.max(0,(this._blockTypeCounts.get($)??0)-1),K=this.getBlockTypeCollider($);if(K)if(Q===0)this._world.simulation.colliderMap.removeColliderBlockType(K),K.removeFromSimulation(),this._blockTypeColliders.delete($);else K.setVoxel(Z,!1),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set($,Q)}if(J!==0){let Q=(this._blockTypeCounts.get(J)??0)+1,K=this.getOrCreateBlockTypeCollider(J,[Z]);if(Q===1){let W=this._world.blockTypeRegistry.getBlockType(J);K.addToSimulation(this._world.simulation,this._rigidBody),this._world.simulation.colliderMap.setColliderBlockType(K,W),this._combineVoxelStates(K)}else K.setVoxel(Z,!0),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set(J,Q)}this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:Y,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 NH{_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)c.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!Z.rawCollider}}var c50={type:"dynamic",softCcdPrediction:1},l50=0.015625,p50=Math.cos(0.026),RH;((R)=>{R.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";R.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";R.DESPAWN="ENTITY.DESPAWN";R.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";R.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";R.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";R.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";R.SET_MODEL_SCALE="ENTITY.SET_MODEL_SCALE";R.SET_MODEL_SHOWN_NODES="ENTITY.SET_MODEL_SHOWN_NODES";R.SET_MODEL_TEXTURE_URI="ENTITY.SET_MODEL_TEXTURE_URI";R.SET_OPACITY="ENTITY.SET_OPACITY";R.SET_PARENT="ENTITY.SET_PARENT";R.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";R.SPAWN="ENTITY.SPAWN";R.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";R.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";R.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";R.TICK="ENTITY.TICK";R.UPDATE_POSITION="ENTITY.UPDATE_POSITION";R.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})(RH||={});class a8 extends f${_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)c.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(J&&!Z.blockHalfExtents)c.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(Z.parent&&!Z.parent.isSpawned)c.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(Z.parent?.modelUri&&Z.parentNodeName&&!g5.instance.modelHasNode(Z.parent.modelUri,Z.parentNodeName))c.fatalError(`Entity.constructor(): Parent node name ${Z.parentNodeName} not found in parent model ${Z.parent.modelUri}!`);super(Z.rigidBodyOptions??c50);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((Y)=>this._modelHiddenNodes.add(Y.toLowerCase())),Z.modelLoopedAnimations?.forEach((Y)=>this._modelLoopedAnimations.add(Y)),Z.modelShownNodes?.forEach((Y)=>this._modelShownNodes.add(Y.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=l50,this._rotationUpdateThreshold=p50,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?g5.instance.getDepth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.z*2}get height(){return this.isModelEntity?g5.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?g5.instance.getWidth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.x*2}get world(){return this._world}spawn(Z,J,X){if(this.isSpawned)return c.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 F9(F9.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new F9(F9.optionsFromModelUri(this._modelUri,this._modelScale,this._modelPreferredShape)));if(this.colliders.forEach((Y)=>{if(this.hasListeners("ENTITY.BLOCK_COLLISION")||this.hasListeners("ENTITY.ENTITY_COLLISION"))Y.enableCollisionEvents(!0);if(this.hasListeners("ENTITY.BLOCK_CONTACT_FORCE")||this.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Y.enableContactForceEvents(!0);if(g4.isDefaultCollisionGroups(Y.collisionGroups)){let $=this.isEnvironmental?[8]:[Y.isSensor?4:2],Q=this.isEnvironmental?[65535&~8&~1]:[65535];Y.setCollisionGroups({belongsTo:$,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((Y)=>{Z.simulation.colliderMap.setColliderEntity(Y,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,Y){if(!this._requireSpawned("setParent"))return;if(Z&&!Z.isSpawned)return c.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(($)=>$.setEnabled(!Z)),this.setType(!Z?this._lastParentlessType:"kinematic_velocity"),this.setPosition(X??{x:0,y:0,z:0}),this.setRotation(Y??{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 k0.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,Y=Z.y-J.y,$=Z.z-J.z;return X*X+Y*Y+$*$>this._positionUpdateThresholdSq}_requireSpawned(Z){if(!this.isSpawned)c.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),Y=[];for(let $ of Z)for(let Q of $)if(!X.has(Q))Y.push(Q);if(Y.length>0)this.stopModelAnimations(Y)}}class m1 extends V${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 nG({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 Y=Z.linearVelocity;Z.setLinearVelocity({x:Y.x*this.swimGravity,y:Y.y*this.swimGravity,z:Y.z*this.swimGravity})}if(this._liquidContactCount+=X?1:-1,this._liquidContactCount>0)Z.setGravityScale(this.swimGravity),Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),this._swimUpwardCooldownAt=performance.now()+m1.SWIM_UPWARD_COOLDOWN_MS;else Z.setGravityScale(1),Z.stopModelAnimations(this.swimLoopedAnimations)})}spawn(Z){if(!Z.isSpawned)return c.error("DefaultPlayerEntityController.spawn(): Entity is not spawned!");Z.createAndAddChildCollider({shape:"cylinder",radius:m1.GROUND_SENSOR_RADIUS_SCALE*(Z.height/m1.BASE_ENTITY_HEIGHT),halfHeight:m1.GROUND_SENSOR_HEIGHT_SCALE*(Z.height/m1.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 q9)||!J.isLiquid){if(X&&this._groundContactCount===0&&Z.linearVelocity.y<-1)if(Z.linearVelocity.y<m1.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 a8))return;if(X&&this.sticksToPlatforms)this._platform=J;else if(J===this._platform&&!X)this._platform=void 0}}),Z.createAndAddChildCollider({shape:"capsule",halfHeight:m1.WALL_COLLIDER_HEIGHT_SCALE*(Z.height/m1.BASE_ENTITY_HEIGHT),radius:m1.WALL_COLLIDER_RADIUS_SCALE*(Z.height/m1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},friction:0,frictionCombineRule:1,tag:"wallCollider"})}tickWithPlayerInput(Z,J,X,Y){if(!Z.isSpawned||!Z.world)return;if(super.tickWithPlayerInput(Z,J,X,Y),Z.parent)return;let{w:$,a:Q,s:K,d:W,c:G,sp:V,sh:z,ml:F}=J,{yaw:H}=X,q=Z.linearVelocity;this._reusableTargetVelocities.x=0,this._reusableTargetVelocities.y=0,this._reusableTargetVelocities.z=0,this._isActivelyMoving=!!($||Q||K||W);let U=z,B=Q&&W&&!$&&!K||$&&K&&!Q&&!W,L=U&&this.canRun(this)||!U&&this.canWalk(this);if(this.isSwimming&&!this._isFullySubmerged)this._isFullySubmerged=!0,this._justSubmergedUntil=performance.now()+m1.WATER_ENTRY_SINKING_MS;else if(!this.isSwimming)this._isFullySubmerged=!1,this._justSubmergedUntil=0;if(this.isGrounded&&!this.isSwimming&&this._isActivelyMoving&&!B&&L){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&&L){if($&&Q&&!W&&!K)w=m1.MOVEMENT_ROTATIONS.wa;else if($&&W&&!Q&&!K)w=m1.MOVEMENT_ROTATIONS.wd;else if(K&&Q&&!$&&!W)w=m1.MOVEMENT_ROTATIONS.sa;else if(K&&W&&!$&&!Q)w=m1.MOVEMENT_ROTATIONS.sd;else if(K&&!$&&!Q&&!W||Q&&K&&W&&!$)w=m1.MOVEMENT_ROTATIONS.s;else if(Q&&!$&&!K&&!W)w=m1.MOVEMENT_ROTATIONS.a;else if(W&&!$&&!Q&&!K)w=m1.MOVEMENT_ROTATIONS.d}if(F)Z.startModelOneshotAnimations(this.interactOneshotAnimations),J.ml=!this.autoCancelMouseLeftClick;if(L){let D=!this.isSwimming?U?this.runVelocity:this.walkVelocity:U?this.swimFastVelocity:this.swimSlowVelocity,C=Math.sin(H),T=Math.cos(H);if($)this._reusableTargetVelocities.x-=D*C,this._reusableTargetVelocities.z-=D*T;if(K)this._reusableTargetVelocities.x+=D*C,this._reusableTargetVelocities.z+=D*T;if(Q)this._reusableTargetVelocities.x-=D*T,this._reusableTargetVelocities.z+=D*C;if(W)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(q.y<this.swimMaxGravityVelocity)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimMaxGravityVelocity,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(q.y>this.swimUpwardVelocity*2)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimUpwardVelocity*2,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(G)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*m1.WATER_ENTRY_SINKING_FACTOR;else if(!V)this._reusableTargetVelocities.y=-q.y*m1.SWIMMING_DRAG_FACTOR}if(V&&this.canJump(this)){if(this.isGrounded&&!this.isSwimming&&q.y>-0.001&&q.y<=3)this._reusableTargetVelocities.y=this.jumpVelocity;else if(this.isSwimming&&performance.now()>this._swimUpwardCooldownAt)this._reusableTargetVelocities.y=this.swimUpwardVelocity}let M=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-m1.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 N=this._reusableTargetVelocities.x+this._externalVelocity.x-q.x+M.x,R=this._reusableTargetVelocities.y+this._externalVelocity.y+M.y,P=this._reusableTargetVelocities.z+this._externalVelocity.z-q.z+M.z;if(this._externalVelocity.y=0,N!==0||R!==0||P!==0){let D=Z.mass;this._reusableImpulse.x=N*D,this._reusableImpulse.y=R*D,this._reusableImpulse.z=P*D,this._internalApplyImpulse(this._reusableImpulse)}if(H!==void 0&&(this.faceForwardOnStop||this.isActivelyMoving)){let C=(w!==void 0?H+w:H)*0.5;Z.setRotation({x:0,y:Math.sin(C),z:0,w:Math.cos(C)})}}}var R_;((W)=>{W.LOAD="SCENE_UI.LOAD";W.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";W.SET_OFFSET="SCENE_UI.SET_OFFSET";W.SET_POSITION="SCENE_UI.SET_POSITION";W.SET_STATE="SCENE_UI.SET_STATE";W.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";W.UNLOAD="SCENE_UI.UNLOAD"})(R_||={});class jH extends O0{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)c.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 c.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 c.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 k0.serializeSceneUI(this)}}var i50=0.010000000000000002,n50=Math.cos(0.026);class i7 extends a8{player;nametagSceneUI;constructor(Z){super(Z);this._positionUpdateThresholdSq=i50,this._rotationUpdateThreshold=n50,this.player=Z.player,this.nametagSceneUI=new jH({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:Y})=>{this.nametagSceneUI.setState({chat:Y})})}tick(Z){if(!this.isSpawned||!this.world)return;if(!this.controller)return c.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 j_ extends i7{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 m1)}}class DH{_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)c.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 c.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 i7)Z.push(J)}),Z}getPlayerEntitiesByPlayer(Z){let J=[];return this._entities.forEach((X)=>{if(X instanceof i7&&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()}}var WH1=r(_V(),1);import{gzipSync as VG6}from"zlib";var Tg1=r(d90(),1),kg1=r(E_(),1),Eg1=r(__(),1),iO=r(lO(),1),y_=r(s90(),1);var q5=r(e40(),1),Wl6=q5.default.v1,Gl6=q5.default.v1ToV6,Vl6=q5.default.v3,Z70=q5.default.v4,zl6=q5.default.v5,Hl6=q5.default.v6,Fl6=q5.default.v6ToV1,ql6=q5.default.v7,Ul6=q5.default.NIL,Bl6=q5.default.MAX,Ll6=q5.default.version,wl6=q5.default.validate,Ol6=q5.default.stringify,Ml6=q5.default.parse;var p_;try{p_=new TextDecoder}catch(Z){}var $0,O9,g=0;var s_=[],o$=s_,xH=0,x1={},W1,OJ,w9=0,J4=0,s8,MJ,p5=[],Y1,J70={useRecords:!1,mapsAsObjects:!0};class ZM{}var o_=new ZM;o_.name="MessagePack 0xC1";var nX=!1,z70=2,i_,n_,a_;try{new Function("")}catch(Z){z70=1/0}class NJ{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($0)return R70(()=>{return eO(),this?this.unpack(Z,J):NJ.prototype.unpack.call(J70,Z,J)});if(!Z.buffer&&Z.constructor===ArrayBuffer)Z=typeof Buffer!=="undefined"?Buffer.from(Z):new Uint8Array(Z);if(typeof J==="object")O9=J.end||Z.length,g=J.start||0;else g=0,O9=J>-1?J:Z.length;xH=0,J4=0,OJ=null,o$=s_,s8=null,$0=Z;try{Y1=Z.dataView||(Z.dataView=new DataView(Z.buffer,Z.byteOffset,Z.byteLength))}catch(X){if($0=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 NJ){if(x1=this,this.structures)return W1=this.structures,rO(J);else if(!W1||W1.length>0)W1=[]}else if(x1=J70,!W1||W1.length>0)W1=[];return rO(J)}unpackMultiple(Z,J){let X,Y=0;try{nX=!0;let $=Z.length,Q=this?this.unpack(Z,$):JM.unpack(Z,$);if(J){if(J(Q,Y,g)===!1)return;while(g<$)if(Y=g,J(rO(),Y,g)===!1)return}else{X=[Q];while(g<$)Y=g,X.push(rO());return X}}catch($){throw $.lastPosition=Y,$.values=X,$}finally{nX=!1,eO()}}_mergeStructures(Z,J){if(n_)Z=n_.call(this,Z);if(Z=Z||[],Object.isFrozen(Z))Z=Z.map((X)=>X.slice(0));for(let X=0,Y=Z.length;X<Y;X++){let $=Z[X];if($){if($.isShared=!0,X>=32)$.highByte=X-32>>5}}Z.sharedLength=Z.length;for(let X in J||[])if(X>=0){let Y=Z[X],$=J[X];if($){if(Y)(Z.restoreStructures||(Z.restoreStructures=[]))[X]=Y;Z[X]=$}}return this.structures=Z}decode(Z,J){return this.unpack(Z,J)}}function rO(Z){try{if(!x1.trusted&&!nX){let X=W1.sharedLength||0;if(X<W1.length)W1.length=X}let J;if(x1.randomAccessStructure&&$0[g]<64&&$0[g]>=32&&i_){if(J=i_($0,g,O9,x1),$0=null,!(Z&&Z.lazy)&&J)J=J.toJSON();g=O9}else J=I8();if(s8)g=s8.postBundlePosition,s8=null;if(nX)W1.restoreStructures=null;if(g==O9){if(W1&&W1.restoreStructures)X70();if(W1=null,$0=null,MJ)MJ=null}else if(g>O9)throw new Error("Unexpected end of MessagePack data");else if(!nX){let X;try{X=JSON.stringify(J,(Y,$)=>typeof $==="bigint"?`${$}n`:$).slice(0,100)}catch(Y){X="(JSON view not available "+Y+")"}throw new Error("Data read, but end of buffer not reached "+X)}return J}catch(J){if(W1&&W1.restoreStructures)X70();if(eO(),J instanceof RangeError||J.message.startsWith("Unexpected end of buffer")||g>O9)J.incomplete=!0;throw J}}function X70(){for(let Z in W1.restoreStructures)W1[Z]=W1.restoreStructures[Z];W1.restoreStructures=null}function I8(){let Z=$0[g++];if(Z<160)if(Z<128)if(Z<64)return Z;else{let J=W1[Z&63]||x1.getStructures&&H70()[Z&63];if(J){if(!J.read)J.read=r_(J,Z&63);return J.read()}else return Z}else if(Z<144)if(Z-=128,x1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let Y=M70();if(Y==="__proto__")Y="__proto_";J[Y]=I8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(I8(),I8());return J}else{Z-=144;let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=I8();if(x1.freezeData)return Object.freeze(J);return J}else if(Z<192){let J=Z-160;if(J4>=g)return OJ.slice(g-w9,(g+=J)-w9);if(J4==0&&O9<140){let X=J<16?t_(J):O70(J);if(X!=null)return X}return tO(J)}else{let J;switch(Z){case 192:return null;case 193:if(s8)if(J=I8(),J>0)return s8[1].slice(s8.position1,s8.position1+=J);else return s8[0].slice(s8.position0,s8.position0-=J);return o_;case 194:return!1;case 195:return!0;case 196:if(J=$0[g++],J===void 0)throw new Error("Unexpected end of buffer");return l_(J);case 197:return J=Y1.getUint16(g),g+=2,l_(J);case 198:return J=Y1.getUint32(g),g+=4,l_(J);case 199:return s$($0[g++]);case 200:return J=Y1.getUint16(g),g+=2,s$(J);case 201:return J=Y1.getUint32(g),g+=4,s$(J);case 202:if(J=Y1.getFloat32(g),x1.useFloat32>2){let X=t$[($0[g]&127)<<1|$0[g+1]>>7];return g+=4,(X*J+(J>0?0.5:-0.5)>>0)/X}return g+=4,J;case 203:return J=Y1.getFloat64(g),g+=8,J;case 204:return $0[g++];case 205:return J=Y1.getUint16(g),g+=2,J;case 206:return J=Y1.getUint32(g),g+=4,J;case 207:if(x1.int64AsType==="number")J=Y1.getUint32(g)*4294967296,J+=Y1.getUint32(g+4);else if(x1.int64AsType==="string")J=Y1.getBigUint64(g).toString();else if(x1.int64AsType==="auto"){if(J=Y1.getBigUint64(g),J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=Y1.getBigUint64(g);return g+=8,J;case 208:return Y1.getInt8(g++);case 209:return J=Y1.getInt16(g),g+=2,J;case 210:return J=Y1.getInt32(g),g+=4,J;case 211:if(x1.int64AsType==="number")J=Y1.getInt32(g)*4294967296,J+=Y1.getUint32(g+4);else if(x1.int64AsType==="string")J=Y1.getBigInt64(g).toString();else if(x1.int64AsType==="auto"){if(J=Y1.getBigInt64(g),J>=BigInt(-2)<<BigInt(52)&&J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=Y1.getBigInt64(g);return g+=8,J;case 212:if(J=$0[g++],J==114)return G70($0[g++]&63);else{let X=p5[J];if(X)if(X.read)return g++,X.read(I8());else if(X.noBuffer)return g++,X();else return X($0.subarray(g,++g));else throw new Error("Unknown extension "+J)}case 213:if(J=$0[g],J==114)return g++,G70($0[g++]&63,$0[g++]);else return s$(2);case 214:return s$(4);case 215:return s$(8);case 216:return s$(16);case 217:if(J=$0[g++],J4>=g)return OJ.slice(g-w9,(g+=J)-w9);return F70(J);case 218:if(J=Y1.getUint16(g),g+=2,J4>=g)return OJ.slice(g-w9,(g+=J)-w9);return q70(J);case 219:if(J=Y1.getUint32(g),g+=4,J4>=g)return OJ.slice(g-w9,(g+=J)-w9);return U70(J);case 220:return J=Y1.getUint16(g),g+=2,$70(J);case 221:return J=Y1.getUint32(g),g+=4,$70(J);case 222:return J=Y1.getUint16(g),g+=2,Q70(J);case 223:return J=Y1.getUint32(g),g+=4,Q70(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 Yu1=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function r_(Z,J){function X(){if(X.count++>z70){let $=Z.read=new Function("r","return function(){return "+(x1.freezeData?"Object.freeze":"")+"({"+Z.map((Q)=>Q==="__proto__"?"__proto_:r()":Yu1.test(Q)?Q+":r()":"["+JSON.stringify(Q)+"]:r()").join(",")+"})}")(I8);if(Z.highByte===0)Z.read=Y70(J,Z.read);return $()}let Y={};for(let $=0,Q=Z.length;$<Q;$++){let K=Z[$];if(K==="__proto__")K="__proto_";Y[K]=I8()}if(x1.freezeData)return Object.freeze(Y);return Y}if(X.count=0,Z.highByte===0)return Y70(J,X);return X}var Y70=(Z,J)=>{return function(){let X=$0[g++];if(X===0)return J();let Y=Z<32?-(Z+(X<<5)):Z+(X<<5),$=W1[Y]||H70()[Y];if(!$)throw new Error("Record id is not defined for "+Y);if(!$.read)$.read=r_($,Z);return $.read()}};function H70(){let Z=R70(()=>{return $0=null,x1.getStructures()});return W1=x1._mergeStructures(Z,W1)}var tO=r$,F70=r$,q70=r$,U70=r$,B70=!1;function L70(Z){B70=!0,tO=J(1),F70=J(2),q70=J(3),U70=J(5);function J(X){return function Y($){let Q=o$[xH++];if(Q==null){if(s8)return r$($);let W=$0.byteOffset,G=Z(g-X+W,O9+W,$0.buffer);if(typeof G=="string")Q=G,o$=s_;else if(o$=G,xH=1,J4=1,Q=o$[0],Q===void 0)throw new Error("Unexpected end of buffer")}let K=Q.length;if(K<=$)return g+=$,Q;return OJ=Q,w9=g,J4=g+K,g+=$,Q.slice(0,$)}}}function r$(Z){let J;if(Z<16){if(J=t_(Z))return J}if(Z>64&&p_)return p_.decode($0.subarray(g,g+=Z));let X=g+Z,Y=[];J="";while(g<X){let $=$0[g++];if(($&128)===0)Y.push($);else if(($&224)===192){let Q=$0[g++]&63;Y.push(($&31)<<6|Q)}else if(($&240)===224){let Q=$0[g++]&63,K=$0[g++]&63;Y.push(($&31)<<12|Q<<6|K)}else if(($&248)===240){let Q=$0[g++]&63,K=$0[g++]&63,W=$0[g++]&63,G=($&7)<<18|Q<<12|K<<6|W;if(G>65535)G-=65536,Y.push(G>>>10&1023|55296),G=56320|G&1023;Y.push(G)}else Y.push($);if(Y.length>=4096)J+=Q6.apply(String,Y),Y.length=0}if(Y.length>0)J+=Q6.apply(String,Y);return J}function w70(Z,J,X){let Y=$0;$0=Z,g=J;try{return r$(X)}finally{$0=Y}}function $70(Z){let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=I8();if(x1.freezeData)return Object.freeze(J);return J}function Q70(Z){if(x1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let Y=M70();if(Y==="__proto__")Y="__proto_";J[Y]=I8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(I8(),I8());return J}}var Q6=String.fromCharCode;function O70(Z){let J=g,X=new Array(Z);for(let Y=0;Y<Z;Y++){let $=$0[g++];if(($&128)>0){g=J;return}X[Y]=$}return Q6.apply(String,X)}function t_(Z){if(Z<4)if(Z<2)if(Z===0)return"";else{let J=$0[g++];if((J&128)>1){g-=1;return}return Q6(J)}else{let J=$0[g++],X=$0[g++];if((J&128)>0||(X&128)>0){g-=2;return}if(Z<3)return Q6(J,X);let Y=$0[g++];if((Y&128)>0){g-=3;return}return Q6(J,X,Y)}else{let J=$0[g++],X=$0[g++],Y=$0[g++],$=$0[g++];if((J&128)>0||(X&128)>0||(Y&128)>0||($&128)>0){g-=4;return}if(Z<6)if(Z===4)return Q6(J,X,Y,$);else{let Q=$0[g++];if((Q&128)>0){g-=5;return}return Q6(J,X,Y,$,Q)}else if(Z<8){let Q=$0[g++],K=$0[g++];if((Q&128)>0||(K&128)>0){g-=6;return}if(Z<7)return Q6(J,X,Y,$,Q,K);let W=$0[g++];if((W&128)>0){g-=7;return}return Q6(J,X,Y,$,Q,K,W)}else{let Q=$0[g++],K=$0[g++],W=$0[g++],G=$0[g++];if((Q&128)>0||(K&128)>0||(W&128)>0||(G&128)>0){g-=8;return}if(Z<10)if(Z===8)return Q6(J,X,Y,$,Q,K,W,G);else{let V=$0[g++];if((V&128)>0){g-=9;return}return Q6(J,X,Y,$,Q,K,W,G,V)}else if(Z<12){let V=$0[g++],z=$0[g++];if((V&128)>0||(z&128)>0){g-=10;return}if(Z<11)return Q6(J,X,Y,$,Q,K,W,G,V,z);let F=$0[g++];if((F&128)>0){g-=11;return}return Q6(J,X,Y,$,Q,K,W,G,V,z,F)}else{let V=$0[g++],z=$0[g++],F=$0[g++],H=$0[g++];if((V&128)>0||(z&128)>0||(F&128)>0||(H&128)>0){g-=12;return}if(Z<14)if(Z===12)return Q6(J,X,Y,$,Q,K,W,G,V,z,F,H);else{let q=$0[g++];if((q&128)>0){g-=13;return}return Q6(J,X,Y,$,Q,K,W,G,V,z,F,H,q)}else{let q=$0[g++],U=$0[g++];if((q&128)>0||(U&128)>0){g-=14;return}if(Z<15)return Q6(J,X,Y,$,Q,K,W,G,V,z,F,H,q,U);let B=$0[g++];if((B&128)>0){g-=15;return}return Q6(J,X,Y,$,Q,K,W,G,V,z,F,H,q,U,B)}}}}}function K70(){let Z=$0[g++],J;if(Z<192)J=Z-160;else switch(Z){case 217:J=$0[g++];break;case 218:J=Y1.getUint16(g),g+=2;break;case 219:J=Y1.getUint32(g),g+=4;break;default:throw new Error("Expected string")}return r$(J)}function l_(Z){return x1.copyBuffers?Uint8Array.prototype.slice.call($0,g,g+=Z):$0.subarray(g,g+=Z)}function s$(Z){let J=$0[g++];if(p5[J]){let X;return p5[J]($0.subarray(g,X=g+=Z),(Y)=>{g=Y;try{return I8()}finally{g=X}})}else throw new Error("Unknown extension type "+J)}var W70=new Array(4096);function M70(){let Z=$0[g++];if(Z>=160&&Z<192){if(Z=Z-160,J4>=g)return OJ.slice(g-w9,(g+=Z)-w9);else if(!(J4==0&&O9<180))return tO(Z)}else return g--,N70(I8());let J=(Z<<5^(Z>1?Y1.getUint16(g):Z>0?$0[g]:0))&4095,X=W70[J],Y=g,$=g+Z-3,Q,K=0;if(X&&X.bytes==Z){while(Y<$){if(Q=Y1.getUint32(Y),Q!=X[K++]){Y=1879048192;break}Y+=4}$+=3;while(Y<$)if(Q=$0[Y++],Q!=X[K++]){Y=1879048192;break}if(Y===$)return g=Y,X.string;$-=3,Y=g}X=[],W70[J]=X,X.bytes=Z;while(Y<$)Q=Y1.getUint32(Y),X.push(Q),Y+=4;$+=3;while(Y<$)Q=$0[Y++],X.push(Q);let W=Z<16?t_(Z):O70(Z);if(W!=null)return X.string=W;return X.string=tO(Z)}function N70(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(x1.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 G70=(Z,J)=>{let X=I8().map(N70),Y=Z;if(J!==void 0)Z=Z<32?-((J<<5)+Z):(J<<5)+Z,X.highByte=J;let $=W1[Z];if($&&($.isShared||nX))(W1.restoreStructures||(W1.restoreStructures=[]))[Z]=$;return W1[Z]=X,X.read=r_(X,Y),X.read()};p5[0]=()=>{};p5[0].noBuffer=!0;p5[66]=(Z)=>{let J=Z.byteLength%8||8,X=BigInt(Z[0]&128?Z[0]-256:Z[0]);for(let Y=1;Y<J;Y++)X<<=BigInt(8),X+=BigInt(Z[Y]);if(Z.byteLength!==J){let Y=new DataView(Z.buffer,Z.byteOffset,Z.byteLength),$=(Q,K)=>{let W=K-Q;if(W<=40){let F=Y.getBigUint64(Q);for(let H=Q+8;H<K;H+=8)F<<=BigInt(64n),F|=Y.getBigUint64(H);return F}let G=Q+(W>>4<<3),V=$(Q,G),z=$(G,K);return V<<BigInt((K-G)*8)|z};X=X<<BigInt((Y.byteLength-J)*8)|$(J,Y.byteLength)}return X};var V70={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==="function"?AggregateError:null};p5[101]=()=>{let Z=I8();if(!V70[Z[0]]){let J=Error(Z[1],{cause:Z[2]});return J.name=Z[0],J}return V70[Z[0]](Z[1],{cause:Z[2]})};p5[105]=(Z)=>{if(x1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=Y1.getUint32(g-4);if(!MJ)MJ=new Map;let X=$0[g],Y;if(X>=144&&X<160||X==220||X==221)Y=[];else if(X>=128&&X<144||X==222||X==223)Y=new Map;else if((X>=199&&X<=201||X>=212&&X<=216)&&$0[g+1]===115)Y=new Set;else Y={};let $={target:Y};MJ.set(J,$);let Q=I8();if(!$.used)return $.target=Q;else Object.assign(Y,Q);if(Y instanceof Map)for(let[K,W]of Q.entries())Y.set(K,W);if(Y instanceof Set)for(let K of Array.from(Q))Y.add(K);return Y};p5[112]=(Z)=>{if(x1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=Y1.getUint32(g-4),X=MJ.get(J);return X.used=!0,X.target};p5[115]=()=>new Set(I8());var e_=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((Z)=>Z+"Array"),$u1=typeof globalThis==="object"?globalThis:window;p5[116]=(Z)=>{let J=Z[0],X=Uint8Array.prototype.slice.call(Z,1).buffer,Y=e_[J];if(!Y){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 $u1[Y](X)};p5[120]=()=>{let Z=I8();return new RegExp(Z[0],Z[1])};var Qu1=[];p5[98]=(Z)=>{let J=(Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3],X=g;return g+=J-Z.length,s8=Qu1,s8=[K70(),K70()],s8.position0=0,s8.position1=0,s8.postBundlePosition=g,g=X,I8()};p5[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 R70(Z){if(a_)a_();let J=O9,X=g,Y=xH,$=w9,Q=J4,K=OJ,W=o$,G=MJ,V=s8,z=new Uint8Array($0.slice(0,O9)),F=W1,H=W1.slice(0,W1.length),q=x1,U=nX,B=Z();return O9=J,g=X,xH=Y,w9=$,J4=Q,OJ=K,o$=W,MJ=G,s8=V,$0=z,nX=U,W1=F,W1.splice(0,W1.length,...H),x1=q,Y1=new DataView($0.buffer,$0.byteOffset,$0.byteLength),B}function eO(){$0=null,MJ=null,W1=null}var t$=new Array(147);for(let Z=0;Z<256;Z++)t$[Z]=+("1e"+Math.floor(45.15-Z*0.30103));var JM=new NJ({useRecords:!1}),Ku1=JM.unpack,Wu1=JM.unpackMultiple,Gu1=JM.unpack,hH={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},Vu1=new Float32Array(1),Rl6=new Uint8Array(Vu1.buffer,0,4);function j70(Z,J,X){i_=Z,n_=J,a_=X}var YM;try{YM=new TextEncoder}catch(Z){}var Xv,T70,sW=typeof Buffer!=="undefined",XM=sW?function(Z){return Buffer.allocUnsafeSlow(Z)}:Uint8Array,k70=sW?Buffer:Uint8Array,D70=sW?4294967296:2144337920,p,fH,h1,d=0,p6,K8=null,E70,zu1=21760,Hu1=/[\u0080-\uFFFF]/,a7=Symbol("record-id");class e$ extends NJ{constructor(Z){super(Z);this.offset=0;let J,X,Y,$,Q,K=k70.prototype.utf8Write?function(I,_){return p.utf8Write(I,_,p.byteLength-_)}:YM&&YM.encodeInto?function(I,_){return YM.encodeInto(I,p.subarray(_)).written}:!1,W=this;if(!Z)Z={};let G=Z&&Z.sequential,V=Z.structures||Z.saveStructures,z=Z.maxSharedStructures;if(z==null)z=V?32:0;if(z>8160)throw new Error("Maximum maxSharedStructure is 8160");if(Z.structuredClone&&Z.moreTypes==null)this.moreTypes=!0;let F=Z.maxOwnStructures;if(F==null)F=V?32:64;if(!this.structures&&Z.useRecords!=!1)this.structures=[];let H=z>32||F+z>64,q=z+64,U=z+F+64;if(U>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let B=[],L=0,w=0;this.pack=this.encode=function(I,_){if(!p)p=new XM(8192),h1=p.dataView||(p.dataView=new DataView(p.buffer,0,8192)),d=0;if(p6=p.length-10,p6-d<2048)p=new XM(p.length),h1=p.dataView||(p.dataView=new DataView(p.buffer,0,p.length)),p6=p.length-10,d=0;else d=d+7&2147483640;if(X=d,_&wu1)d+=_&255;if(Q=W.structuredClone?new Map:null,W.bundleStrings&&typeof I!=="string")K8=[],K8.size=1/0;else K8=null;if($=W.structures,$){if($.uninitialized)$=W._mergeStructures(W.getStructures());let u=$.sharedLength||0;if(u>z)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+$.sharedLength);if(!$.transitions){$.transitions=Object.create(null);for(let i=0;i<u;i++){let e=$[i];if(!e)continue;let Z0,K0=$.transitions;for(let S0=0,A0=e.length;S0<A0;S0++){let s0=e[S0];if(Z0=K0[s0],!Z0)Z0=K0[s0]=Object.create(null);K0=Z0}K0[a7]=i+64}this.lastNamedStructuresLength=u}if(!G)$.nextId=u+64}if(Y)Y=!1;let b;try{if(W.randomAccessStructure&&I&&I.constructor&&I.constructor===Object)x(I);else R(I);let u=K8;if(K8)C70(X,R,0);if(Q&&Q.idsToInsert){let i=Q.idsToInsert.sort((S0,A0)=>S0.offset>A0.offset?1:-1),e=i.length,Z0=-1;while(u&&e>0){let S0=i[--e].offset+X;if(S0<u.stringsPosition+X&&Z0===-1)Z0=0;if(S0>u.position+X){if(Z0>=0)Z0+=6}else{if(Z0>=0)h1.setUint32(u.position+X,h1.getUint32(u.position+X)+Z0),Z0=-1;u=u.previous,e++}}if(Z0>=0&&u)h1.setUint32(u.position+X,h1.getUint32(u.position+X)+Z0);if(d+=i.length*6,d>p6)k(d);W.offset=d;let K0=Fu1(p.subarray(X,d),i);return Q=null,K0}if(W.offset=d,_&Bu1)return p.start=X,p.end=d,p;return p.subarray(X,d)}catch(u){throw b=u,u}finally{if($){if(M(),Y&&W.saveStructures){let u=$.sharedLength||0,i=p.subarray(X,d),e=I70($,W);if(!b){if(W.saveStructures(e,e.isCompatible)===!1)return W.pack(I,_);if(W.lastNamedStructuresLength=u,p.length>1073741824)p=null;return i}}}if(p.length>1073741824)p=null;if(_&Lu1)d=X}};let M=()=>{if(w<10)w++;let I=$.sharedLength||0;if($.length>I&&!G)$.length=I;if(L>1e4){if($.transitions=null,w=0,L=0,B.length>0)B=[]}else if(B.length>0&&!G){for(let _=0,b=B.length;_<b;_++)B[_][a7]=0;B=[]}},N=(I)=>{var _=I.length;if(_<16)p[d++]=144|_;else if(_<65536)p[d++]=220,p[d++]=_>>8,p[d++]=_&255;else p[d++]=221,h1.setUint32(d,_),d+=4;for(let b=0;b<_;b++)R(I[b])},R=(I)=>{if(d>p6)p=k(d);var _=typeof I,b;if(_==="string"){let u=I.length;if(K8&&u>=4&&u<4096){if((K8.size+=u)>zu1){let K0,S0=(K8[0]?K8[0].length*3+K8[1].length:0)+10;if(d+S0>p6)p=k(d+S0);let A0;if(K8.position)A0=K8,p[d]=200,d+=3,p[d++]=98,K0=d-X,d+=4,C70(X,R,0),h1.setUint16(K0+X-3,d-X-K0);else p[d++]=214,p[d++]=98,K0=d-X,d+=4;K8=["",""],K8.previous=A0,K8.size=0,K8.position=K0}let Z0=Hu1.test(I);K8[Z0?0:1]+=I,p[d++]=193,R(Z0?-u:u);return}let i;if(u<32)i=1;else if(u<256)i=2;else if(u<65536)i=3;else i=5;let e=u*3;if(d+e>p6)p=k(d+e);if(u<64||!K){let Z0,K0,S0,A0=d+i;for(Z0=0;Z0<u;Z0++)if(K0=I.charCodeAt(Z0),K0<128)p[A0++]=K0;else if(K0<2048)p[A0++]=K0>>6|192,p[A0++]=K0&63|128;else if((K0&64512)===55296&&((S0=I.charCodeAt(Z0+1))&64512)===56320)K0=65536+((K0&1023)<<10)+(S0&1023),Z0++,p[A0++]=K0>>18|240,p[A0++]=K0>>12&63|128,p[A0++]=K0>>6&63|128,p[A0++]=K0&63|128;else p[A0++]=K0>>12|224,p[A0++]=K0>>6&63|128,p[A0++]=K0&63|128;b=A0-d-i}else b=K(I,d+i);if(b<32)p[d++]=160|b;else if(b<256){if(i<2)p.copyWithin(d+2,d+1,d+1+b);p[d++]=217,p[d++]=b}else if(b<65536){if(i<3)p.copyWithin(d+3,d+2,d+2+b);p[d++]=218,p[d++]=b>>8,p[d++]=b&255}else{if(i<5)p.copyWithin(d+5,d+3,d+3+b);p[d++]=219,h1.setUint32(d,b),d+=4}d+=b}else if(_==="number")if(I>>>0===I)if(I<32||I<128&&this.useRecords===!1||I<64&&!this.randomAccessStructure)p[d++]=I;else if(I<256)p[d++]=204,p[d++]=I;else if(I<65536)p[d++]=205,p[d++]=I>>8,p[d++]=I&255;else p[d++]=206,h1.setUint32(d,I),d+=4;else if(I>>0===I)if(I>=-32)p[d++]=256+I;else if(I>=-128)p[d++]=208,p[d++]=I+256;else if(I>=-32768)p[d++]=209,h1.setInt16(d,I),d+=2;else p[d++]=210,h1.setInt32(d,I),d+=4;else{let u;if((u=this.useFloat32)>0&&I<4294967296&&I>=-2147483648){p[d++]=202,h1.setFloat32(d,I);let i;if(u<4||(i=I*t$[(p[d]&127)<<1|p[d+1]>>7])>>0===i){d+=4;return}else d--}p[d++]=203,h1.setFloat64(d,I),d+=8}else if(_==="object"||_==="function")if(!I)p[d++]=192;else{if(Q){let i=Q.get(I);if(i){if(!i.id){let e=Q.idsToInsert||(Q.idsToInsert=[]);i.id=e.push(i)}p[d++]=214,p[d++]=112,h1.setUint32(d,i.id),d+=4;return}else Q.set(I,{offset:d-X})}let u=I.constructor;if(u===Object)T(I);else if(u===Array)N(I);else if(u===Map)if(this.mapAsEmptyObject)p[d++]=128;else{if(b=I.size,b<16)p[d++]=128|b;else if(b<65536)p[d++]=222,p[d++]=b>>8,p[d++]=b&255;else p[d++]=223,h1.setUint32(d,b),d+=4;for(let[i,e]of I)R(i),R(e)}else{for(let i=0,e=Xv.length;i<e;i++){let Z0=T70[i];if(I instanceof Z0){let K0=Xv[i];if(K0.write){if(K0.type)p[d++]=212,p[d++]=K0.type,p[d++]=0;let J8=K0.write.call(this,I);if(J8===I)if(Array.isArray(I))N(I);else T(I);else R(J8);return}let S0=p,A0=h1,s0=d;p=null;let x8;try{x8=K0.pack.call(this,I,(J8)=>{if(p=S0,S0=null,d+=J8,d>p6)k(d);return{target:p,targetView:h1,position:d-J8}},R)}finally{if(S0)p=S0,h1=A0,d=s0,p6=p.length-10}if(x8){if(x8.length+d>p6)k(x8.length+d);d=P70(x8,p,d,K0.type)}return}}if(Array.isArray(I))N(I);else{if(I.toJSON){let i=I.toJSON();if(i!==I)return R(i)}if(_==="function")return R(this.writeFunction&&this.writeFunction(I));T(I)}}}else if(_==="boolean")p[d++]=I?195:194;else if(_==="bigint"){if(I<9223372036854776000&&I>=-9223372036854776000)p[d++]=211,h1.setBigInt64(d,I);else if(I<18446744073709552000&&I>0)p[d++]=207,h1.setBigUint64(d,I);else if(this.largeBigIntToFloat)p[d++]=203,h1.setFloat64(d,Number(I));else if(this.largeBigIntToString)return R(I.toString());else if(this.useBigIntExtension||this.moreTypes){let u=I<0?BigInt(-1):BigInt(0),i;if(I>>BigInt(65536)===u){let e=BigInt(18446744073709552000)-BigInt(1),Z0=[];while(!0){if(Z0.push(I&e),I>>BigInt(63)===u)break;I>>=BigInt(64)}i=new Uint8Array(new BigUint64Array(Z0).buffer),i.reverse()}else{let e=I<0,Z0=(e?~I:I).toString(16);if(Z0.length%2)Z0="0"+Z0;else if(parseInt(Z0.charAt(0),16)>=8)Z0="00"+Z0;if(sW)i=Buffer.from(Z0,"hex");else{i=new Uint8Array(Z0.length/2);for(let K0=0;K0<i.length;K0++)i[K0]=parseInt(Z0.slice(K0*2,K0*2+2),16)}if(e)for(let K0=0;K0<i.length;K0++)i[K0]=~i[K0]}if(i.length+d>p6)k(i.length+d);d=P70(i,p,d,66);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(_==="undefined")if(this.encodeUndefinedAsNil)p[d++]=192;else p[d++]=212,p[d++]=0,p[d++]=0;else throw new Error("Unknown type: "+_)},P=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(I)=>{let _;if(this.skipValues){_=[];for(let i in I)if((typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(i))&&!this.skipValues.includes(I[i]))_.push(i)}else _=Object.keys(I);let b=_.length;if(b<16)p[d++]=128|b;else if(b<65536)p[d++]=222,p[d++]=b>>8,p[d++]=b&255;else p[d++]=223,h1.setUint32(d,b),d+=4;let u;if(this.coercibleKeyAsNumber)for(let i=0;i<b;i++){u=_[i];let e=Number(u);R(isNaN(e)?u:e),R(I[u])}else for(let i=0;i<b;i++)R(u=_[i]),R(I[u])}:(I)=>{p[d++]=222;let _=d-X;d+=2;let b=0;for(let u in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(u))R(u),R(I[u]),b++;if(b>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');p[_+++X]=b>>8,p[_+X]=b&255},D=this.useRecords===!1?P:Z.progressiveRecords&&!H?(I)=>{let _,b=$.transitions||($.transitions=Object.create(null)),u=d++-X,i;for(let e in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(e)){if(_=b[e],_)b=_;else{let Z0=Object.keys(I),K0=b;b=$.transitions;let S0=0;for(let A0=0,s0=Z0.length;A0<s0;A0++){let x8=Z0[A0];if(_=b[x8],!_)_=b[x8]=Object.create(null),S0++;b=_}if(u+X+1==d)d--,A(b,Z0,S0);else v(b,Z0,u,S0);i=!0,b=K0[e]}R(I[e])}if(!i){let e=b[a7];if(e)p[u+X]=e;else v(b,Object.keys(I),u,0)}}:(I)=>{let _,b=$.transitions||($.transitions=Object.create(null)),u=0;for(let e in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(e)){if(_=b[e],!_)_=b[e]=Object.create(null),u++;b=_}let i=b[a7];if(i)if(i>=96&&H)p[d++]=((i-=96)&31)+96,p[d++]=i>>5;else p[d++]=i;else A(b,b.__keys__||Object.keys(I),u);for(let e in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(e))R(I[e])},C=typeof this.useRecords=="function"&&this.useRecords,T=C?(I)=>{C(I)?D(I):P(I)}:D,k=(I)=>{let _;if(I>16777216){if(I-X>D70)throw new Error("Packed buffer would be larger than maximum buffer size");_=Math.min(D70,Math.round(Math.max((I-X)*(I>67108864?1.25:2),4194304)/4096)*4096)}else _=(Math.max(I-X<<2,p.length-1)>>12)+1<<12;let b=new XM(_);if(h1=b.dataView||(b.dataView=new DataView(b.buffer,0,_)),I=Math.min(I,p.length),p.copy)p.copy(b,0,X,I);else b.set(p.slice(X,I));return d-=X,X=0,p6=b.length-10,p=b},A=(I,_,b)=>{let u=$.nextId;if(!u)u=64;if(u<q&&this.shouldShareStructure&&!this.shouldShareStructure(_)){if(u=$.nextOwnId,!(u<U))u=q;$.nextOwnId=u+1}else{if(u>=U)u=q;$.nextId=u+1}let i=_.highByte=u>=96&&H?u-96>>5:-1;if(I[a7]=u,I.__keys__=_,$[u-64]=_,u<q)if(_.isShared=!0,$.sharedLength=u-63,Y=!0,i>=0)p[d++]=(u&31)+96,p[d++]=i;else p[d++]=u;else{if(i>=0)p[d++]=213,p[d++]=114,p[d++]=(u&31)+96,p[d++]=i;else p[d++]=212,p[d++]=114,p[d++]=u;if(b)L+=w*b;if(B.length>=F)B.shift()[a7]=0;B.push(I),R(_)}},v=(I,_,b,u)=>{let i=p,e=d,Z0=p6,K0=X;if(p=fH,d=0,X=0,!p)fH=p=new XM(8192);p6=p.length-10,A(I,_,u),fH=p;let S0=d;if(p=i,d=e,p6=Z0,X=K0,S0>1){let A0=d+S0-1;if(A0>p6)k(A0);let s0=b+X;p.copyWithin(s0+S0,s0+1,d),p.set(fH.slice(0,S0),s0),d=A0}else p[b+X]=fH[0]},x=(I)=>{let _=E70(I,p,X,d,$,k,(b,u,i)=>{if(i)return Y=!0;d=u;let e=p;if(R(b),M(),e!==p)return{position:d,targetView:h1,target:p};return d},this);if(_===0)return T(I);d=_}}useBuffer(Z){p=Z,p.dataView||(p.dataView=new DataView(p.buffer,p.byteOffset,p.byteLength)),h1=p.dataView,d=0}set position(Z){d=Z}get position(){return d}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}T70=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,ZM];Xv=[{pack(Z,J,X){let Y=Z.getTime()/1000;if((this.useTimestamp32||Z.getMilliseconds()===0)&&Y>=0&&Y<4294967296){let{target:$,targetView:Q,position:K}=J(6);$[K++]=214,$[K++]=255,Q.setUint32(K,Y)}else if(Y>0&&Y<4294967296){let{target:$,targetView:Q,position:K}=J(10);$[K++]=215,$[K++]=255,Q.setUint32(K,Z.getMilliseconds()*4000000+(Y/1000/4294967296>>0)),Q.setUint32(K+4,Y)}else if(isNaN(Y)){if(this.onInvalidDate)return J(0),X(this.onInvalidDate());let{target:$,targetView:Q,position:K}=J(3);$[K++]=212,$[K++]=255,$[K++]=255}else{let{target:$,targetView:Q,position:K}=J(15);$[K++]=199,$[K++]=12,$[K++]=255,Q.setUint32(K,Z.getMilliseconds()*1e6),Q.setBigInt64(K+4,BigInt(Math.floor(Y)))}}},{pack(Z,J,X){if(this.setAsEmptyObject)return J(0),X({});let Y=Array.from(Z),{target:$,position:Q}=J(this.moreTypes?3:0);if(this.moreTypes)$[Q++]=212,$[Q++]=115,$[Q++]=0;X(Y)}},{pack(Z,J,X){let{target:Y,position:$}=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:Y,position:$}=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)Zv(Z,16,J);else Jv(sW?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let X=Z.constructor;if(X!==k70&&this.moreTypes)Zv(Z,e_.indexOf(X.name),J);else Jv(Z,J)}},{pack(Z,J){if(this.moreTypes)Zv(Z,17,J);else Jv(sW?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let{target:X,position:Y}=J(1);X[Y]=193}}];function Zv(Z,J,X,Y){let $=Z.byteLength;if($+1<256){var{target:Q,position:K}=X(4+$);Q[K++]=199,Q[K++]=$+1}else if($+1<65536){var{target:Q,position:K}=X(5+$);Q[K++]=200,Q[K++]=$+1>>8,Q[K++]=$+1&255}else{var{target:Q,position:K,targetView:W}=X(7+$);Q[K++]=201,W.setUint32(K,$+1),K+=4}if(Q[K++]=116,Q[K++]=J,!Z.buffer)Z=new Uint8Array(Z);Q.set(new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength),K)}function Jv(Z,J){let X=Z.byteLength;var Y,$;if(X<256){var{target:Y,position:$}=J(X+2);Y[$++]=196,Y[$++]=X}else if(X<65536){var{target:Y,position:$}=J(X+3);Y[$++]=197,Y[$++]=X>>8,Y[$++]=X&255}else{var{target:Y,position:$,targetView:Q}=J(X+5);Y[$++]=198,Q.setUint32($,X),$+=4}Y.set(Z,$)}function P70(Z,J,X,Y){let $=Z.length;switch($){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($<256)J[X++]=199,J[X++]=$;else if($<65536)J[X++]=200,J[X++]=$>>8,J[X++]=$&255;else J[X++]=201,J[X++]=$>>24,J[X++]=$>>16&255,J[X++]=$>>8&255,J[X++]=$&255}return J[X++]=Y,J.set(Z,X),X+=$,X}function Fu1(Z,J){let X,Y=J.length*6,$=Z.length-Y;while(X=J.pop()){let{offset:Q,id:K}=X;Z.copyWithin(Q+Y,Q,$),Y-=6;let W=Q+Y;Z[W++]=214,Z[W++]=105,Z[W++]=K>>24,Z[W++]=K>>16&255,Z[W++]=K>>8&255,Z[W++]=K&255,$=Q}return Z}function C70(Z,J,X){if(K8.length>0){h1.setUint32(K8.position+Z,d+X-K8.position-Z),K8.stringsPosition=d-Z;let Y=K8;K8=null,J(Y[0]),J(Y[1])}}function I70(Z,J){return Z.isCompatible=(X)=>{let Y=!X||(J.lastNamedStructuresLength||0)===X.length;if(!Y)J._mergeStructures(X);return Y},Z}function _70(Z,J){E70=Z,I70=J}var v70=new e$({useRecords:!1}),qu1=v70.pack,Uu1=v70.pack;var Bu1=512,Lu1=1024,wu1=2048;var Yv=3,rW=0,yH=2,$M=1,Qv=16,A70=["num","object","string","ascii"];A70[Qv]="date";var Mu1=[!1,!0,!0,!1,!1,!0,!0,!1],x70;try{new Function(""),x70=!0}catch(Z){}var ZQ,Nu1=typeof Buffer!=="undefined",QM,s7;try{QM=new TextEncoder}catch(Z){}var Ru1=Nu1?function(Z,J,X){return Z.utf8Write(J,X,Z.byteLength-X)}:QM&&QM.encodeInto?function(Z,J,X){return QM.encodeInto(J,Z.subarray(X)).written}:!1,_l6=Symbol("type"),vl6=Symbol("parent");_70(h70,Tu1);function h70(Z,J,X,Y,$,Q,K,W){let G=W.typedStructs||(W.typedStructs=[]),V=J.dataView,z=(G.lastStringStart||100)+Y,F=J.length-10,H=Y;if(Y>F)J=Q(Y),V=J.dataView,Y-=X,H-=X,z-=X,X=0,F=J.length-10;let q,U=z,B=G.transitions||(G.transitions=Object.create(null)),L=G.nextId||G.length,w=L<15?1:L<240?2:L<61440?3:L<15728640?4:0;if(w===0)return 0;Y+=w;let M=[],N,R=0;for(let D in Z){let C=Z[D],T=B[D];if(!T)B[D]=T={key:D,parent:B,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};if(Y>F)J=Q(Y),V=J.dataView,Y-=X,H-=X,z-=X,U-=X,X=0,F=J.length-10;switch(typeof C){case"number":let k=C;if(L<200||!T.num64){if(k>>0===k&&k<536870912&&k>-520093696){if(k<246&&k>=0&&(T.num8&&!(L>200&&T.num32)||k<32&&!T.num32))B=T.num8||i5(T,rW,1),J[Y++]=k;else B=T.num32||i5(T,rW,4),V.setUint32(Y,k,!0),Y+=4;break}else if(k<4294967296&&k>=-2147483648){if(V.setFloat32(Y,k,!0),Mu1[J[Y+3]>>>5]){let I;if((I=k*t$[(J[Y+3]&127)<<1|J[Y+2]>>7])>>0===I){B=T.num32||i5(T,rW,4),Y+=4;break}}}}B=T.num64||i5(T,rW,8),V.setFloat64(Y,k,!0),Y+=8;break;case"string":let A=C.length;if(q=U-z,(A<<2)+U>F)J=Q((A<<2)+U),V=J.dataView,Y-=X,H-=X,z-=X,U-=X,X=0,F=J.length-10;if(A>65280+q>>2){M.push(D,C,Y-H);break}let v,x=U;if(A<64){let I,_,b;for(I=0;I<A;I++)if(_=C.charCodeAt(I),_<128)J[U++]=_;else if(_<2048)v=!0,J[U++]=_>>6|192,J[U++]=_&63|128;else if((_&64512)===55296&&((b=C.charCodeAt(I+1))&64512)===56320)v=!0,_=65536+((_&1023)<<10)+(b&1023),I++,J[U++]=_>>18|240,J[U++]=_>>12&63|128,J[U++]=_>>6&63|128,J[U++]=_&63|128;else v=!0,J[U++]=_>>12|224,J[U++]=_>>6&63|128,J[U++]=_&63|128}else U+=Ru1(J,C,U),v=U-x>A;if(q<160||q<246&&(T.ascii8||T.string8)){if(v){if(!(B=T.string8))if(G.length>10&&(B=T.ascii8))B.__type=yH,T.ascii8=null,T.string8=B,K(null,0,!0);else B=i5(T,yH,1)}else if(q===0&&!N){N=!0,B=T.ascii0||i5(T,Yv,0);break}else if(!(B=T.ascii8)&&!(G.length>10&&(B=T.string8)))B=i5(T,Yv,1);J[Y++]=q}else B=T.string16||i5(T,yH,2),V.setUint16(Y,q,!0),Y+=2;break;case"object":if(C){if(C.constructor===Date)B=T.date64||i5(T,Qv,8),V.setFloat64(Y,C.getTime(),!0),Y+=8;else M.push(D,C,R);break}else if(T=S70(T,Y,V,-10),T)B=T,Y=ZQ;else M.push(D,C,R);break;case"boolean":B=T.num8||T.ascii8||i5(T,rW,1),J[Y++]=C?249:248;break;case"undefined":if(T=S70(T,Y,V,-9),T)B=T,Y=ZQ;else M.push(D,C,R);break;default:M.push(D,C,R)}R++}for(let D=0,C=M.length;D<C;){let T=M[D++],k=M[D++],A=M[D++],v=B[T];if(!v)B[T]=v={key:T,parent:B,enumerationOffset:A-R,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null};let x;if(k){let I;if(q=U-z,q<65280)if(B=v.object16,B)I=2;else if(B=v.object32)I=4;else B=i5(v,$M,2),I=2;else B=v.object32||i5(v,$M,4),I=4;if(x=K(k,U),typeof x==="object")U=x.position,V=x.targetView,J=x.target,z-=X,Y-=X,H-=X,X=0;else U=x;if(I===2)V.setUint16(Y,q,!0),Y+=2;else V.setUint32(Y,q,!0),Y+=4}else B=v.object16||i5(v,$M,2),V.setInt16(Y,k===null?-10:-9,!0),Y+=2;R++}let P=B[a7];if(P==null){P=W.typedStructs.length;let D=[],C=B,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(),B[a7]=P,W.typedStructs[P]=D,K(null,0,!0)}switch(w){case 1:if(P>=16)return 0;J[H]=P+32;break;case 2:if(P>=256)return 0;J[H]=56,J[H+1]=P;break;case 3:if(P>=65536)return 0;J[H]=57,V.setUint16(H+1,P,!0);break;case 4:if(P>=16777216)return 0;V.setUint32(H,(P<<8)+58,!0);break}if(Y<z){if(z===U)return Y;J.copyWithin(Y,z,U),U+=Y-z,G.lastStringStart=Y-H}else if(Y>z){if(z===U)return Y;return G.lastStringStart=Y-H,h70(Z,J,X,H,$,Q,K,W)}return U}function S70(Z,J,X,Y){let $;if($=Z.ascii8||Z.num8)return X.setInt8(J,Y,!0),ZQ=J+1,$;if($=Z.string16||Z.object16)return X.setInt16(J,Y,!0),ZQ=J+2,$;if($=Z.num32)return X.setUint32(J,3758096640+Y,!0),ZQ=J+4,$;if($=Z.num64)return X.setFloat64(J,NaN,!0),X.setInt8(J,Y),ZQ=J+8,$;ZQ=J;return}function i5(Z,J,X){let Y=A70[J]+(X<<3),$=Z[Y]||(Z[Y]=Object.create(null));return $.__type=J,$.__size=X,$.__parent=Z,$}function ju1(Z){if(!(Z instanceof Map))return Z;let J=Z.get("typed")||[];if(Object.isFrozen(J))J=J.map(($)=>$.slice(0));let X=Z.get("named"),Y=Object.create(null);for(let $=0,Q=J.length;$<Q;$++){let K=J[$],W=Y;for(let[G,V,z]of K){let F=W[z];if(!F)W[z]=F={key:z,parent:W,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};W=i5(F,G,V)}W[a7]=$}return J.transitions=Y,this.typedStructs=J,this.lastTypedStructuresLength=J.length,X}var $v=Symbol.for("source");function Du1(Z,J,X,Y){let $=Z[J++]-32;if($>=24)switch($){case 24:$=Z[J++];break;case 25:$=Z[J++]+(Z[J++]<<8);break;case 26:$=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16);break;case 27:$=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16)+(Z[J++]<<24);break}let Q=Y.typedStructs&&Y.typedStructs[$];if(!Q){if(Z=Uint8Array.prototype.slice.call(Z,J,X),X-=J,J=0,!Y.getStructures)throw new Error(`Reference to shared structure ${$} without getStructures method`);if(Y._mergeStructures(Y.getStructures()),!Y.typedStructs)throw new Error("Could not find any shared typed structures");if(Y.lastTypedStructuresLength=Y.typedStructs.length,Q=Y.typedStructs[$],!Q)throw new Error("Could not find typed structure "+$)}var{construct:K,fullConstruct:W}=Q;if(!K){K=Q.construct=function q(){},W=Q.fullConstruct=function q(){},W.prototype=Y.structPrototype||{};var G=K.prototype=Y.structPrototype?Object.create(Y.structPrototype):{};let z=[],F=0,H;for(let q=0,U=Q.length;q<U;q++){let B=Q[q],[L,w,M,N]=B;if(M==="__proto__")M="__proto_";let R={key:M,offset:F};if(N)z.splice(q+N,0,R);else z.push(R);let P;switch(w){case 0:P=()=>0;break;case 1:P=(C,T)=>{let k=C.bytes[T+R.offset];return k>=246?oW(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+R.offset,!0);return v>=65280?oW(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+R.offset,!0);return v>=4294967040?oW(v&255):v};break}R.getRef=P,F+=w;let D;switch(L){case Yv:if(H&&!H.next)H.next=R;H=R,R.multiGetCount=0,D=function(C){let{bytes:T,position:k}=C,A=F+k,v=P(C,k);if(typeof v!=="number")return v;let x,I=R.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 w70(T,v+A,x-v)};break;case yH:case $M:if(H&&!H.next)H.next=R;H=R,D=function(C){let T=C.position,k=F+T,A=P(C,T);if(typeof A!=="number")return A;let v=C.bytes,x,I=R.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(L===yH)return v.toString("utf8",A+k,x+k);else{s7=C;try{return Y.unpack(v,{start:A+k,end:x+k})}finally{s7=null}}};break;case rW: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+R.offset,v=k.getInt32(A,!0);if(v<536870912){if(v>-520093696)return v;if(v>-536870912)return oW(v&255)}let x=k.getFloat32(A,!0),I=t$[(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+R.offset,!0);if(isNaN(A)){let v=T[C.position+R.offset];if(v>=246)return oW(v)}return A};break;case 1:D=function(C){let k=C.bytes[C.position+R.offset];return k<246?k:oW(k)};break}break;case Qv: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+R.offset,!0))};break}R.get=D}if(x70){let q=[],U=[],B=0,L;for(let M of z){if(Y.alwaysLazyProperty&&Y.alwaysLazyProperty(M.key)){L=!0;continue}Object.defineProperty(G,M.key,{get:Pu1(M.get),enumerable:!0});let N="v"+B++;U.push(N),q.push("o["+JSON.stringify(M.key)+"]="+N+"(s)")}if(L)q.push("__proto__:this");let w=new Function(...U,"var c=this;return function(s){var o=new c();"+q.join(";")+";return o;}").apply(W,z.map((M)=>M.get));Object.defineProperty(G,"toJSON",{value(M){return w.call(this,this[$v])}})}else Object.defineProperty(G,"toJSON",{value(q){let U={};for(let B=0,L=z.length;B<L;B++){let w=z[B].key;U[w]=this[w]}return U}})}var V=new K;return V[$v]={bytes:Z,position:J,srcString:"",bytesEnd:X},V}function oW(Z){switch(Z){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw new Error("Unknown constant")}function Pu1(Z){return function(){return Z(this[$v])}}function Cu1(){if(s7)s7.bytes=Uint8Array.prototype.slice.call(s7.bytes,s7.position,s7.bytesEnd),s7.position=0,s7.bytesEnd=s7.bytes.length}function Tu1(Z,J){if(J.typedStructs){let Y=new Map;Y.set("named",Z),Y.set("typed",J.typedStructs),Z=Y}let X=J.lastTypedStructuresLength||0;return Z.isCompatible=(Y)=>{let $=!0;if(Y instanceof Map){if((Y.get("named")||[]).length!==(J.lastNamedStructuresLength||0))$=!1;if((Y.get("typed")||[]).length!==X)$=!1}else if(Y instanceof Array||Array.isArray(Y)){if(Y.length!==(J.lastNamedStructuresLength||0))$=!1}if(!$)J._mergeStructures(Y);return $},J.lastTypedStructuresLength=J.typedStructs&&J.typedStructs.length,Z}j70(Du1,ju1,Cu1);var Iu1=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!Iu1){let Z;try{if(Z=m("msgpackr-extract"),Z)L70(Z.extractStrings)}catch(J){}}var FN=r(BW0(),1);import je1 from"http";import De1 from"https";import HN from"fs";import Pe1 from"path";import Ce1 from"url";var LW0=`-----BEGIN CERTIFICATE-----
414
414
  MIIDRjCCAi6gAwIBAgIFOTEzNTIwDQYJKoZIhvcNAQELBQAwWDEQMA4GA1UEAxMH
415
415
  SFlUT1BJQTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNV
@@ -455,7 +455,7 @@ qYGMwU/HBVHkLAn5XvT2a9xM0mzZ558d+ahbw8qAgRxg7BZ+2PW/bf7F2WRBUk1f
455
455
  xauhAoGBALEspoxQozwohGQnP7EMF0/0JoKNpdNv0b0qCVvNiMo0+N297lI2mFQp
456
456
  6xYlW/1l9afLokklF/J2IsyBrTCZoY7SaEk/lMMrQSyra+y0z71ogZ8A4ny9fxsj
457
457
  0dDYJZGllL+3E/MQfd7k+KnOM/+A+cPoAnci76+L3vdkUb2P8SJk
458
- -----END RSA PRIVATE KEY-----`;var BA=process.env.PORT??8080,LA="0.8.6-dev1",wA;(($)=>{$.READY="WEBSERVER.READY";$.STOPPED="WEBSERVER.STOPPED";$.ERROR="WEBSERVER.ERROR";$.UPGRADE="WEBSERVER.UPGRADE"})(wA||={});class I3 extends O0{static instance=new I3;_webserver=FN.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:LA,runtime:"Bun"in globalThis?"bun":("Deno"in globalThis)?"deno":"node"})}),this._webserver.use(FN.default.static("assets"));try{this._webserver.use(FN.default.static(Pe1.dirname(m.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js"))))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?je1.createServer(this._webserver):De1.createServer({key:HN.existsSync("assets/certs/localhost.key")?HN.readFileSync("assets/certs/localhost.key"):wW0,cert:HN.existsSync("assets/certs/localhost.crt")?HN.readFileSync("assets/certs/localhost.crt"):LW0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else c.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(BA,this._onStarted),console.info(`WebServer.start(): Server running on port ${BA}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return c.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let Y=Ce1.parse(Z.url??"",!0).query,$=Y.connectionId?.toString(),Q=Y.sessionToken?.toString()??"";if($&&YZ.instance.isValidConnectionId($))Z.connectionId=$;else{let K=await p7.instance.getPlayerSession(Q);if(K?.error){let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
458
+ -----END RSA PRIVATE KEY-----`;var BA=process.env.PORT??8080,LA="0.8.6-dev3",wA;(($)=>{$.READY="WEBSERVER.READY";$.STOPPED="WEBSERVER.STOPPED";$.ERROR="WEBSERVER.ERROR";$.UPGRADE="WEBSERVER.UPGRADE"})(wA||={});class I3 extends O0{static instance=new I3;_webserver=FN.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:LA,runtime:"Bun"in globalThis?"bun":("Deno"in globalThis)?"deno":"node"})}),this._webserver.use(FN.default.static("assets"));try{this._webserver.use(FN.default.static(Pe1.dirname(m.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js"))))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?je1.createServer(this._webserver):De1.createServer({key:HN.existsSync("assets/certs/localhost.key")?HN.readFileSync("assets/certs/localhost.key"):wW0,cert:HN.existsSync("assets/certs/localhost.crt")?HN.readFileSync("assets/certs/localhost.crt"):LW0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else c.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(BA,this._onStarted),console.info(`WebServer.start(): Server running on port ${BA}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return c.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let Y=Ce1.parse(Z.url??"",!0).query,$=Y.connectionId?.toString(),Q=Y.sessionToken?.toString()??"";if($&&YZ.instance.isValidConnectionId($))Z.connectionId=$;else{let K=await p7.instance.getPlayerSession(Q);if(K?.error){let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
459
459
  Content-Type: text/plain\r
460
460
  Content-Length: ${W.length}\r
461
461
  Connection: close\r
@@ -490,4 +490,4 @@ ${$.stack}`:"unknown"}}}}}var rT8=(Z={})=>{let J=Z.limit??lT8;return{name:pT8,pr
490
490
  `;let W=ZX1(Y);Y.write(`${K}\r
491
491
  `);let{connect:G,buffered:V}=await W;if(Z.emit("proxyConnect",G),this.emit("proxyConnect",G,Z),G.statusCode===200){if(Z.once("socket",gJ6),J.secureEndpoint){MU("Upgrading socket connection to TLS");let F=J.servername||J.host;return Ng.connect({...JX1(J,"host","path","port"),socket:Y,servername:dJ.isIP(F)?void 0:F})}return Y}Y.destroy();let z=new dJ.Socket({writable:!1});return z.readable=!0,Z.once("socket",(F)=>{MU("Replaying proxy buffer for failed request"),F.push(V),F.push(null)}),z}}xj.__initStatic();function gJ6(Z){Z.resume()}function JX1(Z,...J){let X={},Y;for(Y in Z)if(!J.includes(Y))X[Y]=Z[Y];return X}var lJ6=32768;function pJ6(Z){return new dJ6({read(){this.push(Z),this.push(null)}})}function NU(Z){let J;try{J=new URL(Z.url)}catch(G){return e0(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),KG(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",Y=iJ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),$=X?uJ6:mJ6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=Y?new xj(Y):new $.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),W=nJ6(Z,Z.httpModule??$,K);return KG(Z,W)}function iJ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some(($)=>Z.host.endsWith($)||Z.hostname.endsWith($)))return;else return J}function nJ6(Z,J,X){let{hostname:Y,pathname:$,port:Q,protocol:K,search:W}=new URL(Z.url);return function G(V){return new Promise((z,F)=>{cQ(()=>{let H=pJ6(V.body),q={...Z.headers};if(V.body.length>lJ6)q["content-encoding"]="gzip",H=H.pipe(cJ6());let U=J.request({method:"POST",agent:X,headers:q,hostname:Y,path:`${$}${W}`,port:Q,protocol:K,ca:Z.caCerts},(B)=>{B.on("data",()=>{}),B.on("end",()=>{}),B.setEncoding("utf8");let L=B.headers["retry-after"]??null,w=B.headers["x-sentry-rate-limits"]??null;z({statusCode:B.statusCode,headers:{"retry-after":L,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});U.on("error",F),H.pipe(U)})})}}var aJ6=new Set(["false","f","n","no","off","0"]),sJ6=new Set(["true","t","y","yes","on","1"]);function hj(Z,J){let X=String(Z).toLowerCase();if(aJ6.has(X))return!1;if(sJ6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as oJ6,sep as rJ6}from"node:path";function XX1(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function RU(Z=process.argv[1]?vy(process.argv[1]):process.cwd(),J=rJ6==="\\"){let X=J?XX1(Z):Z;return(Y)=>{if(!Y)return;let $=J?XX1(Y):Y,{dir:Q,base:K,ext:W}=oJ6.parse($);if(W===".js"||W===".mjs"||W===".cjs")K=K.slice(0,W.length*-1);let G=decodeURIComponent(K);if(!Q)Q=".";let V=Q.lastIndexOf("/node_modules");if(V>-1)return`${Q.slice(V+14).replace(/\//g,".")}:${G}`;if(Q.startsWith(X)){let z=Q.slice(X.length+1).replace(/\//g,".");return z?`${z}:${G}`:G}return G}}function jU(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(M0.SENTRY_RELEASE?.id)return M0.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,X=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,Y=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||X||Y||Z}var DU=DR(Wb(RU()));var $X1=r(Y0(),1),QX1=r(r0(),1);import*as YX1 from"node:os";import{threadId as tJ6,isMainThread as eJ6}from"worker_threads";var ZX6=60000;class IG extends nR{constructor(Z){let J=Z.includeServerName===!1?void 0:Z.serverName||global.process.env.SENTRY_NAME||YX1.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)QX1.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});nQ(X,"node"),h.log(`Initializing Sentry: process: ${process.pid}, thread: ${eJ6?"main":`worker-${tJ6}`}.`);super(X);let{enableLogs:Y,_experiments:$}=this.getOptions();if(Y??$?.enableLogs){if(this._logOnExitFlushListener=()=>{NY(this)},J)this.on("beforeCaptureLog",(K)=>{K.attributes={...K.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=R1,X=$X1.trace.getTracer(Z,J);return this._tracer=X,X}async flush(Z){if(await this.traceProvider?.forceFlush(),this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);return super.close(Z)}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{G1&&h.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??ZX6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return JJ1(this,Z)}}var KX1=r(LR(),1);import JX6 from"module";function WX1(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!M0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=KX1.createAddHookMessageChannel();JX6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){h.warn("Failed to register ESM hook",X)}}else e0(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function fj(){return[lq(),cq(),pq(),iq(),nq(),FJ1(),OJ1(),qU(),UU(),GU(),zU(),WU(),LU(),eJ1(),HU()]}function Rg(Z={}){return XX6(Z,fj)}function XX6(Z={},J){let X=YX6(Z,J);if(X.debug===!0)if(G1)h.enable();else e0(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!C4()&&X.registerEsmLoaderHooks!==!1)WX1();if(Tj(),T0().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===qg))X.integrations.push(BU({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));nQ(X,"node-core");let $=new IG(X);return T0().setClient($),$.init(),h.log(`Running in ${C4()?"CommonJS":"ESM"} mode.`),$.startClientReportTracking(),KX6(),iZ1($),XJ1($),$}function PU(){if(!G1)return;let Z=oZ1(),J=["SentryContextManager","SentryPropagator"];if(u8())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))h.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))h.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function YX6(Z,J){let X=$X6(Z.release),Y=Z.spotlight??hj(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,$=QX6(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??NU,stackParser:Ff(Z.stackParser||DU),release:X,tracesSampleRate:$,spotlight:Y,debug:hj(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,W=Z.defaultIntegrations??J(Q);return{...Q,integrations:zy({defaultIntegrations:W,integrations:K})}}function $X6(Z){if(Z!==void 0)return Z;let J=jU();if(J!==void 0)return J;return}function QX6(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function KX6(){if(hj(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=yQ(Z,J);T0().setPropagationContext(X)}}function s1(Z,J){Z.setAttribute(v0,J)}var VX1=r(r0(),1);var GX1=(Z)=>({package:Z,"javascript.is_cjs":C4()});function cJ(Z,J){let X=X0()?.getOptions();if(!X?.disableInstrumentationWarnings&&!VX1.isWrapped(Z)&&lQ()&&u8(X))e0(()=>{if(C4())console.warn(`[Sentry] ${J} is not instrumented. This is likely because you required/imported ${J} before calling \`Sentry.init()\`.`);else console.warn(`[Sentry] ${J} is not instrumented. Please make sure to initialize Sentry in a separate file that you \`--import\` when running node, see: https://docs.sentry.io/platforms/javascript/guides/${J}/install/esm/.`)}),z7().setContext("missing_instrumentation",GX1(J))}var WX6=[["january","1"],["february","2"],["march","3"],["april","4"],["may","5"],["june","6"],["july","7"],["august","8"],["september","9"],["october","10"],["november","11"],["december","12"],["jan","1"],["feb","2"],["mar","3"],["apr","4"],["may","5"],["jun","6"],["jul","7"],["aug","8"],["sep","9"],["oct","10"],["nov","11"],["dec","12"],["sunday","0"],["monday","1"],["tuesday","2"],["wednesday","3"],["thursday","4"],["friday","5"],["saturday","6"],["sun","0"],["mon","1"],["tue","2"],["wed","3"],["thu","4"],["fri","5"],["sat","6"]];function zK(Z){return WX6.reduce((J,[X,Y])=>J.replace(new RegExp(X,"gi"),Y),Z)}var zX1="Automatic instrumentation of CronJob only supports crontab string";function HX1(Z,J){let X=!1;return new Proxy(Z,{construct(Y,$){let[Q,K,W,G,V,...z]=$;if(typeof Q!=="string")throw new Error(zX1);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let F=zK(Q);async function H(q,U){return UZ(J,async()=>{try{await K(q,U)}catch(B){throw Z1(B),B}},{schedule:{type:"crontab",value:F},timezone:V||void 0})}return new Y(Q,H,W,G,V,...z)},get(Y,$){if($==="from")return(Q)=>{let{cronTime:K,onTick:W,timeZone:G}=Q;if(typeof K!=="string")throw new Error(zX1);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let V=zK(K);return Q.onTick=async(z,F)=>{return UZ(J,async()=>{try{await W(z,F)}catch(H){throw Z1(H),H}},{schedule:{type:"crontab",value:V},timezone:G||void 0})},Y.from(Q)};else return Y[$]}})}function FX1(Z){return new Proxy(Z,{get(J,X){if(X==="schedule"&&J.schedule)return new Proxy(J.schedule,{apply(Y,$,Q){let[K,W,G]=Q,V=G?.name,z=G?.timezone;if(!V)throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');let F=async()=>{return UZ(V,async()=>{try{return await W()}catch(H){throw Z1(H),H}},{schedule:{type:"crontab",value:zK(K)},timezone:z})};return Y.apply($,[K,F,G])}});else return J[X]}})}function qX1(Z){return new Proxy(Z,{get(J,X){if(X==="scheduleJob")return new Proxy(J.scheduleJob,{apply(Y,$,Q){let[K,W,G]=Q;if(typeof K!=="string"||typeof W!=="string"||typeof G!=="function")throw new Error("Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string");let V=K,z=W;async function F(){return UZ(V,async()=>{await G?.()},{schedule:{type:"crontab",value:zK(z)}})}return Y.apply($,[V,z,F])}});return J[X]}})}var jg={instrumentCron:HX1,instrumentNodeCron:FX1,instrumentNodeSchedule:qX1};var Dg="Http",UX1="@opentelemetry_sentry-patched/instrumentation-http",GX6=B0(`${Dg}.sentry`,(Z)=>{return new CG(Z)}),Pg=B0(Dg,(Z)=>{let J=new LX1.HttpInstrumentation(Z);try{J._diag=BX1.diag.createComponentLogger({namespace:UX1}),J.instrumentationName=UX1}catch{}return J});function VX6(Z,J={}){if(typeof Z.spans==="boolean")return Z.spans;if(J.skipOpenTelemetrySetup)return!1;if(!u8(J)&&_9.major>=22)return!1;return!0}var yj=a((Z={})=>{let J=Z.dropSpansForIncomingRequestStatusCodes??[[401,404],[300,399]];return{name:Dg,setupOnce(){let X=VX6(Z,X0()?.getOptions());if(GX6({...Z,extractIncomingTraceFromHeader:!X,propagateTraceInOutgoingRequests:!X}),X){let Y=FX6(Z);Pg(Y)}},processEvent(X){if(X.type==="transaction"){let Y=X.contexts?.trace?.data?.["http.response.status_code"];if(typeof Y==="number"&&J.some(($)=>{if(typeof $==="number")return $===Y;let[Q,K]=$;return Y>=Q&&Y<=K}))return null}return X}}});function zX6(Z){return"outputData"in Z&&"outputSize"in Z&&!("client"in Z)&&!("statusCode"in Z)}function HX6(Z){return Z.headers["next-router-prefetch"]==="1"}function FX6(Z={}){return{...Z.instrumentation?._experimentalConfig,disableIncomingRequestInstrumentation:Z.disableIncomingRequestSpans,ignoreOutgoingRequestHook:(X)=>{let Y=DG(X);if(!Y)return!1;let $=Z.ignoreOutgoingRequests;if($?.(Y,X))return!0;return!1},ignoreIncomingRequestHook:(X)=>{let Y=X.url,$=X.method?.toUpperCase();if($==="OPTIONS"||$==="HEAD")return!0;let Q=Z.ignoreIncomingRequests;if(Y&&Q?.(Y,X))return!0;return!1},requireParentforOutgoingSpans:!1,requireParentforIncomingSpans:!1,requestHook:(X,Y)=>{if(s1(X,"auto.http.otel.http"),!zX6(Y)&&HX6(Y))X.setAttribute("sentry.http.prefetch",!0);Z.instrumentation?.requestHook?.(X,Y)},responseHook:(X,Y)=>{Z.instrumentation?.responseHook?.(X,Y)},applyCustomAttributesOnSpan:(X,Y,$)=>{Z.instrumentation?.applyCustomAttributesOnSpan?.(X,Y,$)}}}var SX1=r(vX1(),1);var AX1="NodeFetch",LX6=B0(AX1,SX1.UndiciInstrumentation,(Z)=>{return RX6(Z)}),wX6=B0(`${AX1}.sentry`,kG,(Z)=>{return Z}),OX6=(Z={})=>{return{name:"NodeFetch",setupOnce(){if(NX6(Z,X0()?.getOptions()))LX6(Z);wX6(Z)}}},gj=a(OX6);function MX6(Z,J="/"){let X=`${Z}`;if(X.endsWith("/")&&J.startsWith("/"))return`${X}${J.slice(1)}`;if(!X.endsWith("/")&&!J.startsWith("/"))return`${X}/${J.slice(1)}`;return`${X}${J}`}function NX6(Z,J={}){return typeof Z.spans==="boolean"?Z.spans:!J.skipOpenTelemetrySetup&&u8(J)}function RX6(Z={}){return{requireParentforSpans:!1,ignoreRequestHook:(X)=>{let Y=MX6(X.origin,X.path),$=Z.ignoreOutgoingRequests;return!!($&&Y&&$(Y))},startSpanHook:()=>{return{[v0]:"auto.http.otel.node_fetch"}}}}var ZY1=r(tX1(),1);var eX1="FileSystem",JY1=a((Z={})=>{return{name:eX1,setupOnce(){B0(eX1,()=>new ZY1.FsInstrumentation({requireParentSpan:!0,endHook(J,{args:X,span:Y,error:$}){if(Y.updateName(`fs.${J}`),Y.setAttributes({[j0]:"file",[v0]:"auto.file.fs"}),Z.recordErrorMessagesAsSpanAttributes){if(typeof X[0]==="string"&&xX6.includes(J))Y.setAttribute("path_argument",X[0]);else if(typeof X[0]==="string"&&typeof X[1]==="string"&&AX6.includes(J))Y.setAttribute("target_argument",X[0]),Y.setAttribute("path_argument",X[1]);else if(typeof X[0]==="string"&&SX6.includes(J))Y.setAttribute("prefix_argument",X[0]);else if(typeof X[0]==="string"&&typeof X[1]==="string"&&vX6.includes(J))Y.setAttribute("existing_path_argument",X[0]),Y.setAttribute("new_path_argument",X[1]);else if(typeof X[0]==="string"&&typeof X[1]==="string"&&_X6.includes(J))Y.setAttribute("src_argument",X[0]),Y.setAttribute("dest_argument",X[1]);else if(typeof X[0]==="string"&&typeof X[1]==="string"&&IX6.includes(J))Y.setAttribute("old_path_argument",X[0]),Y.setAttribute("new_path_argument",X[1])}if($&&Z.recordErrorMessagesAsSpanAttributes)Y.setAttribute("fs_error",$.message)}}))()}}}),IX6=["rename","renameSync"],_X6=["copyFile","cp","copyFileSync","cpSync"],vX6=["link","linkSync"],SX6=["mkdtemp","mkdtempSync"],AX6=["symlink","symlinkSync"],xX6=["access","appendFile","chmod","chown","exists","mkdir","lchown","lstat","lutimes","open","opendir","readdir","readFile","readlink","realpath","realpath.native","rm","rmdir","stat","truncate","unlink","utimes","writeFile","accessSync","appendFileSync","chmodSync","chownSync","existsSync","lchownSync","lstatSync","lutimesSync","opendirSync","mkdirSync","openSync","readdirSync","readFileSync","readlinkSync","realpathSync","realpathSync.native","rmdirSync","rmSync","statSync","truncateSync","unlinkSync","utimesSync","writeFileSync"];var _Y1=r(DY1(),1);var T4=typeof __SENTRY_DEBUG__==="undefined"||__SENTRY_DEBUG__;var R7=r(Y0(),1),ij=r(q1(),1),DZ=r(r0(),1),IY1=r(j1(),1);var k4;(function(Z){Z.EXPRESS_TYPE="express.type";let X="express.name";Z.EXPRESS_NAME=X})(k4||(k4={}));var pJ;(function(Z){Z.ROUTER="router";let X="middleware";Z.MIDDLEWARE=X;let Y="request_handler";Z.REQUEST_HANDLER=Y})(pJ||(pJ={}));var vg=Symbol("express-layer-patched"),SY="__ot_middlewares";var CY1=(Z,J)=>{if(Array.isArray(Z[SY])===!1)Object.defineProperty(Z,SY,{enumerable:!1,value:[]});if(J===void 0)return;Z[SY].push(J)},TY1=(Z,J)=>{let X=J.handle?.stack?.[0];if(X?.route?.path)return`${Z}${X.route.path}`;if(X?.handle?.stack)return TY1(Z,X);return Z},kY1=(Z,J,X)=>{if(J.name==="router"){let Y=TY1("",J),$=Y?Y:X||Z||"/";return{attributes:{[k4.EXPRESS_NAME]:$,[k4.EXPRESS_TYPE]:pJ.ROUTER},name:`router - ${$}`}}else if(J.name==="bound dispatch"||J.name==="handle")return{attributes:{[k4.EXPRESS_NAME]:(Z||X)??"request handler",[k4.EXPRESS_TYPE]:pJ.REQUEST_HANDLER},name:`request handler${J.path?` - ${Z||X}`:""}`};else return{attributes:{[k4.EXPRESS_NAME]:J.name,[k4.EXPRESS_TYPE]:pJ.MIDDLEWARE},name:`middleware - ${J.name}`}},tX6=(Z,J)=>{if(typeof J==="string")return J===Z;else if(J instanceof RegExp)return J.test(Z);else if(typeof J==="function")return J(Z);else throw new TypeError("Pattern is in unsupported datatype")},EY1=(Z,J,X)=>{if(Array.isArray(X?.ignoreLayersType)&&X?.ignoreLayersType?.includes(J))return!0;if(Array.isArray(X?.ignoreLayers)===!1)return!1;try{for(let Y of X.ignoreLayers)if(tX6(Z,Y))return!0}catch{}return!1},Sg=(Z)=>Z instanceof Error?[Z,Z.message]:[String(Z),String(Z)],pj=(Z)=>{let J=Z[0];if(Array.isArray(J))return J.map((X)=>PY1(X)||"").join(",");return PY1(J)},PY1=(Z)=>{if(typeof Z==="string")return Z;if(Z instanceof RegExp||typeof Z==="number")return Z.toString();return};var eX6="0.1.0",ZY6="@sentry/instrumentation-express-v5";class Ag extends DZ.InstrumentationBase{constructor(Z={}){super(ZY6,eX6,Z)}init(){return[new DZ.InstrumentationNodeModuleDefinition("express",[">=5.0.0"],(Z)=>this._setup(Z),(Z)=>this._tearDown(Z))]}_setup(Z){let J=Z.Router.prototype;if(DZ.isWrapped(J.route))this._unwrap(J,"route");if(this._wrap(J,"route",this._getRoutePatch()),DZ.isWrapped(J.use))this._unwrap(J,"use");if(this._wrap(J,"use",this._getRouterUsePatch()),DZ.isWrapped(Z.application.use))this._unwrap(Z.application,"use");return this._wrap(Z.application,"use",this._getAppUsePatch()),Z}_tearDown(Z){if(Z===void 0)return;let J=Z.Router.prototype;this._unwrap(J,"route"),this._unwrap(J,"use"),this._unwrap(Z.application,"use")}_getRoutePatch(){let Z=this;return function(J){return function X(...Y){let $=J.apply(this,Y),Q=this.stack[this.stack.length-1];return Z._applyPatch(Q,pj(Y)),$}}}_getRouterUsePatch(){let Z=this;return function(J){return function X(...Y){let $=J.apply(this,Y),Q=this.stack[this.stack.length-1];return Z._applyPatch(Q,pj(Y)),$}}}_getAppUsePatch(){let Z=this;return function(J){return function X(...Y){let $=this.router,Q=J.apply(this,Y);if($){let K=$.stack[$.stack.length-1];Z._applyPatch(K,pj(Y))}return Q}}}_applyPatch(Z,J){let X=this;if(Z[vg]===!0)return;Z[vg]=!0,this._wrap(Z,"handle",(Y)=>{if(Y.length===4)return Y;let $=function(Q,K){CY1(Q,J);let W=Q[SY].filter((R)=>R!=="/"&&R!=="/*").join("").replace(/\/{2,}/g,"/"),G=W.length>0?W:void 0,V={[IY1.SEMATTRS_HTTP_ROUTE]:G},z=kY1(W,Z,J),F=z.attributes[k4.EXPRESS_TYPE],H=ij.getRPCMetadata(R7.context.active());if(H?.type===ij.RPCType.HTTP)H.route=G;if(EY1(z.name,F,X.getConfig())){if(F===pJ.MIDDLEWARE)Q[SY].pop();return Y.apply(this,arguments)}if(R7.trace.getSpan(R7.context.active())===void 0)return Y.apply(this,arguments);let q=X._getSpanName({request:Q,layerType:F,route:W},z.name),U=X.tracer.startSpan(q,{attributes:Object.assign(V,z.attributes)}),{requestHook:B}=X.getConfig();if(B)DZ.safeExecuteInTheMiddle(()=>B(U,{request:Q,layerType:F,route:W}),(R)=>{if(R)R7.diag.error("express instrumentation: request hook failed",R)},!0);let L=!1;if(z.attributes[k4.EXPRESS_TYPE]!==pJ.MIDDLEWARE)U.end(),L=!0;let w=()=>{if(L===!1)L=!0,U.end()},M=Array.from(arguments),N=M.findIndex((R)=>typeof R==="function");if(N>=0)arguments[N]=function(){let R=arguments[0],P=![void 0,null,"route","router"].includes(R);if(!L&&P){let[C,T]=Sg(R);U.recordException(C),U.setStatus({code:R7.SpanStatusCode.ERROR,message:T})}if(L===!1)L=!0,Q.res?.removeListener("finish",w),U.end();if(!(Q.route&&P))Q[SY].pop();return M[N].apply(this,arguments)};try{return Y.apply(this,arguments)}catch(R){let[P,D]=Sg(R);throw U.recordException(P),U.setStatus({code:R7.SpanStatusCode.ERROR,message:D}),R}finally{if(!L)K.once("finish",w)}};for(let Q in Y)Object.defineProperty($,Q,{get(){return Y[Q]},set(K){Y[Q]=K}});return $})}_getSpanName(Z,J){let{spanNameHook:X}=this.getConfig();if(!(X instanceof Function))return J;try{return X(Z,J)??J}catch(Y){return R7.diag.error("express instrumentation: error calling span name rewrite hook",Y),J}}}var vY1="Express",JY6="Express-V5";function SY1(Z){s1(Z,"auto.http.otel.express");let J=L0(Z).data,X=J["express.type"];if(X)Z.setAttribute(j0,`${X}.express`);let Y=J["express.name"];if(typeof Y==="string")Z.updateName(Y)}function AY1(Z,J){if(E0()===B4())return T4&&h.warn("Isolation scope is still default isolation scope - skipping setting transactionName"),J;if(Z.layerType==="request_handler"){let X=Z.request,Y=X.method?X.method.toUpperCase():"GET";E0().setTransactionName(`${Y} ${Z.route}`)}return J}var xg=B0(vY1,()=>new _Y1.ExpressInstrumentation({requestHook:(Z)=>SY1(Z),spanNameHook:(Z,J)=>AY1(Z,J)})),hg=B0(JY6,()=>new Ag({requestHook:(Z)=>SY1(Z),spanNameHook:(Z,J)=>AY1(Z,J)})),XY6=()=>{return{name:vY1,setupOnce(){xg(),hg()}}},nj=a(XY6);function fg(Z){return function J(X,Y,$,Q){let K=WG(Y);if(E0().setSDKProcessingMetadata({normalizedRequest:K}),(Z?.shouldHandleError||QY6)(X)){let G=Z1(X,{mechanism:{type:"middleware",handled:!1}});$.sentry=G}Q(X)}}function YY6(){return function Z(J,X,Y){let $=WG(J);E0().setSDKProcessingMetadata({normalizedRequest:$}),Y()}}function xY1(Z,J){Z.use(YY6()),Z.use(fg(J)),cJ(Z.use,"express")}function $Y6(Z){let J=Z.status||Z.statusCode||Z.status_code||Z.output?.statusCode;return J?parseInt(J,10):500}function QY6(Z){return $Y6(Z)>=500}import*as lg from"node:diagnostics_channel";var A8=r(Y0(),1),oj=r(q1(),1),H$1=r(r0(),1),d8=r(j1(),1);import K$1 from"node:diagnostics_channel";var J$1=r(nY1(),1);var IU=(Z)=>{if(typeof Z!=="string")throw new TypeError("invalid pattern");if(Z.length>65536)throw new TypeError("pattern is too long")};var qY6={"[: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]},_U=(Z)=>Z.replace(/[[\]\\-]/g,"\\$&"),UY6=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),aY1=(Z)=>Z.join(""),sY1=(Z,J)=>{let X=J;if(Z.charAt(X)!=="[")throw new Error("not in a brace expression");let Y=[],$=[],Q=X+1,K=!1,W=!1,G=!1,V=!1,z=X,F="";Z:while(Q<Z.length){let B=Z.charAt(Q);if((B==="!"||B==="^")&&Q===X+1){V=!0,Q++;continue}if(B==="]"&&K&&!G){z=Q+1;break}if(K=!0,B==="\\"){if(!G){G=!0,Q++;continue}}if(B==="["&&!G){for(let[L,[w,M,N]]of Object.entries(qY6))if(Z.startsWith(L,Q)){if(F)return["$.",!1,Z.length-X,!0];if(Q+=L.length,N)$.push(w);else Y.push(w);W=W||M;continue Z}}if(G=!1,F){if(B>F)Y.push(_U(F)+"-"+_U(B));else if(B===F)Y.push(_U(B));F="",Q++;continue}if(Z.startsWith("-]",Q+1)){Y.push(_U(B+"-")),Q+=2;continue}if(Z.startsWith("-",Q+1)){F=B,Q+=2;continue}Y.push(_U(B)),Q++}if(z<Q)return["",!1,0,!1];if(!Y.length&&!$.length)return["$.",!1,Z.length-X,!0];if($.length===0&&Y.length===1&&/^\\?.$/.test(Y[0])&&!V){let B=Y[0].length===2?Y[0].slice(-1):Y[0];return[UY6(B),!1,z-X,!1]}let H="["+(V?"^":"")+aY1(Y)+"]",q="["+(V?"":"^")+aY1($)+"]";return[Y.length&&$.length?"("+H+"|"+q+")":Y.length?H:q,W,z-X,!0]};var AY=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/\[([^\/\\])\]/g,"$1"):Z.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")};var BY6=new Set(["!","?","+","*","@"]),oY1=(Z)=>BY6.has(Z),LY6="(?!(?:^|/)\\.\\.?(?:$|/))",aj="(?!\\.)",wY6=new Set(["[","."]),OY6=new Set(["..","."]),MY6=new Set("().*{}+?[]^$\\!"),NY6=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),gg="[^/]",rY1=gg+"*?",tY1=gg+"+?";class I6{type;#Z;#J;#Y=!1;#X=[];#$;#z;#F;#W=!1;#G;#V;#H=!1;constructor(Z,J,X={}){if(this.type=Z,Z)this.#J=!0;if(this.#$=J,this.#Z=this.#$?this.#$.#Z:this,this.#G=this.#Z===this?X:this.#Z.#G,this.#F=this.#Z===this?[]:this.#Z.#F,Z==="!"&&!this.#Z.#W)this.#F.push(this);this.#z=this.#$?this.#$.#X.length:0}get hasMagic(){if(this.#J!==void 0)return this.#J;for(let Z of this.#X){if(typeof Z==="string")continue;if(Z.type||Z.hasMagic)return this.#J=!0}return this.#J}toString(){if(this.#V!==void 0)return this.#V;if(!this.type)return this.#V=this.#X.map((Z)=>String(Z)).join("");else return this.#V=this.type+"("+this.#X.map((Z)=>String(Z)).join("|")+")"}#Q(){if(this!==this.#Z)throw new Error("should only call on root");if(this.#W)return this;this.toString(),this.#W=!0;let Z;while(Z=this.#F.pop()){if(Z.type!=="!")continue;let J=Z,X=J.#$;while(X){for(let Y=J.#z+1;!X.type&&Y<X.#X.length;Y++)for(let $ of Z.#X){if(typeof $==="string")throw new Error("string part in extglob AST??");$.copyIn(X.#X[Y])}J=X,X=J.#$}}return this}push(...Z){for(let J of Z){if(J==="")continue;if(typeof J!=="string"&&!(J instanceof I6&&J.#$===this))throw new Error("invalid part: "+J);this.#X.push(J)}}toJSON(){let Z=this.type===null?this.#X.slice().map((J)=>typeof J==="string"?J:J.toJSON()):[this.type,...this.#X.map((J)=>J.toJSON())];if(this.isStart()&&!this.type)Z.unshift([]);if(this.isEnd()&&(this===this.#Z||this.#Z.#W&&this.#$?.type==="!"))Z.push({});return Z}isStart(){if(this.#Z===this)return!0;if(!this.#$?.isStart())return!1;if(this.#z===0)return!0;let Z=this.#$;for(let J=0;J<this.#z;J++){let X=Z.#X[J];if(!(X instanceof I6&&X.type==="!"))return!1}return!0}isEnd(){if(this.#Z===this)return!0;if(this.#$?.type==="!")return!0;if(!this.#$?.isEnd())return!1;if(!this.type)return this.#$?.isEnd();let Z=this.#$?this.#$.#X.length:0;return this.#z===Z-1}copyIn(Z){if(typeof Z==="string")this.push(Z);else this.push(Z.clone(this))}clone(Z){let J=new I6(this.type,Z);for(let X of this.#X)J.copyIn(X);return J}static#U(Z,J,X,Y){let $=!1,Q=!1,K=-1,W=!1;if(J.type===null){let H=X,q="";while(H<Z.length){let U=Z.charAt(H++);if($||U==="\\"){$=!$,q+=U;continue}if(Q){if(H===K+1){if(U==="^"||U==="!")W=!0}else if(U==="]"&&!(H===K+2&&W))Q=!1;q+=U;continue}else if(U==="["){Q=!0,K=H,W=!1,q+=U;continue}if(!Y.noext&&oY1(U)&&Z.charAt(H)==="("){J.push(q),q="";let B=new I6(U,J);H=I6.#U(Z,B,H,Y),J.push(B);continue}q+=U}return J.push(q),H}let G=X+1,V=new I6(null,J),z=[],F="";while(G<Z.length){let H=Z.charAt(G++);if($||H==="\\"){$=!$,F+=H;continue}if(Q){if(G===K+1){if(H==="^"||H==="!")W=!0}else if(H==="]"&&!(G===K+2&&W))Q=!1;F+=H;continue}else if(H==="["){Q=!0,K=G,W=!1,F+=H;continue}if(oY1(H)&&Z.charAt(G)==="("){V.push(F),F="";let q=new I6(H,V);V.push(q),G=I6.#U(Z,q,G,Y);continue}if(H==="|"){V.push(F),F="",z.push(V),V=new I6(null,J);continue}if(H===")"){if(F===""&&J.#X.length===0)J.#H=!0;return V.push(F),F="",J.push(...z,V),G}F+=H}return J.type=null,J.#J=void 0,J.#X=[Z.substring(X-1)],G}static fromGlob(Z,J={}){let X=new I6(null,void 0,J);return I6.#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(!(Y||this.#J||this.#G.nocase&&!this.#G.nocaseMagicOnly&&Z.toUpperCase()!==Z.toLowerCase()))return X;let K=(this.#G.nocase?"i":"")+($?"u":"");return Object.assign(new RegExp(`^${J}$`,K),{_src:J,_glob:Z})}get options(){return this.#G}toRegExpSource(Z){let J=Z??!!this.#G.dot;if(this.#Z===this)this.#Q();if(!this.type){let W=this.isStart()&&this.isEnd(),G=this.#X.map((H)=>{let[q,U,B,L]=typeof H==="string"?I6.#B(H,this.#J,W):H.toRegExpSource(Z);return this.#J=this.#J||B,this.#Y=this.#Y||L,q}).join(""),V="";if(this.isStart()){if(typeof this.#X[0]==="string"){if(!(this.#X.length===1&&OY6.has(this.#X[0]))){let q=wY6,U=J&&q.has(G.charAt(0))||G.startsWith("\\.")&&q.has(G.charAt(2))||G.startsWith("\\.\\.")&&q.has(G.charAt(4)),B=!J&&!Z&&q.has(G.charAt(0));V=U?LY6:B?aj:""}}}let z="";if(this.isEnd()&&this.#Z.#W&&this.#$?.type==="!")z="(?:$|\\/)";return[V+G+z,AY(G),this.#J=!!this.#J,this.#Y]}let X=this.type==="*"||this.type==="+",Y=this.type==="!"?"(?:(?!(?:":"(?:",$=this.#L(J);if(this.isStart()&&this.isEnd()&&!$&&this.type!=="!"){let W=this.toString();return this.#X=[W],this.type=null,this.#J=void 0,[W,AY(this.toString()),!1,!1]}let Q=!X||Z||J||!aj?"":this.#L(!0);if(Q===$)Q="";if(Q)$=`(?:${$})(?:${Q})*?`;let K="";if(this.type==="!"&&this.#H)K=(this.isStart()&&!J?aj:"")+tY1;else{let W=this.type==="!"?"))"+(this.isStart()&&!J&&!Z?aj:"")+rY1+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&Q?")":this.type==="*"&&Q?")?":`)${this.type}`;K=Y+$+W}return[K,AY($),this.#J=!!this.#J,this.#Y]}#L(Z){return this.#X.map((J)=>{if(typeof J==="string")throw new Error("string type in extglob ast??");let[X,Y,$,Q]=J.toRegExpSource(Z);return this.#Y=this.#Y||Q,X}).filter((J)=>!(this.isStart()&&this.isEnd())||!!J).join("|")}static#B(Z,J,X=!1){let Y=!1,$="",Q=!1;for(let K=0;K<Z.length;K++){let W=Z.charAt(K);if(Y){Y=!1,$+=(MY6.has(W)?"\\":"")+W;continue}if(W==="\\"){if(K===Z.length-1)$+="\\\\";else Y=!0;continue}if(W==="["){let[G,V,z,F]=sY1(Z,K);if(z){$+=G,Q=Q||V,K+=z-1,J=J||F;continue}}if(W==="*"){if(X&&Z==="*")$+=tY1;else $+=rY1;J=!0;continue}if(W==="?"){$+=gg,J=!0;continue}$+=NY6(W)}return[$,AY(Z),!!J,Q]}}var mg=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/[?*()[\]]/g,"[$&]"):Z.replace(/[?*()[\]\\]/g,"\\$&")};var _6=(Z,J,X={})=>{if(IU(J),!X.nocomment&&J.charAt(0)==="#")return!1;return new vU(J,X).match(Z)},RY6=/^\*+([^+@!?\*\[\(]*)$/,jY6=(Z)=>(J)=>!J.startsWith(".")&&J.endsWith(Z),DY6=(Z)=>(J)=>J.endsWith(Z),PY6=(Z)=>{return Z=Z.toLowerCase(),(J)=>!J.startsWith(".")&&J.toLowerCase().endsWith(Z)},CY6=(Z)=>{return Z=Z.toLowerCase(),(J)=>J.toLowerCase().endsWith(Z)},TY6=/^\*+\.\*+$/,kY6=(Z)=>!Z.startsWith(".")&&Z.includes("."),EY6=(Z)=>Z!=="."&&Z!==".."&&Z.includes("."),IY6=/^\.\*+$/,_Y6=(Z)=>Z!=="."&&Z!==".."&&Z.startsWith("."),vY6=/^\*+$/,SY6=(Z)=>Z.length!==0&&!Z.startsWith("."),AY6=(Z)=>Z.length!==0&&Z!=="."&&Z!=="..",xY6=/^\?+([^+@!?\*\[\(]*)?$/,hY6=([Z,J=""])=>{let X=X$1([Z]);if(!J)return X;return J=J.toLowerCase(),(Y)=>X(Y)&&Y.toLowerCase().endsWith(J)},fY6=([Z,J=""])=>{let X=Y$1([Z]);if(!J)return X;return J=J.toLowerCase(),(Y)=>X(Y)&&Y.toLowerCase().endsWith(J)},yY6=([Z,J=""])=>{let X=Y$1([Z]);return!J?X:(Y)=>X(Y)&&Y.endsWith(J)},bY6=([Z,J=""])=>{let X=X$1([Z]);return!J?X:(Y)=>X(Y)&&Y.endsWith(J)},X$1=([Z])=>{let J=Z.length;return(X)=>X.length===J&&!X.startsWith(".")},Y$1=([Z])=>{let J=Z.length;return(X)=>X.length===J&&X!=="."&&X!==".."},$$1=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",eY1={win32:{sep:"\\"},posix:{sep:"/"}},gY6=$$1==="win32"?eY1.win32.sep:eY1.posix.sep;_6.sep=gY6;var I4=Symbol("globstar **");_6.GLOBSTAR=I4;var mY6="[^/]",uY6=mY6+"*?",dY6="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",cY6="(?:(?!(?:\\/|^)\\.).)*?",lY6=(Z,J={})=>(X)=>_6(X,Z,J);_6.filter=lY6;var E4=(Z,J={})=>Object.assign({},Z,J),pY6=(Z)=>{if(!Z||typeof Z!=="object"||!Object.keys(Z).length)return _6;let J=_6;return Object.assign((Y,$,Q={})=>J(Y,$,E4(Z,Q)),{Minimatch:class Y extends J.Minimatch{constructor($,Q={}){super($,E4(Z,Q))}static defaults($){return J.defaults(E4(Z,$)).Minimatch}},AST:class Y extends J.AST{constructor($,Q,K={}){super($,Q,E4(Z,K))}static fromGlob($,Q={}){return J.AST.fromGlob($,E4(Z,Q))}},unescape:(Y,$={})=>J.unescape(Y,E4(Z,$)),escape:(Y,$={})=>J.escape(Y,E4(Z,$)),filter:(Y,$={})=>J.filter(Y,E4(Z,$)),defaults:(Y)=>J.defaults(E4(Z,Y)),makeRe:(Y,$={})=>J.makeRe(Y,E4(Z,$)),braceExpand:(Y,$={})=>J.braceExpand(Y,E4(Z,$)),match:(Y,$,Q={})=>J.match(Y,$,E4(Z,Q)),sep:J.sep,GLOBSTAR:I4})};_6.defaults=pY6;var Q$1=(Z,J={})=>{if(IU(Z),J.nobrace||!/\{(?:(?!\{).)*\}/.test(Z))return[Z];return J$1.default(Z)};_6.braceExpand=Q$1;var iY6=(Z,J={})=>new vU(Z,J).makeRe();_6.makeRe=iY6;var nY6=(Z,J,X={})=>{let Y=new vU(J,X);if(Z=Z.filter(($)=>Y.match($)),Y.options.nonull&&!Z.length)Z.push(J);return Z};_6.match=nY6;var Z$1=/[?*]|[+@!]\(.*?\)|\[|\]/,aY6=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class vU{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(Z,J={}){if(IU(Z),J=J||{},this.options=J,this.pattern=Z,this.platform=J.platform||$$1,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=(...$)=>console.error(...$);this.debug(this.pattern,this.globSet);let X=this.globSet.map(($)=>this.slashSplit($));this.globParts=this.preprocess(X),this.debug(this.pattern,this.globParts);let Y=this.globParts.map(($,Q,K)=>{if(this.isWindows&&this.windowsNoMagicRoot){let W=$[0]===""&&$[1]===""&&($[2]==="?"||!Z$1.test($[2]))&&!Z$1.test($[3]),G=/^[a-z]:/i.test($[0]);if(W)return[...$.slice(0,4),...$.slice(4).map((V)=>this.parse(V))];else if(G)return[$[0],...$.slice(1).map((V)=>this.parse(V))]}return $.map((W)=>this.parse(W))});if(this.debug(this.pattern,Y),this.set=Y.filter(($)=>$.indexOf(!1)===-1),this.isWindows)for(let $=0;$<this.set.length;$++){let Q=this.set[$];if(Q[0]===""&&Q[1]===""&&this.globParts[$][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 Y=0;Y<Z[X].length;Y++)if(Z[X][Y]==="**")Z[X][Y]="*"}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 Y=X;while(J[Y+1]==="**")Y++;if(Y!==X)J.splice(X,Y-X)}return J})}levelOneOptimize(Z){return Z.map((J)=>{return J=J.reduce((X,Y)=>{let $=X[X.length-1];if(Y==="**"&&$==="**")return X;if(Y===".."){if($&&$!==".."&&$!=="."&&$!=="**")return X.pop(),X}return X.push(Y),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 Y=1;Y<Z.length-1;Y++){let $=Z[Y];if(Y===1&&$===""&&Z[0]==="")continue;if($==="."||$==="")J=!0,Z.splice(Y,1),Y--}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 Y=Z[X-1];if(Y&&Y!=="."&&Y!==".."&&Y!=="**")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 Y=-1;while((Y=X.indexOf("**",Y+1))!==-1){let Q=Y;while(X[Q+1]==="**")Q++;if(Q>Y)X.splice(Y+1,Q-Y);let K=X[Y+1],W=X[Y+2],G=X[Y+3];if(K!=="..")continue;if(!W||W==="."||W===".."||!G||G==="."||G==="..")continue;J=!0,X.splice(Y,1);let V=X.slice(0);V[Y]="**",Z.push(V),Y--}if(!this.preserveMultipleSlashes){for(let Q=1;Q<X.length-1;Q++){let K=X[Q];if(Q===1&&K===""&&X[0]==="")continue;if(K==="."||K==="")J=!0,X.splice(Q,1),Q--}if(X[0]==="."&&X.length===2&&(X[1]==="."||X[1]===""))J=!0,X.pop()}let $=0;while(($=X.indexOf("..",$+1))!==-1){let Q=X[$-1];if(Q&&Q!=="."&&Q!==".."&&Q!=="**"){J=!0;let W=$===1&&X[$+1]==="**"?["."]:[];if(X.splice($-1,2,...W),X.length===0)X.push("");$-=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 Y=this.partsMatch(Z[J],Z[X],!this.preserveMultipleSlashes);if(Y){Z[J]=[],Z[X]=Y;break}}return Z.filter((J)=>J.length)}partsMatch(Z,J,X=!1){let Y=0,$=0,Q=[],K="";while(Y<Z.length&&$<J.length)if(Z[Y]===J[$])Q.push(K==="b"?J[$]:Z[Y]),Y++,$++;else if(X&&Z[Y]==="**"&&J[$]===Z[Y+1])Q.push(Z[Y]),Y++;else if(X&&J[$]==="**"&&Z[Y]===J[$+1])Q.push(J[$]),$++;else if(Z[Y]==="*"&&J[$]&&(this.options.dot||!J[$].startsWith("."))&&J[$]!=="**"){if(K==="b")return!1;K="a",Q.push(Z[Y]),Y++,$++}else if(J[$]==="*"&&Z[Y]&&(this.options.dot||!Z[Y].startsWith("."))&&Z[Y]!=="**"){if(K==="a")return!1;K="b",Q.push(J[$]),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 Y=0;Y<Z.length&&Z.charAt(Y)==="!";Y++)J=!J,X++;if(X)this.pattern=Z.slice(X);this.negate=J}matchOne(Z,J,X=!1){let Y=this.options;if(this.isWindows){let U=typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0]),B=!U&&Z[0]===""&&Z[1]===""&&Z[2]==="?"&&/^[a-z]:$/i.test(Z[3]),L=typeof J[0]==="string"&&/^[a-z]:$/i.test(J[0]),w=!L&&J[0]===""&&J[1]===""&&J[2]==="?"&&typeof J[3]==="string"&&/^[a-z]:$/i.test(J[3]),M=B?3:U?0:void 0,N=w?3:L?0:void 0;if(typeof M==="number"&&typeof N==="number"){let[R,P]=[Z[M],J[N]];if(R.toLowerCase()===P.toLowerCase()){if(J[N]=R,N>M)J=J.slice(N);else if(M>N)Z=Z.slice(M)}}}let{optimizationLevel:$=1}=this.options;if($>=2)Z=this.levelTwoFileOptimize(Z);this.debug("matchOne",this,{file:Z,pattern:J}),this.debug("matchOne",Z.length,J.length);for(var Q=0,K=0,W=Z.length,G=J.length;Q<W&&K<G;Q++,K++){this.debug("matchOne loop");var V=J[K],z=Z[Q];if(this.debug(J,V,z),V===!1)return!1;if(V===I4){this.debug("GLOBSTAR",[J,V,z]);var F=Q,H=K+1;if(H===G){this.debug("** at the end");for(;Q<W;Q++)if(Z[Q]==="."||Z[Q]===".."||!Y.dot&&Z[Q].charAt(0)===".")return!1;return!0}while(F<W){var q=Z[F];if(this.debug(`
492
492
  globstar while`,Z,F,J,H,q),this.matchOne(Z.slice(F),J.slice(H),X))return this.debug("globstar found match!",F,W,q),!0;else{if(q==="."||q===".."||!Y.dot&&q.charAt(0)==="."){this.debug("dot detected!",Z,F,J,H);break}this.debug("globstar swallow a segment, and continue"),F++}}if(X){if(this.debug(`
493
- >>> no match, partial?`,Z,F,J,H),F===W)return!0}return!1}let U;if(typeof V==="string")U=z===V,this.debug("string match",V,z,U);else U=V.test(z),this.debug("pattern match",V,z,U);if(!U)return!1}if(Q===W&&K===G)return!0;else if(Q===W)return X;else if(K===G)return Q===W-1&&Z[Q]==="";else throw new Error("wtf?")}braceExpand(){return Q$1(this.pattern,this.options)}parse(Z){IU(Z);let J=this.options;if(Z==="**")return I4;if(Z==="")return"";let X,Y=null;if(X=Z.match(vY6))Y=J.dot?AY6:SY6;else if(X=Z.match(RY6))Y=(J.nocase?J.dot?CY6:PY6:J.dot?DY6:jY6)(X[1]);else if(X=Z.match(xY6))Y=(J.nocase?J.dot?fY6:hY6:J.dot?yY6:bY6)(X);else if(X=Z.match(TY6))Y=J.dot?EY6:kY6;else if(X=Z.match(IY6))Y=_Y6;let $=I6.fromGlob(Z,this.options).toMMPattern();if(Y&&typeof $==="object")Reflect.defineProperty($,"test",{value:Y});return $}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?uY6:J.dot?dY6:cY6,Y=new Set(J.nocase?["i"]:[]),$=Z.map((W)=>{let G=W.map((V)=>{if(V instanceof RegExp)for(let z of V.flags.split(""))Y.add(z);return typeof V==="string"?aY6(V):V===I4?I4:V._src});return G.forEach((V,z)=>{let F=G[z+1],H=G[z-1];if(V!==I4||H===I4)return;if(H===void 0)if(F!==void 0&&F!==I4)G[z+1]="(?:\\/|"+X+"\\/)?"+F;else G[z]=X;else if(F===void 0)G[z-1]=H+"(?:\\/|"+X+")?";else if(F!==I4)G[z-1]=H+"(?:\\/|\\/"+X+"\\/)"+F,G[z+1]=I4}),G.filter((V)=>V!==I4).join("/")}).join("|"),[Q,K]=Z.length>1?["(?:",")"]:["",""];if($="^"+Q+$+K+"$",this.negate)$="^(?!"+$+").+$";try{this.regexp=new RegExp($,[...Y].join(""))}catch(W){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 Y=this.slashSplit(Z);this.debug(this.pattern,"split",Y);let $=this.set;this.debug(this.pattern,"set",$);let Q=Y[Y.length-1];if(!Q)for(let K=Y.length-2;!Q&&K>=0;K--)Q=Y[K];for(let K=0;K<$.length;K++){let W=$[K],G=Y;if(X.matchBase&&W.length===1)G=[Q];if(this.matchOne(G,W,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return _6.defaults(Z).Minimatch}}_6.AST=I6;_6.Minimatch=vU;_6.escape=mg;_6.unescape=AY;var W$1="@fastify/otel",oY6="0.8.0",rY6=">=4.0.0 <6",G$1=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],o1={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},xY={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},iJ="anonymous",T5=Symbol("fastify otel instance"),hY=Symbol("fastify otel request spans"),SU=Symbol("fastify otel request context"),V$1=Symbol("fastify otel addhook original"),z$1=Symbol("fastify otel setnotfound original"),sj=Symbol("fastify otel ignore path");class ug extends H$1.InstrumentationBase{constructor(Z){super(W$1,oY6,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[sj]=null,this._logger=A8.diag.createComponentLogger({namespace:W$1}),Z?.ignorePaths!=null||process.env.OTEL_FASTIFY_IGNORE_PATHS!=null){let J=Z?.ignorePaths??process.env.OTEL_FASTIFY_IGNORE_PATHS;if((typeof J!=="string"||J.length===0)&&typeof J!=="function")throw new TypeError("ignorePaths must be a string or a function");let X=_6;this[sj]=(Y)=>{if(typeof J==="function")return J(Y);else return X(Y.url,J)}}}enable(){if(this._handleInitialization===void 0&&this.getConfig().registerOnInitialization){let Z=this.plugin();this._handleInitialization=(J)=>{J.fastify.register(Z)},K$1.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)K$1.unsubscribe("fastify.initialization",this._handleInitialization),this._handleInitialization=void 0;return super.disable()}init(){return[]}plugin(){let Z=this;return J[Symbol.for("skip-override")]=!0,J[Symbol.for("fastify.display-name")]="@fastify/otel",J[Symbol.for("plugin-meta")]={fastify:rY6,name:"@fastify/otel"},J;function J(X,Y,$){X.decorate(T5,Z),X.decorate(V$1,X.addHook),X.decorate(z$1,X.setNotFoundHandler),X.decorateRequest("opentelemetry",function z(){let F=this[SU];return{span:this[hY],tracer:Z.tracer,context:F,inject:(q,U)=>{return A8.propagation.inject(F,q,U)},extract:(q,U)=>{return A8.propagation.extract(F,q,U)}}}),X.decorateRequest(hY,null),X.decorateRequest(SU,null),X.addHook("onRoute",function(z){if(Z[sj]?.(z)===!0){Z._logger.debug(`Ignoring route instrumentation ${z.method} ${z.url} because it matches the ignore path`);return}for(let F of G$1)if(z[F]!=null){let H=z[F];if(typeof H==="function")z[F]=V(H,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route -> ${F}`,[o1.FASTIFY_TYPE]:xY.ROUTE,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:iJ});else if(Array.isArray(H)){let q=[];for(let U of H)q.push(V(U,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route -> ${F}`,[o1.FASTIFY_TYPE]:xY.ROUTE,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:iJ}));z[F]=q}}if(z.onSend!=null)z.onSend=Array.isArray(z.onSend)?[...z.onSend,Q]:[z.onSend,Q];else z.onSend=Q;if(z.onError!=null)z.onError=Array.isArray(z.onError)?[...z.onError,K]:[z.onError,K];else z.onError=K;z.handler=V(z.handler,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route-handler`,[o1.FASTIFY_TYPE]:xY.HANDLER,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:z.handler.name.length>0?z.handler.name:iJ})}),X.addHook("onRequest",function(z,F,H){if(this[T5].isEnabled()===!1)return H();else if(this[T5][sj]?.({url:z.url,method:z.method})===!0)return this[T5]._logger.debug(`Ignoring request ${z.method} ${z.url} because it matches the ignore path`),H();let q=A8.context.active();if(A8.trace.getSpan(q)==null)q=A8.propagation.extract(q,z.headers);let U=oj.getRPCMetadata(q);if(z.routeOptions.url!=null&&U?.type===oj.RPCType.HTTP)U.route=z.routeOptions.url;let B=this[T5].tracer.startSpan("request",{attributes:{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.ROOT]:"@fastify/otel",[d8.ATTR_HTTP_ROUTE]:z.url,[d8.ATTR_HTTP_REQUEST_METHOD]:z.method}},q);z[SU]=A8.trace.setSpan(q,B),z[hY]=B,A8.context.with(z[SU],()=>{H()})}),X.addHook("onResponse",function(z,F,H){let q=z[hY];if(q!=null)q.setStatus({code:A8.SpanStatusCode.OK,message:"OK"}),q.setAttributes({[d8.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),q.end();z[hY]=null,H()}),X.addHook=W,X.setNotFoundHandler=G,$();function Q(z,F,H,q){let U=z[hY];if(U!=null){if(F.statusCode<500)U.setStatus({code:A8.SpanStatusCode.OK,message:"OK"});U.setAttributes({[d8.ATTR_HTTP_RESPONSE_STATUS_CODE]:F.statusCode}),U.end()}z[hY]=null,q(null,H)}function K(z,F,H,q){let U=z[hY];if(U!=null)U.setStatus({code:A8.SpanStatusCode.ERROR,message:H.message}),U.recordException(H);q()}function W(z,F){let H=this[V$1];if(G$1.includes(z))return H.call(this,z,V(F,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - ${z}`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:iJ}));else return H.call(this,z,F)}function G(z,F){let H=this[z$1];if(typeof z==="function")F=V(z,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.name?.length>0?z.name:iJ}),H.call(this,F);else{if(z.preValidation!=null)z.preValidation=V(z.preValidation,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.preValidation.name?.length>0?z.preValidation.name:iJ});if(z.preHandler!=null)z.preHandler=V(z.preHandler,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.preHandler.name?.length>0?z.preHandler.name:iJ});F=V(F,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:iJ}),H.call(this,z,F)}}function V(z,F={}){return function H(...q){let U=this[T5],[B]=q;if(U.isEnabled()===!1)return z.call(this,...q);let L=B[SU]??A8.context.active(),w=U.tracer.startSpan(`handler - ${z.name?.length>0?z.name:this.pluginName??iJ}`,{attributes:F},L);return A8.context.with(A8.trace.setSpan(L,w),function(){try{let M=z.call(this,...q);if(typeof M?.then==="function")return M.then((N)=>{return w.end(),N},(N)=>{return w.setStatus({code:A8.SpanStatusCode.ERROR,message:N.message}),w.recordException(N),w.end(),Promise.reject(N)});return w.end(),M}catch(M){throw w.setStatus({code:A8.SpanStatusCode.ERROR,message:M.message}),w.recordException(M),w.end(),M}},this)}}}}}var j7=r(Y0(),1),tj=r(q1(),1),FK=r(r0(),1),L$1=r(j1(),1);var nJ;(function(Z){Z.FASTIFY_NAME="fastify.name";let X="fastify.type";Z.FASTIFY_TYPE=X;let Y="hook.name";Z.HOOK_NAME=Y;let $="plugin.name";Z.PLUGIN_NAME=$})(nJ||(nJ={}));var AU;(function(Z){Z.MIDDLEWARE="middleware";let X="request_handler";Z.REQUEST_HANDLER=X})(AU||(AU={}));var xU;(function(Z){Z.MIDDLEWARE="middleware";let X="request handler";Z.REQUEST_HANDLER=X})(xU||(xU={}));var q$1=r(Y0(),1);var hU=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function dg(Z,J,X,Y={}){let $=J.startSpan(X,{attributes:Y}),Q=Z[hU]||[];return Q.push($),Object.defineProperty(Z,hU,{enumerable:!1,configurable:!0,value:Q}),$}function rj(Z,J){let X=Z[hU]||[];if(!X.length)return;X.forEach((Y)=>{if(J)Y.setStatus({code:q$1.SpanStatusCode.ERROR,message:J.message}),Y.recordException(J);Y.end()}),delete Z[hU]}function U$1(Z,J,X){let Y,$=void 0;try{if($=Z(),F$1($))$.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){Y=Q}finally{if(!F$1($)){if(J(Y,$),Y)throw Y}return $}}function F$1(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var tY6="0.1.0",eY6="@sentry/instrumentation-fastify-v3",B$1="anonymous",Z$6=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class cg extends FK.InstrumentationBase{constructor(Z={}){super(eY6,tY6,Z)}init(){return[new FK.InstrumentationNodeModuleDefinition("fastify",[">=3.0.0 <4"],(Z)=>{return this._patchConstructor(Z)})]}_hookOnRequest(){let Z=this;return function J(X,Y,$){if(!Z.isEnabled())return $();Z._wrap(Y,"send",Z._patchSend());let Q=X,K=tj.getRPCMetadata(j7.context.active()),W=Q.routeOptions?Q.routeOptions.url:X.routerPath;if(W&&K?.type===tj.RPCType.HTTP)K.route=W;let G=X.method||"GET";E0().setTransactionName(`${G} ${W}`),$()}}_wrapHandler(Z,J,X,Y){let $=this;return this._diag.debug("Patching fastify route.handler function"),function(...Q){if(!$.isEnabled())return X.apply(this,Q);let K=X.name||Z||B$1,W=`${xU.MIDDLEWARE} - ${K}`,G=Q[1],V=dg(G,$.tracer,W,{[nJ.FASTIFY_TYPE]:AU.MIDDLEWARE,[nJ.PLUGIN_NAME]:Z,[nJ.HOOK_NAME]:J}),z=Y&&Q[Q.length-1];if(z)Q[Q.length-1]=function(...F){rj(G),z.apply(this,F)};return j7.context.with(j7.trace.setSpan(j7.context.active(),V),()=>{return U$1(()=>{return X.apply(this,Q)},(F)=>{if(F instanceof Error)V.setStatus({code:j7.SpanStatusCode.ERROR,message:F.message}),V.recordException(F);if(!Y)rj(G)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function X(...Y){let $=Y[0],Q=Y[1],K=this.pluginName;if(!Z$6.has($))return J.apply(this,Y);let W=typeof Y[Y.length-1]==="function"&&Q.constructor.name!=="AsyncFunction";return J.apply(this,[$,Z._wrapHandler(K,$,Q,W)])}}}_patchConstructor(Z){let J=this;function X(...Y){let $=Z.fastify.apply(this,Y);return $.addHook("onRequest",J._hookOnRequest()),$.addHook("preHandler",J._hookPreHandler()),J$6(),J._wrap($,"addHook",J._wrapAddHook()),$}if(Z.errorCodes!==void 0)X.errorCodes=Z.errorCodes;return X.fastify=X,X.default=X,X}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function J(X){return function Y(...$){let Q=$[0];if(!Z.isEnabled())return X.apply(this,$);return FK.safeExecuteInTheMiddle(()=>{return X.apply(this,$)},(K)=>{if(!K&&Q instanceof Error)K=Q;rj(this,K)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function J(X,Y,$){if(!Z.isEnabled())return $();let Q=X,K=Q.routeOptions?.handler||Q.context?.handler,W=K?.name.startsWith("bound ")?K.name.substring(6):K?.name,G=`${xU.REQUEST_HANDLER} - ${W||this.pluginName||B$1}`,V={[nJ.PLUGIN_NAME]:this.pluginName,[nJ.FASTIFY_TYPE]:AU.REQUEST_HANDLER,[L$1.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:X.routerPath};if(W)V[nJ.FASTIFY_NAME]=W;let z=dg(Y,Z.tracer,G,V);w$1(z);let{requestHook:F}=Z.getConfig();if(F)FK.safeExecuteInTheMiddle(()=>F(z,{request:X}),(H)=>{if(H)Z._diag.error("request hook failed",H)},!0);return j7.context.with(j7.trace.setSpan(j7.context.active(),z),()=>{$()})}}}function J$6(){let Z=X0();if(Z)Z.on("spanStart",(J)=>{w$1(J)})}function w$1(Z){let J=L0(Z).data,X=J["fastify.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.fastify",[j0]:`${X}.fastify`});let Y=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof Y==="string"){let $=Y.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName($)}}var O$1="Fastify",X$6="Fastify-V5",Y$6="Fastify-V3",pg=B0(Y$6,()=>new cg);function M$1(){let Z=X0();if(!Z)return;else return Z.getIntegrationByName(O$1)}function ej(Z,J,X,Y){let $=M$1()?.getShouldHandleError()||N$1;if(Y==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&Y==="onError-hook"){T4&&h.warn("Fastify error handler was already registered via diagnostics channel.","You can safely remove `setupFastifyErrorHandler` call and set `shouldHandleError` on the integration options.");return}if($(Z,J,X))Z1(Z,{mechanism:{handled:!1,type:"fastify"}})}var ig=B0(X$6,()=>{let Z=new ug,J=Z.plugin();return lg.subscribe("fastify.initialization",(X)=>{let Y=X.fastify;Y?.register(J).after(($)=>{if($)T4&&h.error("Failed to setup Fastify instrumentation",$);else if(Q$6(),Y)K$6(Y)})}),lg.subscribe("tracing:fastify.request.handler:error",(X)=>{let{error:Y,request:$,reply:Q}=X;ej.call(ej,Y,$,Q,"diagnostics-channel")}),Z}),$$6=({shouldHandleError:Z})=>{let J;return{name:O$1,setupOnce(){J=Z||N$1,pg(),ig()},getShouldHandleError(){return J},setShouldHandleError(X){J=X}}},ZD=a((Z={})=>$$6(Z));function N$1(Z,J,X){let Y=X.statusCode;return Y>=500||Y<=299}function R$1(Z,J){if(J?.shouldHandleError)M$1()?.setShouldHandleError(J.shouldHandleError);let X=Object.assign(function(Y,$,Q){Y.addHook("onError",async(K,W,G)=>{ej.call(ej,G,K,W,"onError-hook")}),Q()},{[Symbol.for("skip-override")]:!0,[Symbol.for("fastify.display-name")]:"sentry-fastify-error-handler"});Z.register(X)}function j$1(Z){let J=L0(Z),X=J.description,Y=J.data,$=Y["fastify.type"],Q=$==="hook",K=$===X?.startsWith("handler -"),W=X==="request"||$==="request-handler";if(Y[j0]||!K&&!W&&!Q)return;let G=Q?"hook":K?"middleware":W?"request-handler":"<unknown>";Z.setAttributes({[v0]:"auto.http.otel.fastify",[j0]:`${G}.fastify`});let V=Y["fastify.name"]||Y["plugin.name"]||Y["hook.name"];if(typeof V==="string"){let z=V.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(z)}}function Q$6(){let Z=X0();if(Z)Z.on("spanStart",(J)=>{j$1(J)})}function K$6(Z){Z.addHook("onRequest",async(J,X)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)j$1(Q)}let Y=J.routeOptions?.url,$=J.method||"GET";E0().setTransactionName(`${$} ${Y}`)})}var KQ1=r(Y0(),1),WQ1=r(QQ1(),1);var GQ1="Graphql",eg=B0(GQ1,WQ1.GraphQLInstrumentation,(Z)=>{let J=VQ1(Z);return{...J,responseHook(X,Y){if(s1(X,"auto.graphql.otel.graphql"),Y.errors?.length&&!L0(X).status)X.setStatus({code:KQ1.SpanStatusCode.ERROR});let Q=L0(X).data,K=Q["graphql.operation.type"],W=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&K){let G=a1(X),z=L0(G).data[RG]||[],F=W?`${K} ${W}`:`${K}`;if(Array.isArray(z))z.push(F),G.setAttribute(RG,z);else if(typeof z==="string")G.setAttribute(RG,[z,F]);else G.setAttribute(RG,F);if(!L0(G).data["original-description"])G.setAttribute("original-description",L0(G).description);G.updateName(`${L0(G).data["original-description"]} (${A$6(z)})`)}}}}),S$6=(Z={})=>{return{name:GQ1,setupOnce(){eg(VQ1(Z))}}},$D=a(S$6);function VQ1(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function A$6(Z){if(Array.isArray(Z)){let J=Z.slice().sort();if(J.length<=5)return J.join(", ");else return`${J.slice(0,5).join(", ")}, +${J.length-5}`}return`${Z}`}var TQ1=r(CQ1(),1);var kQ1="Kafka",Zm=B0(kQ1,()=>new TQ1.KafkaJsInstrumentation({consumerHook(Z){s1(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){s1(Z,"auto.kafkajs.otel.producer")}})),f$6=()=>{return{name:kQ1,setupOnce(){Zm()}}},QD=a(f$6);var gQ1=r(bQ1(),1);var mQ1="LruMemoizer",Jm=B0(mQ1,()=>new gQ1.LruMemoizerInstrumentation),m$6=()=>{return{name:mQ1,setupOnce(){Jm()}}},KD=a(m$6);var JK1=r(ZK1(),1);var XK1="Mongo",Km=B0(XK1,()=>new JK1.MongoDBInstrumentation({dbStatementSerializer:p$6,responseHook(Z){s1(Z,"auto.db.otel.mongo")}}));function p$6(Z){let J=Qm(Z);return JSON.stringify(J)}function Qm(Z){if(Array.isArray(Z))return Z.map((J)=>Qm(J));if(i$6(Z)){let J={};return Object.entries(Z).map(([X,Y])=>[X,Qm(Y)]).reduce((X,Y)=>{if(a$6(Y))X[Y[0]]=Y[1];return X},J)}return"?"}function i$6(Z){return typeof Z==="object"&&Z!==null&&!n$6(Z)}function n$6(Z){let J=!1;if(typeof Buffer!=="undefined")J=Buffer.isBuffer(Z);return J}function a$6(Z){return Array.isArray(Z)}var s$6=()=>{return{name:XK1,setupOnce(){Km()}}},WD=a(s$6);var DK1=r(jK1(),1);var PK1="Mongoose",Vm=B0(PK1,()=>new DK1.MongooseInstrumentation({responseHook(Z){s1(Z,"auto.db.otel.mongoose")}})),GQ6=()=>{return{name:PK1,setupOnce(){Vm()}}},VD=a(GQ6);var dK1=r(uK1(),1);var cK1="Mysql",qm=B0(cK1,()=>new dK1.MySQLInstrumentation({})),PQ6=()=>{return{name:cK1,setupOnce(){qm()}}},HD=a(PQ6);var VW1=r(GW1(),1);var zW1="Mysql2",Om=B0(zW1,()=>new VW1.MySQL2Instrumentation({responseHook(Z){s1(Z,"auto.db.otel.mysql2")}})),uQ6=()=>{return{name:zW1,setupOnce(){Om()}}},qD=a(uQ6);var rW1=r(IW1(),1),tW1=r(iW1(),1);var JK6=["get","set","setex"],Nm=["get","mget"],XK6=["set","setex"];function lU(Z,J){return Z.includes(J.toLowerCase())}function Rm(Z){if(lU(Nm,Z))return"cache.get";else if(lU(XK6,Z))return"cache.put";else return}function YK6(Z,J){return J.some((X)=>Z.startsWith(X))}function aW1(Z,J){try{if(J.length===0)return;let X=($)=>{if(typeof $==="string"||typeof $==="number"||Buffer.isBuffer($))return[$.toString()];else if(Array.isArray($))return nW1($.map((Q)=>X(Q)));else return["<unknown>"]},Y=J[0];if(lU(JK6,Z)&&Y!=null)return X(Y);return nW1(J.map(($)=>X($)))}catch{return}}function sW1(Z,J,X){if(!Rm(Z))return!1;for(let Y of J)if(YK6(Y,X))return!0;return!1}function oW1(Z){let J=(X)=>{try{if(Buffer.isBuffer(X))return X.byteLength;else if(typeof X==="string")return X.length;else if(typeof X==="number")return X.toString().length;else if(X===null||X===void 0)return 0;return JSON.stringify(X).length}catch{return}};return Array.isArray(Z)?Z.reduce((X,Y)=>{let $=J(Y);return typeof $==="number"?X!==void 0?X+$:$:X},0):J(Z)}function nW1(Z){let J=[],X=(Y)=>{Y.forEach(($)=>{if(Array.isArray($))X($);else J.push($)})};return X(Z),J}var eW1="Redis",jm={},Z31=(Z,J,X,Y)=>{Z.setAttribute(v0,"auto.db.otel.redis");let $=aW1(J,X),Q=Rm(J);if(!$||!Q||!jm.cachePrefixes||!sW1(J,$,jm.cachePrefixes))return;let K=L0(Z).data["net.peer.name"],W=L0(Z).data["net.peer.port"];if(W&&K)Z.setAttributes({"network.peer.address":K,"network.peer.port":W});let G=oW1(Y);if(G)Z.setAttribute(vf,G);if(lU(Nm,J)&&G!==void 0)Z.setAttribute(If,G>0);Z.setAttributes({[j0]:Q,[_f]:$});let V=$.join(", ");Z.updateName(t5(V,1024))},$K6=B0("IORedis",()=>{return new rW1.IORedisInstrumentation({responseHook:Z31})}),QK6=B0("Redis-4",()=>{return new tW1.RedisInstrumentation({responseHook:Z31})}),Dm=Object.assign(()=>{$K6(),QK6()},{id:eW1}),KK6=(Z={})=>{return{name:eW1,setupOnce(){jm=Z,Dm()}}},BD=a(KK6);var S31=r(v31(),1);var A31="Postgres",vm=B0(A31,()=>new S31.PgInstrumentation({requireParentSpan:!0,requestHook(Z){s1(Z,"auto.db.otel.postgres")}})),lK6=()=>{return{name:A31,setupOnce(){vm()}}},MD=a(lK6);var yG=r(Y0(),1),ZX=r(r0(),1),Z5=r(j1(),1);var Sm="PostgresJs",x31=[">=3.0.0 <4"],Am=B0(Sm,(Z)=>new h31({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class h31 extends ZX.InstrumentationBase{constructor(Z){super("sentry-postgres-js",R1,Z)}init(){let Z=new ZX.InstrumentationNodeModuleDefinition("postgres",x31);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new ZX.InstrumentationNodeModuleFile(`postgres/${J}/connection.js`,["*"],this._patchConnection.bind(this),this._unwrap.bind(this))),Z.files.push(new ZX.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,x31,this._patchQuery.bind(this),this._unwrap.bind(this)))}),[Z]}_shouldCreateSpans(){let Z=this.getConfig();return yG.trace.getSpan(yG.context.active())!==void 0||!Z.requireParentSpan}_patchReject(Z,J){return new Proxy(Z,{apply:(X,Y,$)=>{J.setStatus({code:S8,message:$?.[0]?.message||"unknown_error"});let Q=Reflect.apply(X,Y,$);return J.setAttribute(Z5.ATTR_DB_RESPONSE_STATUS_CODE,$?.[0]?.code||"Unknown error"),J.setAttribute(Z5.ATTR_ERROR_TYPE,$?.[0]?.name||"Unknown error"),J.end(),Q}})}_patchResolve(Z,J){return new Proxy(Z,{apply:(X,Y,$)=>{let Q=Reflect.apply(X,Y,$),K=$?.[0]?.command;if(K)J.setAttribute(Z5.ATTR_DB_OPERATION_NAME,K);return J.end(),Q}})}_patchQuery(Z){return Z.Query.prototype.handle=new Proxy(Z.Query.prototype.handle,{apply:async(J,X,Y)=>{if(!this._shouldCreateSpans())return Reflect.apply(J,X,Y);let $=this._sanitizeSqlQuery(X.strings?.[0]);return dQ({name:$||"postgresjs.query",op:"db"},(Q)=>{let W=T0().getScopeData().contexts.postgresjsConnection;s1(Q,"auto.db.otel.postgres");let{requestHook:G}=this.getConfig();if(G)ZX.safeExecuteInTheMiddle(()=>G(Q,$,W),(H)=>{if(H)h.error(`Error in requestHook for ${Sm} integration:`,H)});let V=W?.ATTR_DB_NAMESPACE||"<unknown database>",z=W?.ATTR_SERVER_ADDRESS||"<unknown host>",F=W?.ATTR_SERVER_PORT||"<unknown port>";Q.setAttribute(Z5.ATTR_DB_SYSTEM_NAME,"postgres"),Q.setAttribute(Z5.ATTR_DB_NAMESPACE,V),Q.setAttribute(Z5.ATTR_SERVER_ADDRESS,z),Q.setAttribute(Z5.ATTR_SERVER_PORT,F),Q.setAttribute(Z5.ATTR_DB_QUERY_TEXT,$),X.resolve=this._patchResolve(X.resolve,Q),X.reject=this._patchReject(X.reject,Q);try{return Reflect.apply(J,X,Y)}catch(H){throw Q.setStatus({code:S8}),Q.end(),H}})}}),Z}_patchConnection(Z){return new Proxy(Z,{apply:(J,X,Y)=>{let $=Y[0]?.database||"<unknown database>",Q=Y[0]?.host?.[0]||"<unknown host>",K=Y[0]?.port?.[0]||"<unknown port>";return T0().setContext("postgresjsConnection",{ATTR_DB_NAMESPACE:$,ATTR_SERVER_ADDRESS:Q,ATTR_SERVER_PORT:K}),Reflect.apply(J,X,Y)}})}_sanitizeSqlQuery(Z){if(!Z)return"Unknown SQL Query";return Z.replace(/\s+/g," ").trim().substring(0,1024).replace(/--.*?(\r?\n|$)/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/;\s*$/,"").replace(/\b\d+\b/g,"?").replace(/\s+/g," ").replace(/\bIN\b\s*\(\s*\?(?:\s*,\s*\?)*\s*\)/g,"IN (?)")}}var pK6=()=>{return{name:Sm,setupOnce(){Am()}}},ND=a(pK6);var b31=r(Y0(),1),RD=r(r0(),1),oY=r(Y0(),1);var iK6=process.env.PRISMA_SHOW_ALL_TRACES==="true",nK6="00-10-10-00";function aK6(Z){switch(Z){case"client":return oY.SpanKind.CLIENT;case"internal":default:return oY.SpanKind.INTERNAL}}var sK6=class{traceMiddleware;tracerProvider;ignoreSpanTypes;constructor({traceMiddleware:Z,tracerProvider:J,ignoreSpanTypes:X}){this.traceMiddleware=Z,this.tracerProvider=J,this.ignoreSpanTypes=X}isEnabled(){return!0}getTraceParent(Z){let J=oY.trace.getSpanContext(Z??oY.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return nK6}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),X=new Map,Y=Z.filter(($)=>$.parentId===null);for(let $ of Y)g31(J,$,Z,X,this.ignoreSpanTypes)}getActiveContext(){return oY.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!iK6)return J();if(Z.middleware&&!this.traceMiddleware)return J();let X=this.tracerProvider.getTracer("prisma"),Y=Z.context??this.getActiveContext(),$=`prisma:client:${Z.name}`;if(m31($,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=X.startSpan($,Z,Y);return f31(Q,J(Q,Y))}return X.startActiveSpan($,Z,(Q)=>f31(Q,J(Q,Y)))}};function g31(Z,J,X,Y,$){if(m31(J.name,$))return;let Q={attributes:J.attributes,kind:aK6(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(K)=>{if(Y.set(J.id,K.spanContext().spanId),J.links)K.addLinks(J.links.flatMap((G)=>{let V=Y.get(G);if(!V)return[];return{context:{spanId:V,traceId:K.spanContext().traceId,traceFlags:K.spanContext().traceFlags}}}));let W=X.filter((G)=>G.parentId===J.id);for(let G of W)g31(Z,G,X,Y,$);K.end(J.endTime)})}function f31(Z,J){if(oK6(J))return J.then((X)=>{return Z.end(),X},(X)=>{throw Z.end(),X});return Z.end(),J}function oK6(Z){return Z!=null&&typeof Z.then==="function"}function m31(Z,J){return J.some((X)=>typeof X==="string"?X===Z:X.test(Z))}var u31={name:"@prisma/instrumentation",version:"6.11.1",description:"OpenTelemetry compliant instrumentation for Prisma Client",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{require:{types:"./dist/index.d.ts",default:"./dist/index.js"},import:{types:"./dist/index.d.ts",default:"./dist/index.mjs"}}},license:"Apache-2.0",homepage:"https://www.prisma.io",repository:{type:"git",url:"https://github.com/prisma/prisma.git",directory:"packages/instrumentation"},bugs:"https://github.com/prisma/prisma/issues",devDependencies:{"@prisma/internals":"workspace:*","@swc/core":"1.11.5","@types/jest":"29.5.14","@types/node":"18.19.76","@opentelemetry/api":"1.9.0",jest:"29.7.0","jest-junit":"16.0.0",typescript:"5.4.5"},dependencies:{"@opentelemetry/instrumentation":"^0.52.0 || ^0.53.0 || ^0.54.0 || ^0.55.0 || ^0.56.0 || ^0.57.0"},peerDependencies:{"@opentelemetry/api":"^1.8"},files:["dist"],keywords:["prisma","instrumentation","opentelemetry","otel"],scripts:{dev:"DEV=true tsx helpers/build.ts",build:"tsx helpers/build.ts",prepublishOnly:"pnpm run build",test:"jest"},sideEffects:!1},hm=u31.version,rK6=hm.split(".")[0],y31="PRISMA_INSTRUMENTATION",xm=`V${rK6}_PRISMA_INSTRUMENTATION`,tK6=u31.name,eK6="@prisma/client",d31=class extends RD.InstrumentationBase{tracerProvider;constructor(Z={}){super(tK6,hm,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new RD.InstrumentationNodeModuleDefinition(eK6,[hm])]}enable(){let Z=this._config,J={helper:new sK6({traceMiddleware:Z.middleware??!1,tracerProvider:this.tracerProvider??b31.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[y31]=J,global[xm]=J}disable(){delete global[y31],delete global[xm]}isEnabled(){return Boolean(global[xm])}};var c31="Prisma";function ZW6(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function l31(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class p31 extends d31{constructor(){super()}enable(){super.enable();let Z=l31(),J=!1;if(ZW6(Z))Z.createEngineSpan=()=>{e0(()=>{if(!J)J=!0,console.warn("[Sentry] The Sentry SDK supports tracing with Prisma version 5 only with limited capabilities. For full tracing capabilities pass `prismaInstrumentation` for version 5 to the Sentry `prismaIntegration`. Read more: https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/prisma/")})}}}var JW6=B0(c31,(Z)=>{if(Z?.prismaInstrumentation)return Z.prismaInstrumentation;return new p31}),jD=a(({prismaInstrumentation:Z}={})=>{return{name:c31,setupOnce(){JW6({prismaInstrumentation:Z})},setup(J){if(!l31())return;J.on("spanStart",(X)=>{let Y=L0(X);if(Y.description?.startsWith("prisma:"))X.setAttribute(v0,"auto.db.otel.prisma");if(Y.description==="prisma:engine:db_query"&&Y.data["db.query.text"])X.updateName(Y.data["db.query.text"]);if(Y.description==="prisma:engine:db_query"&&!Y.data["db.system"])X.setAttribute("db.system","prisma")})}}});var VG1=r(GG1(),1);var zG1="Hapi",CD=B0(zG1,()=>new VG1.HapiInstrumentation),jW6=()=>{return{name:zG1,setupOnce(){CD()}}},TD=a(jW6);function DW6(Z){return!!(Z&&typeof Z==="object"&&("error"in Z)&&Z.error)}function PW6(Z){Z1(Z,{mechanism:{type:"hapi",handled:!1,data:{function:"hapiErrorPlugin"}}})}var CW6={name:"SentryHapiErrorPlugin",version:R1,register:async function(Z){Z.events.on({name:"request",channels:["error"]},(X,Y)=>{if(E0()!==B4()){let $=X.route;if($.path)E0().setTransactionName(`${$.method.toUpperCase()} ${$.path}`)}else T4&&h.warn("Isolation scope is still the default isolation scope - skipping setting transactionName");if(DW6(Y))PW6(Y.error)})}};async function HG1(Z){await Z.register(CW6);let J=X0();if(J)J.on("spanStart",(X)=>{TW6(X)});cJ(Z.register,"hapi")}function TW6(Z){let J=L0(Z).data,X=J["hapi.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.hapi",[j0]:`${X}.hapi`})}var xG1=r(AG1(),1),hG1=r(j1(),1);var fG1="Koa",lm=B0(fG1,xG1.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,X){s1(J,"auto.http.otel.koa");let Y=L0(J).data,$=Y["koa.type"];if($)J.setAttribute(j0,`${$}.koa`);let Q=Y["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(E0()===B4()){T4&&h.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let K=Y[hG1.ATTR_HTTP_ROUTE],W=X.context?.request?.method?.toUpperCase()||"GET";if(K)E0().setTransactionName(`${W} ${K}`)}}}),hW6=(Z={})=>{return{name:fG1,setupOnce(){lm(Z)}}},ID=a(hW6),yG1=(Z)=>{Z.use(async(J,X)=>{try{await X()}catch(Y){throw Z1(Y),Y}}),cJ(Z.use,"koa")};var $V1=r(YV1(),1);var QV1="Connect",sm=B0(QV1,()=>new $V1.ConnectInstrumentation),sW6=()=>{return{name:QV1,setupOnce(){sm()}}},vD=a(sW6);function oW6(Z,J,X,Y){Z1(Z),Y(Z)}var KV1=(Z)=>{Z.use(oW6);let J=X0();if(J)J.on("spanStart",(X)=>{rW6(X)});cJ(Z.use,"connect")};function rW6(Z){let J=L0(Z).data,X=J["connect.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.connect",[j0]:`${X}.connect`});let Y=J["connect.name"];if(typeof Y==="string")Z.updateName(Y)}var kV1=r(TV1(),1);var EV1="Knex",q36=B0(EV1,()=>new kV1.KnexInstrumentation({requireParentSpan:!0})),U36=()=>{let Z;return{name:EV1,setupOnce(){let J=q36();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{data:Y}=L0(X);if("knex.version"in Y)X.setAttribute(v0,"auto.db.otel.knex")}))}}},IV1=a(U36);var nV1=r(iV1(),1);var R36=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),aV1="Tedious",rm=B0(aV1,()=>new nV1.TediousInstrumentation({})),j36=()=>{let Z;return{name:aV1,setupOnce(){let J=rm();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{description:Y,data:$}=L0(X);if(!Y||$["db.system"]!=="mssql")return;let Q=Y.split(" ")[0]||"";if(R36.has(Q))X.setAttribute(v0,"auto.db.otel.tedious")}))}}},fD=a(j36);var $z1=r(Yz1(),1);var Qz1="GenericPool",em=B0(Qz1,()=>new $z1.GenericPoolInstrumentation({})),T36=()=>{let Z;return{name:Qz1,setupOnce(){let J=em();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let $=L0(X).description;if($==="generic-pool.aquire"||$==="generic-pool.acquire")X.setAttribute(v0,"auto.db.otel.generic_pool")}))}}},yD=a(T36);var Oz1=r(wz1(),1);var Mz1="Dataloader",I36=B0(Mz1,()=>new Oz1.DataloaderInstrumentation({requireParentSpan:!0})),_36=()=>{let Z;return{name:Mz1,setupOnce(){let J=I36();Z=fJ(J)},setup(J){Z?.(()=>{J.on("spanStart",(X)=>{let Y=L0(X);if(Y.description?.startsWith("dataloader"))X.setAttribute(v0,"auto.db.otel.dataloader");if(Y.description==="dataloader.load"||Y.description==="dataloader.loadMany"||Y.description==="dataloader.batch")X.setAttribute(j0,"cache.get")})})}}},Nz1=a(_36);var mz1=r(gz1(),1);var uz1="Amqplib",o36={consumeEndHook:(Z)=>{s1(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{s1(Z,"auto.amqplib.otel.publisher")}},$u=B0(uz1,()=>new mz1.AmqplibInstrumentation(o36)),r36=()=>{return{name:uz1,setupOnce(){$u()}}},mD=a(r36);var oU="VercelAI";var uD=r(r0(),1);var dz1=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function t36(Z,J,X,Y){let $=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:X===!0?!0:Y,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:X===!0?!0:Y;return{recordInputs:$,recordOutputs:Q}}class rU extends uD.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",R1,Z);rU.prototype.__init.call(this),rU.prototype.__init2.call(this)}init(){return new uD.InstrumentationNodeModuleDefinition("ai",[">=3.0.0 <5"],this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach((X)=>X()),this._callbacks=[];function J(X){return(...Y)=>{let $=Y[0].experimental_telemetry||{},Q=$.isEnabled,K=T0().getClient(),W=K?.getIntegrationByName(oU),G=W?.options,V=W?Boolean(K?.getOptions().sendDefaultPii):!1,{recordInputs:z,recordOutputs:F}=t36(G,$,Q,V);return Y[0].experimental_telemetry={...$,isEnabled:Q!==void 0?Q:!0,recordInputs:z,recordOutputs:F},SJ(()=>{return X.apply(this,Y)},(H)=>{if(H&&typeof H==="object")e1(H,"_sentry_active_span",C6())})}}if(Object.prototype.toString.call(Z)==="[object Module]"){for(let X of dz1)Z[X]=J(Z[X]);return Z}else{let X=dz1.reduce((Y,$)=>{return Y[$]=J(Z[$]),Y},{});return{...Z,...X}}}}var Qu=B0(oU,()=>new rU({}));function e36(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var ZG6=(Z={})=>{let J;return{name:oU,options:Z,setupOnce(){J=Qu()},afterAllSetup(X){if(Z.force??e36(X))Kj(X);else J?.callWhenPatched(()=>Kj(X))}}},dD=a(ZG6);var cD=r(r0(),1);var JG6=[">=4.0.0 <6"];function XG6(Z,J){let X=Z?.recordInputs??J,Y=Z?.recordOutputs??J;return{recordInputs:X,recordOutputs:Y}}class Ku extends cD.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",R1,Z)}init(){return new cD.InstrumentationNodeModuleDefinition("openai",JG6,this._patch.bind(this))}_patch(Z){let J=Z.OpenAI,X=function(...Y){let $=Reflect.construct(J,Y),Q=T0().getClient(),W=Q?.getIntegrationByName(PY)?.options,G=Boolean(Q?.getOptions().sendDefaultPii),{recordInputs:V,recordOutputs:z}=XG6(W,G);return Kb($,{recordInputs:V,recordOutputs:z})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let $=Object.getOwnPropertyDescriptor(J,Y);if($)Object.defineProperty(X,Y,$)}try{Z.OpenAI=X}catch(Y){Object.defineProperty(Z,"OpenAI",{value:X,writable:!0,configurable:!0,enumerable:!0})}return Z}}var Wu=B0(PY,()=>new Ku({})),YG6=(Z={})=>{return{name:PY,options:Z,setupOnce(){Wu()}}},lD=a(YG6);var cz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The launchDarklyIntegration() can only be used in the browser.")});return{name:"LaunchDarkly"}});function lz1(){if(!O7())e0(()=>{console.warn("The buildLaunchDarklyFlagUsedHandler() can only be used in the browser.")});return{name:"sentry-flag-auditor",type:"flag-used",synchronous:!0,method:()=>null}}var pz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The openFeatureIntegration() can only be used in the browser.")});return{name:"OpenFeature"}});class Gu{constructor(){if(!O7())e0(()=>{console.warn("The OpenFeatureIntegrationHook can only be used in the browser.")})}after(){}error(){}}var iz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The statsigIntegration() can only be used in the browser.")});return{name:"Statsig"}});var nz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The unleashIntegration() can only be used in the browser.")});return{name:"Unleash"}});function pD(){return[nj(),ZD(),$D(),WD(),VD(),HD(),qD(),BD(),MD(),jD(),TD(),ID(),vD(),fD(),yD(),QD(),mD(),KD(),dD(),lD(),ND()]}function az1(){return[Pg,xg,hg,sm,ig,pg,CD,Zm,lm,Jm,Km,Vm,qm,Om,vm,CD,eg,Dm,rm,em,$u,Qu,Wu,Am]}var dG=r(Y0(),1),sz1=r(hb(),1),oz1=r(bb(),1),cG=r(j1(),1);var rz1=r(LR(),1);import $G6 from"module";var Vu=1e6;function iD(Z,J={}){if(Z.getOptions().debug)wg();let X=WG6(Z,J);Z.traceProvider=X}function QG6(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!M0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=rz1.createAddHookMessageChannel();$G6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){h.warn("Failed to register ESM hook",X)}}else e0(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function tz1(Z={}){let{debug:J}=Z;if(J)h.enable();if(!C4())QG6();KG6(Z.integrations).forEach((X)=>{if(X(),J)h.log(`[Sentry] Preloaded ${X.id} instrumentation`)})}function KG6(Z){let J=az1();if(!Z)return J;return J.filter((X)=>Z.includes(X.id))}function WG6(Z,J={}){let X=new oz1.BasicTracerProvider({sampler:new Yg(Z),resource:new sz1.Resource({[cG.ATTR_SERVICE_NAME]:"node",[cG.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[cG.ATTR_SERVICE_VERSION]:R1}),forceFlushTimeoutMillis:500,spanProcessors:[new Xg({timeout:GG6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return dG.trace.setGlobalTracerProvider(X),dG.propagation.setGlobalPropagator(new rb),dG.context.setGlobalContextManager(new wU),X}function GG6(Z){if(Z==null)return;if(Z>Vu)return T4&&h.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${Vu}`),Vu;else if(Z<=0||Number.isNaN(Z)){T4&&h.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function zu(){return fj().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(yj(),gj())}function Hu(Z){return[...zu(),...u8(Z)?pD():[]]}function nD(Z={}){return ez1(Z,Hu)}function ez1(Z={},J){nQ(Z,"node");let X=Rg({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if(X&&!Z.skipOpenTelemetrySetup)iD(X,{spanProcessors:Z.openTelemetrySpanProcessors}),PU();return X}function ZH1(Z={}){return ez1(Z,()=>[])}var NK;((B)=>{B.BUILD_PACKETS="build_packets";B.ENTITIES_EMIT_UPDATES="entities_emit_updates";B.ENTITIES_TICK="entities_tick";B.NETWORK_SYNCHRONIZE="network_synchronize";B.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";B.PHYSICS_CLEANUP="physics_cleanup";B.PHYSICS_STEP="physics_step";B.SEND_ALL_PACKETS="send_all_packets";B.SEND_PACKETS="send_packets";B.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";B.SERIALIZE_PACKETS="serialize_packets";B.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";B.SIMULATION_STEP="simulation_step";B.TICKER_TICK="ticker_tick";B.WORLD_TICK="world_tick"})(NK||={});class R8{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){nD({dsn:Z,release:LA,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=R8.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let $=X?.start_timestamp,Q=X?.timestamp;if(!$||!Q)return null;if((Q-$)*1000>J)return X.measurements=R8.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(uq())return O4({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return Fu}}var JH1=new e$({useFloat32:hH.ALWAYS}),zG6=5000,XH1={RAW:0,GZIP:1};class Q7 extends O0{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=Z70(),this.onPacket(Q0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(Q0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),O0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(Q7._cachedPacketsSerializedBuffer.size>0)Q7._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!Q0.isValidPacket(X))return c.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=Q7._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return R8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=JH1.pack(Z),$=Y.byteLength>1536,Q=$?VG6(Y,{level:1}):Y,K=$?XH1.GZIP:XH1.RAW;return Y=Buffer.allocUnsafe(Q.length+1),Y[0]=K,Q.copy(Y,1),X?.setAttribute("serializedBytes",Y.byteLength),Q7._cachedPacketsSerializedBuffer.set(Z,Y),Y})}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([Q0.createPacket(Q0.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([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(YZ.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){if(this._ws.readyState!==iO.default.OPEN)return;try{this._ws.close()}catch(Z){c.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!==iO.default.OPEN)return;if(!J&&this._ws.bufferedAmount>4096)return;R8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=Q7.serializePackets(Z);if(!Y)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&Y.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send(Y)}catch{this._ws.send(Y)}else this._ws.send(Y);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch(Y){c.error(`Connection.send(): Packet send failed. Error: ${Y}`)}})}_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,Y=J.d;if(X){let{i:$,d:Q}=X,K=!1;if($==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if($==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([Q0.createPacket(Q0.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){c.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()},zG6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await YZ.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:Y}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=Y,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),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 $=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push($,Q),this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:$.id,pi:$.dataProducerId,l:"scr",s:$.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=JH1.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return c.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!Q0.isValidPacket(J))return c.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class tU{_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 U6{_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,Y)=>{Z.call(J,X,Y,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 YH1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(YH1||={});var qu;((H)=>{H.DESPAWN="LIGHT.DESPAWN";H.SET_ANGLE="LIGHT.SET_ANGLE";H.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";H.SET_COLOR="LIGHT.SET_COLOR";H.SET_DISTANCE="LIGHT.SET_DISTANCE";H.SET_INTENSITY="LIGHT.SET_INTENSITY";H.SET_OFFSET="LIGHT.SET_OFFSET";H.SET_PENUMBRA="LIGHT.SET_PENUMBRA";H.SET_POSITION="LIGHT.SET_POSITION";H.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";H.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";H.SPAWN="LIGHT.SPAWN"})(qu||={});class Uu extends O0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)c.fatalError("Either attachedToEntity or position must be set, but not both.");super();c.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 c.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 c.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 c.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 k0.serializeLight(this)}}var Bu;((u)=>{u.BURST="PARTICLE_EMITTER.BURST";u.DESPAWN="PARTICLE_EMITTER.DESPAWN";u.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";u.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";u.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";u.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";u.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";u.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";u.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";u.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";u.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";u.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";u.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";u.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";u.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";u.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";u.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";u.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";u.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";u.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";u.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";u.SET_RATE="PARTICLE_EMITTER.SET_RATE";u.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";u.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";u.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";u.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";u.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";u.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";u.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";u.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";u.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";u.SPAWN="PARTICLE_EMITTER.SPAWN"})(Bu||={});class Lu extends O0{_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)c.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)c.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 c.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 c.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 k0.serializeParticleEmitter(this)}}var eU=r(_V(),1);var HG6={x:0,y:-32,z:0},wu=60,Ou;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Ou||={});class Z2 extends O0{_colliderMap=new NH;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=wu,X=HG6){super();this._rapierEventQueue=new eU.default.EventQueue(!0),this._rapierSimulation=new eU.default.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=eU.default.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,(Y,$)=>{if(Y.numContacts()===0)return;let Q=Y.normal(),K=[];for(let W=0;W<Y.numSolverContacts();W++)K.push(Y.solverContactPoint(W));X.push({contactPoints:K,localNormalA:!$?Y.localNormal1():Y.localNormal2(),localNormalB:!$?Y.localNormal2():Y.localNormal1(),normal:!$?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,Y={}){let $=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(K)=>{let W=this._colliderMap.getColliderHandleBlockType(K.handle);if(W&&!$.has(W))return $.add(W),Q.push({intersectedBlockType:W}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!$.has(G))return $.add(G),Q.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),Q}raycast(Z,J,X,Y={}){let $=new eU.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.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 K=$.pointAt(Q.timeOfImpact),W=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:IK.fromGlobalCoordinate({x:Math.floor(K.x-($.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-($.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-($.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:W};let z=this._colliderMap.getColliderHandleEntity(G.handle);if(z)return{hitEntity:z,hitPoint:K,hitDistance:W};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(R8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),R8.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=(K,W)=>{if(K instanceof q9&&W instanceof a8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof a8&&W instanceof q9&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof a8&&W instanceof a8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof a8||W instanceof q9))K(W,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 Y={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},$=(Q,K)=>{if(Q instanceof q9&&K instanceof a8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:Y});else if(Q instanceof a8&&K instanceof q9&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:Y});else if(Q instanceof a8&&K instanceof a8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:Y})};$(J,X),$(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),Y=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,Y]}}class aD{_synchronizedPlayerReliablePackets=new U6;_queuedBroadcasts=[];_queuedAudioSynchronizations=new U6;_queuedBlockSynchronizations=new U6;_queuedBlockTypeSynchronizations=new U6;_queuedChunkSynchronizations=new U6;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new U6;_queuedLightSynchronizations=new U6;_queuedParticleEmitterSynchronizations=new U6;_queuedPerPlayerSynchronizations=new U6;_queuedPerPlayerCameraSynchronizations=new U6;_queuedPerPlayerUISynchronizations=new U6;_queuedPerPlayerUIDatasSynchronizations=new U6;_queuedPlayerSynchronizations=new U6;_queuedSceneUISynchronizations=new U6;_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(Y,Z).push(...$);if(this._queuedEntitySynchronizations.size>0){let Y=[],$=[];for(let Q of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let W in Q)if(W!=="i"&&W!=="p"&&W!=="r"){K=!0;break}if(K)Y.push(Q);else $.push(Q)}if($.length>0){let Q=Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,$,X);J.push(Q)}if(Y.length>0){let Q=Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,Y,X);Z.push(Q);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(Q)}}if(this._queuedAudioSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUISynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.uiPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUIDatasSynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.uiDatasPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedSceneUISynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedWorldSynchronization){let Y=Q0.createPacket(Q0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerCameraSynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.cameraPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPlayerSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=Q0.createPacket(Q0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}R8.startSpan({operation:"send_all_packets"},()=>{for(let Y of N9.instance.getConnectedPlayersByWorld(this._world)){let $=this._synchronizedPlayerReliablePackets.get(Y)??Z;if($.length>0)Y.connection.send($);if(J.length>0)Y.connection.send(J,!1)}}),R8.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();Q7.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?k0.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:Y}=Z;this._queuedBroadcasts.push(Q0.createPacket(Q0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:Y}=Z,$=this._queuedPerPlayerSynchronizations.get(J)??[];$.push(Q0.createPacket(Q0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,$)};_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?k0.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=k0.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?k0.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?k0.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?k0.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?k0.serializeRgbColor(Z.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?k0.serializeRgbColor(Z.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?k0.serializeRgbColor(Z.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?k0.serializeRgbColor(Z.colorStartVariance):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?k0.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?k0.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?k0.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?k0.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?k0.serializeVector(Z.velocity):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?k0.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=k0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?k0.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?k0.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?k0.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?k0.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(Q0.createPacket(Q0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map(($)=>{if(J.camera.attachedToEntity===void 0&&$ instanceof i7&&$.player===J)J.camera.setAttachedToEntity($);return $.serialize()}),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.playersPacketDefinition,N9.instance.getConnectedPlayers().map(($)=>$.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...Y}),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([Q0.createPacket(Q0.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?k0.serializeVector(Z.offset):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?k0.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(k0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(Q0.createPacket(Q0.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=k0.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=k0.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=k0.serializeVector(Z.position)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=k0.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)c.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:Y}=Z,$=`${J},${X},${Y}`,Q=this._queuedBlockSynchronizations.get($);if(!Q)Q={i:0,c:[J,X,Y]},this._queuedBlockSynchronizations.set($,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)c.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate,$=`${J},${X},${Y}`,Q=this._queuedChunkSynchronizations.get($);if(!Q)Q={c:[J,X,Y]},this._queuedChunkSynchronizations.set($,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)c.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)c.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)c.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)c.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)c.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)c.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 J2{_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 X2{_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 FG6=2,qG6=3;class Y2{_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*qG6,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)R8.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<FG6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});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 c.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var $H1;((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"})($H1||={});class $2 extends O0{_currentTick=0;_ticker;_world;constructor(Z,J=wu){super();this._ticker=new Y2(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();R8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:N9.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}},()=>{R8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),R8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),R8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),R8.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)=>{c.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var Mu;((F)=>{F.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";F.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";F.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";F.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";F.SET_FOG_FAR="WORLD.SET_FOG_FAR";F.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";F.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";F.START="WORLD.START";F.STOP="WORLD.STOP"})(Mu||={});class Q2 extends O0{_id;_ambientLightColor;_ambientLightIntensity;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_fogColor;_fogFar;_fogNear;_name;_skyboxIntensity;_skyboxUri;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_entityManager;_lightManager;_loop;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_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 aG(this),this._blockTypeRegistry=new dz(this),this._chatManager=new OH(this),this._chunkLattice=new MH(this),this._entityManager=new DH(this),this._lightManager=new tU(this),this._loop=new $2(this,Z.tickRate),this._networkSynchronizer=new aD(this),this._particleEmitterManager=new J2(this),this._sceneUIManager=new X2(this),this._simulation=new Z2(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 directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get name(){return this._name}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get entityManager(){return this._entityManager}get lightManager(){return this._lightManager}get loop(){return this._loop}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,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 a8({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 k0.serializeWorld(this)}}var QH1;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(QH1||={});class K${static instance=new K$;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new Q2({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),O0.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 KH1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(KH1||={});class N9{static instance=new N9;worldSelectionHandler;_connectionPlayers=new Map;constructor(){O0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),O0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),O0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),O0.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 uW(Z,J);await X.loadInitialPersistedData(),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??K$.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(),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else c.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),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else c.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var GH1;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(GH1||={});function UG6(Z){WH1.default.init().then(()=>{return RK.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(RK.instance.worldManager.getDefaultWorld());else Z();RK.instance.start()}).catch((J)=>{c.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class RK{static _instance;_modelRegistry=g5.instance;_playerManager=N9.instance;_socket=YZ.instance;_worldManager=K$.instance;_webServer=I3.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new RK;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(){O0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var B6=r(PK(),1);class CK extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return B6.mat2.determinant(this)}get frobeniusNorm(){return B6.mat2.frob(this)}static create(){let Z=new CK(0,0,0,0);return B6.mat2.identity(Z),Z}static fromRotation(Z){let J=CK.create();return B6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=CK.create();return B6.mat2.fromScaling(J,Z),J}add(Z){return B6.mat2.add(this,this,Z),this}adjoint(){return B6.mat2.adjoint(this,this),this}clone(){return new CK(this[0],this[1],this[2],this[3])}copy(Z){return B6.mat2.copy(this,Z),this}equals(Z){return B6.mat2.equals(this,Z)}exactEquals(Z){return B6.mat2.exactEquals(this,Z)}identity(){return B6.mat2.identity(this),this}invert(){return B6.mat2.invert(this,this),this}multiply(Z){return B6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return B6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return B6.mat2.rotate(this,this,Z),this}subtract(Z){return B6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return B6.mat2.transpose(this,this),this}}var j8=r(PK(),1);class kZ extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G){super([Z,J,X,Y,$,Q,K,W,G])}get determinant(){return j8.mat3.determinant(this)}get frobeniusNorm(){return j8.mat3.frob(this)}static create(){let Z=new kZ(0,0,0,0,0,0,0,0,0);return j8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=kZ.create();return j8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=kZ.create();return j8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=kZ.create();return j8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=kZ.create();return j8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=kZ.create();return j8.mat3.fromTranslation(J,Z),J}add(Z){return j8.mat3.add(this,this,Z),this}adjoint(){return j8.mat3.adjoint(this,this),this}clone(){return new kZ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return j8.mat3.copy(this,Z),this}equals(Z){return j8.mat3.equals(this,Z)}exactEquals(Z){return j8.mat3.exactEquals(this,Z)}identity(){return j8.mat3.identity(this),this}invert(){return j8.mat3.invert(this,this),this}multiply(Z){return j8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return j8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return j8.mat3.projection(this,Z,J),this}rotate(Z){return j8.mat3.rotate(this,this,Z),this}subtract(Z){return j8.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 j8.mat3.transpose(this,this),this}}var $1=r(PK(),1);class v5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G,V,z,F,H,q,U,B){super([Z,J,X,Y,$,Q,K,W,G,V,z,F,H,q,U,B])}get determinant(){return $1.mat4.determinant(this)}get frobeniusNorm(){return $1.mat4.frob(this)}static create(){let Z=new v5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return $1.mat4.identity(Z),Z}static fromQuaternion(Z){let J=v5.create();return $1.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=v5.create();return $1.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=v5.create();return $1.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=v5.create();return $1.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=v5.create();return $1.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=v5.create();return $1.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=v5.create();return $1.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=v5.create();return $1.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=v5.create();return $1.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=v5.create();return $1.mat4.fromZRotation(J,Z),J}add(Z){return $1.mat4.add(this,this,Z),this}adjoint(){return $1.mat4.adjoint(this,this),this}clone(){return new v5(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 $1.mat4.copy(this,Z),this}equals(Z){return $1.mat4.equals(this,Z)}exactEquals(Z){return $1.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return $1.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return $1.mat4.identity(this),this}invert(){return $1.mat4.invert(this,this),this}lookAt(Z,J,X){return $1.mat4.lookAt(this,Z,J,X),this}multiply(Z){return $1.mat4.mul(this,this,Z),this}multiplyScalar(Z){return $1.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return $1.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return $1.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return $1.mat4.rotate(this,this,Z,J),this}rotateX(Z){return $1.mat4.rotateX(this,this,Z),this}rotateY(Z){return $1.mat4.rotateY(this,this,Z),this}rotateZ(Z){return $1.mat4.rotateZ(this,this,Z),this}scale(Z){return $1.mat4.scale(this,this,Z),this}subtract(Z){return $1.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return $1.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 $1.mat4.translate(this,this,Z),this}transpose(){return $1.mat4.transpose(this,this),this}}var b1=r(PK(),1);class lG extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return b1.quat.length(this)}get squaredLength(){return b1.quat.squaredLength(this)}get magnitude(){return b1.quat.length(this)}get squaredMagnitude(){return b1.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 Y=b1.quat.fromEuler(new Float32Array(4),Z,J,X);return new lG(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new lG(Z.x,Z.y,Z.z,Z.w)}clone(){return new lG(this.x,this.y,this.z,this.w)}conjugate(){return b1.quat.conjugate(this,this),this}copy(Z){return b1.quat.copy(this,Z),this}dot(Z){return b1.quat.dot(this,Z)}exponential(){return b1.quat.exp(this,this),this}equals(Z){return b1.quat.equals(this,Z)}exactEquals(Z){return b1.quat.exactEquals(this,Z)}getAngle(Z){return b1.quat.getAngle(this,Z)}identity(){return b1.quat.identity(this),this}invert(){return b1.quat.invert(this,this),this}lerp(Z,J){return b1.quat.lerp(this,this,Z,J),this}logarithm(){return b1.quat.ln(this,this),this}multiply(Z){return b1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return b1.quat.normalize(this,this),this}power(Z){return b1.quat.pow(this,this,Z),this}randomize(){return b1.quat.random(this),this}rotateX(Z){return b1.quat.rotateX(this,this,Z),this}rotateY(Z){return b1.quat.rotateY(this,this,Z),this}rotateZ(Z){return b1.quat.rotateZ(this,this,Z),this}scale(Z){return b1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return b1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return b1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var U1=r(PK(),1);class K2 extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return U1.vec2.length(this)}get squaredLength(){return U1.vec2.squaredLength(this)}get magnitude(){return U1.vec2.length(this)}get squaredMagnitude(){return U1.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 K2(0,0)}add(Z){return U1.vec2.add(this,this,Z),this}angle(Z){return U1.vec2.angle(this,Z)}ceil(){return U1.vec2.ceil(this,this),this}clone(){return new K2(this.x,this.y)}copy(Z){return U1.vec2.copy(this,Z),this}distance(Z){return U1.vec2.distance(this,Z)}divide(Z){return U1.vec2.divide(this,this,Z),this}dot(Z){return U1.vec2.dot(this,Z)}equals(Z){return U1.vec2.equals(this,Z)}exactEquals(Z){return U1.vec2.exactEquals(this,Z)}floor(){return U1.vec2.floor(this,this),this}invert(){return U1.vec2.inverse(this,this),this}lerp(Z,J){return U1.vec2.lerp(this,this,Z,J),this}max(Z){return U1.vec2.max(this,this,Z),this}min(Z){return U1.vec2.min(this,this,Z),this}multiply(Z){return U1.vec2.mul(this,this,Z),this}negate(){return U1.vec2.negate(this,this),this}normalize(){return U1.vec2.normalize(this,this),this}randomize(Z){return U1.vec2.random(this,Z),this}rotate(Z,J){return U1.vec2.rotate(this,this,Z,J),this}round(){return U1.vec2.round(this,this),this}scale(Z){return U1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return U1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return U1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return U1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return U1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return U1.vec2.transformMat4(this,this,Z),this}zero(){return U1.vec2.zero(this),this}}var H1=r(PK(),1);class pG extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return H1.vec3.length(this)}get squaredLength(){return H1.vec3.squaredLength(this)}get magnitude(){return H1.vec3.length(this)}get squaredMagnitude(){return H1.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 pG(0,0,0)}static fromVector3Like(Z){return new pG(Z.x,Z.y,Z.z)}add(Z){return H1.vec3.add(this,this,Z),this}ceil(){return H1.vec3.ceil(this,this),this}clone(){return new pG(this.x,this.y,this.z)}copy(Z){return H1.vec3.copy(this,Z),this}cross(Z){return H1.vec3.cross(this,this,Z),this}distance(Z){return H1.vec3.distance(this,Z)}divide(Z){return H1.vec3.div(this,this,Z),this}dot(Z){return H1.vec3.dot(this,Z)}equals(Z){return H1.vec3.equals(this,Z)}exactEquals(Z){return H1.vec3.exactEquals(this,Z)}floor(){return H1.vec3.floor(this,this),this}invert(){return H1.vec3.inverse(this,this),this}lerp(Z,J){return H1.vec3.lerp(this,this,Z,J),this}max(Z){return H1.vec3.max(this,this,Z),this}min(Z){return H1.vec3.min(this,this,Z),this}multiply(Z){return H1.vec3.mul(this,this,Z),this}negate(){return H1.vec3.negate(this,this),this}normalize(){return H1.vec3.normalize(this,this),this}randomize(Z){return H1.vec3.random(this,Z),this}rotateX(Z,J){return H1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return H1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return H1.vec3.rotateZ(this,this,Z,J),this}round(){return H1.vec3.round(this,this),this}scale(Z){return H1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return H1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return H1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return H1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return H1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return H1.vec3.transformQuat(this,this,Z),this}zero(){return H1.vec3.zero(this),this}}var oF1=r(aF1(),1);var sF1=0.099856;class W2 extends V${faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=sF1;_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:sF1,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,Y=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let $=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*$*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let $={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-Y.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-Y.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-Y.z},Q=$.x*$.x+$.y*$.y+$.z*$.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let W=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(W*W+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let W=Math.sqrt(Q),G=this.moveSpeed*X,z=Math.min(W,G)/W,F={x:Y.x+$.x*z,y:Y.y+$.y*z,z:Y.z+$.z*z};if(Z.setPosition(F),this._onMove)this._onMove(F,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 W=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,W(Y)}}}if(this._faceTarget){let $={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},Q=Math.atan2(-$.x,-$.z),K=Z.rotation,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;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,z=Math.abs(G)<V?G:Math.sign(G)*V,H=(W+z)/2,q={x:0,y:Math.fround(Math.sin(H)),z:0,w:Math.fround(Math.cos(H))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}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 Eu extends W2{_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 c.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)c.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)},Y=Math.abs(X.x-J.x),$=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if(Y<=2&&$<=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 W=this._coordinateToKey(J),G=new Map,V=new Map([[W,0]]),z=new Map([[W,this._pathfindingHeuristic(J,X)]]),F=new Set,H=new oF1.Heap((N,R)=>{let P=z.get(N[0])??1/0,D=z.get(R[0])??1/0;return P-D});H.push([W,J]);let q=[{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 N=this._maxJump;N>=this._maxFall;N--){if(N===0)continue;let R=Math.abs(J.y+N-X.y);U.push({y:N,distanceToTargetY:R})}U.sort((N,R)=>N.distanceToTargetY-R.distanceToTargetY);let B=[...q,...U.flatMap(({y:N})=>q.map((R)=>({...R,y:N})))],L=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),M=Math.min(this._maxOpenSetIterations,w*20);while(!H.isEmpty()&&L<M){L++;let[N,R]=H.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let C=this._reconstructPath(G,R);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 ${L} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}F.add(N);let P=V.get(N),D=new Map;for(let C of B){let T=`${C.x},${C.z}`,k=C.y<0;if(k&&D.has(T))continue;let A={x:R.x+C.x,y:R.y+C.y,z:R.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(F.has(x))continue;let I=this._isNeighborCoordinateBlocked(R,A,this._entity.height);if(k&&I){D.set(T,!0);continue}if(I)continue;let _=Math.abs(C.x),b=Math.abs(C.y),u=Math.abs(C.z),i=b===0?0:this._verticalPenalty,e=(Math.max(_,b,u)===1&&_+b+u>1?1.4:1)+i,Z0=P+e,K0=V.get(x)??1/0;if(Z0>=K0)continue;G.set(x,R),V.set(x,Z0);let S0=Z0+this._pathfindingHeuristic(A,X);z.set(x,S0),H.push([x,A])}}if(L>=M){if(this._onPathfindAbort?.(),this._debug)c.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${M}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)c.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],Y=J;while(Z.has(this._coordinateToKey(Y)))Y=Z.get(this._coordinateToKey(Y)),X.unshift(Y);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 Y=J.y-Z.y,$=Math.min(Y,this._maxJump)+0.75;this.jump($);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*$),W=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,z=J.z+0.5,F=V-W,H=z-G,q=Math.sqrt(F*F+H*H),U=K/Q,B=q/this._speed;X=Math.min(U*0.8,B)*1000}setTimeout(()=>{if(!this._entity)return;let Y=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()-Y>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 Y=this._entity.world,$=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:$,y:Q+V,z:K}))return!0;if($!==W&&K!==G)for(let V=0;V<X;V++){let z=Y.chunkLattice.hasBlock({x:$,y:Q+V,z:G}),F=Y.chunkLattice.hasBlock({x:W,y:Q+V,z:K});if(z||F)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,Y={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let $=0;$<=Math.abs(this._maxFall);$++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-$-1}))return{...Y,y:Y.y-$};return}}export{UG6 as startServer,QH1 as WorldManagerEvent,K$ as WorldManager,$H1 as WorldLoopEvent,$2 as WorldLoop,Mu as WorldEvent,Q2 as World,wA as WebServerEvent,I3 as WebServer,pG as Vector3,K2 as Vector2,Y2 as Ticker,NK as TelemetrySpanOperation,R8 as Telemetry,Ou as SimulationEvent,Z2 as Simulation,W2 as SimpleEntityController,X2 as SceneUIManager,R_ as SceneUIEvent,jH as SceneUI,d50 as SUPPORTED_INPUT_KEYS,mz as RigidBodyType,f$ as RigidBody,lG as Quaternion,AO as PlayerUIEvent,LH as PlayerUI,KH1 as PlayerManagerEvent,N9 as PlayerManager,wH as PlayerEvent,i7 as PlayerEntity,u50 as PlayerCameraMode,w_ as PlayerCameraEvent,BH as PlayerCamera,uW as Player,l$ as PersistenceManager,Eu as PathfindingEntityController,J2 as ParticleEmitterManager,Bu as ParticleEmitterEvent,Lu as ParticleEmitter,BA as PORT,n50 as PLAYER_ROTATION_UPDATE_THRESHOLD,i50 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,g5 as ModelRegistry,v5 as Matrix4,kZ as Matrix3,CK as Matrix2,YH1 as LightType,tU as LightManager,qu as LightEvent,Uu as Light,U6 as IterationMap,GH1 as GameServerEvent,RK as GameServer,O0 as EventRouter,c as ErrorHandler,DH as EntityManager,RH as EntityEvent,a8 as Entity,p50 as ENTITY_ROTATION_UPDATE_THRESHOLD,l50 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,m1 as DefaultPlayerEntityController,j_ as DefaultPlayerEntity,c50 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,g4 as CollisionGroupsBuilder,B$ as CollisionGroup,uz as ColliderShape,NH as ColliderMap,F9 as Collider,fE as CoefficientCombineRule,N_ as ChunkLatticeEvent,MH as ChunkLattice,B9 as Chunk,OH as ChatManager,O_ as ChatEvent,bE as BlockTypeRegistryEvent,dz as BlockTypeRegistry,yE as BlockTypeEvent,q9 as BlockType,IK as Block,hu as BaseEntityControllerEvent,V$ as BaseEntityController,aG as AudioManager,HP as AudioEvent,nG as Audio};
493
+ >>> no match, partial?`,Z,F,J,H),F===W)return!0}return!1}let U;if(typeof V==="string")U=z===V,this.debug("string match",V,z,U);else U=V.test(z),this.debug("pattern match",V,z,U);if(!U)return!1}if(Q===W&&K===G)return!0;else if(Q===W)return X;else if(K===G)return Q===W-1&&Z[Q]==="";else throw new Error("wtf?")}braceExpand(){return Q$1(this.pattern,this.options)}parse(Z){IU(Z);let J=this.options;if(Z==="**")return I4;if(Z==="")return"";let X,Y=null;if(X=Z.match(vY6))Y=J.dot?AY6:SY6;else if(X=Z.match(RY6))Y=(J.nocase?J.dot?CY6:PY6:J.dot?DY6:jY6)(X[1]);else if(X=Z.match(xY6))Y=(J.nocase?J.dot?fY6:hY6:J.dot?yY6:bY6)(X);else if(X=Z.match(TY6))Y=J.dot?EY6:kY6;else if(X=Z.match(IY6))Y=_Y6;let $=I6.fromGlob(Z,this.options).toMMPattern();if(Y&&typeof $==="object")Reflect.defineProperty($,"test",{value:Y});return $}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?uY6:J.dot?dY6:cY6,Y=new Set(J.nocase?["i"]:[]),$=Z.map((W)=>{let G=W.map((V)=>{if(V instanceof RegExp)for(let z of V.flags.split(""))Y.add(z);return typeof V==="string"?aY6(V):V===I4?I4:V._src});return G.forEach((V,z)=>{let F=G[z+1],H=G[z-1];if(V!==I4||H===I4)return;if(H===void 0)if(F!==void 0&&F!==I4)G[z+1]="(?:\\/|"+X+"\\/)?"+F;else G[z]=X;else if(F===void 0)G[z-1]=H+"(?:\\/|"+X+")?";else if(F!==I4)G[z-1]=H+"(?:\\/|\\/"+X+"\\/)"+F,G[z+1]=I4}),G.filter((V)=>V!==I4).join("/")}).join("|"),[Q,K]=Z.length>1?["(?:",")"]:["",""];if($="^"+Q+$+K+"$",this.negate)$="^(?!"+$+").+$";try{this.regexp=new RegExp($,[...Y].join(""))}catch(W){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 Y=this.slashSplit(Z);this.debug(this.pattern,"split",Y);let $=this.set;this.debug(this.pattern,"set",$);let Q=Y[Y.length-1];if(!Q)for(let K=Y.length-2;!Q&&K>=0;K--)Q=Y[K];for(let K=0;K<$.length;K++){let W=$[K],G=Y;if(X.matchBase&&W.length===1)G=[Q];if(this.matchOne(G,W,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return _6.defaults(Z).Minimatch}}_6.AST=I6;_6.Minimatch=vU;_6.escape=mg;_6.unescape=AY;var W$1="@fastify/otel",oY6="0.8.0",rY6=">=4.0.0 <6",G$1=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],o1={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},xY={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},iJ="anonymous",T5=Symbol("fastify otel instance"),hY=Symbol("fastify otel request spans"),SU=Symbol("fastify otel request context"),V$1=Symbol("fastify otel addhook original"),z$1=Symbol("fastify otel setnotfound original"),sj=Symbol("fastify otel ignore path");class ug extends H$1.InstrumentationBase{constructor(Z){super(W$1,oY6,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[sj]=null,this._logger=A8.diag.createComponentLogger({namespace:W$1}),Z?.ignorePaths!=null||process.env.OTEL_FASTIFY_IGNORE_PATHS!=null){let J=Z?.ignorePaths??process.env.OTEL_FASTIFY_IGNORE_PATHS;if((typeof J!=="string"||J.length===0)&&typeof J!=="function")throw new TypeError("ignorePaths must be a string or a function");let X=_6;this[sj]=(Y)=>{if(typeof J==="function")return J(Y);else return X(Y.url,J)}}}enable(){if(this._handleInitialization===void 0&&this.getConfig().registerOnInitialization){let Z=this.plugin();this._handleInitialization=(J)=>{J.fastify.register(Z)},K$1.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)K$1.unsubscribe("fastify.initialization",this._handleInitialization),this._handleInitialization=void 0;return super.disable()}init(){return[]}plugin(){let Z=this;return J[Symbol.for("skip-override")]=!0,J[Symbol.for("fastify.display-name")]="@fastify/otel",J[Symbol.for("plugin-meta")]={fastify:rY6,name:"@fastify/otel"},J;function J(X,Y,$){X.decorate(T5,Z),X.decorate(V$1,X.addHook),X.decorate(z$1,X.setNotFoundHandler),X.decorateRequest("opentelemetry",function z(){let F=this[SU];return{span:this[hY],tracer:Z.tracer,context:F,inject:(q,U)=>{return A8.propagation.inject(F,q,U)},extract:(q,U)=>{return A8.propagation.extract(F,q,U)}}}),X.decorateRequest(hY,null),X.decorateRequest(SU,null),X.addHook("onRoute",function(z){if(Z[sj]?.(z)===!0){Z._logger.debug(`Ignoring route instrumentation ${z.method} ${z.url} because it matches the ignore path`);return}for(let F of G$1)if(z[F]!=null){let H=z[F];if(typeof H==="function")z[F]=V(H,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route -> ${F}`,[o1.FASTIFY_TYPE]:xY.ROUTE,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:iJ});else if(Array.isArray(H)){let q=[];for(let U of H)q.push(V(U,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route -> ${F}`,[o1.FASTIFY_TYPE]:xY.ROUTE,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:iJ}));z[F]=q}}if(z.onSend!=null)z.onSend=Array.isArray(z.onSend)?[...z.onSend,Q]:[z.onSend,Q];else z.onSend=Q;if(z.onError!=null)z.onError=Array.isArray(z.onError)?[...z.onError,K]:[z.onError,K];else z.onError=K;z.handler=V(z.handler,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route-handler`,[o1.FASTIFY_TYPE]:xY.HANDLER,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:z.handler.name.length>0?z.handler.name:iJ})}),X.addHook("onRequest",function(z,F,H){if(this[T5].isEnabled()===!1)return H();else if(this[T5][sj]?.({url:z.url,method:z.method})===!0)return this[T5]._logger.debug(`Ignoring request ${z.method} ${z.url} because it matches the ignore path`),H();let q=A8.context.active();if(A8.trace.getSpan(q)==null)q=A8.propagation.extract(q,z.headers);let U=oj.getRPCMetadata(q);if(z.routeOptions.url!=null&&U?.type===oj.RPCType.HTTP)U.route=z.routeOptions.url;let B=this[T5].tracer.startSpan("request",{attributes:{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.ROOT]:"@fastify/otel",[d8.ATTR_HTTP_ROUTE]:z.url,[d8.ATTR_HTTP_REQUEST_METHOD]:z.method}},q);z[SU]=A8.trace.setSpan(q,B),z[hY]=B,A8.context.with(z[SU],()=>{H()})}),X.addHook("onResponse",function(z,F,H){let q=z[hY];if(q!=null)q.setStatus({code:A8.SpanStatusCode.OK,message:"OK"}),q.setAttributes({[d8.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),q.end();z[hY]=null,H()}),X.addHook=W,X.setNotFoundHandler=G,$();function Q(z,F,H,q){let U=z[hY];if(U!=null){if(F.statusCode<500)U.setStatus({code:A8.SpanStatusCode.OK,message:"OK"});U.setAttributes({[d8.ATTR_HTTP_RESPONSE_STATUS_CODE]:F.statusCode}),U.end()}z[hY]=null,q(null,H)}function K(z,F,H,q){let U=z[hY];if(U!=null)U.setStatus({code:A8.SpanStatusCode.ERROR,message:H.message}),U.recordException(H);q()}function W(z,F){let H=this[V$1];if(G$1.includes(z))return H.call(this,z,V(F,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - ${z}`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:iJ}));else return H.call(this,z,F)}function G(z,F){let H=this[z$1];if(typeof z==="function")F=V(z,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.name?.length>0?z.name:iJ}),H.call(this,F);else{if(z.preValidation!=null)z.preValidation=V(z.preValidation,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.preValidation.name?.length>0?z.preValidation.name:iJ});if(z.preHandler!=null)z.preHandler=V(z.preHandler,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.preHandler.name?.length>0?z.preHandler.name:iJ});F=V(F,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:iJ}),H.call(this,z,F)}}function V(z,F={}){return function H(...q){let U=this[T5],[B]=q;if(U.isEnabled()===!1)return z.call(this,...q);let L=B[SU]??A8.context.active(),w=U.tracer.startSpan(`handler - ${z.name?.length>0?z.name:this.pluginName??iJ}`,{attributes:F},L);return A8.context.with(A8.trace.setSpan(L,w),function(){try{let M=z.call(this,...q);if(typeof M?.then==="function")return M.then((N)=>{return w.end(),N},(N)=>{return w.setStatus({code:A8.SpanStatusCode.ERROR,message:N.message}),w.recordException(N),w.end(),Promise.reject(N)});return w.end(),M}catch(M){throw w.setStatus({code:A8.SpanStatusCode.ERROR,message:M.message}),w.recordException(M),w.end(),M}},this)}}}}}var j7=r(Y0(),1),tj=r(q1(),1),FK=r(r0(),1),L$1=r(j1(),1);var nJ;(function(Z){Z.FASTIFY_NAME="fastify.name";let X="fastify.type";Z.FASTIFY_TYPE=X;let Y="hook.name";Z.HOOK_NAME=Y;let $="plugin.name";Z.PLUGIN_NAME=$})(nJ||(nJ={}));var AU;(function(Z){Z.MIDDLEWARE="middleware";let X="request_handler";Z.REQUEST_HANDLER=X})(AU||(AU={}));var xU;(function(Z){Z.MIDDLEWARE="middleware";let X="request handler";Z.REQUEST_HANDLER=X})(xU||(xU={}));var q$1=r(Y0(),1);var hU=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function dg(Z,J,X,Y={}){let $=J.startSpan(X,{attributes:Y}),Q=Z[hU]||[];return Q.push($),Object.defineProperty(Z,hU,{enumerable:!1,configurable:!0,value:Q}),$}function rj(Z,J){let X=Z[hU]||[];if(!X.length)return;X.forEach((Y)=>{if(J)Y.setStatus({code:q$1.SpanStatusCode.ERROR,message:J.message}),Y.recordException(J);Y.end()}),delete Z[hU]}function U$1(Z,J,X){let Y,$=void 0;try{if($=Z(),F$1($))$.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){Y=Q}finally{if(!F$1($)){if(J(Y,$),Y)throw Y}return $}}function F$1(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var tY6="0.1.0",eY6="@sentry/instrumentation-fastify-v3",B$1="anonymous",Z$6=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class cg extends FK.InstrumentationBase{constructor(Z={}){super(eY6,tY6,Z)}init(){return[new FK.InstrumentationNodeModuleDefinition("fastify",[">=3.0.0 <4"],(Z)=>{return this._patchConstructor(Z)})]}_hookOnRequest(){let Z=this;return function J(X,Y,$){if(!Z.isEnabled())return $();Z._wrap(Y,"send",Z._patchSend());let Q=X,K=tj.getRPCMetadata(j7.context.active()),W=Q.routeOptions?Q.routeOptions.url:X.routerPath;if(W&&K?.type===tj.RPCType.HTTP)K.route=W;let G=X.method||"GET";E0().setTransactionName(`${G} ${W}`),$()}}_wrapHandler(Z,J,X,Y){let $=this;return this._diag.debug("Patching fastify route.handler function"),function(...Q){if(!$.isEnabled())return X.apply(this,Q);let K=X.name||Z||B$1,W=`${xU.MIDDLEWARE} - ${K}`,G=Q[1],V=dg(G,$.tracer,W,{[nJ.FASTIFY_TYPE]:AU.MIDDLEWARE,[nJ.PLUGIN_NAME]:Z,[nJ.HOOK_NAME]:J}),z=Y&&Q[Q.length-1];if(z)Q[Q.length-1]=function(...F){rj(G),z.apply(this,F)};return j7.context.with(j7.trace.setSpan(j7.context.active(),V),()=>{return U$1(()=>{return X.apply(this,Q)},(F)=>{if(F instanceof Error)V.setStatus({code:j7.SpanStatusCode.ERROR,message:F.message}),V.recordException(F);if(!Y)rj(G)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function X(...Y){let $=Y[0],Q=Y[1],K=this.pluginName;if(!Z$6.has($))return J.apply(this,Y);let W=typeof Y[Y.length-1]==="function"&&Q.constructor.name!=="AsyncFunction";return J.apply(this,[$,Z._wrapHandler(K,$,Q,W)])}}}_patchConstructor(Z){let J=this;function X(...Y){let $=Z.fastify.apply(this,Y);return $.addHook("onRequest",J._hookOnRequest()),$.addHook("preHandler",J._hookPreHandler()),J$6(),J._wrap($,"addHook",J._wrapAddHook()),$}if(Z.errorCodes!==void 0)X.errorCodes=Z.errorCodes;return X.fastify=X,X.default=X,X}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function J(X){return function Y(...$){let Q=$[0];if(!Z.isEnabled())return X.apply(this,$);return FK.safeExecuteInTheMiddle(()=>{return X.apply(this,$)},(K)=>{if(!K&&Q instanceof Error)K=Q;rj(this,K)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function J(X,Y,$){if(!Z.isEnabled())return $();let Q=X,K=Q.routeOptions?.handler||Q.context?.handler,W=K?.name.startsWith("bound ")?K.name.substring(6):K?.name,G=`${xU.REQUEST_HANDLER} - ${W||this.pluginName||B$1}`,V={[nJ.PLUGIN_NAME]:this.pluginName,[nJ.FASTIFY_TYPE]:AU.REQUEST_HANDLER,[L$1.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:X.routerPath};if(W)V[nJ.FASTIFY_NAME]=W;let z=dg(Y,Z.tracer,G,V);w$1(z);let{requestHook:F}=Z.getConfig();if(F)FK.safeExecuteInTheMiddle(()=>F(z,{request:X}),(H)=>{if(H)Z._diag.error("request hook failed",H)},!0);return j7.context.with(j7.trace.setSpan(j7.context.active(),z),()=>{$()})}}}function J$6(){let Z=X0();if(Z)Z.on("spanStart",(J)=>{w$1(J)})}function w$1(Z){let J=L0(Z).data,X=J["fastify.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.fastify",[j0]:`${X}.fastify`});let Y=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof Y==="string"){let $=Y.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName($)}}var O$1="Fastify",X$6="Fastify-V5",Y$6="Fastify-V3",pg=B0(Y$6,()=>new cg);function M$1(){let Z=X0();if(!Z)return;else return Z.getIntegrationByName(O$1)}function ej(Z,J,X,Y){let $=M$1()?.getShouldHandleError()||N$1;if(Y==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&Y==="onError-hook"){T4&&h.warn("Fastify error handler was already registered via diagnostics channel.","You can safely remove `setupFastifyErrorHandler` call and set `shouldHandleError` on the integration options.");return}if($(Z,J,X))Z1(Z,{mechanism:{handled:!1,type:"fastify"}})}var ig=B0(X$6,()=>{let Z=new ug,J=Z.plugin();return lg.subscribe("fastify.initialization",(X)=>{let Y=X.fastify;Y?.register(J).after(($)=>{if($)T4&&h.error("Failed to setup Fastify instrumentation",$);else if(Q$6(),Y)K$6(Y)})}),lg.subscribe("tracing:fastify.request.handler:error",(X)=>{let{error:Y,request:$,reply:Q}=X;ej.call(ej,Y,$,Q,"diagnostics-channel")}),Z}),$$6=({shouldHandleError:Z})=>{let J;return{name:O$1,setupOnce(){J=Z||N$1,pg(),ig()},getShouldHandleError(){return J},setShouldHandleError(X){J=X}}},ZD=a((Z={})=>$$6(Z));function N$1(Z,J,X){let Y=X.statusCode;return Y>=500||Y<=299}function R$1(Z,J){if(J?.shouldHandleError)M$1()?.setShouldHandleError(J.shouldHandleError);let X=Object.assign(function(Y,$,Q){Y.addHook("onError",async(K,W,G)=>{ej.call(ej,G,K,W,"onError-hook")}),Q()},{[Symbol.for("skip-override")]:!0,[Symbol.for("fastify.display-name")]:"sentry-fastify-error-handler"});Z.register(X)}function j$1(Z){let J=L0(Z),X=J.description,Y=J.data,$=Y["fastify.type"],Q=$==="hook",K=$===X?.startsWith("handler -"),W=X==="request"||$==="request-handler";if(Y[j0]||!K&&!W&&!Q)return;let G=Q?"hook":K?"middleware":W?"request-handler":"<unknown>";Z.setAttributes({[v0]:"auto.http.otel.fastify",[j0]:`${G}.fastify`});let V=Y["fastify.name"]||Y["plugin.name"]||Y["hook.name"];if(typeof V==="string"){let z=V.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(z)}}function Q$6(){let Z=X0();if(Z)Z.on("spanStart",(J)=>{j$1(J)})}function K$6(Z){Z.addHook("onRequest",async(J,X)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)j$1(Q)}let Y=J.routeOptions?.url,$=J.method||"GET";E0().setTransactionName(`${$} ${Y}`)})}var KQ1=r(Y0(),1),WQ1=r(QQ1(),1);var GQ1="Graphql",eg=B0(GQ1,WQ1.GraphQLInstrumentation,(Z)=>{let J=VQ1(Z);return{...J,responseHook(X,Y){if(s1(X,"auto.graphql.otel.graphql"),Y.errors?.length&&!L0(X).status)X.setStatus({code:KQ1.SpanStatusCode.ERROR});let Q=L0(X).data,K=Q["graphql.operation.type"],W=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&K){let G=a1(X),z=L0(G).data[RG]||[],F=W?`${K} ${W}`:`${K}`;if(Array.isArray(z))z.push(F),G.setAttribute(RG,z);else if(typeof z==="string")G.setAttribute(RG,[z,F]);else G.setAttribute(RG,F);if(!L0(G).data["original-description"])G.setAttribute("original-description",L0(G).description);G.updateName(`${L0(G).data["original-description"]} (${A$6(z)})`)}}}}),S$6=(Z={})=>{return{name:GQ1,setupOnce(){eg(VQ1(Z))}}},$D=a(S$6);function VQ1(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function A$6(Z){if(Array.isArray(Z)){let J=Z.slice().sort();if(J.length<=5)return J.join(", ");else return`${J.slice(0,5).join(", ")}, +${J.length-5}`}return`${Z}`}var TQ1=r(CQ1(),1);var kQ1="Kafka",Zm=B0(kQ1,()=>new TQ1.KafkaJsInstrumentation({consumerHook(Z){s1(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){s1(Z,"auto.kafkajs.otel.producer")}})),f$6=()=>{return{name:kQ1,setupOnce(){Zm()}}},QD=a(f$6);var gQ1=r(bQ1(),1);var mQ1="LruMemoizer",Jm=B0(mQ1,()=>new gQ1.LruMemoizerInstrumentation),m$6=()=>{return{name:mQ1,setupOnce(){Jm()}}},KD=a(m$6);var JK1=r(ZK1(),1);var XK1="Mongo",Km=B0(XK1,()=>new JK1.MongoDBInstrumentation({dbStatementSerializer:p$6,responseHook(Z){s1(Z,"auto.db.otel.mongo")}}));function p$6(Z){let J=Qm(Z);return JSON.stringify(J)}function Qm(Z){if(Array.isArray(Z))return Z.map((J)=>Qm(J));if(i$6(Z)){let J={};return Object.entries(Z).map(([X,Y])=>[X,Qm(Y)]).reduce((X,Y)=>{if(a$6(Y))X[Y[0]]=Y[1];return X},J)}return"?"}function i$6(Z){return typeof Z==="object"&&Z!==null&&!n$6(Z)}function n$6(Z){let J=!1;if(typeof Buffer!=="undefined")J=Buffer.isBuffer(Z);return J}function a$6(Z){return Array.isArray(Z)}var s$6=()=>{return{name:XK1,setupOnce(){Km()}}},WD=a(s$6);var DK1=r(jK1(),1);var PK1="Mongoose",Vm=B0(PK1,()=>new DK1.MongooseInstrumentation({responseHook(Z){s1(Z,"auto.db.otel.mongoose")}})),GQ6=()=>{return{name:PK1,setupOnce(){Vm()}}},VD=a(GQ6);var dK1=r(uK1(),1);var cK1="Mysql",qm=B0(cK1,()=>new dK1.MySQLInstrumentation({})),PQ6=()=>{return{name:cK1,setupOnce(){qm()}}},HD=a(PQ6);var VW1=r(GW1(),1);var zW1="Mysql2",Om=B0(zW1,()=>new VW1.MySQL2Instrumentation({responseHook(Z){s1(Z,"auto.db.otel.mysql2")}})),uQ6=()=>{return{name:zW1,setupOnce(){Om()}}},qD=a(uQ6);var rW1=r(IW1(),1),tW1=r(iW1(),1);var JK6=["get","set","setex"],Nm=["get","mget"],XK6=["set","setex"];function lU(Z,J){return Z.includes(J.toLowerCase())}function Rm(Z){if(lU(Nm,Z))return"cache.get";else if(lU(XK6,Z))return"cache.put";else return}function YK6(Z,J){return J.some((X)=>Z.startsWith(X))}function aW1(Z,J){try{if(J.length===0)return;let X=($)=>{if(typeof $==="string"||typeof $==="number"||Buffer.isBuffer($))return[$.toString()];else if(Array.isArray($))return nW1($.map((Q)=>X(Q)));else return["<unknown>"]},Y=J[0];if(lU(JK6,Z)&&Y!=null)return X(Y);return nW1(J.map(($)=>X($)))}catch{return}}function sW1(Z,J,X){if(!Rm(Z))return!1;for(let Y of J)if(YK6(Y,X))return!0;return!1}function oW1(Z){let J=(X)=>{try{if(Buffer.isBuffer(X))return X.byteLength;else if(typeof X==="string")return X.length;else if(typeof X==="number")return X.toString().length;else if(X===null||X===void 0)return 0;return JSON.stringify(X).length}catch{return}};return Array.isArray(Z)?Z.reduce((X,Y)=>{let $=J(Y);return typeof $==="number"?X!==void 0?X+$:$:X},0):J(Z)}function nW1(Z){let J=[],X=(Y)=>{Y.forEach(($)=>{if(Array.isArray($))X($);else J.push($)})};return X(Z),J}var eW1="Redis",jm={},Z31=(Z,J,X,Y)=>{Z.setAttribute(v0,"auto.db.otel.redis");let $=aW1(J,X),Q=Rm(J);if(!$||!Q||!jm.cachePrefixes||!sW1(J,$,jm.cachePrefixes))return;let K=L0(Z).data["net.peer.name"],W=L0(Z).data["net.peer.port"];if(W&&K)Z.setAttributes({"network.peer.address":K,"network.peer.port":W});let G=oW1(Y);if(G)Z.setAttribute(vf,G);if(lU(Nm,J)&&G!==void 0)Z.setAttribute(If,G>0);Z.setAttributes({[j0]:Q,[_f]:$});let V=$.join(", ");Z.updateName(t5(V,1024))},$K6=B0("IORedis",()=>{return new rW1.IORedisInstrumentation({responseHook:Z31})}),QK6=B0("Redis-4",()=>{return new tW1.RedisInstrumentation({responseHook:Z31})}),Dm=Object.assign(()=>{$K6(),QK6()},{id:eW1}),KK6=(Z={})=>{return{name:eW1,setupOnce(){jm=Z,Dm()}}},BD=a(KK6);var S31=r(v31(),1);var A31="Postgres",vm=B0(A31,()=>new S31.PgInstrumentation({requireParentSpan:!0,requestHook(Z){s1(Z,"auto.db.otel.postgres")}})),lK6=()=>{return{name:A31,setupOnce(){vm()}}},MD=a(lK6);var yG=r(Y0(),1),ZX=r(r0(),1),Z5=r(j1(),1);var Sm="PostgresJs",x31=[">=3.0.0 <4"],Am=B0(Sm,(Z)=>new h31({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class h31 extends ZX.InstrumentationBase{constructor(Z){super("sentry-postgres-js",R1,Z)}init(){let Z=new ZX.InstrumentationNodeModuleDefinition("postgres",x31);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new ZX.InstrumentationNodeModuleFile(`postgres/${J}/connection.js`,["*"],this._patchConnection.bind(this),this._unwrap.bind(this))),Z.files.push(new ZX.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,x31,this._patchQuery.bind(this),this._unwrap.bind(this)))}),[Z]}_shouldCreateSpans(){let Z=this.getConfig();return yG.trace.getSpan(yG.context.active())!==void 0||!Z.requireParentSpan}_patchReject(Z,J){return new Proxy(Z,{apply:(X,Y,$)=>{J.setStatus({code:S8,message:$?.[0]?.message||"unknown_error"});let Q=Reflect.apply(X,Y,$);return J.setAttribute(Z5.ATTR_DB_RESPONSE_STATUS_CODE,$?.[0]?.code||"Unknown error"),J.setAttribute(Z5.ATTR_ERROR_TYPE,$?.[0]?.name||"Unknown error"),J.end(),Q}})}_patchResolve(Z,J){return new Proxy(Z,{apply:(X,Y,$)=>{let Q=Reflect.apply(X,Y,$),K=$?.[0]?.command;if(K)J.setAttribute(Z5.ATTR_DB_OPERATION_NAME,K);return J.end(),Q}})}_patchQuery(Z){return Z.Query.prototype.handle=new Proxy(Z.Query.prototype.handle,{apply:async(J,X,Y)=>{if(!this._shouldCreateSpans())return Reflect.apply(J,X,Y);let $=this._sanitizeSqlQuery(X.strings?.[0]);return dQ({name:$||"postgresjs.query",op:"db"},(Q)=>{let W=T0().getScopeData().contexts.postgresjsConnection;s1(Q,"auto.db.otel.postgres");let{requestHook:G}=this.getConfig();if(G)ZX.safeExecuteInTheMiddle(()=>G(Q,$,W),(H)=>{if(H)h.error(`Error in requestHook for ${Sm} integration:`,H)});let V=W?.ATTR_DB_NAMESPACE||"<unknown database>",z=W?.ATTR_SERVER_ADDRESS||"<unknown host>",F=W?.ATTR_SERVER_PORT||"<unknown port>";Q.setAttribute(Z5.ATTR_DB_SYSTEM_NAME,"postgres"),Q.setAttribute(Z5.ATTR_DB_NAMESPACE,V),Q.setAttribute(Z5.ATTR_SERVER_ADDRESS,z),Q.setAttribute(Z5.ATTR_SERVER_PORT,F),Q.setAttribute(Z5.ATTR_DB_QUERY_TEXT,$),X.resolve=this._patchResolve(X.resolve,Q),X.reject=this._patchReject(X.reject,Q);try{return Reflect.apply(J,X,Y)}catch(H){throw Q.setStatus({code:S8}),Q.end(),H}})}}),Z}_patchConnection(Z){return new Proxy(Z,{apply:(J,X,Y)=>{let $=Y[0]?.database||"<unknown database>",Q=Y[0]?.host?.[0]||"<unknown host>",K=Y[0]?.port?.[0]||"<unknown port>";return T0().setContext("postgresjsConnection",{ATTR_DB_NAMESPACE:$,ATTR_SERVER_ADDRESS:Q,ATTR_SERVER_PORT:K}),Reflect.apply(J,X,Y)}})}_sanitizeSqlQuery(Z){if(!Z)return"Unknown SQL Query";return Z.replace(/\s+/g," ").trim().substring(0,1024).replace(/--.*?(\r?\n|$)/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/;\s*$/,"").replace(/\b\d+\b/g,"?").replace(/\s+/g," ").replace(/\bIN\b\s*\(\s*\?(?:\s*,\s*\?)*\s*\)/g,"IN (?)")}}var pK6=()=>{return{name:Sm,setupOnce(){Am()}}},ND=a(pK6);var b31=r(Y0(),1),RD=r(r0(),1),oY=r(Y0(),1);var iK6=process.env.PRISMA_SHOW_ALL_TRACES==="true",nK6="00-10-10-00";function aK6(Z){switch(Z){case"client":return oY.SpanKind.CLIENT;case"internal":default:return oY.SpanKind.INTERNAL}}var sK6=class{traceMiddleware;tracerProvider;ignoreSpanTypes;constructor({traceMiddleware:Z,tracerProvider:J,ignoreSpanTypes:X}){this.traceMiddleware=Z,this.tracerProvider=J,this.ignoreSpanTypes=X}isEnabled(){return!0}getTraceParent(Z){let J=oY.trace.getSpanContext(Z??oY.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return nK6}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),X=new Map,Y=Z.filter(($)=>$.parentId===null);for(let $ of Y)g31(J,$,Z,X,this.ignoreSpanTypes)}getActiveContext(){return oY.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!iK6)return J();if(Z.middleware&&!this.traceMiddleware)return J();let X=this.tracerProvider.getTracer("prisma"),Y=Z.context??this.getActiveContext(),$=`prisma:client:${Z.name}`;if(m31($,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=X.startSpan($,Z,Y);return f31(Q,J(Q,Y))}return X.startActiveSpan($,Z,(Q)=>f31(Q,J(Q,Y)))}};function g31(Z,J,X,Y,$){if(m31(J.name,$))return;let Q={attributes:J.attributes,kind:aK6(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(K)=>{if(Y.set(J.id,K.spanContext().spanId),J.links)K.addLinks(J.links.flatMap((G)=>{let V=Y.get(G);if(!V)return[];return{context:{spanId:V,traceId:K.spanContext().traceId,traceFlags:K.spanContext().traceFlags}}}));let W=X.filter((G)=>G.parentId===J.id);for(let G of W)g31(Z,G,X,Y,$);K.end(J.endTime)})}function f31(Z,J){if(oK6(J))return J.then((X)=>{return Z.end(),X},(X)=>{throw Z.end(),X});return Z.end(),J}function oK6(Z){return Z!=null&&typeof Z.then==="function"}function m31(Z,J){return J.some((X)=>typeof X==="string"?X===Z:X.test(Z))}var u31={name:"@prisma/instrumentation",version:"6.11.1",description:"OpenTelemetry compliant instrumentation for Prisma Client",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{require:{types:"./dist/index.d.ts",default:"./dist/index.js"},import:{types:"./dist/index.d.ts",default:"./dist/index.mjs"}}},license:"Apache-2.0",homepage:"https://www.prisma.io",repository:{type:"git",url:"https://github.com/prisma/prisma.git",directory:"packages/instrumentation"},bugs:"https://github.com/prisma/prisma/issues",devDependencies:{"@prisma/internals":"workspace:*","@swc/core":"1.11.5","@types/jest":"29.5.14","@types/node":"18.19.76","@opentelemetry/api":"1.9.0",jest:"29.7.0","jest-junit":"16.0.0",typescript:"5.4.5"},dependencies:{"@opentelemetry/instrumentation":"^0.52.0 || ^0.53.0 || ^0.54.0 || ^0.55.0 || ^0.56.0 || ^0.57.0"},peerDependencies:{"@opentelemetry/api":"^1.8"},files:["dist"],keywords:["prisma","instrumentation","opentelemetry","otel"],scripts:{dev:"DEV=true tsx helpers/build.ts",build:"tsx helpers/build.ts",prepublishOnly:"pnpm run build",test:"jest"},sideEffects:!1},hm=u31.version,rK6=hm.split(".")[0],y31="PRISMA_INSTRUMENTATION",xm=`V${rK6}_PRISMA_INSTRUMENTATION`,tK6=u31.name,eK6="@prisma/client",d31=class extends RD.InstrumentationBase{tracerProvider;constructor(Z={}){super(tK6,hm,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new RD.InstrumentationNodeModuleDefinition(eK6,[hm])]}enable(){let Z=this._config,J={helper:new sK6({traceMiddleware:Z.middleware??!1,tracerProvider:this.tracerProvider??b31.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[y31]=J,global[xm]=J}disable(){delete global[y31],delete global[xm]}isEnabled(){return Boolean(global[xm])}};var c31="Prisma";function ZW6(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function l31(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class p31 extends d31{constructor(){super()}enable(){super.enable();let Z=l31(),J=!1;if(ZW6(Z))Z.createEngineSpan=()=>{e0(()=>{if(!J)J=!0,console.warn("[Sentry] The Sentry SDK supports tracing with Prisma version 5 only with limited capabilities. For full tracing capabilities pass `prismaInstrumentation` for version 5 to the Sentry `prismaIntegration`. Read more: https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/prisma/")})}}}var JW6=B0(c31,(Z)=>{if(Z?.prismaInstrumentation)return Z.prismaInstrumentation;return new p31}),jD=a(({prismaInstrumentation:Z}={})=>{return{name:c31,setupOnce(){JW6({prismaInstrumentation:Z})},setup(J){if(!l31())return;J.on("spanStart",(X)=>{let Y=L0(X);if(Y.description?.startsWith("prisma:"))X.setAttribute(v0,"auto.db.otel.prisma");if(Y.description==="prisma:engine:db_query"&&Y.data["db.query.text"])X.updateName(Y.data["db.query.text"]);if(Y.description==="prisma:engine:db_query"&&!Y.data["db.system"])X.setAttribute("db.system","prisma")})}}});var VG1=r(GG1(),1);var zG1="Hapi",CD=B0(zG1,()=>new VG1.HapiInstrumentation),jW6=()=>{return{name:zG1,setupOnce(){CD()}}},TD=a(jW6);function DW6(Z){return!!(Z&&typeof Z==="object"&&("error"in Z)&&Z.error)}function PW6(Z){Z1(Z,{mechanism:{type:"hapi",handled:!1,data:{function:"hapiErrorPlugin"}}})}var CW6={name:"SentryHapiErrorPlugin",version:R1,register:async function(Z){Z.events.on({name:"request",channels:["error"]},(X,Y)=>{if(E0()!==B4()){let $=X.route;if($.path)E0().setTransactionName(`${$.method.toUpperCase()} ${$.path}`)}else T4&&h.warn("Isolation scope is still the default isolation scope - skipping setting transactionName");if(DW6(Y))PW6(Y.error)})}};async function HG1(Z){await Z.register(CW6);let J=X0();if(J)J.on("spanStart",(X)=>{TW6(X)});cJ(Z.register,"hapi")}function TW6(Z){let J=L0(Z).data,X=J["hapi.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.hapi",[j0]:`${X}.hapi`})}var xG1=r(AG1(),1),hG1=r(j1(),1);var fG1="Koa",lm=B0(fG1,xG1.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,X){s1(J,"auto.http.otel.koa");let Y=L0(J).data,$=Y["koa.type"];if($)J.setAttribute(j0,`${$}.koa`);let Q=Y["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(E0()===B4()){T4&&h.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let K=Y[hG1.ATTR_HTTP_ROUTE],W=X.context?.request?.method?.toUpperCase()||"GET";if(K)E0().setTransactionName(`${W} ${K}`)}}}),hW6=(Z={})=>{return{name:fG1,setupOnce(){lm(Z)}}},ID=a(hW6),yG1=(Z)=>{Z.use(async(J,X)=>{try{await X()}catch(Y){throw Z1(Y),Y}}),cJ(Z.use,"koa")};var $V1=r(YV1(),1);var QV1="Connect",sm=B0(QV1,()=>new $V1.ConnectInstrumentation),sW6=()=>{return{name:QV1,setupOnce(){sm()}}},vD=a(sW6);function oW6(Z,J,X,Y){Z1(Z),Y(Z)}var KV1=(Z)=>{Z.use(oW6);let J=X0();if(J)J.on("spanStart",(X)=>{rW6(X)});cJ(Z.use,"connect")};function rW6(Z){let J=L0(Z).data,X=J["connect.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.connect",[j0]:`${X}.connect`});let Y=J["connect.name"];if(typeof Y==="string")Z.updateName(Y)}var kV1=r(TV1(),1);var EV1="Knex",q36=B0(EV1,()=>new kV1.KnexInstrumentation({requireParentSpan:!0})),U36=()=>{let Z;return{name:EV1,setupOnce(){let J=q36();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{data:Y}=L0(X);if("knex.version"in Y)X.setAttribute(v0,"auto.db.otel.knex")}))}}},IV1=a(U36);var nV1=r(iV1(),1);var R36=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),aV1="Tedious",rm=B0(aV1,()=>new nV1.TediousInstrumentation({})),j36=()=>{let Z;return{name:aV1,setupOnce(){let J=rm();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{description:Y,data:$}=L0(X);if(!Y||$["db.system"]!=="mssql")return;let Q=Y.split(" ")[0]||"";if(R36.has(Q))X.setAttribute(v0,"auto.db.otel.tedious")}))}}},fD=a(j36);var $z1=r(Yz1(),1);var Qz1="GenericPool",em=B0(Qz1,()=>new $z1.GenericPoolInstrumentation({})),T36=()=>{let Z;return{name:Qz1,setupOnce(){let J=em();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let $=L0(X).description;if($==="generic-pool.aquire"||$==="generic-pool.acquire")X.setAttribute(v0,"auto.db.otel.generic_pool")}))}}},yD=a(T36);var Oz1=r(wz1(),1);var Mz1="Dataloader",I36=B0(Mz1,()=>new Oz1.DataloaderInstrumentation({requireParentSpan:!0})),_36=()=>{let Z;return{name:Mz1,setupOnce(){let J=I36();Z=fJ(J)},setup(J){Z?.(()=>{J.on("spanStart",(X)=>{let Y=L0(X);if(Y.description?.startsWith("dataloader"))X.setAttribute(v0,"auto.db.otel.dataloader");if(Y.description==="dataloader.load"||Y.description==="dataloader.loadMany"||Y.description==="dataloader.batch")X.setAttribute(j0,"cache.get")})})}}},Nz1=a(_36);var mz1=r(gz1(),1);var uz1="Amqplib",o36={consumeEndHook:(Z)=>{s1(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{s1(Z,"auto.amqplib.otel.publisher")}},$u=B0(uz1,()=>new mz1.AmqplibInstrumentation(o36)),r36=()=>{return{name:uz1,setupOnce(){$u()}}},mD=a(r36);var oU="VercelAI";var uD=r(r0(),1);var dz1=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function t36(Z,J,X,Y){let $=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:X===!0?!0:Y,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:X===!0?!0:Y;return{recordInputs:$,recordOutputs:Q}}class rU extends uD.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",R1,Z);rU.prototype.__init.call(this),rU.prototype.__init2.call(this)}init(){return new uD.InstrumentationNodeModuleDefinition("ai",[">=3.0.0 <5"],this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach((X)=>X()),this._callbacks=[];function J(X){return(...Y)=>{let $=Y[0].experimental_telemetry||{},Q=$.isEnabled,K=T0().getClient(),W=K?.getIntegrationByName(oU),G=W?.options,V=W?Boolean(K?.getOptions().sendDefaultPii):!1,{recordInputs:z,recordOutputs:F}=t36(G,$,Q,V);return Y[0].experimental_telemetry={...$,isEnabled:Q!==void 0?Q:!0,recordInputs:z,recordOutputs:F},SJ(()=>{return X.apply(this,Y)},(H)=>{if(H&&typeof H==="object")e1(H,"_sentry_active_span",C6())})}}if(Object.prototype.toString.call(Z)==="[object Module]"){for(let X of dz1)Z[X]=J(Z[X]);return Z}else{let X=dz1.reduce((Y,$)=>{return Y[$]=J(Z[$]),Y},{});return{...Z,...X}}}}var Qu=B0(oU,()=>new rU({}));function e36(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var ZG6=(Z={})=>{let J;return{name:oU,options:Z,setupOnce(){J=Qu()},afterAllSetup(X){if(Z.force??e36(X))Kj(X);else J?.callWhenPatched(()=>Kj(X))}}},dD=a(ZG6);var cD=r(r0(),1);var JG6=[">=4.0.0 <6"];function XG6(Z,J){let X=Z?.recordInputs??J,Y=Z?.recordOutputs??J;return{recordInputs:X,recordOutputs:Y}}class Ku extends cD.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",R1,Z)}init(){return new cD.InstrumentationNodeModuleDefinition("openai",JG6,this._patch.bind(this))}_patch(Z){let J=Z.OpenAI,X=function(...Y){let $=Reflect.construct(J,Y),Q=T0().getClient(),W=Q?.getIntegrationByName(PY)?.options,G=Boolean(Q?.getOptions().sendDefaultPii),{recordInputs:V,recordOutputs:z}=XG6(W,G);return Kb($,{recordInputs:V,recordOutputs:z})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let $=Object.getOwnPropertyDescriptor(J,Y);if($)Object.defineProperty(X,Y,$)}try{Z.OpenAI=X}catch(Y){Object.defineProperty(Z,"OpenAI",{value:X,writable:!0,configurable:!0,enumerable:!0})}return Z}}var Wu=B0(PY,()=>new Ku({})),YG6=(Z={})=>{return{name:PY,options:Z,setupOnce(){Wu()}}},lD=a(YG6);var cz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The launchDarklyIntegration() can only be used in the browser.")});return{name:"LaunchDarkly"}});function lz1(){if(!O7())e0(()=>{console.warn("The buildLaunchDarklyFlagUsedHandler() can only be used in the browser.")});return{name:"sentry-flag-auditor",type:"flag-used",synchronous:!0,method:()=>null}}var pz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The openFeatureIntegration() can only be used in the browser.")});return{name:"OpenFeature"}});class Gu{constructor(){if(!O7())e0(()=>{console.warn("The OpenFeatureIntegrationHook can only be used in the browser.")})}after(){}error(){}}var iz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The statsigIntegration() can only be used in the browser.")});return{name:"Statsig"}});var nz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The unleashIntegration() can only be used in the browser.")});return{name:"Unleash"}});function pD(){return[nj(),ZD(),$D(),WD(),VD(),HD(),qD(),BD(),MD(),jD(),TD(),ID(),vD(),fD(),yD(),QD(),mD(),KD(),dD(),lD(),ND()]}function az1(){return[Pg,xg,hg,sm,ig,pg,CD,Zm,lm,Jm,Km,Vm,qm,Om,vm,CD,eg,Dm,rm,em,$u,Qu,Wu,Am]}var dG=r(Y0(),1),sz1=r(hb(),1),oz1=r(bb(),1),cG=r(j1(),1);var rz1=r(LR(),1);import $G6 from"module";var Vu=1e6;function iD(Z,J={}){if(Z.getOptions().debug)wg();let X=WG6(Z,J);Z.traceProvider=X}function QG6(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!M0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=rz1.createAddHookMessageChannel();$G6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){h.warn("Failed to register ESM hook",X)}}else e0(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function tz1(Z={}){let{debug:J}=Z;if(J)h.enable();if(!C4())QG6();KG6(Z.integrations).forEach((X)=>{if(X(),J)h.log(`[Sentry] Preloaded ${X.id} instrumentation`)})}function KG6(Z){let J=az1();if(!Z)return J;return J.filter((X)=>Z.includes(X.id))}function WG6(Z,J={}){let X=new oz1.BasicTracerProvider({sampler:new Yg(Z),resource:new sz1.Resource({[cG.ATTR_SERVICE_NAME]:"node",[cG.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[cG.ATTR_SERVICE_VERSION]:R1}),forceFlushTimeoutMillis:500,spanProcessors:[new Xg({timeout:GG6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return dG.trace.setGlobalTracerProvider(X),dG.propagation.setGlobalPropagator(new rb),dG.context.setGlobalContextManager(new wU),X}function GG6(Z){if(Z==null)return;if(Z>Vu)return T4&&h.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${Vu}`),Vu;else if(Z<=0||Number.isNaN(Z)){T4&&h.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function zu(){return fj().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(yj(),gj())}function Hu(Z){return[...zu(),...u8(Z)?pD():[]]}function nD(Z={}){return ez1(Z,Hu)}function ez1(Z={},J){nQ(Z,"node");let X=Rg({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if(X&&!Z.skipOpenTelemetrySetup)iD(X,{spanProcessors:Z.openTelemetrySpanProcessors}),PU();return X}function ZH1(Z={}){return ez1(Z,()=>[])}var NK;((B)=>{B.BUILD_PACKETS="build_packets";B.ENTITIES_EMIT_UPDATES="entities_emit_updates";B.ENTITIES_TICK="entities_tick";B.NETWORK_SYNCHRONIZE="network_synchronize";B.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";B.PHYSICS_CLEANUP="physics_cleanup";B.PHYSICS_STEP="physics_step";B.SEND_ALL_PACKETS="send_all_packets";B.SEND_PACKETS="send_packets";B.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";B.SERIALIZE_PACKETS="serialize_packets";B.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";B.SIMULATION_STEP="simulation_step";B.TICKER_TICK="ticker_tick";B.WORLD_TICK="world_tick"})(NK||={});class R8{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){nD({dsn:Z,release:LA,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=R8.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let $=X?.start_timestamp,Q=X?.timestamp;if(!$||!Q)return null;if((Q-$)*1000>J)return X.measurements=R8.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(uq())return O4({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return Fu}}var JH1=new e$({useFloat32:hH.ALWAYS}),zG6=5000,XH1={RAW:0,GZIP:1};class Q7 extends O0{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=Z70(),this.onPacket(Q0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(Q0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),O0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(Q7._cachedPacketsSerializedBuffer.size>0)Q7._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!Q0.isValidPacket(X))return c.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=Q7._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return R8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=JH1.pack(Z),$=Y.byteLength>1536,Q=$?VG6(Y,{level:1}):Y,K=$?XH1.GZIP:XH1.RAW;return Y=Buffer.allocUnsafe(Q.length+1),Y[0]=K,Q.copy(Y,1),X?.setAttribute("serializedBytes",Y.byteLength),Q7._cachedPacketsSerializedBuffer.set(Z,Y),Y})}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([Q0.createPacket(Q0.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([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(YZ.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){if(this._ws.readyState!==iO.default.OPEN)return;try{this._ws.close()}catch(Z){c.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!==iO.default.OPEN)return;if(!J&&this._ws.bufferedAmount>4096)return;R8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=Q7.serializePackets(Z);if(!Y)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&Y.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send(Y)}catch{this._ws.send(Y)}else this._ws.send(Y);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch(Y){c.error(`Connection.send(): Packet send failed. Error: ${Y}`)}})}_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,Y=J.d;if(X){let{i:$,d:Q}=X,K=!1;if($==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if($==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([Q0.createPacket(Q0.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){c.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()},zG6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await YZ.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:Y}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=Y,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),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 $=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push($,Q),this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:$.id,pi:$.dataProducerId,l:"scr",s:$.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=JH1.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return c.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!Q0.isValidPacket(J))return c.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class tU{_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 U6{_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,Y)=>{Z.call(J,X,Y,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 YH1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(YH1||={});var qu;((H)=>{H.DESPAWN="LIGHT.DESPAWN";H.SET_ANGLE="LIGHT.SET_ANGLE";H.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";H.SET_COLOR="LIGHT.SET_COLOR";H.SET_DISTANCE="LIGHT.SET_DISTANCE";H.SET_INTENSITY="LIGHT.SET_INTENSITY";H.SET_OFFSET="LIGHT.SET_OFFSET";H.SET_PENUMBRA="LIGHT.SET_PENUMBRA";H.SET_POSITION="LIGHT.SET_POSITION";H.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";H.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";H.SPAWN="LIGHT.SPAWN"})(qu||={});class Uu extends O0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)c.fatalError("Either attachedToEntity or position must be set, but not both.");super();c.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 c.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 c.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 c.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 k0.serializeLight(this)}}var Bu;((u)=>{u.BURST="PARTICLE_EMITTER.BURST";u.DESPAWN="PARTICLE_EMITTER.DESPAWN";u.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";u.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";u.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";u.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";u.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";u.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";u.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";u.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";u.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";u.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";u.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";u.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";u.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";u.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";u.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";u.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";u.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";u.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";u.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";u.SET_RATE="PARTICLE_EMITTER.SET_RATE";u.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";u.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";u.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";u.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";u.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";u.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";u.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";u.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";u.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";u.SPAWN="PARTICLE_EMITTER.SPAWN"})(Bu||={});class Lu extends O0{_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)c.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)c.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 c.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 c.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 k0.serializeParticleEmitter(this)}}var eU=r(_V(),1);var HG6={x:0,y:-32,z:0},wu=60,Ou;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Ou||={});class Z2 extends O0{_colliderMap=new NH;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=wu,X=HG6){super();this._rapierEventQueue=new eU.default.EventQueue(!0),this._rapierSimulation=new eU.default.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=eU.default.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,(Y,$)=>{if(Y.numContacts()===0)return;let Q=Y.normal(),K=[];for(let W=0;W<Y.numSolverContacts();W++)K.push(Y.solverContactPoint(W));X.push({contactPoints:K,localNormalA:!$?Y.localNormal1():Y.localNormal2(),localNormalB:!$?Y.localNormal2():Y.localNormal1(),normal:!$?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,Y={}){let $=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(K)=>{let W=this._colliderMap.getColliderHandleBlockType(K.handle);if(W&&!$.has(W))return $.add(W),Q.push({intersectedBlockType:W}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!$.has(G))return $.add(G),Q.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),Q}raycast(Z,J,X,Y={}){let $=new eU.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.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 K=$.pointAt(Q.timeOfImpact),W=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:IK.fromGlobalCoordinate({x:Math.floor(K.x-($.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-($.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-($.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:W};let z=this._colliderMap.getColliderHandleEntity(G.handle);if(z)return{hitEntity:z,hitPoint:K,hitDistance:W};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(R8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),R8.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=(K,W)=>{if(K instanceof q9&&W instanceof a8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof a8&&W instanceof q9&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof a8&&W instanceof a8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof a8||W instanceof q9))K(W,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 Y={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},$=(Q,K)=>{if(Q instanceof q9&&K instanceof a8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:Y});else if(Q instanceof a8&&K instanceof q9&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:Y});else if(Q instanceof a8&&K instanceof a8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:Y})};$(J,X),$(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),Y=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,Y]}}class aD{_synchronizedPlayerReliablePackets=new U6;_queuedBroadcasts=[];_queuedAudioSynchronizations=new U6;_queuedBlockSynchronizations=new U6;_queuedBlockTypeSynchronizations=new U6;_queuedChunkSynchronizations=new U6;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new U6;_queuedLightSynchronizations=new U6;_queuedParticleEmitterSynchronizations=new U6;_queuedPerPlayerSynchronizations=new U6;_queuedPerPlayerCameraSynchronizations=new U6;_queuedPerPlayerUISynchronizations=new U6;_queuedPerPlayerUIDatasSynchronizations=new U6;_queuedPlayerSynchronizations=new U6;_queuedSceneUISynchronizations=new U6;_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(Y,Z).push(...$);if(this._queuedEntitySynchronizations.size>0){let Y=[],$=[];for(let Q of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let W in Q)if(W!=="i"&&W!=="p"&&W!=="r"){K=!0;break}if(K)Y.push(Q);else $.push(Q)}if($.length>0){let Q=Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,$,X);J.push(Q)}if(Y.length>0){let Q=Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,Y,X);Z.push(Q);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(Q)}}if(this._queuedAudioSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUISynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.uiPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUIDatasSynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.uiDatasPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedSceneUISynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedWorldSynchronization){let Y=Q0.createPacket(Q0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerCameraSynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.cameraPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPlayerSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=Q0.createPacket(Q0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}R8.startSpan({operation:"send_all_packets"},()=>{for(let Y of N9.instance.getConnectedPlayersByWorld(this._world)){let $=this._synchronizedPlayerReliablePackets.get(Y)??Z;if($.length>0)Y.connection.send($);if(J.length>0)Y.connection.send(J,!1)}}),R8.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();Q7.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?k0.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:Y}=Z;this._queuedBroadcasts.push(Q0.createPacket(Q0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:Y}=Z,$=this._queuedPerPlayerSynchronizations.get(J)??[];$.push(Q0.createPacket(Q0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,$)};_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?k0.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=k0.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?k0.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?k0.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?k0.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?k0.serializeRgbColor(Z.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?k0.serializeRgbColor(Z.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?k0.serializeRgbColor(Z.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?k0.serializeRgbColor(Z.colorStartVariance):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?k0.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?k0.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?k0.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?k0.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?k0.serializeVector(Z.velocity):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?k0.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=k0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?k0.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?k0.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?k0.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?k0.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(Q0.createPacket(Q0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map(($)=>{if(J.camera.attachedToEntity===void 0&&$ instanceof i7&&$.player===J)J.camera.setAttachedToEntity($);return $.serialize()}),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.playersPacketDefinition,N9.instance.getConnectedPlayers().map(($)=>$.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...Y}),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([Q0.createPacket(Q0.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?k0.serializeVector(Z.offset):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?k0.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(k0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(Q0.createPacket(Q0.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=k0.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=k0.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=k0.serializeVector(Z.position)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=k0.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)c.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:Y}=Z,$=`${J},${X},${Y}`,Q=this._queuedBlockSynchronizations.get($);if(!Q)Q={i:0,c:[J,X,Y]},this._queuedBlockSynchronizations.set($,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)c.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate,$=`${J},${X},${Y}`,Q=this._queuedChunkSynchronizations.get($);if(!Q)Q={c:[J,X,Y]},this._queuedChunkSynchronizations.set($,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)c.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)c.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)c.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)c.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)c.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)c.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 J2{_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 X2{_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 FG6=2,qG6=3;class Y2{_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*qG6,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)R8.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<FG6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});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 c.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var $H1;((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"})($H1||={});class $2 extends O0{_currentTick=0;_ticker;_world;constructor(Z,J=wu){super();this._ticker=new Y2(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();R8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:N9.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}},()=>{R8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),R8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),R8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),R8.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)=>{c.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var Mu;((F)=>{F.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";F.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";F.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";F.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";F.SET_FOG_FAR="WORLD.SET_FOG_FAR";F.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";F.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";F.START="WORLD.START";F.STOP="WORLD.STOP"})(Mu||={});class Q2 extends O0{_id;_ambientLightColor;_ambientLightIntensity;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_fogColor;_fogFar;_fogNear;_name;_skyboxIntensity;_skyboxUri;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_entityManager;_lightManager;_loop;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_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 aG(this),this._blockTypeRegistry=new dz(this),this._chatManager=new OH(this),this._chunkLattice=new MH(this),this._entityManager=new DH(this),this._lightManager=new tU(this),this._loop=new $2(this,Z.tickRate),this._networkSynchronizer=new aD(this),this._particleEmitterManager=new J2(this),this._sceneUIManager=new X2(this),this._simulation=new Z2(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 directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get name(){return this._name}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get entityManager(){return this._entityManager}get lightManager(){return this._lightManager}get loop(){return this._loop}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,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 a8({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 k0.serializeWorld(this)}}var QH1;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(QH1||={});class K${static instance=new K$;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new Q2({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),O0.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 KH1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(KH1||={});class N9{static instance=new N9;worldSelectionHandler;_connectionPlayers=new Map;constructor(){O0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),O0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),O0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),O0.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 uW(Z,J);await X.loadInitialPersistedData(),this._connectionPlayers.set(Z,X),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??K$.instance.getDefaultWorld())}_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(),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else c.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),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else c.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var GH1;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(GH1||={});function UG6(Z){WH1.default.init().then(()=>{return RK.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(RK.instance.worldManager.getDefaultWorld());else Z();RK.instance.start()}).catch((J)=>{c.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class RK{static _instance;_modelRegistry=g5.instance;_playerManager=N9.instance;_socket=YZ.instance;_worldManager=K$.instance;_webServer=I3.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new RK;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(){O0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var B6=r(PK(),1);class CK extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return B6.mat2.determinant(this)}get frobeniusNorm(){return B6.mat2.frob(this)}static create(){let Z=new CK(0,0,0,0);return B6.mat2.identity(Z),Z}static fromRotation(Z){let J=CK.create();return B6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=CK.create();return B6.mat2.fromScaling(J,Z),J}add(Z){return B6.mat2.add(this,this,Z),this}adjoint(){return B6.mat2.adjoint(this,this),this}clone(){return new CK(this[0],this[1],this[2],this[3])}copy(Z){return B6.mat2.copy(this,Z),this}equals(Z){return B6.mat2.equals(this,Z)}exactEquals(Z){return B6.mat2.exactEquals(this,Z)}identity(){return B6.mat2.identity(this),this}invert(){return B6.mat2.invert(this,this),this}multiply(Z){return B6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return B6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return B6.mat2.rotate(this,this,Z),this}subtract(Z){return B6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return B6.mat2.transpose(this,this),this}}var j8=r(PK(),1);class kZ extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G){super([Z,J,X,Y,$,Q,K,W,G])}get determinant(){return j8.mat3.determinant(this)}get frobeniusNorm(){return j8.mat3.frob(this)}static create(){let Z=new kZ(0,0,0,0,0,0,0,0,0);return j8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=kZ.create();return j8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=kZ.create();return j8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=kZ.create();return j8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=kZ.create();return j8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=kZ.create();return j8.mat3.fromTranslation(J,Z),J}add(Z){return j8.mat3.add(this,this,Z),this}adjoint(){return j8.mat3.adjoint(this,this),this}clone(){return new kZ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return j8.mat3.copy(this,Z),this}equals(Z){return j8.mat3.equals(this,Z)}exactEquals(Z){return j8.mat3.exactEquals(this,Z)}identity(){return j8.mat3.identity(this),this}invert(){return j8.mat3.invert(this,this),this}multiply(Z){return j8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return j8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return j8.mat3.projection(this,Z,J),this}rotate(Z){return j8.mat3.rotate(this,this,Z),this}subtract(Z){return j8.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 j8.mat3.transpose(this,this),this}}var $1=r(PK(),1);class v5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G,V,z,F,H,q,U,B){super([Z,J,X,Y,$,Q,K,W,G,V,z,F,H,q,U,B])}get determinant(){return $1.mat4.determinant(this)}get frobeniusNorm(){return $1.mat4.frob(this)}static create(){let Z=new v5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return $1.mat4.identity(Z),Z}static fromQuaternion(Z){let J=v5.create();return $1.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=v5.create();return $1.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=v5.create();return $1.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=v5.create();return $1.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=v5.create();return $1.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=v5.create();return $1.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=v5.create();return $1.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=v5.create();return $1.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=v5.create();return $1.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=v5.create();return $1.mat4.fromZRotation(J,Z),J}add(Z){return $1.mat4.add(this,this,Z),this}adjoint(){return $1.mat4.adjoint(this,this),this}clone(){return new v5(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 $1.mat4.copy(this,Z),this}equals(Z){return $1.mat4.equals(this,Z)}exactEquals(Z){return $1.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return $1.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return $1.mat4.identity(this),this}invert(){return $1.mat4.invert(this,this),this}lookAt(Z,J,X){return $1.mat4.lookAt(this,Z,J,X),this}multiply(Z){return $1.mat4.mul(this,this,Z),this}multiplyScalar(Z){return $1.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return $1.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return $1.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return $1.mat4.rotate(this,this,Z,J),this}rotateX(Z){return $1.mat4.rotateX(this,this,Z),this}rotateY(Z){return $1.mat4.rotateY(this,this,Z),this}rotateZ(Z){return $1.mat4.rotateZ(this,this,Z),this}scale(Z){return $1.mat4.scale(this,this,Z),this}subtract(Z){return $1.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return $1.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 $1.mat4.translate(this,this,Z),this}transpose(){return $1.mat4.transpose(this,this),this}}var b1=r(PK(),1);class lG extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return b1.quat.length(this)}get squaredLength(){return b1.quat.squaredLength(this)}get magnitude(){return b1.quat.length(this)}get squaredMagnitude(){return b1.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 Y=b1.quat.fromEuler(new Float32Array(4),Z,J,X);return new lG(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new lG(Z.x,Z.y,Z.z,Z.w)}clone(){return new lG(this.x,this.y,this.z,this.w)}conjugate(){return b1.quat.conjugate(this,this),this}copy(Z){return b1.quat.copy(this,Z),this}dot(Z){return b1.quat.dot(this,Z)}exponential(){return b1.quat.exp(this,this),this}equals(Z){return b1.quat.equals(this,Z)}exactEquals(Z){return b1.quat.exactEquals(this,Z)}getAngle(Z){return b1.quat.getAngle(this,Z)}identity(){return b1.quat.identity(this),this}invert(){return b1.quat.invert(this,this),this}lerp(Z,J){return b1.quat.lerp(this,this,Z,J),this}logarithm(){return b1.quat.ln(this,this),this}multiply(Z){return b1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return b1.quat.normalize(this,this),this}power(Z){return b1.quat.pow(this,this,Z),this}randomize(){return b1.quat.random(this),this}rotateX(Z){return b1.quat.rotateX(this,this,Z),this}rotateY(Z){return b1.quat.rotateY(this,this,Z),this}rotateZ(Z){return b1.quat.rotateZ(this,this,Z),this}scale(Z){return b1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return b1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return b1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var U1=r(PK(),1);class K2 extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return U1.vec2.length(this)}get squaredLength(){return U1.vec2.squaredLength(this)}get magnitude(){return U1.vec2.length(this)}get squaredMagnitude(){return U1.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 K2(0,0)}add(Z){return U1.vec2.add(this,this,Z),this}angle(Z){return U1.vec2.angle(this,Z)}ceil(){return U1.vec2.ceil(this,this),this}clone(){return new K2(this.x,this.y)}copy(Z){return U1.vec2.copy(this,Z),this}distance(Z){return U1.vec2.distance(this,Z)}divide(Z){return U1.vec2.divide(this,this,Z),this}dot(Z){return U1.vec2.dot(this,Z)}equals(Z){return U1.vec2.equals(this,Z)}exactEquals(Z){return U1.vec2.exactEquals(this,Z)}floor(){return U1.vec2.floor(this,this),this}invert(){return U1.vec2.inverse(this,this),this}lerp(Z,J){return U1.vec2.lerp(this,this,Z,J),this}max(Z){return U1.vec2.max(this,this,Z),this}min(Z){return U1.vec2.min(this,this,Z),this}multiply(Z){return U1.vec2.mul(this,this,Z),this}negate(){return U1.vec2.negate(this,this),this}normalize(){return U1.vec2.normalize(this,this),this}randomize(Z){return U1.vec2.random(this,Z),this}rotate(Z,J){return U1.vec2.rotate(this,this,Z,J),this}round(){return U1.vec2.round(this,this),this}scale(Z){return U1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return U1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return U1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return U1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return U1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return U1.vec2.transformMat4(this,this,Z),this}zero(){return U1.vec2.zero(this),this}}var H1=r(PK(),1);class pG extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return H1.vec3.length(this)}get squaredLength(){return H1.vec3.squaredLength(this)}get magnitude(){return H1.vec3.length(this)}get squaredMagnitude(){return H1.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 pG(0,0,0)}static fromVector3Like(Z){return new pG(Z.x,Z.y,Z.z)}add(Z){return H1.vec3.add(this,this,Z),this}ceil(){return H1.vec3.ceil(this,this),this}clone(){return new pG(this.x,this.y,this.z)}copy(Z){return H1.vec3.copy(this,Z),this}cross(Z){return H1.vec3.cross(this,this,Z),this}distance(Z){return H1.vec3.distance(this,Z)}divide(Z){return H1.vec3.div(this,this,Z),this}dot(Z){return H1.vec3.dot(this,Z)}equals(Z){return H1.vec3.equals(this,Z)}exactEquals(Z){return H1.vec3.exactEquals(this,Z)}floor(){return H1.vec3.floor(this,this),this}invert(){return H1.vec3.inverse(this,this),this}lerp(Z,J){return H1.vec3.lerp(this,this,Z,J),this}max(Z){return H1.vec3.max(this,this,Z),this}min(Z){return H1.vec3.min(this,this,Z),this}multiply(Z){return H1.vec3.mul(this,this,Z),this}negate(){return H1.vec3.negate(this,this),this}normalize(){return H1.vec3.normalize(this,this),this}randomize(Z){return H1.vec3.random(this,Z),this}rotateX(Z,J){return H1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return H1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return H1.vec3.rotateZ(this,this,Z,J),this}round(){return H1.vec3.round(this,this),this}scale(Z){return H1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return H1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return H1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return H1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return H1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return H1.vec3.transformQuat(this,this,Z),this}zero(){return H1.vec3.zero(this),this}}var oF1=r(aF1(),1);var sF1=0.099856;class W2 extends V${faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=sF1;_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:sF1,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,Y=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let $=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*$*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let $={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-Y.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-Y.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-Y.z},Q=$.x*$.x+$.y*$.y+$.z*$.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let W=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(W*W+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let W=Math.sqrt(Q),G=this.moveSpeed*X,z=Math.min(W,G)/W,F={x:Y.x+$.x*z,y:Y.y+$.y*z,z:Y.z+$.z*z};if(Z.setPosition(F),this._onMove)this._onMove(F,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 W=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,W(Y)}}}if(this._faceTarget){let $={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},Q=Math.atan2(-$.x,-$.z),K=Z.rotation,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;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,z=Math.abs(G)<V?G:Math.sign(G)*V,H=(W+z)/2,q={x:0,y:Math.fround(Math.sin(H)),z:0,w:Math.fround(Math.cos(H))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}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 Eu extends W2{_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 c.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)c.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)},Y=Math.abs(X.x-J.x),$=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if(Y<=2&&$<=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 W=this._coordinateToKey(J),G=new Map,V=new Map([[W,0]]),z=new Map([[W,this._pathfindingHeuristic(J,X)]]),F=new Set,H=new oF1.Heap((N,R)=>{let P=z.get(N[0])??1/0,D=z.get(R[0])??1/0;return P-D});H.push([W,J]);let q=[{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 N=this._maxJump;N>=this._maxFall;N--){if(N===0)continue;let R=Math.abs(J.y+N-X.y);U.push({y:N,distanceToTargetY:R})}U.sort((N,R)=>N.distanceToTargetY-R.distanceToTargetY);let B=[...q,...U.flatMap(({y:N})=>q.map((R)=>({...R,y:N})))],L=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),M=Math.min(this._maxOpenSetIterations,w*20);while(!H.isEmpty()&&L<M){L++;let[N,R]=H.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let C=this._reconstructPath(G,R);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 ${L} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}F.add(N);let P=V.get(N),D=new Map;for(let C of B){let T=`${C.x},${C.z}`,k=C.y<0;if(k&&D.has(T))continue;let A={x:R.x+C.x,y:R.y+C.y,z:R.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(F.has(x))continue;let I=this._isNeighborCoordinateBlocked(R,A,this._entity.height);if(k&&I){D.set(T,!0);continue}if(I)continue;let _=Math.abs(C.x),b=Math.abs(C.y),u=Math.abs(C.z),i=b===0?0:this._verticalPenalty,e=(Math.max(_,b,u)===1&&_+b+u>1?1.4:1)+i,Z0=P+e,K0=V.get(x)??1/0;if(Z0>=K0)continue;G.set(x,R),V.set(x,Z0);let S0=Z0+this._pathfindingHeuristic(A,X);z.set(x,S0),H.push([x,A])}}if(L>=M){if(this._onPathfindAbort?.(),this._debug)c.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${M}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)c.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],Y=J;while(Z.has(this._coordinateToKey(Y)))Y=Z.get(this._coordinateToKey(Y)),X.unshift(Y);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 Y=J.y-Z.y,$=Math.min(Y,this._maxJump)+0.75;this.jump($);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*$),W=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,z=J.z+0.5,F=V-W,H=z-G,q=Math.sqrt(F*F+H*H),U=K/Q,B=q/this._speed;X=Math.min(U*0.8,B)*1000}setTimeout(()=>{if(!this._entity)return;let Y=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()-Y>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 Y=this._entity.world,$=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:$,y:Q+V,z:K}))return!0;if($!==W&&K!==G)for(let V=0;V<X;V++){let z=Y.chunkLattice.hasBlock({x:$,y:Q+V,z:G}),F=Y.chunkLattice.hasBlock({x:W,y:Q+V,z:K});if(z||F)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,Y={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let $=0;$<=Math.abs(this._maxFall);$++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-$-1}))return{...Y,y:Y.y-$};return}}export{UG6 as startServer,QH1 as WorldManagerEvent,K$ as WorldManager,$H1 as WorldLoopEvent,$2 as WorldLoop,Mu as WorldEvent,Q2 as World,wA as WebServerEvent,I3 as WebServer,pG as Vector3,K2 as Vector2,Y2 as Ticker,NK as TelemetrySpanOperation,R8 as Telemetry,Ou as SimulationEvent,Z2 as Simulation,W2 as SimpleEntityController,X2 as SceneUIManager,R_ as SceneUIEvent,jH as SceneUI,d50 as SUPPORTED_INPUT_KEYS,mz as RigidBodyType,f$ as RigidBody,lG as Quaternion,AO as PlayerUIEvent,LH as PlayerUI,KH1 as PlayerManagerEvent,N9 as PlayerManager,wH as PlayerEvent,i7 as PlayerEntity,u50 as PlayerCameraMode,w_ as PlayerCameraEvent,BH as PlayerCamera,uW as Player,l$ as PersistenceManager,Eu as PathfindingEntityController,J2 as ParticleEmitterManager,Bu as ParticleEmitterEvent,Lu as ParticleEmitter,BA as PORT,n50 as PLAYER_ROTATION_UPDATE_THRESHOLD,i50 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,g5 as ModelRegistry,v5 as Matrix4,kZ as Matrix3,CK as Matrix2,YH1 as LightType,tU as LightManager,qu as LightEvent,Uu as Light,U6 as IterationMap,GH1 as GameServerEvent,RK as GameServer,O0 as EventRouter,c as ErrorHandler,DH as EntityManager,RH as EntityEvent,a8 as Entity,p50 as ENTITY_ROTATION_UPDATE_THRESHOLD,l50 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,m1 as DefaultPlayerEntityController,j_ as DefaultPlayerEntity,c50 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,g4 as CollisionGroupsBuilder,B$ as CollisionGroup,uz as ColliderShape,NH as ColliderMap,F9 as Collider,fE as CoefficientCombineRule,N_ as ChunkLatticeEvent,MH as ChunkLattice,B9 as Chunk,OH as ChatManager,O_ as ChatEvent,bE as BlockTypeRegistryEvent,dz as BlockTypeRegistry,yE as BlockTypeEvent,q9 as BlockType,IK as Block,hu as BaseEntityControllerEvent,V$ as BaseEntityController,aG as AudioManager,HP as AudioEvent,nG as Audio};