@genex-ai/multiplayer 0.17.8 → 0.17.9
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/PROTOCOL.md +2 -2
- package/dist/authority/fast-webtransport.js +2 -2
- package/dist/authority/index.js +4 -4
- package/dist/bridge-authority.global.js +9 -9
- package/dist/bridge-authority.js +4 -4
- package/dist/bridge.js +3 -3
- package/dist/{chunk-QY3QQNDJ.js → chunk-DJ2XYETS.js} +2 -2
- package/dist/{chunk-QZOCUQJT.js → chunk-MQYARUGU.js} +47 -5
- package/dist/{chunk-FPWP22Y7.js → chunk-TEHGMFAG.js} +1 -1
- package/dist/{chunk-CSQEEANB.js → chunk-WEMRRIHH.js} +3 -1
- package/dist/{chunk-NFMGIKFZ.js → chunk-ZDGSUR6E.js} +1 -1
- package/dist/index.js +3 -3
- package/dist/protocol.d.ts +5 -2
- package/dist/protocol.js +3 -1
- package/package.json +1 -1
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
"use strict";(()=>{var eE=Object.create;var cu=Object.defineProperty;var tE=Object.getOwnPropertyDescriptor;var nE=Object.getOwnPropertyNames;var rE=Object.getPrototypeOf,sE=Object.prototype.hasOwnProperty;var zm=t=>{throw TypeError(t)};var oE=(t,e,n)=>e in t?cu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var pt=(t,e)=>()=>(t&&(e=t(t=0)),e);var iE=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),sf=(t,e)=>{for(var n in e)cu(t,n,{get:e[n],enumerable:!0})},aE=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of nE(e))!sE.call(t,s)&&s!==n&&cu(t,s,{get:()=>e[s],enumerable:!(r=tE(e,s))||r.enumerable});return t};var cE=(t,e,n)=>(n=t!=null?eE(rE(t)):{},aE(e||!t||!t.__esModule?cu(n,"default",{value:t,enumerable:!0}):n,t));var m=(t,e,n)=>oE(t,typeof e!="symbol"?e+"":e,n),of=(t,e,n)=>e.has(t)||zm("Cannot "+n);var le=(t,e,n)=>(of(t,e,"read from private field"),n?n.call(t):e.get(t)),Ve=(t,e,n)=>e.has(t)?zm("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),He=(t,e,n,r)=>(of(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),zs=(t,e,n)=>(of(t,e,"access private method"),n);var Ke,Zo,Vf,Cu,Ou,$s,wt,qy=pt(()=>{"use strict";Ke={JOIN_ROOM:10,ERROR:11,LEAVE_ROOM:12,ROOM_DATA:13,ROOM_STATE:14,ROOM_STATE_PATCH:15,ROOM_DATA_SCHEMA:16,ROOM_DATA_BYTES:17,PING:18,ROOM_INPUT_RELIABLE:19,ROOM_INPUT_UNRELIABLE:20,ROOM_REQUEST:21,ROOM_RESPONSE:22},Zo={TIMED:128,UNRELIABLE:64},Vf=31,Cu={OK:0,REJECTED:1,ERROR:2},Ou={INPUT_REFLECTION:1,INPUT_OPTIONS:2},$s={RENDER_TIME:1,FIXED_TIMESTEP:2,PATCH_RATE:4,SUB_STEPS:8,RECKON_TIME:16},wt={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,CONSENTED:4e3,SERVER_SHUTDOWN:4001,WITH_ERROR:4002,FAILED_TO_RECONNECT:4003,MAY_TRY_RECONNECT:4010}});var Ar=pt(()=>{"use strict";qy()});function Bg(t){Object.defineProperty(t,Symbol.metadata,{value:void 0,writable:!0,configurable:!0,enumerable:!1})}function Ug(t,e,n){for(var r=0,s=0,o=e.length;s<o;s++)r=e.charCodeAt(s),r<128?t[n.offset++]=r:r<2048?(t[n.offset]=192|r>>6,t[n.offset+1]=128|r&63,n.offset+=2):r<55296||r>=57344?(t[n.offset]=224|r>>12,t[n.offset+1]=128|r>>6&63,t[n.offset+2]=128|r&63,n.offset+=3):(s++,r=65536+((r&1023)<<10|e.charCodeAt(s)&1023),t[n.offset]=240|r>>18,t[n.offset+1]=128|r>>12&63,t[n.offset+2]=128|r>>6&63,t[n.offset+3]=128|r&63,n.offset+=4)}function Vg(t,e,n){t[n.offset++]=e&255}function qk(t,e,n){t[n.offset++]=e&255}function Hg(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function Qf(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function Mr(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255,t[n.offset++]=e>>16&255,t[n.offset++]=e>>24&255}function qs(t,e,n){let r=e>>24,s=e>>16,o=e>>8,i=e;t[n.offset++]=i&255,t[n.offset++]=o&255,t[n.offset++]=s&255,t[n.offset++]=r&255}function $g(t,e,n){let r=Math.floor(e/Math.pow(2,32)),s=e>>>0;qs(t,s,n),qs(t,r,n)}function jg(t,e,n){let r=e/Math.pow(2,32)>>0,s=e>>>0;qs(t,s,n),qs(t,r,n)}function Gk(t,e,n){Fg[0]=BigInt.asIntN(64,e),Mr(t,Ws[0],n),Mr(t,Ws[1],n)}function Yk(t,e,n){Fg[0]=BigInt.asIntN(64,e),Mr(t,Ws[0],n),Mr(t,Ws[1],n)}function Wg(t,e,n){qf[0]=e,Mr(t,Ws[0],n)}function qg(t,e,n){jk[0]=e,Mr(t,Ws[0],n),Mr(t,Ws[1],n)}function Kk(t,e,n){t[n.offset++]=e?1:0}function Xk(t,e,n){e||(e="");let r=zg(e,"utf8"),s=0;if(r<32)t[n.offset++]=r|160,s=1;else if(r<256)t[n.offset++]=217,t[n.offset++]=r,s=2;else if(r<65536)t[n.offset++]=218,Qf(t,r,n),s=3;else if(r<4294967296)t[n.offset++]=219,qs(t,r,n),s=5;else throw new Error("String too long");return Ug(t,e,n),s+r}function Gf(t,e,n){if(isNaN(e))return Gf(t,0,n);if(isFinite(e)){if(e!==(e|0))return Math.abs(e)<=34028235e31&&(qf[0]=e,Math.abs(Math.abs(qf[0])-Math.abs(e))<1e-4)?(t[n.offset++]=202,Wg(t,e,n),5):(t[n.offset++]=203,qg(t,e,n),9)}else return Gf(t,e>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER,n);return e>=0?e<128?(t[n.offset++]=e&255,1):e<256?(t[n.offset++]=204,t[n.offset++]=e&255,2):e<65536?(t[n.offset++]=205,Qf(t,e,n),3):e<4294967296?(t[n.offset++]=206,qs(t,e,n),5):(t[n.offset++]=207,jg(t,e,n),9):e>=-32?(t[n.offset++]=224|e+32,1):e>=-128?(t[n.offset++]=208,Vg(t,e,n),2):e>=-32768?(t[n.offset++]=209,Hg(t,e,n),3):e>=-2147483648?(t[n.offset++]=210,Mr(t,e,n),5):(t[n.offset++]=211,$g(t,e,n),9)}function Gg(t,e,n){n>t.length-e.offset&&(n=t.length-e.offset);for(var r="",s=0,o=e.offset,i=e.offset+n;o<i;o++){var a=t[o];if((a&128)===0){r+=String.fromCharCode(a);continue}if((a&224)===192){r+=String.fromCharCode((a&31)<<6|t[++o]&63);continue}if((a&240)===224){r+=String.fromCharCode((a&15)<<12|(t[++o]&63)<<6|(t[++o]&63)<<0);continue}if((a&248)===240){s=(a&7)<<18|(t[++o]&63)<<12|(t[++o]&63)<<6|(t[++o]&63)<<0,s>=65536?(s-=65536,r+=String.fromCharCode((s>>>10)+55296,(s&1023)+56320)):r+=String.fromCharCode(s);continue}console.error("decode.utf8Read(): Invalid byte "+a+" at offset "+o+". Skip to end of string: "+(e.offset+n));break}return e.offset+=n,r}function Yg(t,e){return Ma(t,e)<<24>>24}function Ma(t,e){return t[e.offset++]}function Kg(t,e){return Xu(t,e)<<16>>16}function Xu(t,e){return t[e.offset++]|t[e.offset++]<<8}function Bn(t,e){return t[e.offset++]|t[e.offset++]<<8|t[e.offset++]<<16|t[e.offset++]<<24}function ti(t,e){return Bn(t,e)>>>0}function Xg(t,e){return Gs[0]=Bn(t,e),Jk[0]}function Jg(t,e){return Gs[0]=Bn(t,e),Gs[1]=Bn(t,e),Zk[0]}function Zg(t,e){let n=ti(t,e);return Bn(t,e)*Math.pow(2,32)+n}function Qg(t,e){let n=ti(t,e);return ti(t,e)*Math.pow(2,32)+n}function tA(t,e){return Gs[0]=Bn(t,e),Gs[1]=Bn(t,e),eA[0]}function nA(t,e){return Gs[0]=Bn(t,e),Gs[1]=Bn(t,e),Qk[0]}function rA(t,e){return Ma(t,e)>0}function sA(t,e){let n=t[e.offset++],r;return n<192?r=n&31:n===217?r=Ma(t,e):n===218?r=Xu(t,e):n===219&&(r=ti(t,e)),Gg(t,e,r)}function oA(t,e){let n=t[e.offset++];if(n<128)return n;if(n===202)return Xg(t,e);if(n===203)return Jg(t,e);if(n===204)return Ma(t,e);if(n===205)return Xu(t,e);if(n===206)return ti(t,e);if(n===207)return Qg(t,e);if(n===208)return Yg(t,e);if(n===209)return Kg(t,e);if(n===210)return Bn(t,e);if(n===211)return Zg(t,e);if(n>223)return(255-n+1)*-1}function iA(t,e){let n=t[e.offset];return n<192&&n>160||n===217||n===218||n===219}function Or(t,e){e.constructor&&(Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor[Symbol.metadata]==null&&Bg(e.constructor),aA.set(e.constructor,t),ep[t]=e),e.encode&&(Se[t]=e.encode),e.decode&&(Ae[t]=e.decode)}function eb(t){return ep[t]}function Cr(){return{pendingByView:new Map,sentByView:new Map,broadcastPending:new Set,sentBroadcast:new Set,broadcastDeletes:new Set,maxPerTick:32}}function tp(t){return t._stream??(t._stream=Cr())}function Ju(t,e,n){e.activeViews.size===0&&tp(t).broadcastPending.add(n)}function Zu(t,e,n,r){let s=t._stream;if(s===void 0)return!0;let o=!1;return s.broadcastPending.delete(r)?o=!0:s.sentBroadcast.delete(r)&&s.broadcastDeletes.add(r),e.forEachActiveView(i=>{let a=s.pendingByView.get(i.id);if(a?.has(r)){a.delete(r),o=!0;return}let c=s.sentByView.get(i.id);if(c?.has(r)){c.delete(r);let u=i.changes.get(n);u===void 0&&(u=new Map,i.changes.set(n,u)),u.set(r,N.DELETE)}}),o}function cA(t,e,n){let r=t._stream;if(r!==void 0){r.broadcastPending.clear();for(let s of r.sentBroadcast)r.broadcastDeletes.add(s);r.sentBroadcast.clear(),e.forEachActiveView(s=>{r.pendingByView.get(s.id)?.clear();let o=r.sentByView.get(s.id);if(o!==void 0&&o.size>0){let i=s.changes.get(n);i===void 0&&(i=new Map,s.changes.set(n,i));for(let a of o)i.set(a,N.DELETE);o.clear()}})}}function uA(t,e){let n=t._stream?.pendingByView;if(n===void 0)return!1;for(let[r,s]of n)if(s.size>0&&e.activeViews.get(r)?.deref()!==void 0)return!0;return!1}function lA(t){let e=t._stream;return e!==void 0&&(e.broadcastPending.size>0||e.broadcastDeletes.size>0)}function dA(t,e,n){let r=tp(t),s=r.pendingByView.get(e);s===void 0&&(s=new Set,r.pendingByView.set(e,s)),s.add(n)}function Qu(t,e){let n=t._stream;n!==void 0&&(n.pendingByView.delete(e),n.sentByView.delete(e),n.priorityByView?.delete(e))}function np(t){if(t==null||typeof t!="object")throw new Error("t.quantized(): options object with { min, max } is required.");let{min:e,max:n}=t;if(typeof e!="number"||typeof n!="number"||!(n>e)||!Number.isFinite(e)||!Number.isFinite(n))throw new Error(`t.quantized(): require finite min < max (got min=${e}, max=${n}).`);let r=t.bits??16;if(r!==8&&r!==16&&r!==32)throw new Error(`t.quantized(): bits must be 8, 16 or 32 (got ${r}).`);let s=t.mode??"clamp";if(s!=="clamp"&&s!=="wrap")throw new Error(`t.quantized(): mode must be "clamp" or "wrap" (got ${JSON.stringify(s)}).`);let o=s==="wrap",i=Math.pow(2,r);return{min:e,max:n,bits:r,wrap:o,wire:fA[r],range:n-e,span:o?i:e===-n?i-2:i-1}}function Ys(t){return t!==null&&typeof t=="object"&&t.quantized!==void 0}function nb(t,e){if(t.wrap){if(!Number.isFinite(e))return 0;let r=t.range,s=(e-t.min)%r;s<0&&(s+=r);let o=t.span;return Math.floor(s/r*o+.5)%o}if(e!==e)return 0;let n=e<t.min?t.min:e>t.max?t.max:e;return Math.floor((n-t.min)/t.range*t.span+.5)}function rb(t,e){return t.min+e/t.span*t.range}function pA(t){let e=Se[t.wire];return(n,r,s)=>e(n,nb(t,r),s)}function hA(t,e,n){let r=Ae[t.wire];return rb(t,r(e,n))}function mA(t){let e=typeof Object.keys(t)[0]=="string"&&eb(Object.keys(t)[0]);return{complexTypeKlass:e,childType:e?Object.values(t)[0]:t}}function ni(t){if(Array.isArray(t))return{array:ni(t[0])};if(Ys(t))return typeof t.quantized.wire=="string"?t:{quantized:np(t.quantized)};if(typeof t.type<"u")return t.type;if(yA(t))return Object.keys(t).every(e=>typeof t[e]=="string")?"string":"number";if(typeof t=="object"&&t!==null){let e=Object.keys(t).find(n=>ep[n]!==void 0);if(e)return t[e]=ni(t[e]),t}return t}function yA(t){if(typeof t=="function"&&t[Symbol.metadata])return!1;let e=Object.keys(t),n=e.filter(r=>/\d+/.test(r));return!!(n.length>0&&n.length===e.length/2&&t[t[n[0]]]==n[0]||e.length>0&&e.every(r=>typeof t[r]=="string"&&t[r]===r))}function Du(t,e,n){t[e]||Object.defineProperty(t,e,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[e].push(n)}function Vu(t){return t=t-(t>>>1&1431655765),t=(t&858993459)+(t>>>2&858993459),(t+(t>>>4)&252645135)*16843009>>>24}function Nu(t){if(t===void 0)return 0;let e=0;for(let n=0,r=t.length;n<r;n++){let s=t[n];s<32&&(e|=1<<s)}return e}function bA(t){let e=[],n=[],r=[],s=[],o=t?.[kt];if(o===void 0)return{names:e,types:n,tags:r,encoders:s};let i=t[Tr];for(let a=0;a<=o;a++){let c=t[a];if(c===void 0){e[a]=void 0,n[a]=void 0,r[a]=void 0,s[a]=void 0;continue}e[a]=c.name,n[a]=c.type,r[a]=c.tag,s[a]=i?.[a]}return{names:e,types:n,tags:r,encoders:s}}function rp(t){let e=t.constructor;if(Object.prototype.hasOwnProperty.call(e,xa))return e[xa];let n=e[Symbol.metadata],r=Ie.isValidInstance(t),s=(n?.[Cn]?.length??0)>0,o=bA(n),i=r&&!s?void 0:e[Xs],a={encoder:e[ir],filter:i,metadata:n,isSchema:r,filterBitmask:r?Nu(n?.[Cn]):0,hasAnyFullStateOnly:(n?.[ei]?.length??0)>0,hasAnyUnreliable:(n?.[js]?.length??0)>0,hasAnyStream:(n?.[cn]?.length??0)>0,hasAnyView:s,fullStateOnlyBitmask:Nu(n?.[ei]),unreliableBitmask:Nu(n?.[js]),streamBitmask:Nu(n?.[cn]),names:o.names,types:o.types,tags:o.tags,encoders:o.encoders};return Object.defineProperty(e,xa,{value:a,enumerable:!1,writable:!0,configurable:!0}),a}function wA(t,e,n){if(t.parentRef){if(t.parentRef[I]===e[I]){t._parentIndex=n;return}if(ob(t,(r,s)=>r[I]===e[I])){t._parentIndex=n;return}}t.parentRef===void 0?(t.parentRef=e,t._parentIndex=n):(t.extraParents={ref:t.parentRef,index:t._parentIndex,next:t.extraParents},t.parentRef=e,t._parentIndex=n)}function SA(t,e,n){if(t.extraParents===void 0){t._parentIndex=n;return}if(t.parentRef[I]===e[I]){t._parentIndex=n;return}for(let r=t.extraParents;r!==void 0;r=r.next)if(r.ref[I]===e[I]){r.index=n;return}}function xA(t,e){if(t.parentRef&&t.parentRef[I]===e[I])return t.extraParents?(t.parentRef=t.extraParents.ref,t._parentIndex=t.extraParents.index,t.extraParents=t.extraParents.next):(t.parentRef=void 0,t._parentIndex=void 0),!0;let n=t.extraParents,r=null;for(;n;){if(n.ref[I]===e[I])return r?r.next=n.next:t.extraParents=n.next,!0;r=n,n=n.next}return t.parentRef===void 0}function _A(t,e){if(t.parentRef!==void 0&&e(t.parentRef,t._parentIndex))return{ref:t.parentRef,index:t._parentIndex};for(let n=t.extraParents;n!==void 0;n=n.next)if(e(n.ref,n.index))return{ref:n.ref,index:n.index}}function ob(t,e){if(t.parentRef!==void 0&&e(t.parentRef,t._parentIndex))return!0;for(let n=t.extraParents;n!==void 0;n=n.next)if(e(n.ref,n.index))return!0;return!1}function RA(t,e){if(t.parentRef&&t.parentRef[I]===e[I])return t._parentIndex;for(let n=t.extraParents;n!==void 0;n=n.next)if(n.ref[I]===e[I])return n.index}function EA(t){let e=[];t.parentRef&&e.push({ref:t.parentRef,index:t._parentIndex});let n=t.extraParents;for(;n;)e.push({ref:n.ref,index:n.index}),n=n.next;return e}function kA(t,e,n){let r=e.refTarget;if(e.isArray){let o=r.items,i=o[n];if(i!==void 0&&i[I]===t)return!0;for(let a=0,c=o.length;a<c;a++){let u=o[a];if(u!==void 0&&u[I]===t)return!0}return!1}let s=e.getValue(n);return s!==void 0&&s[I]===t}function PA(t,e){sp(t,e,AA)}function sp(t,e,n){let r=t.refTarget;if(r[ge]!==void 0){if(t.isPatchOnly)return;if(Array.isArray(r.items)){let s=r.items;for(let o=0,i=s.length;o<i;o++)s[o]!==void 0&&n(e,o)}else if(r.journal!==void 0)for(let[s,o]of r.journal.keyByIndex)r.$items.has(o)&&n(e,s);else if(r.$items!==void 0)for(let s of r.$items.keys())n(e,s)}else{let s=t.metadata;if(!s)return;let o=s[kt]??-1,i=s[Uu],a=t.encDescriptor.names;for(let c=0;c<=o;c++){let u=a[c];if(u===void 0||i&&i.includes(c))continue;let l=r[u];l!=null&&n(e,c)}}}function ab(t,e,n,r){TA(t,e,n),!t.isFullStateOnly&&(t.has()&&t.root?.enqueueChangeTree(t),t.unreliableRecorder?.has()&&t.root?.enqueueUnreliable(t),!t.has()&&!t.unreliableRecorder?.has()&&t.root?.enqueueChangeTree(t))}function TA(t,e,n){if(!e)return;let r=e[I],s=!r._isSchema,o;s?(e=r.parent,n=r.parentIndex,o=e?.[I].metadata):o=r.metadata;let i=(o?.[Ra]?.includes(n)?_a:0)|(o?.[ei]?.includes(n)?Qo:0),a=r.flags&UA|i,c=t.flags;if(t.flags=c|a,a&~c&Qo&&(t.reset(),t.unreliableRecorder?.reset()),!t.root?.types?.hasFilters)return;let d=o?.[Cn]?.includes(n)??!1,f=o?.[cn]?.includes(n)??!1,h=r.isFiltered||d||f;if(t.isFiltered=h,f&&!s){t.isStreamCollection=!0;let p=tp(t.ref);if(p.priority===void 0){let y=Ie.getStreamPriority(o,n);y!==void 0&&(p.priority=y)}t.root?.registerStream(t.ref)}if(h){let p=cb(t);t.isVisibilitySharedWithParent=r.isFiltered&&p&&!f&&(!d||s&&o[n].tag!==rl)}}function Ky(t){let e=t.pendingFilterRefresh;for(let n=0;n<e.length;n++){let r=e[n];(r.flags&Ea)!==0&&op(r)}e.length=0}function cb(t){return t._isSchema||typeof t.refTarget[ge]!="string"}function op(t){t.flags&=~Ea;let e=t.root;if(e===void 0||t.parentRef===void 0)return;let n=cb(t),r=Xy(t,t.parentRef,t._parentIndex,n);for(let o=t.extraParents;o!==void 0&&r!==vA;o=o.next)r|=Xy(t,o.ref,o.index,n);if(r===0)return;t.isVisibilitySharedWithParent=(r&$u)!==0;let s=(r&Hu)===0;s!==t.isFiltered&&(t.isFiltered=s,!s&&!t.isFullStateOnly&&(t.forEachLiveWithCtx(t,ib),t.has()&&e.enqueueChangeTree(t),t.unreliableRecorder?.has()&&e.enqueueUnreliable(t)),t.forEachChildWithCtx(t,MA))}function Xy(t,e,n,r){let s=e[I];if(s.root!==t.root||!kA(t,s,n))return 0;s.flags&Ea&&op(s);let o=ub;if(s._isSchema)s.encDescriptor.tags[n]!==void 0||s.isFieldStream(n)||(s.isFiltered?r&&(o|=$u):o|=Hu);else if(!s.isFiltered)o|=Hu;else if(r&&!s.isStreamCollection){let i=s.parent?.[I];(i?._isSchema?i.encDescriptor.tags[s.parentIndex]:void 0)!==rl&&(o|=$u)}return o}function CA(t,e,n,r){let s=t.subscribedViews;if(s===void 0)return;let o=t.isStreamCollection,i=o?t.ref:void 0,a=o?void 0:n[I];for(let c=0,u=s.length;c<u;c++){let l=s[c];for(;l!==0;){let d=l&-l;l^=d;let f=c*32+(31-Math.clz32(d)),p=r.activeViews.get(f)?.deref();if(p===void 0){s[c]&=~d;continue}o?dA(i,f,e):a!==void 0&&p.markVisible(a)}}}function OA(t,e){t.root=e;let n=e.add(t);ab(t,t.parent,t.parentIndex),n&&Ca(t,e,BA)}function IA(t,e,n,r){if(t.addParent(e,r),!n)return;let s=n.add(t);n!==t.root&&(t.root=n,ab(t,e,r));let o=e?.[I];if(o!==void 0&&o.subscribedViews!==void 0&&e[ge]!==void 0&&CA(o,r,t.ref,n),s){let i=Jy[Bu];i===void 0&&(i={parentRef:void 0,root:void 0},Jy[Bu]=i),i.parentRef=t.ref,i.root=n,Bu++,Ca(t,i,LA),Bu--}}function DA(t,e){Ca(t,e,NA)}function NA(t,e,n){t(e,n)}function Ca(t,e,n){let r=t.refTarget;if(r[ge]){if(typeof r[ge]!="string"){let s=r.items;if(s!==void 0)for(let o=0,i=s.length;o<i;o++){let a=s[o];a&&n(e,a[I],o)}else{let o=r.$items,i=r._collectionIndexes;for(let a of o.keys()){let c=o.get(a);c&&n(e,c[I],i?.[a]??a)}}}}else{let o=t.metadata?.[us];if(!o)return;let i=t.encDescriptor.names;for(let a=0,c=o.length;a<c;a++){let u=o[a],l=r[i[u]];l&&n(e,l[I],u)}}}function BA(t,e,n){e.root!==t?e.setRoot(t):t.add(e)}function LA(t,e,n){if(e.root===t.root){t.root.add(e),t.root.moveNextToParent(e);return}e.setParent(t.parentRef,t.root,n)}function FA(t,e,n){let r=(n&3)<<3;return n<4?t>>>r&255:e>>>r&255}function Zy(){return{next:void 0,tail:void 0,nextPosition:0}}function VA(t){return new Xf(t)}function si(t,e=t){Object.defineProperty(t,I,{value:VA(e),enumerable:!1,writable:!0})}function el(t,e,n,r,s,o,i){i!==void 0?i(e,r,o):typeof n=="string"?Se[n]?.(e,r,o):n[Symbol.metadata]!=null?(Se.number(e,r[ee],o),(s&N.ADD)===N.ADD&&t.tryEncodeTypeId(e,n,r.constructor,o)):Se.number(e,r[ee],o)}function lb(t,e,n,r,s,o,i){let a=t.resyncVisited,c=a.get(t.currentRefId);if(c===void 0&&a.set(t.currentRefId,c=new Set),c.add(r),s!==void 0&&n===N.ADD&&s!==o){let u=s[ee];u!==void 0&&(t.root.removeRef(u),i?.push({ref:e,refId:t.currentRefId,op:N.DELETE,dynamicIndex:r,value:void 0,previousValue:s}))}}function WA(t,e){let n=t.resyncVisited;n.has(e)||n.set(e,new Set)}function qA(t,e){if(t.resyncDamaged){console.warn("@colyseus/schema: resync sweep skipped \u2014 parts of the payload could not be decoded. Stale entries may persist until the next resync.");return}cp(t,t.state,new Set,e)}function cp(t,e,n,r){let s=e[ee];if(s===void 0||n.has(s))return;n.add(s);let o=e.constructor[Symbol.metadata],i=o?.[us];if(i===void 0)return;let a=o[Ra];for(let c=0;c<i.length;c++){let u=i[c];if(a!==void 0&&a.includes(u))continue;let l=o[u],d=e[l.name];d&&(Xe.is(l.type)?cp(t,d,n,r):GA(t,d,n,r))}}function GA(t,e,n,r){let s=e[lt]??e,o=s[ee];if(o===void 0||n.has(o))return;n.add(o);let i=t.resyncVisited.get(o);if(i===void 0)return;let a=t.root;s[ri](i,(c,u)=>{r?.push({ref:e,refId:o,op:N.DELETE,dynamicIndex:u,value:void 0,previousValue:c});let l=c?.[ee];l!==void 0&&a.removeRef(l)},c=>{Xe.isSchema(c)&&cp(t,c,n,r)})}function up(t,e,n,r,s,o,i,a,c){let u=t.root,l;if((e&N.DELETE)===N.DELETE){let d=s?.[ee];d!==void 0&&u.removeRef(d),e!==N.DELETE_AND_ADD&&n[Nn](r),l=void 0}if(e!==N.DELETE)if(typeof o=="string")l=Ae[o](i,a);else if(Ys(o))l=hA(o.quantized,i,a);else if(Xe.is(o)){let d=Ae.number(i,a);if(l=u.refs.get(d),(e&N.ADD)===N.ADD){let f=t.getInstanceType(i,a,o);l||(l=t.createInstanceOfType(f)),u.addRef(d,l,l!==s||e===N.DELETE_AND_ADD&&l===s)}}else{let d=eb(Object.keys(o)[0]),f=Ae.number(i,a);t.resyncVisited!==null&&WA(t,f);let h=u.refs.has(f)?s||u.refs.get(f):d.constructor.initializeForDecoder();if(l=h.clone(!0),l[ge]=Object.values(o)[0],s){let p=s[ee];if(p!==void 0&&f!==p){(e&N.DELETE)!==N.DELETE&&u.removeRef(p);let y=s.entries(),S;for(;(S=y.next())&&!S.done;){let[w,x]=S.value;typeof x=="object"&&(p=x[ee]),c?.push({ref:s,refId:p,op:N.DELETE,field:w,value:void 0,previousValue:x})}}}u.addRef(f,l,h!==s||e===N.DELETE_AND_ADD&&h===s)}return l}function nl(t,e,n,r){if(!(t instanceof e))throw new ka(`a '${e.name}' was expected, but '${t&&t.constructor.name}' was provided in ${n.constructor.name}#${r}`)}function fb(t){return t!=null&&t[Lg]===!0}function Bt(t){return(()=>new ar(t))}function Oa(t){if(fb(t)){let e=t._type,n=typeof e=="string"?`use the type name instead: t.array("${e}")`:'collections accept a Schema class or a primitive type name ("string", "number", \u2026)';throw new Error(`t.array/map/set/collection(): a t.* builder is not a valid element type \u2014 ${n}.`)}return t}function eg(t){return new ar({quantized:np(t)})}function rP(t=rl){return function(e,n){let r=Ie.initialize(e.constructor);Ie.setTag(r,n,t)}}function sP(t,e){let n=Ie.initialize(t.constructor);Ie.setUnreliable(n,e)}function oP(t,e){let n=Ie.initialize(t.constructor);Ie.setPatchOnly(n,e)}function aP(t,e,n){let r=iP[n],s=n==="string",o=n==="boolean";return function(i){let a=this[vt],c=a[e];if(i!==c){if(i!=null){if(!o&&r!==void 0&&typeof i!==r&&!(s&&i===null)){let u=i&&i.constructor?` (${i.constructor.name})`:"";throw new ka(`a '${r}' was expected, but '${JSON.stringify(i)}'${u} was provided in ${this.constructor.name}#${t}`)}this.constructor[or](this[I],e,N.ADD)}else c!=null&&this[I].delete(e);a[e]=i}}}function cP(t,e,n){return function(r){let s=this[vt],o=s[e];if(r!==o){if(r!=null){nl(r,n,this,t);let i=this[I],a=this.constructor;o!=null&&o[I]?(i.root?.remove(o[I]),a[or](i,e,N.DELETE_AND_ADD)):a[or](i,e,N.ADD),r[I]?.setParent(this,i.root,e)}else o!=null&&this[I].delete(e);s[e]=r}}}function uP(t,e,n,r){let s=r.constructor===ls,o=r.constructor===ds;return function(i){let a=this[vt],c=a[e];if(i!==c){if(i!=null){if(s&&!(i instanceof ls)){let d=new ls;d[ge]=n,d.push(...i),i=d}else if(o&&!(i instanceof ds)){let d=new ds;if(d[ge]=n,i instanceof Map)i.forEach((f,h)=>d.set(h,f));else for(let f in i)d.set(f,i[f]);i=d}else i[ge]=n;let u=this[I],l=this.constructor;c!=null&&c[I]?(u.root?.remove(c[I]),l[or](u,e,N.DELETE_AND_ADD)):l[or](u,e,N.ADD),i[I]?.setParent(this,u.root,e)}else c!=null&&this[I].delete(e);a[e]=i}}}function lP(t,e,n){return function(r){let s=this[vt],o=s[e];if(r!=null){if(typeof r!="number")throw new ka(`a 'number' was expected, but '${JSON.stringify(r)}' was provided in ${this.constructor.name}#${t}`);if(r=rb(n,nb(n,r)),r===o)return;this.constructor[or](this[I],e,N.ADD)}else{if(r===o)return;o!=null&&this[I].delete(e)}s[e]=r}}function dP(t,e,n,r){let s;return r?s=uP(t,e,n,r):typeof n=="string"?s=aP(t,e,n):Ys(n)?s=lP(t,e,n.quantized):s=cP(t,e,n),{get:function(){return this[vt][e]},set:s,enumerable:!0,configurable:!0}}function fP(t=!0){return function(e,n){let r=Ie.initialize(e.constructor);Ie.setDeprecated(r,n),t&&(r[an]??(r[an]={}),r[an][n]={get:function(){throw new Error(`${n} is deprecated.`)},set:function(s){},enumerable:!1,configurable:!0},Object.defineProperty(e,n,r[an][n]))}}function pP(t){if(t&&typeof t=="object"){if(t.array!==void 0)return()=>new ls;if(t.map!==void 0)return()=>new ds;if(t.set!==void 0)return()=>new Pa;if(t.collection!==void 0)return()=>new Aa;if(t.stream!==void 0)return()=>new Wu}else if(typeof t=="function"&&Xe.is(t)&&(!t.prototype.initialize||t.prototype.initialize.length===0))return()=>new t}function Lt(t,e,n=Xe){if(t==null||typeof t!="object")throw new Error(`schema(): first argument must be a fields object (got ${typeof t}).`);let r={},s={},o={},i={},a=(k,M)=>{typeof M=="function"?i[k]=M:M&&typeof M.clone=="function"?i[k]=()=>M.clone():o[k]=M},c=(k,M)=>{if(M.hasDefault)a(k,M.default);else if(!M.optional){let L=pP(M.type);L&&(i[k]=L)}},u={},l=[],d=[],f={},h=[],p=[],y={},S=[];for(let k in t){let M=t[k];if(fb(M)){let L=M.toDefinition();if(L.noSync){if(L.view!==void 0||L.unreliable||L.patchOnly||L.fullStateOnly||L.stream)throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' uses .noSync() together with a sync-only modifier (.view/.unreliable/.patchOnly/.fullStateOnly/.stream). A local-only field cannot be synchronized.`);c(k,L);continue}if(L.patchOnly&&L.fullStateOnly)throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' uses .patchOnly() together with .fullStateOnly(). Those are the only two delivery channels, so the field would never reach a client \u2014 use .noSync() if that is intended.`);let K=ni(L.type);if(typeof K=="function"&&!Xe.is(K))throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' is a synced ref to non-Schema class '${K.name||"(anonymous)"}' \u2014 use .noSync(), or Metadata.setFields().`);r[k]=K,L.view!==void 0&&(u[k]=L.view),L.unreliable&&l.push(k),L.patchOnly&&d.push(k),L.deprecated&&(f[k]=L.deprecatedThrows),L.fullStateOnly&&h.push(k),L.stream&&p.push(k),L.streamPriority!==void 0&&(y[k]=L.streamPriority),L.optional&&S.push(k),c(k,L)}else if(typeof M=="function")Xe.is(M)?(r[k]=ni(M),(!M.prototype.initialize||M.prototype.initialize.length===0)&&(i[k]=()=>new M)):s[k]=M;else throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' must be a t.* builder, Schema subclass, or method (got ${typeof M}).`)}let w=k=>{for(let M in o)k[M]=o[M];for(let M in i)k[M]=i[M]()},x=()=>{let k={};return w(k),k},R=k=>{let M=Object.keys(r),L={};for(let K in k)M.includes(K)||(L[K]=k[K]);return L},A=typeof s.initialize=="function",E=s.initialize??n._initialize,P=class extends n{constructor(...k){let M=k[0];M===void 0?(super(),w(this)):super(Object.assign(x(),A?R(M):M)),E&&new.target===P&&E.apply(this,k)}};e&&Object.defineProperty(P,"name",{value:e}),Ie.setFields(P,r),P._getDefaultValues=x,P._initialize=E,Object.assign(P.prototype,s);for(let k in u)rP(u[k])(P.prototype,k);for(let k of l)sP(P.prototype,k);for(let k of d)oP(P.prototype,k);for(let k in f)fP(f[k])(P.prototype,k);if(h.length>0||p.length>0){let k=P[Symbol.metadata];for(let M of h)Ie.setFullStateOnly(k,M);for(let M of p)Ie.setStream(k,M);for(let M in y)Ie.setStreamPriority(k,M,y[M])}if(S.length>0){let k=P[Symbol.metadata];for(let M of S)k[k[M]].optional=!0}return P.extend=(k,M)=>Lt(k,M,P),P}function hP(t){return new Array(t).fill(0).map((e,n)=>n===t-1?"\u2514\u2500 ":" ").join("")}function mP(t,e){if(e===-1||e>=t.length)return!1;let n=t.length-1;for(let r=e;r<n;r++)t[r]=t[r+1];return t.length=n,!0}function yP(t,e,n){let r=~n,s=t.changeTrees;for(let o in s){let i=s[o],a=i.visibleViews;a!==void 0&&e<a.length&&(a[e]&=r);let c=i.subscribedViews;c!==void 0&&e<c.length&&(c[e]&=r);let u=i.tagViews;u!==void 0&&u.forEach(l=>{e<l.length&&(l[e]&=r)})}}function ng(t){t.structSwitchEmitted||(t.shouldEmitSwitch&&(t.buffer[t.it.offset++]=255,Se.number(t.buffer,t.ref[ee],t.it)),t.structSwitchEmitted=!0)}function bP(t,e){hb(t,e,N.ADD)}function pb(t,e){if(e._fullSyncGen===t.gen)return;if(e._fullSyncGen=t.gen,!t.hasView||t.view.isChangeTreeVisible(e)){let r=e.encDescriptor;t.changeTree=e,t.ref=e.ref,t.encoder=r.encoder,t.filter=r.filter,t.metadata=r.metadata,t.treeIsFiltered=e.isFiltered,t.isSchema=r.isSchema,t.filterBitmask=r.filterBitmask,t.tags=r.tags,t.structSwitchEmitted=!1,t.shouldEmitSwitch=t.hasView||t.it.offset>t.initialOffset||e!==t.rootChangeTree,e.isArray&&e.collDirty.size>0&&(e.flags|=ip),sp(e,t,bP)}Ca(e,t,wP)}function wP(t,e,n){pb(t,e)}function hb(t,e,n){if(e<0){if(t.treeIsFiltered!==t.emitFiltered)return;ng(t),t.buffer[t.it.offset++]=Math.abs(e)&255;return}if((t.isSchema?t.treeIsFiltered||(e<32?(t.filterBitmask&1<<e)!==0:t.tags[e]!==void 0):t.treeIsFiltered)!==t.emitFiltered)return;let s=t.isEncodeAll?N.ADD:n;s!==void 0&&(t.filter!==void 0&&!t.filter(t.ref,e,t.view)||(ng(t),t.encoder(t.self,t.buffer,t.changeTree,e,s,t.it,t.isEncodeAll,t.hasView,t.metadata)))}function Wf(t,e){let n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function Gu(t){let e=t.root,n=e.callbacks,r=new WeakMap,s;t.triggerChanges=function(a){let c=new Set;for(let u=0,l=a.length;u<l;u++){let d=a[u],f=d.refId,h=d.ref,p=n[f];if(p){if((d.op&N.DELETE)===N.DELETE&&Xe.isSchema(d.previousValue)){let y=n[d.previousValue[ee]]?.[N.DELETE];for(let S=y?.length-1;S>=0;S--)y[S]()}if(Xe.isSchema(h)){if(!c.has(f)){let y=p?.[N.REPLACE];for(let S=y?.length-1;S>=0;S--)y[S]()}if(p.hasOwnProperty(d.field)){let y=p[d.field];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.previousValue)}}else{if((d.op&N.DELETE)===N.DELETE){if(d.previousValue!==void 0){let y=p[N.DELETE];for(let S=y?.length-1;S>=0;S--)y[S](d.previousValue,d.dynamicIndex??d.field)}if((d.op&N.ADD)===N.ADD){let y=p[N.ADD];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.dynamicIndex??d.field)}}else if((d.op&N.ADD)===N.ADD&&d.previousValue!==d.value){let y=p[N.ADD];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.dynamicIndex??d.field)}if(d.value!==d.previousValue&&(d.value!==void 0||d.previousValue!==void 0)){let y=p[N.REPLACE];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.dynamicIndex??d.field)}}c.add(f)}}};function o(a,c){let u=c.instance?.constructor[Symbol.metadata]||a,l=c.instance&&typeof c.instance.forEach=="function"||a&&!Xe.is(a);if(u&&!l){let d=function(f,h,p,y){return y&&c.instance[h]!==void 0&&!r.has(s)&&p(c.instance[h],void 0),e.addCallback(f[ee],h,p)};return new Proxy({listen:function(h,p,y=!0){if(c.instance)return d(c.instance,h,p,y);{let S=()=>{};return c.onInstanceAvailable((w,x)=>{S=d(w,h,p,y&&x&&!r.has(s))}),()=>S()}},onChange:function(h){return e.addCallback(c.instance[ee],N.REPLACE,h)},bindTo:function(h,p){return p||(p=Object.keys(u).map(y=>u[y].name)),e.addCallback(c.instance[ee],N.REPLACE,()=>{p.forEach(y=>h[y]=c.instance[y])})}},{get(f,h){let p=u[u[h]];if(p){let y=c.instance?.[h],S=(w=>{let x=i(c.instance).listen(h,(R,A)=>{w(R,!1),x?.()},!1);y?.[ee]!==void 0&&w(y,!0)});return o(p.type,{instance:y?.[ee]!==void 0&&y,parentInstance:c.instance,onInstanceAvailable:S})}else return f[h]},has(f,h){return u[h]!==void 0},set(f,h,p){throw new Error("not allowed")},deleteProperty(f,h){throw new Error("not allowed")}})}else{let d=function(p,y,S){return S&&p.forEach((w,x)=>y(w,x)),e.addCallback(p[ee],N.ADD,(w,x)=>{r.set(y,!0),s=y,y(w,x),r.delete(y),s=void 0})},f=function(p,y){return e.addCallback(p[ee],N.DELETE,y)},h=function(p,y){return e.addCallback(p[ee],N.REPLACE,y)};return new Proxy({onAdd:function(p,y=!0){if(c.instance)return d(c.instance,p,y&&!r.has(s));if(c.onInstanceAvailable){let S=()=>{};return c.onInstanceAvailable((w,x)=>{S=d(w,p,y&&x&&!r.has(s))}),()=>S()}},onRemove:function(p){if(c.instance)return f(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(S=>{y=f(S,p)}),()=>y()}},onChange:function(p){if(c.instance)return h(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(S=>{y=h(S,p)}),()=>y()}}},{get(p,y){if(!p[y])throw new Error(`Can't access '${y}' through callback proxy. access the instance directly.`);return p[y]},has(p,y){return p[y]!==void 0},set(p,y,S){throw new Error("not allowed")},deleteProperty(p,y){throw new Error("not allowed")}})}}function i(a){return o(void 0,{instance:a})}return i}function SP(t,e){t.triggerChanges=e}var N,Gy,ee,or,ir,In,Xs,st,Nn,ri,I,ge,lt,cs,Dn,zu,vt,Lg,an,xa,Tr,kt,us,Cn,Pr,js,Ra,Uu,ei,cn,Iu,$k,Ku,Ws,qf,jk,Fg,Wk,zg,Se,va,Gs,Jk,Zk,Qk,eA,Ae,ep,aA,tb,fA,nr,Ks,Yy,gA,Ie,sb,Yf,Kf,ib,AA,ub,Hu,$u,vA,MA,Jy,Bu,zA,Hf,$f,Sa,jf,_a,Qo,Fu,Lu,Ea,ip,UA,fs,Xf,HA,$A,ap,jA,db,On,YA,tl,KA,ka,XA,Qy,sg,og,ig,ag,cg,ug,lg,on,ls,ju,dg,fg,pg,hg,mg,rr,ds,yg,gg,bg,wg,Sg,is,Aa,xg,_g,Rg,Eg,kg,as,Pa,Ag,Pg,Tg,vg,Mg,vr,Wu,Cg,ar,JA,ZA,QA,eP,tP,nP,X,rl,iP,Og,Ig,Dg,Ng,Mn,Xe,tg,Jf,LB,gP,sr,Ta,qu,rg,Zf,Ln,mb,yb,gb,Fn,Yu,lp,At=pt(()=>{"use strict";(function(t){t[t.ADD=128]="ADD",t[t.REPLACE=0]="REPLACE",t[t.DELETE=64]="DELETE",t[t.DELETE_AND_MOVE=96]="DELETE_AND_MOVE",t[t.MOVE_AND_ADD=160]="MOVE_AND_ADD",t[t.DELETE_AND_ADD=192]="DELETE_AND_ADD",t[t.CLEAR=10]="CLEAR",t[t.REVERSE=15]="REVERSE",t[t.MOVE=32]="MOVE",t[t.DELETE_BY_REFID=33]="DELETE_BY_REFID",t[t.ADD_BY_REFID=129]="ADD_BY_REFID"})(N||(N={}));Symbol.metadata??(Symbol.metadata=Symbol.for("Symbol.metadata"));Gy=(function(){return typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{}})();if(typeof Symbol=="function"&&typeof Symbol.for!="function"){let t="colyseus.symbolRegistry",e=Gy[t]||(Gy[t]=Object.create(null));Symbol.for=function(n){return e[n]||(e[n]=Symbol(n))},Symbol.keyFor=function(n){for(let r in e)if(e[r]===n)return r}}ee=Symbol.for("$refId"),or="~track",ir="~encoder",In="~decoder",Xs="~filter",st="~getByIndex",Nn="~deleteByIndex",ri="~resyncPrune",I=Symbol.for("$changes"),ge=Symbol.for("$childType"),lt=Symbol.for("$proxyTarget"),cs="~onEncodeEnd",Dn="~reset",zu="~onDecodeEnd",vt=Symbol.for("$values"),Lg="~builder",an="~descriptors",xa="~__encodeDescriptor",Tr="~encoders",kt="~__numFields",us="~__refTypeFieldIndexes",Cn="~__viewFieldIndexes",Pr="$__fieldIndexesByViewTag",js="~__unreliableFieldIndexes",Ra="~__patchOnlyFieldIndexes",Uu="~__fullSyncSkipIndexes",ei="~__fullStateOnlyFieldIndexes",cn="~__streamFieldIndexes",Iu="~__streamPriorities";try{$k=new TextEncoder}catch{}Ku=new ArrayBuffer(8),Ws=new Int32Array(Ku),qf=new Float32Array(Ku),jk=new Float64Array(Ku),Fg=new BigInt64Array(Ku),Wk=typeof Buffer<"u"&&Buffer.byteLength,zg=Wk?Buffer.byteLength:function(t,e){for(var n=0,r=0,s=0,o=t.length;s<o;s++)n=t.charCodeAt(s),n<128?r+=1:n<2048?r+=2:n<55296||n>=57344?r+=3:(s++,r+=4);return r};Se={int8:Vg,uint8:qk,int16:Hg,uint16:Qf,int32:Mr,uint32:qs,int64:$g,uint64:jg,bigint64:Gk,biguint64:Yk,float32:Wg,float64:qg,boolean:Kk,string:Xk,number:Gf,utf8Write:Ug,utf8Length:zg},va=new ArrayBuffer(8),Gs=new Int32Array(va),Jk=new Float32Array(va),Zk=new Float64Array(va),Qk=new BigUint64Array(va),eA=new BigInt64Array(va);Ae={utf8Read:Gg,int8:Yg,uint8:Ma,int16:Kg,uint16:Xu,int32:Bn,uint32:ti,float32:Xg,float64:Jg,int64:Zg,uint64:Qg,bigint64:tA,biguint64:nA,boolean:rA,string:sA,number:oA,stringCheck:iA},ep={},aA=new Map;tb="ArraySchema does not support streaming \u2014 positional ops (splice / unshift / reverse) shift subsequent indexes, so holding ADDs back for a later tick under `maxPerTick` would desync the decoder. Use `t.stream(X)` (stable monotonic positions) or `t.map(X).stream()` (stable keys) instead.";fA={8:"uint8",16:"uint16",32:"uint32"};nr=class nr{constructor(e){m(this,"types",{});m(this,"schemas",new Map);m(this,"hasFilters",!1);e&&this.discoverTypes(e)}static register(e){let n=Object.getPrototypeOf(e);if(n!==Xe){let r=nr.inheritedTypes.get(n);r||(r=new Set,nr.inheritedTypes.set(n,r)),r.add(e)}}static cache(e){let n=nr.cachedContexts.get(e);return n||(n=new nr(e),nr.cachedContexts.set(e,n)),n}has(e){return this.schemas.has(e)}get(e){return this.types[e]}add(e,n=this.schemas.size){return this.schemas.has(e)?!1:(this.types[n]=e,e[Symbol.metadata]==null&&Ie.initialize(e),this.schemas.set(e,n),!0)}getTypeId(e){return this.schemas.get(e)}discoverTypes(e){if(!this.add(e))return;nr.inheritedTypes.get(e)?.forEach(s=>{this.discoverTypes(s)});let n=e;for(;(n=Object.getPrototypeOf(n))&&n!==Xe&&n!==Function.prototype;)this.discoverTypes(n);let r=e[Symbol.metadata];(r[Cn]||r[cn])&&(this.hasFilters=!0);for(let s in r){let i=r[s].type;if(typeof i!="string"&&!Ys(i))if(typeof i=="function")this.discoverTypes(i);else{let a=Object.values(i)[0];if(typeof a=="string")continue;this.discoverTypes(a)}}}debug(){return`TypeContext ->
|
|
1
|
+
"use strict";(()=>{var nE=Object.create;var cu=Object.defineProperty;var rE=Object.getOwnPropertyDescriptor;var sE=Object.getOwnPropertyNames;var oE=Object.getPrototypeOf,iE=Object.prototype.hasOwnProperty;var Um=t=>{throw TypeError(t)};var aE=(t,e,n)=>e in t?cu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var ht=(t,e)=>()=>(t&&(e=t(t=0)),e);var cE=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),of=(t,e)=>{for(var n in e)cu(t,n,{get:e[n],enumerable:!0})},uE=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of sE(e))!iE.call(t,s)&&s!==n&&cu(t,s,{get:()=>e[s],enumerable:!(r=rE(e,s))||r.enumerable});return t};var lE=(t,e,n)=>(n=t!=null?nE(oE(t)):{},uE(e||!t||!t.__esModule?cu(n,"default",{value:t,enumerable:!0}):n,t));var m=(t,e,n)=>aE(t,typeof e!="symbol"?e+"":e,n),af=(t,e,n)=>e.has(t)||Um("Cannot "+n);var de=(t,e,n)=>(af(t,e,"read from private field"),n?n.call(t):e.get(t)),He=(t,e,n)=>e.has(t)?Um("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),$e=(t,e,n,r)=>(af(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),zs=(t,e,n)=>(af(t,e,"access private method"),n);var Ke,Zo,Hf,Cu,Ou,$s,St,Gy=ht(()=>{"use strict";Ke={JOIN_ROOM:10,ERROR:11,LEAVE_ROOM:12,ROOM_DATA:13,ROOM_STATE:14,ROOM_STATE_PATCH:15,ROOM_DATA_SCHEMA:16,ROOM_DATA_BYTES:17,PING:18,ROOM_INPUT_RELIABLE:19,ROOM_INPUT_UNRELIABLE:20,ROOM_REQUEST:21,ROOM_RESPONSE:22},Zo={TIMED:128,UNRELIABLE:64},Hf=31,Cu={OK:0,REJECTED:1,ERROR:2},Ou={INPUT_REFLECTION:1,INPUT_OPTIONS:2},$s={RENDER_TIME:1,FIXED_TIMESTEP:2,PATCH_RATE:4,SUB_STEPS:8,RECKON_TIME:16},St={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,CONSENTED:4e3,SERVER_SHUTDOWN:4001,WITH_ERROR:4002,FAILED_TO_RECONNECT:4003,MAY_TRY_RECONNECT:4010}});var Pr=ht(()=>{"use strict";Gy()});function Lg(t){Object.defineProperty(t,Symbol.metadata,{value:void 0,writable:!0,configurable:!0,enumerable:!1})}function Vg(t,e,n){for(var r=0,s=0,o=e.length;s<o;s++)r=e.charCodeAt(s),r<128?t[n.offset++]=r:r<2048?(t[n.offset]=192|r>>6,t[n.offset+1]=128|r&63,n.offset+=2):r<55296||r>=57344?(t[n.offset]=224|r>>12,t[n.offset+1]=128|r>>6&63,t[n.offset+2]=128|r&63,n.offset+=3):(s++,r=65536+((r&1023)<<10|e.charCodeAt(s)&1023),t[n.offset]=240|r>>18,t[n.offset+1]=128|r>>12&63,t[n.offset+2]=128|r>>6&63,t[n.offset+3]=128|r&63,n.offset+=4)}function Hg(t,e,n){t[n.offset++]=e&255}function Yk(t,e,n){t[n.offset++]=e&255}function $g(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function ep(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function Cr(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255,t[n.offset++]=e>>16&255,t[n.offset++]=e>>24&255}function qs(t,e,n){let r=e>>24,s=e>>16,o=e>>8,i=e;t[n.offset++]=i&255,t[n.offset++]=o&255,t[n.offset++]=s&255,t[n.offset++]=r&255}function jg(t,e,n){let r=Math.floor(e/Math.pow(2,32)),s=e>>>0;qs(t,s,n),qs(t,r,n)}function Wg(t,e,n){let r=e/Math.pow(2,32)>>0,s=e>>>0;qs(t,s,n),qs(t,r,n)}function Kk(t,e,n){zg[0]=BigInt.asIntN(64,e),Cr(t,Ws[0],n),Cr(t,Ws[1],n)}function Xk(t,e,n){zg[0]=BigInt.asIntN(64,e),Cr(t,Ws[0],n),Cr(t,Ws[1],n)}function qg(t,e,n){Gf[0]=e,Cr(t,Ws[0],n)}function Gg(t,e,n){qk[0]=e,Cr(t,Ws[0],n),Cr(t,Ws[1],n)}function Jk(t,e,n){t[n.offset++]=e?1:0}function Zk(t,e,n){e||(e="");let r=Ug(e,"utf8"),s=0;if(r<32)t[n.offset++]=r|160,s=1;else if(r<256)t[n.offset++]=217,t[n.offset++]=r,s=2;else if(r<65536)t[n.offset++]=218,ep(t,r,n),s=3;else if(r<4294967296)t[n.offset++]=219,qs(t,r,n),s=5;else throw new Error("String too long");return Vg(t,e,n),s+r}function Yf(t,e,n){if(isNaN(e))return Yf(t,0,n);if(isFinite(e)){if(e!==(e|0))return Math.abs(e)<=34028235e31&&(Gf[0]=e,Math.abs(Math.abs(Gf[0])-Math.abs(e))<1e-4)?(t[n.offset++]=202,qg(t,e,n),5):(t[n.offset++]=203,Gg(t,e,n),9)}else return Yf(t,e>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER,n);return e>=0?e<128?(t[n.offset++]=e&255,1):e<256?(t[n.offset++]=204,t[n.offset++]=e&255,2):e<65536?(t[n.offset++]=205,ep(t,e,n),3):e<4294967296?(t[n.offset++]=206,qs(t,e,n),5):(t[n.offset++]=207,Wg(t,e,n),9):e>=-32?(t[n.offset++]=224|e+32,1):e>=-128?(t[n.offset++]=208,Hg(t,e,n),2):e>=-32768?(t[n.offset++]=209,$g(t,e,n),3):e>=-2147483648?(t[n.offset++]=210,Cr(t,e,n),5):(t[n.offset++]=211,jg(t,e,n),9)}function Yg(t,e,n){n>t.length-e.offset&&(n=t.length-e.offset);for(var r="",s=0,o=e.offset,i=e.offset+n;o<i;o++){var a=t[o];if((a&128)===0){r+=String.fromCharCode(a);continue}if((a&224)===192){r+=String.fromCharCode((a&31)<<6|t[++o]&63);continue}if((a&240)===224){r+=String.fromCharCode((a&15)<<12|(t[++o]&63)<<6|(t[++o]&63)<<0);continue}if((a&248)===240){s=(a&7)<<18|(t[++o]&63)<<12|(t[++o]&63)<<6|(t[++o]&63)<<0,s>=65536?(s-=65536,r+=String.fromCharCode((s>>>10)+55296,(s&1023)+56320)):r+=String.fromCharCode(s);continue}console.error("decode.utf8Read(): Invalid byte "+a+" at offset "+o+". Skip to end of string: "+(e.offset+n));break}return e.offset+=n,r}function Kg(t,e){return Ma(t,e)<<24>>24}function Ma(t,e){return t[e.offset++]}function Xg(t,e){return Xu(t,e)<<16>>16}function Xu(t,e){return t[e.offset++]|t[e.offset++]<<8}function Ln(t,e){return t[e.offset++]|t[e.offset++]<<8|t[e.offset++]<<16|t[e.offset++]<<24}function ti(t,e){return Ln(t,e)>>>0}function Jg(t,e){return Gs[0]=Ln(t,e),Qk[0]}function Zg(t,e){return Gs[0]=Ln(t,e),Gs[1]=Ln(t,e),eA[0]}function Qg(t,e){let n=ti(t,e);return Ln(t,e)*Math.pow(2,32)+n}function eb(t,e){let n=ti(t,e);return ti(t,e)*Math.pow(2,32)+n}function rA(t,e){return Gs[0]=Ln(t,e),Gs[1]=Ln(t,e),nA[0]}function sA(t,e){return Gs[0]=Ln(t,e),Gs[1]=Ln(t,e),tA[0]}function oA(t,e){return Ma(t,e)>0}function iA(t,e){let n=t[e.offset++],r;return n<192?r=n&31:n===217?r=Ma(t,e):n===218?r=Xu(t,e):n===219&&(r=ti(t,e)),Yg(t,e,r)}function aA(t,e){let n=t[e.offset++];if(n<128)return n;if(n===202)return Jg(t,e);if(n===203)return Zg(t,e);if(n===204)return Ma(t,e);if(n===205)return Xu(t,e);if(n===206)return ti(t,e);if(n===207)return eb(t,e);if(n===208)return Kg(t,e);if(n===209)return Xg(t,e);if(n===210)return Ln(t,e);if(n===211)return Qg(t,e);if(n>223)return(255-n+1)*-1}function cA(t,e){let n=t[e.offset];return n<192&&n>160||n===217||n===218||n===219}function Ir(t,e){e.constructor&&(Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor[Symbol.metadata]==null&&Lg(e.constructor),uA.set(e.constructor,t),tp[t]=e),e.encode&&(Se[t]=e.encode),e.decode&&(Pe[t]=e.decode)}function tb(t){return tp[t]}function Or(){return{pendingByView:new Map,sentByView:new Map,broadcastPending:new Set,sentBroadcast:new Set,broadcastDeletes:new Set,maxPerTick:32}}function np(t){return t._stream??(t._stream=Or())}function Ju(t,e,n){e.activeViews.size===0&&np(t).broadcastPending.add(n)}function Zu(t,e,n,r){let s=t._stream;if(s===void 0)return!0;let o=!1;return s.broadcastPending.delete(r)?o=!0:s.sentBroadcast.delete(r)&&s.broadcastDeletes.add(r),e.forEachActiveView(i=>{let a=s.pendingByView.get(i.id);if(a?.has(r)){a.delete(r),o=!0;return}let c=s.sentByView.get(i.id);if(c?.has(r)){c.delete(r);let u=i.changes.get(n);u===void 0&&(u=new Map,i.changes.set(n,u)),u.set(r,N.DELETE)}}),o}function lA(t,e,n){let r=t._stream;if(r!==void 0){r.broadcastPending.clear();for(let s of r.sentBroadcast)r.broadcastDeletes.add(s);r.sentBroadcast.clear(),e.forEachActiveView(s=>{r.pendingByView.get(s.id)?.clear();let o=r.sentByView.get(s.id);if(o!==void 0&&o.size>0){let i=s.changes.get(n);i===void 0&&(i=new Map,s.changes.set(n,i));for(let a of o)i.set(a,N.DELETE);o.clear()}})}}function dA(t,e){let n=t._stream?.pendingByView;if(n===void 0)return!1;for(let[r,s]of n)if(s.size>0&&e.activeViews.get(r)?.deref()!==void 0)return!0;return!1}function fA(t){let e=t._stream;return e!==void 0&&(e.broadcastPending.size>0||e.broadcastDeletes.size>0)}function pA(t,e,n){let r=np(t),s=r.pendingByView.get(e);s===void 0&&(s=new Set,r.pendingByView.set(e,s)),s.add(n)}function Qu(t,e){let n=t._stream;n!==void 0&&(n.pendingByView.delete(e),n.sentByView.delete(e),n.priorityByView?.delete(e))}function rp(t){if(t==null||typeof t!="object")throw new Error("t.quantized(): options object with { min, max } is required.");let{min:e,max:n}=t;if(typeof e!="number"||typeof n!="number"||!(n>e)||!Number.isFinite(e)||!Number.isFinite(n))throw new Error(`t.quantized(): require finite min < max (got min=${e}, max=${n}).`);let r=t.bits??16;if(r!==8&&r!==16&&r!==32)throw new Error(`t.quantized(): bits must be 8, 16 or 32 (got ${r}).`);let s=t.mode??"clamp";if(s!=="clamp"&&s!=="wrap")throw new Error(`t.quantized(): mode must be "clamp" or "wrap" (got ${JSON.stringify(s)}).`);let o=s==="wrap",i=Math.pow(2,r);return{min:e,max:n,bits:r,wrap:o,wire:hA[r],range:n-e,span:o?i:e===-n?i-2:i-1}}function Ys(t){return t!==null&&typeof t=="object"&&t.quantized!==void 0}function rb(t,e){if(t.wrap){if(!Number.isFinite(e))return 0;let r=t.range,s=(e-t.min)%r;s<0&&(s+=r);let o=t.span;return Math.floor(s/r*o+.5)%o}if(e!==e)return 0;let n=e<t.min?t.min:e>t.max?t.max:e;return Math.floor((n-t.min)/t.range*t.span+.5)}function sb(t,e){return t.min+e/t.span*t.range}function mA(t){let e=Se[t.wire];return(n,r,s)=>e(n,rb(t,r),s)}function yA(t,e,n){let r=Pe[t.wire];return sb(t,r(e,n))}function gA(t){let e=typeof Object.keys(t)[0]=="string"&&tb(Object.keys(t)[0]);return{complexTypeKlass:e,childType:e?Object.values(t)[0]:t}}function ni(t){if(Array.isArray(t))return{array:ni(t[0])};if(Ys(t))return typeof t.quantized.wire=="string"?t:{quantized:rp(t.quantized)};if(typeof t.type<"u")return t.type;if(bA(t))return Object.keys(t).every(e=>typeof t[e]=="string")?"string":"number";if(typeof t=="object"&&t!==null){let e=Object.keys(t).find(n=>tp[n]!==void 0);if(e)return t[e]=ni(t[e]),t}return t}function bA(t){if(typeof t=="function"&&t[Symbol.metadata])return!1;let e=Object.keys(t),n=e.filter(r=>/\d+/.test(r));return!!(n.length>0&&n.length===e.length/2&&t[t[n[0]]]==n[0]||e.length>0&&e.every(r=>typeof t[r]=="string"&&t[r]===r))}function Du(t,e,n){t[e]||Object.defineProperty(t,e,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[e].push(n)}function Vu(t){return t=t-(t>>>1&1431655765),t=(t&858993459)+(t>>>2&858993459),(t+(t>>>4)&252645135)*16843009>>>24}function Nu(t){if(t===void 0)return 0;let e=0;for(let n=0,r=t.length;n<r;n++){let s=t[n];s<32&&(e|=1<<s)}return e}function SA(t){let e=[],n=[],r=[],s=[],o=t?.[At];if(o===void 0)return{names:e,types:n,tags:r,encoders:s};let i=t[vr];for(let a=0;a<=o;a++){let c=t[a];if(c===void 0){e[a]=void 0,n[a]=void 0,r[a]=void 0,s[a]=void 0;continue}e[a]=c.name,n[a]=c.type,r[a]=c.tag,s[a]=i?.[a]}return{names:e,types:n,tags:r,encoders:s}}function sp(t){let e=t.constructor;if(Object.prototype.hasOwnProperty.call(e,xa))return e[xa];let n=e[Symbol.metadata],r=De.isValidInstance(t),s=(n?.[On]?.length??0)>0,o=SA(n),i=r&&!s?void 0:e[Xs],a={encoder:e[cr],filter:i,metadata:n,isSchema:r,filterBitmask:r?Nu(n?.[On]):0,hasAnyFullStateOnly:(n?.[ei]?.length??0)>0,hasAnyUnreliable:(n?.[js]?.length??0)>0,hasAnyStream:(n?.[un]?.length??0)>0,hasAnyView:s,fullStateOnlyBitmask:Nu(n?.[ei]),unreliableBitmask:Nu(n?.[js]),streamBitmask:Nu(n?.[un]),names:o.names,types:o.types,tags:o.tags,encoders:o.encoders};return Object.defineProperty(e,xa,{value:a,enumerable:!1,writable:!0,configurable:!0}),a}function xA(t,e,n){if(t.parentRef){if(t.parentRef[I]===e[I]){t._parentIndex=n;return}if(ib(t,(r,s)=>r[I]===e[I])){t._parentIndex=n;return}}t.parentRef===void 0?(t.parentRef=e,t._parentIndex=n):(t.extraParents={ref:t.parentRef,index:t._parentIndex,next:t.extraParents},t.parentRef=e,t._parentIndex=n)}function _A(t,e,n){if(t.extraParents===void 0){t._parentIndex=n;return}if(t.parentRef[I]===e[I]){t._parentIndex=n;return}for(let r=t.extraParents;r!==void 0;r=r.next)if(r.ref[I]===e[I]){r.index=n;return}}function RA(t,e){if(t.parentRef&&t.parentRef[I]===e[I])return t.extraParents?(t.parentRef=t.extraParents.ref,t._parentIndex=t.extraParents.index,t.extraParents=t.extraParents.next):(t.parentRef=void 0,t._parentIndex=void 0),!0;let n=t.extraParents,r=null;for(;n;){if(n.ref[I]===e[I])return r?r.next=n.next:t.extraParents=n.next,!0;r=n,n=n.next}return t.parentRef===void 0}function EA(t,e){if(t.parentRef!==void 0&&e(t.parentRef,t._parentIndex))return{ref:t.parentRef,index:t._parentIndex};for(let n=t.extraParents;n!==void 0;n=n.next)if(e(n.ref,n.index))return{ref:n.ref,index:n.index}}function ib(t,e){if(t.parentRef!==void 0&&e(t.parentRef,t._parentIndex))return!0;for(let n=t.extraParents;n!==void 0;n=n.next)if(e(n.ref,n.index))return!0;return!1}function kA(t,e){if(t.parentRef&&t.parentRef[I]===e[I])return t._parentIndex;for(let n=t.extraParents;n!==void 0;n=n.next)if(n.ref[I]===e[I])return n.index}function AA(t){let e=[];t.parentRef&&e.push({ref:t.parentRef,index:t._parentIndex});let n=t.extraParents;for(;n;)e.push({ref:n.ref,index:n.index}),n=n.next;return e}function PA(t,e,n){let r=e.refTarget;if(e.isArray){let o=r.items,i=o[n];if(i!==void 0&&i[I]===t)return!0;for(let a=0,c=o.length;a<c;a++){let u=o[a];if(u!==void 0&&u[I]===t)return!0}return!1}let s=e.getValue(n);return s!==void 0&&s[I]===t}function vA(t,e){op(t,e,TA)}function op(t,e,n){let r=t.refTarget;if(r[be]!==void 0){if(t.isPatchOnly)return;if(Array.isArray(r.items)){let s=r.items;for(let o=0,i=s.length;o<i;o++)s[o]!==void 0&&n(e,o)}else if(r.journal!==void 0)for(let[s,o]of r.journal.keyByIndex)r.$items.has(o)&&n(e,s);else if(r.$items!==void 0)for(let s of r.$items.keys())n(e,s)}else{let s=t.metadata;if(!s)return;let o=s[At]??-1,i=s[Uu],a=t.encDescriptor.names;for(let c=0;c<=o;c++){let u=a[c];if(u===void 0||i&&i.includes(c))continue;let l=r[u];l!=null&&n(e,c)}}}function cb(t,e,n,r){MA(t,e,n),!t.isFullStateOnly&&(t.has()&&t.root?.enqueueChangeTree(t),t.unreliableRecorder?.has()&&t.root?.enqueueUnreliable(t),!t.has()&&!t.unreliableRecorder?.has()&&t.root?.enqueueChangeTree(t))}function MA(t,e,n){if(!e)return;let r=e[I],s=!r._isSchema,o;s?(e=r.parent,n=r.parentIndex,o=e?.[I].metadata):o=r.metadata;let i=(o?.[Ra]?.includes(n)?_a:0)|(o?.[ei]?.includes(n)?Qo:0),a=r.flags&HA|i,c=t.flags;if(t.flags=c|a,a&~c&Qo&&(t.reset(),t.unreliableRecorder?.reset()),!t.root?.types?.hasFilters)return;let d=o?.[On]?.includes(n)??!1,f=o?.[un]?.includes(n)??!1,h=r.isFiltered||d||f;if(t.isFiltered=h,f&&!s){t.isStreamCollection=!0;let p=np(t.ref);if(p.priority===void 0){let y=De.getStreamPriority(o,n);y!==void 0&&(p.priority=y)}t.root?.registerStream(t.ref)}if(h){let p=ub(t);t.isVisibilitySharedWithParent=r.isFiltered&&p&&!f&&(!d||s&&o[n].tag!==rl)}}function Xy(t){let e=t.pendingFilterRefresh;for(let n=0;n<e.length;n++){let r=e[n];(r.flags&Ea)!==0&&ip(r)}e.length=0}function ub(t){return t._isSchema||typeof t.refTarget[be]!="string"}function ip(t){t.flags&=~Ea;let e=t.root;if(e===void 0||t.parentRef===void 0)return;let n=ub(t),r=Jy(t,t.parentRef,t._parentIndex,n);for(let o=t.extraParents;o!==void 0&&r!==CA;o=o.next)r|=Jy(t,o.ref,o.index,n);if(r===0)return;t.isVisibilitySharedWithParent=(r&$u)!==0;let s=(r&Hu)===0;s!==t.isFiltered&&(t.isFiltered=s,!s&&!t.isFullStateOnly&&(t.forEachLiveWithCtx(t,ab),t.has()&&e.enqueueChangeTree(t),t.unreliableRecorder?.has()&&e.enqueueUnreliable(t)),t.forEachChildWithCtx(t,OA))}function Jy(t,e,n,r){let s=e[I];if(s.root!==t.root||!PA(t,s,n))return 0;s.flags&Ea&&ip(s);let o=lb;if(s._isSchema)s.encDescriptor.tags[n]!==void 0||s.isFieldStream(n)||(s.isFiltered?r&&(o|=$u):o|=Hu);else if(!s.isFiltered)o|=Hu;else if(r&&!s.isStreamCollection){let i=s.parent?.[I];(i?._isSchema?i.encDescriptor.tags[s.parentIndex]:void 0)!==rl&&(o|=$u)}return o}function IA(t,e,n,r){let s=t.subscribedViews;if(s===void 0)return;let o=t.isStreamCollection,i=o?t.ref:void 0,a=o?void 0:n[I];for(let c=0,u=s.length;c<u;c++){let l=s[c];for(;l!==0;){let d=l&-l;l^=d;let f=c*32+(31-Math.clz32(d)),p=r.activeViews.get(f)?.deref();if(p===void 0){s[c]&=~d;continue}o?pA(i,f,e):a!==void 0&&p.markVisible(a)}}}function DA(t,e){t.root=e;let n=e.add(t);cb(t,t.parent,t.parentIndex),n&&Ca(t,e,FA)}function NA(t,e,n,r){if(t.addParent(e,r),!n)return;let s=n.add(t);n!==t.root&&(t.root=n,cb(t,e,r));let o=e?.[I];if(o!==void 0&&o.subscribedViews!==void 0&&e[be]!==void 0&&IA(o,r,t.ref,n),s){let i=Zy[Bu];i===void 0&&(i={parentRef:void 0,root:void 0},Zy[Bu]=i),i.parentRef=t.ref,i.root=n,Bu++,Ca(t,i,zA),Bu--}}function BA(t,e){Ca(t,e,LA)}function LA(t,e,n){t(e,n)}function Ca(t,e,n){let r=t.refTarget;if(r[be]){if(typeof r[be]!="string"){let s=r.items;if(s!==void 0)for(let o=0,i=s.length;o<i;o++){let a=s[o];a&&n(e,a[I],o)}else{let o=r.$items,i=r._collectionIndexes;for(let a of o.keys()){let c=o.get(a);c&&n(e,c[I],i?.[a]??a)}}}}else{let o=t.metadata?.[ls];if(!o)return;let i=t.encDescriptor.names;for(let a=0,c=o.length;a<c;a++){let u=o[a],l=r[i[u]];l&&n(e,l[I],u)}}}function FA(t,e,n){e.root!==t?e.setRoot(t):t.add(e)}function zA(t,e,n){if(e.root===t.root){t.root.add(e),t.root.moveNextToParent(e);return}e.setParent(t.parentRef,t.root,n)}function UA(t,e,n){let r=(n&3)<<3;return n<4?t>>>r&255:e>>>r&255}function Qy(){return{next:void 0,tail:void 0,nextPosition:0}}function $A(t){return new Jf(t)}function si(t,e=t){Object.defineProperty(t,I,{value:$A(e),enumerable:!1,writable:!0})}function el(t,e,n,r,s,o,i){i!==void 0?i(e,r,o):typeof n=="string"?Se[n]?.(e,r,o):n[Symbol.metadata]!=null?(Se.number(e,r[Q],o),(s&N.ADD)===N.ADD&&t.tryEncodeTypeId(e,n,r.constructor,o)):Se.number(e,r[Q],o)}function db(t,e,n,r,s,o,i){let a=t.resyncVisited,c=a.get(t.currentRefId);if(c===void 0&&a.set(t.currentRefId,c=new Set),c.add(r),s!==void 0&&n===N.ADD&&s!==o){let u=s[Q];u!==void 0&&(t.root.removeRef(u),i?.push({ref:e,refId:t.currentRefId,op:N.DELETE,dynamicIndex:r,value:void 0,previousValue:s}))}}function GA(t,e){let n=t.resyncVisited;n.has(e)||n.set(e,new Set)}function YA(t,e){if(t.resyncDamaged){console.warn("@colyseus/schema: resync sweep skipped \u2014 parts of the payload could not be decoded. Stale entries may persist until the next resync.");return}up(t,t.state,new Set,e)}function up(t,e,n,r){let s=e[Q];if(s===void 0||n.has(s))return;n.add(s);let o=e.constructor[Symbol.metadata],i=o?.[ls];if(i===void 0)return;let a=o[Ra];for(let c=0;c<i.length;c++){let u=i[c];if(a!==void 0&&a.includes(u))continue;let l=o[u],d=e[l.name];d&&(Xe.is(l.type)?up(t,d,n,r):KA(t,d,n,r))}}function KA(t,e,n,r){let s=e[lt]??e,o=s[Q];if(o===void 0||n.has(o))return;n.add(o);let i=t.resyncVisited.get(o);if(i===void 0)return;let a=t.root;s[ri](i,(c,u)=>{r?.push({ref:e,refId:o,op:N.DELETE,dynamicIndex:u,value:void 0,previousValue:c});let l=c?.[Q];l!==void 0&&a.removeRef(l)},c=>{Xe.isSchema(c)&&up(t,c,n,r)})}function lp(t,e,n,r,s,o,i,a,c){let u=t.root,l;if((e&N.DELETE)===N.DELETE){let d=s?.[Q];d!==void 0&&u.removeRef(d),e!==N.DELETE_AND_ADD&&n[Bn](r),l=void 0}if(e!==N.DELETE)if(typeof o=="string")l=Pe[o](i,a);else if(Ys(o))l=yA(o.quantized,i,a);else if(Xe.is(o)){let d=Pe.number(i,a);if(l=u.refs.get(d),(e&N.ADD)===N.ADD){let f=t.getInstanceType(i,a,o);l||(l=t.createInstanceOfType(f)),u.addRef(d,l,l!==s||e===N.DELETE_AND_ADD&&l===s)}}else{let d=tb(Object.keys(o)[0]),f=Pe.number(i,a);t.resyncVisited!==null&&GA(t,f);let h=u.refs.has(f)?s||u.refs.get(f):d.constructor.initializeForDecoder();if(l=h.clone(!0),l[be]=Object.values(o)[0],s){let p=s[Q];if(p!==void 0&&f!==p){(e&N.DELETE)!==N.DELETE&&u.removeRef(p);let y=s.entries(),S;for(;(S=y.next())&&!S.done;){let[b,x]=S.value;typeof x=="object"&&(p=x[Q]),c?.push({ref:s,refId:p,op:N.DELETE,field:b,value:void 0,previousValue:x})}}}u.addRef(f,l,h!==s||e===N.DELETE_AND_ADD&&h===s)}return l}function nl(t,e,n,r){if(!(t instanceof e))throw new ka(`a '${e.name}' was expected, but '${t&&t.constructor.name}' was provided in ${n.constructor.name}#${r}`)}function pb(t){return t!=null&&t[Fg]===!0}function Ft(t){return(()=>new ur(t))}function Oa(t){if(pb(t)){let e=t._type,n=typeof e=="string"?`use the type name instead: t.array("${e}")`:'collections accept a Schema class or a primitive type name ("string", "number", \u2026)';throw new Error(`t.array/map/set/collection(): a t.* builder is not a valid element type \u2014 ${n}.`)}return t}function tg(t){return new ur({quantized:rp(t)})}function oP(t=rl){return function(e,n){let r=De.initialize(e.constructor);De.setTag(r,n,t)}}function iP(t,e){let n=De.initialize(t.constructor);De.setUnreliable(n,e)}function aP(t,e){let n=De.initialize(t.constructor);De.setPatchOnly(n,e)}function uP(t,e,n){let r=cP[n],s=n==="string",o=n==="boolean";return function(i){let a=this[Mt],c=a[e];if(i!==c){if(i!=null){if(!o&&r!==void 0&&typeof i!==r&&!(s&&i===null)){let u=i&&i.constructor?` (${i.constructor.name})`:"";throw new ka(`a '${r}' was expected, but '${JSON.stringify(i)}'${u} was provided in ${this.constructor.name}#${t}`)}this.constructor[ar](this[I],e,N.ADD)}else c!=null&&this[I].delete(e);a[e]=i}}}function lP(t,e,n){return function(r){let s=this[Mt],o=s[e];if(r!==o){if(r!=null){nl(r,n,this,t);let i=this[I],a=this.constructor;o!=null&&o[I]?(i.root?.remove(o[I]),a[ar](i,e,N.DELETE_AND_ADD)):a[ar](i,e,N.ADD),r[I]?.setParent(this,i.root,e)}else o!=null&&this[I].delete(e);s[e]=r}}}function dP(t,e,n,r){let s=r.constructor===ds,o=r.constructor===fs;return function(i){let a=this[Mt],c=a[e];if(i!==c){if(i!=null){if(s&&!(i instanceof ds)){let d=new ds;d[be]=n,d.push(...i),i=d}else if(o&&!(i instanceof fs)){let d=new fs;if(d[be]=n,i instanceof Map)i.forEach((f,h)=>d.set(h,f));else for(let f in i)d.set(f,i[f]);i=d}else i[be]=n;let u=this[I],l=this.constructor;c!=null&&c[I]?(u.root?.remove(c[I]),l[ar](u,e,N.DELETE_AND_ADD)):l[ar](u,e,N.ADD),i[I]?.setParent(this,u.root,e)}else c!=null&&this[I].delete(e);a[e]=i}}}function fP(t,e,n){return function(r){let s=this[Mt],o=s[e];if(r!=null){if(typeof r!="number")throw new ka(`a 'number' was expected, but '${JSON.stringify(r)}' was provided in ${this.constructor.name}#${t}`);if(r=sb(n,rb(n,r)),r===o)return;this.constructor[ar](this[I],e,N.ADD)}else{if(r===o)return;o!=null&&this[I].delete(e)}s[e]=r}}function pP(t,e,n,r){let s;return r?s=dP(t,e,n,r):typeof n=="string"?s=uP(t,e,n):Ys(n)?s=fP(t,e,n.quantized):s=lP(t,e,n),{get:function(){return this[Mt][e]},set:s,enumerable:!0,configurable:!0}}function hP(t=!0){return function(e,n){let r=De.initialize(e.constructor);De.setDeprecated(r,n),t&&(r[cn]??(r[cn]={}),r[cn][n]={get:function(){throw new Error(`${n} is deprecated.`)},set:function(s){},enumerable:!1,configurable:!0},Object.defineProperty(e,n,r[cn][n]))}}function mP(t){if(t&&typeof t=="object"){if(t.array!==void 0)return()=>new ds;if(t.map!==void 0)return()=>new fs;if(t.set!==void 0)return()=>new Pa;if(t.collection!==void 0)return()=>new Aa;if(t.stream!==void 0)return()=>new Wu}else if(typeof t=="function"&&Xe.is(t)&&(!t.prototype.initialize||t.prototype.initialize.length===0))return()=>new t}function zt(t,e,n=Xe){if(t==null||typeof t!="object")throw new Error(`schema(): first argument must be a fields object (got ${typeof t}).`);let r={},s={},o={},i={},a=(k,M)=>{typeof M=="function"?i[k]=M:M&&typeof M.clone=="function"?i[k]=()=>M.clone():o[k]=M},c=(k,M)=>{if(M.hasDefault)a(k,M.default);else if(!M.optional){let B=mP(M.type);B&&(i[k]=B)}},u={},l=[],d=[],f={},h=[],p=[],y={},S=[];for(let k in t){let M=t[k];if(pb(M)){let B=M.toDefinition();if(B.noSync){if(B.view!==void 0||B.unreliable||B.patchOnly||B.fullStateOnly||B.stream)throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' uses .noSync() together with a sync-only modifier (.view/.unreliable/.patchOnly/.fullStateOnly/.stream). A local-only field cannot be synchronized.`);c(k,B);continue}if(B.patchOnly&&B.fullStateOnly)throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' uses .patchOnly() together with .fullStateOnly(). Those are the only two delivery channels, so the field would never reach a client \u2014 use .noSync() if that is intended.`);let K=ni(B.type);if(typeof K=="function"&&!Xe.is(K))throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' is a synced ref to non-Schema class '${K.name||"(anonymous)"}' \u2014 use .noSync(), or Metadata.setFields().`);r[k]=K,B.view!==void 0&&(u[k]=B.view),B.unreliable&&l.push(k),B.patchOnly&&d.push(k),B.deprecated&&(f[k]=B.deprecatedThrows),B.fullStateOnly&&h.push(k),B.stream&&p.push(k),B.streamPriority!==void 0&&(y[k]=B.streamPriority),B.optional&&S.push(k),c(k,B)}else if(typeof M=="function")Xe.is(M)?(r[k]=ni(M),(!M.prototype.initialize||M.prototype.initialize.length===0)&&(i[k]=()=>new M)):s[k]=M;else throw new Error(`schema(${e?`'${e}'`:""}): field '${k}' must be a t.* builder, Schema subclass, or method (got ${typeof M}).`)}let b=k=>{for(let M in o)k[M]=o[M];for(let M in i)k[M]=i[M]()},x=()=>{let k={};return b(k),k},R=k=>{let M=Object.keys(r),B={};for(let K in k)M.includes(K)||(B[K]=k[K]);return B},A=typeof s.initialize=="function",E=s.initialize??n._initialize,P=class extends n{constructor(...k){let M=k[0];M===void 0?(super(),b(this)):super(Object.assign(x(),A?R(M):M)),E&&new.target===P&&E.apply(this,k)}};e&&Object.defineProperty(P,"name",{value:e}),De.setFields(P,r),P._getDefaultValues=x,P._initialize=E,Object.assign(P.prototype,s);for(let k in u)oP(u[k])(P.prototype,k);for(let k of l)iP(P.prototype,k);for(let k of d)aP(P.prototype,k);for(let k in f)hP(f[k])(P.prototype,k);if(h.length>0||p.length>0){let k=P[Symbol.metadata];for(let M of h)De.setFullStateOnly(k,M);for(let M of p)De.setStream(k,M);for(let M in y)De.setStreamPriority(k,M,y[M])}if(S.length>0){let k=P[Symbol.metadata];for(let M of S)k[k[M]].optional=!0}return P.extend=(k,M)=>zt(k,M,P),P}function yP(t){return new Array(t).fill(0).map((e,n)=>n===t-1?"\u2514\u2500 ":" ").join("")}function gP(t,e){if(e===-1||e>=t.length)return!1;let n=t.length-1;for(let r=e;r<n;r++)t[r]=t[r+1];return t.length=n,!0}function bP(t,e,n){let r=~n,s=t.changeTrees;for(let o in s){let i=s[o],a=i.visibleViews;a!==void 0&&e<a.length&&(a[e]&=r);let c=i.subscribedViews;c!==void 0&&e<c.length&&(c[e]&=r);let u=i.tagViews;u!==void 0&&u.forEach(l=>{e<l.length&&(l[e]&=r)})}}function rg(t){t.structSwitchEmitted||(t.shouldEmitSwitch&&(t.buffer[t.it.offset++]=255,Se.number(t.buffer,t.ref[Q],t.it)),t.structSwitchEmitted=!0)}function SP(t,e){mb(t,e,N.ADD)}function hb(t,e){if(e._fullSyncGen===t.gen)return;if(e._fullSyncGen=t.gen,!t.hasView||t.view.isChangeTreeVisible(e)){let r=e.encDescriptor;t.changeTree=e,t.ref=e.ref,t.encoder=r.encoder,t.filter=r.filter,t.metadata=r.metadata,t.treeIsFiltered=e.isFiltered,t.isSchema=r.isSchema,t.filterBitmask=r.filterBitmask,t.tags=r.tags,t.structSwitchEmitted=!1,t.shouldEmitSwitch=t.hasView||t.it.offset>t.initialOffset||e!==t.rootChangeTree,e.isArray&&e.collDirty.size>0&&(e.flags|=ap),op(e,t,SP)}Ca(e,t,xP)}function xP(t,e,n){hb(t,e)}function mb(t,e,n){if(e<0){if(t.treeIsFiltered!==t.emitFiltered)return;rg(t),t.buffer[t.it.offset++]=Math.abs(e)&255;return}if((t.isSchema?t.treeIsFiltered||(e<32?(t.filterBitmask&1<<e)!==0:t.tags[e]!==void 0):t.treeIsFiltered)!==t.emitFiltered)return;let s=t.isEncodeAll?N.ADD:n;s!==void 0&&(t.filter!==void 0&&!t.filter(t.ref,e,t.view)||(rg(t),t.encoder(t.self,t.buffer,t.changeTree,e,s,t.it,t.isEncodeAll,t.hasView,t.metadata)))}function qf(t,e){let n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function Gu(t){let e=t.root,n=e.callbacks,r=new WeakMap,s;t.triggerChanges=function(a){let c=new Set;for(let u=0,l=a.length;u<l;u++){let d=a[u],f=d.refId,h=d.ref,p=n[f];if(p){if((d.op&N.DELETE)===N.DELETE&&Xe.isSchema(d.previousValue)){let y=n[d.previousValue[Q]]?.[N.DELETE];for(let S=y?.length-1;S>=0;S--)y[S]()}if(Xe.isSchema(h)){if(!c.has(f)){let y=p?.[N.REPLACE];for(let S=y?.length-1;S>=0;S--)y[S]()}if(p.hasOwnProperty(d.field)){let y=p[d.field];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.previousValue)}}else{if((d.op&N.DELETE)===N.DELETE){if(d.previousValue!==void 0){let y=p[N.DELETE];for(let S=y?.length-1;S>=0;S--)y[S](d.previousValue,d.dynamicIndex??d.field)}if((d.op&N.ADD)===N.ADD){let y=p[N.ADD];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.dynamicIndex??d.field)}}else if((d.op&N.ADD)===N.ADD&&d.previousValue!==d.value){let y=p[N.ADD];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.dynamicIndex??d.field)}if(d.value!==d.previousValue&&(d.value!==void 0||d.previousValue!==void 0)){let y=p[N.REPLACE];for(let S=y?.length-1;S>=0;S--)y[S](d.value,d.dynamicIndex??d.field)}}c.add(f)}}};function o(a,c){let u=c.instance?.constructor[Symbol.metadata]||a,l=c.instance&&typeof c.instance.forEach=="function"||a&&!Xe.is(a);if(u&&!l){let d=function(f,h,p,y){return y&&c.instance[h]!==void 0&&!r.has(s)&&p(c.instance[h],void 0),e.addCallback(f[Q],h,p)};return new Proxy({listen:function(h,p,y=!0){if(c.instance)return d(c.instance,h,p,y);{let S=()=>{};return c.onInstanceAvailable((b,x)=>{S=d(b,h,p,y&&x&&!r.has(s))}),()=>S()}},onChange:function(h){return e.addCallback(c.instance[Q],N.REPLACE,h)},bindTo:function(h,p){return p||(p=Object.keys(u).map(y=>u[y].name)),e.addCallback(c.instance[Q],N.REPLACE,()=>{p.forEach(y=>h[y]=c.instance[y])})}},{get(f,h){let p=u[u[h]];if(p){let y=c.instance?.[h],S=(b=>{let x=i(c.instance).listen(h,(R,A)=>{b(R,!1),x?.()},!1);y?.[Q]!==void 0&&b(y,!0)});return o(p.type,{instance:y?.[Q]!==void 0&&y,parentInstance:c.instance,onInstanceAvailable:S})}else return f[h]},has(f,h){return u[h]!==void 0},set(f,h,p){throw new Error("not allowed")},deleteProperty(f,h){throw new Error("not allowed")}})}else{let d=function(p,y,S){return S&&p.forEach((b,x)=>y(b,x)),e.addCallback(p[Q],N.ADD,(b,x)=>{r.set(y,!0),s=y,y(b,x),r.delete(y),s=void 0})},f=function(p,y){return e.addCallback(p[Q],N.DELETE,y)},h=function(p,y){return e.addCallback(p[Q],N.REPLACE,y)};return new Proxy({onAdd:function(p,y=!0){if(c.instance)return d(c.instance,p,y&&!r.has(s));if(c.onInstanceAvailable){let S=()=>{};return c.onInstanceAvailable((b,x)=>{S=d(b,p,y&&x&&!r.has(s))}),()=>S()}},onRemove:function(p){if(c.instance)return f(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(S=>{y=f(S,p)}),()=>y()}},onChange:function(p){if(c.instance)return h(c.instance,p);if(c.onInstanceAvailable){let y=()=>{};return c.onInstanceAvailable(S=>{y=h(S,p)}),()=>y()}}},{get(p,y){if(!p[y])throw new Error(`Can't access '${y}' through callback proxy. access the instance directly.`);return p[y]},has(p,y){return p[y]!==void 0},set(p,y,S){throw new Error("not allowed")},deleteProperty(p,y){throw new Error("not allowed")}})}}function i(a){return o(void 0,{instance:a})}return i}function _P(t,e){t.triggerChanges=e}var N,Yy,Q,ar,cr,Dn,Xs,st,Bn,ri,I,be,lt,us,Nn,zu,Mt,Fg,cn,xa,vr,At,ls,On,Tr,js,Ra,Uu,ei,un,Iu,Wk,Ku,Ws,Gf,qk,zg,Gk,Ug,Se,va,Gs,Qk,eA,tA,nA,Pe,tp,uA,nb,hA,sr,Ks,Ky,wA,De,ob,Kf,Xf,ab,TA,lb,Hu,$u,CA,OA,Zy,Bu,VA,$f,jf,Sa,Wf,_a,Qo,Fu,Lu,Ea,ap,HA,ps,Jf,jA,WA,cp,qA,fb,In,XA,tl,JA,ka,ZA,eg,og,ig,ag,cg,ug,lg,dg,an,ds,ju,fg,pg,hg,mg,yg,or,fs,gg,bg,wg,Sg,xg,as,Aa,_g,Rg,Eg,kg,Ag,cs,Pa,Pg,Tg,vg,Mg,Cg,Mr,Wu,Og,ur,QA,eP,tP,nP,rP,sP,Y,rl,cP,Ig,Dg,Ng,Bg,Cn,Xe,ng,Zf,HB,wP,ir,Ta,qu,sg,Qf,Fn,yb,gb,bb,zn,Yu,dp,Pt=ht(()=>{"use strict";(function(t){t[t.ADD=128]="ADD",t[t.REPLACE=0]="REPLACE",t[t.DELETE=64]="DELETE",t[t.DELETE_AND_MOVE=96]="DELETE_AND_MOVE",t[t.MOVE_AND_ADD=160]="MOVE_AND_ADD",t[t.DELETE_AND_ADD=192]="DELETE_AND_ADD",t[t.CLEAR=10]="CLEAR",t[t.REVERSE=15]="REVERSE",t[t.MOVE=32]="MOVE",t[t.DELETE_BY_REFID=33]="DELETE_BY_REFID",t[t.ADD_BY_REFID=129]="ADD_BY_REFID"})(N||(N={}));Symbol.metadata??(Symbol.metadata=Symbol.for("Symbol.metadata"));Yy=(function(){return typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{}})();if(typeof Symbol=="function"&&typeof Symbol.for!="function"){let t="colyseus.symbolRegistry",e=Yy[t]||(Yy[t]=Object.create(null));Symbol.for=function(n){return e[n]||(e[n]=Symbol(n))},Symbol.keyFor=function(n){for(let r in e)if(e[r]===n)return r}}Q=Symbol.for("$refId"),ar="~track",cr="~encoder",Dn="~decoder",Xs="~filter",st="~getByIndex",Bn="~deleteByIndex",ri="~resyncPrune",I=Symbol.for("$changes"),be=Symbol.for("$childType"),lt=Symbol.for("$proxyTarget"),us="~onEncodeEnd",Nn="~reset",zu="~onDecodeEnd",Mt=Symbol.for("$values"),Fg="~builder",cn="~descriptors",xa="~__encodeDescriptor",vr="~encoders",At="~__numFields",ls="~__refTypeFieldIndexes",On="~__viewFieldIndexes",Tr="$__fieldIndexesByViewTag",js="~__unreliableFieldIndexes",Ra="~__patchOnlyFieldIndexes",Uu="~__fullSyncSkipIndexes",ei="~__fullStateOnlyFieldIndexes",un="~__streamFieldIndexes",Iu="~__streamPriorities";try{Wk=new TextEncoder}catch{}Ku=new ArrayBuffer(8),Ws=new Int32Array(Ku),Gf=new Float32Array(Ku),qk=new Float64Array(Ku),zg=new BigInt64Array(Ku),Gk=typeof Buffer<"u"&&Buffer.byteLength,Ug=Gk?Buffer.byteLength:function(t,e){for(var n=0,r=0,s=0,o=t.length;s<o;s++)n=t.charCodeAt(s),n<128?r+=1:n<2048?r+=2:n<55296||n>=57344?r+=3:(s++,r+=4);return r};Se={int8:Hg,uint8:Yk,int16:$g,uint16:ep,int32:Cr,uint32:qs,int64:jg,uint64:Wg,bigint64:Kk,biguint64:Xk,float32:qg,float64:Gg,boolean:Jk,string:Zk,number:Yf,utf8Write:Vg,utf8Length:Ug},va=new ArrayBuffer(8),Gs=new Int32Array(va),Qk=new Float32Array(va),eA=new Float64Array(va),tA=new BigUint64Array(va),nA=new BigInt64Array(va);Pe={utf8Read:Yg,int8:Kg,uint8:Ma,int16:Xg,uint16:Xu,int32:Ln,uint32:ti,float32:Jg,float64:Zg,int64:Qg,uint64:eb,bigint64:rA,biguint64:sA,boolean:oA,string:iA,number:aA,stringCheck:cA},tp={},uA=new Map;nb="ArraySchema does not support streaming \u2014 positional ops (splice / unshift / reverse) shift subsequent indexes, so holding ADDs back for a later tick under `maxPerTick` would desync the decoder. Use `t.stream(X)` (stable monotonic positions) or `t.map(X).stream()` (stable keys) instead.";hA={8:"uint8",16:"uint16",32:"uint32"};sr=class sr{constructor(e){m(this,"types",{});m(this,"schemas",new Map);m(this,"hasFilters",!1);e&&this.discoverTypes(e)}static register(e){let n=Object.getPrototypeOf(e);if(n!==Xe){let r=sr.inheritedTypes.get(n);r||(r=new Set,sr.inheritedTypes.set(n,r)),r.add(e)}}static cache(e){let n=sr.cachedContexts.get(e);return n||(n=new sr(e),sr.cachedContexts.set(e,n)),n}has(e){return this.schemas.has(e)}get(e){return this.types[e]}add(e,n=this.schemas.size){return this.schemas.has(e)?!1:(this.types[n]=e,e[Symbol.metadata]==null&&De.initialize(e),this.schemas.set(e,n),!0)}getTypeId(e){return this.schemas.get(e)}discoverTypes(e){if(!this.add(e))return;sr.inheritedTypes.get(e)?.forEach(s=>{this.discoverTypes(s)});let n=e;for(;(n=Object.getPrototypeOf(n))&&n!==Xe&&n!==Function.prototype;)this.discoverTypes(n);let r=e[Symbol.metadata];(r[On]||r[un])&&(this.hasFilters=!0);for(let s in r){let i=r[s].type;if(typeof i!="string"&&!Ys(i))if(typeof i=="function")this.discoverTypes(i);else{let a=Object.values(i)[0];if(typeof a=="string")continue;this.discoverTypes(a)}}}debug(){return`TypeContext ->
|
|
2
2
|
Schema types: ${this.schemas.size}
|
|
3
|
-
hasFilters: ${this.hasFilters}`}};m(
|
|
4
|
-
Schema instances may only have up to ${Yy} fields.`);t[e]=Object.assign(t[e]||{},{type:ni(r),index:e,name:n}),Object.defineProperty(t,an,{value:t[an]||{},enumerable:!1,configurable:!0}),s?t[an][n]=s:t[an][n]={value:void 0,writable:!0,enumerable:!0,configurable:!0},Object.defineProperty(t,kt,{value:e,enumerable:!1,configurable:!0}),Object.defineProperty(t,n,{value:e,enumerable:!1,configurable:!0}),typeof t[e].type!="string"&&!Ys(t[e].type)&&(t[us]===void 0&&Object.defineProperty(t,us,{value:[],enumerable:!1,configurable:!0}),t[us].push(e));let o=t[e].type;if(o&&typeof o=="object"&&o.stream!==void 0){if(o.array!==void 0)throw new Error(tb);t[e].stream=!0,t[cn]||Object.defineProperty(t,cn,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[cn].includes(e)||t[cn].push(e);let i=r?.priority;typeof i=="function"&&Ie.setStreamPriority(t,n,i)}},setTag(t,e,n){let r=t[e],s=t[r];if(s.tag=n,t[Cn]||(Object.defineProperty(t,Cn,{value:[],enumerable:!1,configurable:!0}),Object.defineProperty(t,Pr,{value:{},enumerable:!1,configurable:!0})),t[Cn].push(r),n<0)t[Pr][n]||(t[Pr][n]=[]),t[Pr][n].push(r);else for(let o=n;o>0;o&=o-1){let i=o&-o;t[Pr][i]||(t[Pr][i]=[]),t[Pr][i].push(r)}},setUnreliable(t,e){let n=t[e];if(typeof t[n].type!="string")throw new Error(`@unreliable cannot be applied to ref-type field "${e}". For ref-type fields, mark each primitive sub-field with @unreliable instead. See README "Limitations and best practices".`);t[n].unreliable=!0,t[js]||Object.defineProperty(t,js,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[js].push(n)},setPatchOnly(t,e){let n=t[e];if(t[n].fullStateOnly)throw new Error(`field "${e}" cannot be both patchOnly and fullStateOnly \u2014 those are the only two delivery channels, so the field would never reach a client.`);t[n].patchOnly=!0,Du(t,Ra,n),Du(t,Uu,n)},setDeprecated(t,e){let n=t[e];t[n].deprecated=!0,Du(t,Uu,n),Object.defineProperty(t,n,{value:t[n],enumerable:!1,configurable:!0})},setFullStateOnly(t,e){let n=t[e];if(t[n].patchOnly)throw new Error(`field "${e}" cannot be both patchOnly and fullStateOnly \u2014 those are the only two delivery channels, so the field would never reach a client.`);t[n].fullStateOnly=!0,Du(t,ei,n)},setStream(t,e){let n=t[e];t[n].stream=!0,t[cn]||Object.defineProperty(t,cn,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[cn].push(n)},setStreamPriority(t,e,n){let r=t[e];t[Iu]||Object.defineProperty(t,Iu,{value:{},enumerable:!1,configurable:!0,writable:!0}),t[Iu][r]=n},getStreamPriority(t,e){return t?.[Iu]?.[e]},defineField(t,e,n,r,s){let o=ni(s),{complexTypeKlass:i,childType:a}=mA(o);Ie.addField(e,n,r,o,dP(r,n,a,i)),e[an][r]&&Object.defineProperty(t.prototype,r,e[an][r]),(typeof o=="string"||Ys(o))&&(e[Tr]||Object.defineProperty(e,Tr,{value:[],enumerable:!1,configurable:!0,writable:!0}),e[Tr][n]=typeof o=="string"?Se[o]:pA(o.quantized))},setFields(t,e){let n=t.prototype.constructor;Ks.register(n);let r=Object.getPrototypeOf(n),s=r&&r[Symbol.metadata],o=Ie.initialize(n);n[or]||(n[or]=Xe[or]),n[ir]||(n[ir]=Xe[ir]),n[In]||(n[In]=Xe[In]),n.prototype.toJSON||(n.prototype.toJSON=Xe.prototype.toJSON);let i=o[kt]??(s&&s[kt])??-1;i++,o[Tr]||Object.defineProperty(o,Tr,{value:s?.[Tr]?[...s[Tr]]:[],enumerable:!1,configurable:!0,writable:!0});for(let a in e){if(o[a]!==void 0)throw new Error(`@colyseus/schema: Duplicate '${a}' definition on '${n.name||"(anonymous)"}'.`);Ie.defineField(n,o,i,a,e[a]),i++}return t},isDeprecated(t,e){return t[e].deprecated===!0},initialize(t){let e=Object.getPrototypeOf(t),n=e[Symbol.metadata],r=t[Symbol.metadata]??Object.create(null);if(e!==Xe&&r===n&&(r=Object.create(null),n)){Object.setPrototypeOf(r,n),Object.defineProperty(r,kt,{value:n[kt],enumerable:!1,configurable:!0,writable:!0}),n[Cn]!==void 0&&(Object.defineProperty(r,Cn,{value:[...n[Cn]],enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(r,Pr,{value:{...n[Pr]},enumerable:!1,configurable:!0,writable:!0}));for(let s of gA){let o=n[s];o!==void 0&&Object.defineProperty(r,s,{value:[...o],enumerable:!1,configurable:!0,writable:!0})}Object.defineProperty(r,an,{value:{...n[an]},enumerable:!1,configurable:!0,writable:!0})}return Object.defineProperty(t,Symbol.metadata,{value:r,writable:!1,configurable:!0}),r},isValidInstance(t){return t.constructor[Symbol.metadata]&&Object.prototype.hasOwnProperty.call(t.constructor[Symbol.metadata],kt)},getFields(t){let e=t[Symbol.metadata],n={};for(let r=0;r<=e[kt];r++)n[e[r].name]=e[r].type;return n},hasViewTagAtIndex(t,e){return t?.[Cn]?.includes(e)},hasUnreliableAtIndex(t,e){return t?.[js]?.includes(e)},hasPatchOnlyAtIndex(t,e){return t?.[Ra]?.includes(e)},hasFullStateOnlyAtIndex(t,e){return t?.[ei]?.includes(e)},hasStreamAtIndex(t,e){return t?.[cn]?.includes(e)}},sb=(t,e,n)=>t(e,n),Yf=class{constructor(e){m(this,"dirtyLow",0);m(this,"dirtyHigh",0);m(this,"ops");this.ops=new Uint8Array(Math.max(e+1,1))}record(e,n){let r=this.ops[e];r===0?this.ops[e]=n:r===N.DELETE?this.ops[e]=N.DELETE_AND_ADD:r===N.ADD&&n===N.DELETE_AND_ADD&&(this.ops[e]=N.DELETE_AND_ADD),e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordDelete(e,n){this.ops[e]=n,e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordRaw(e,n){this.record(e,n)}operationAt(e){let n=this.ops[e];return n===0?void 0:n}setOperationAt(e,n){this.ops[e]=n}forEach(e){this.forEachWithCtx(e,sb)}forEachWithCtx(e,n){let r=this.dirtyLow,s=this.dirtyHigh,o=this.ops;for(;r!==0;){let i=r&-r,a=31-Math.clz32(i);r^=i,n(e,a,o[a])}for(;s!==0;){let i=s&-s,a=31-Math.clz32(i)+32;s^=i,n(e,a,o[a])}}size(){return Vu(this.dirtyLow)+Vu(this.dirtyHigh)}has(){return(this.dirtyLow|this.dirtyHigh)!==0}reset(){this.dirtyLow=0,this.dirtyHigh=0,this.ops.fill(0)}},Kf=class{constructor(){m(this,"dirty",new Map);m(this,"pureOps",[])}record(e,n){let r=this.dirty.get(e);r===void 0?this.dirty.set(e,n):r===N.DELETE?this.dirty.set(e,N.DELETE_AND_ADD):r===N.ADD&&n===N.DELETE_AND_ADD&&this.dirty.set(e,N.DELETE_AND_ADD)}recordDelete(e,n){this.dirty.set(e,n)}recordRaw(e,n){this.dirty.set(e,n)}recordPure(e){this.pureOps.push([this.dirty.size,e])}operationAt(e){return this.dirty.get(e)}setOperationAt(e,n){this.dirty.has(e)&&this.dirty.set(e,n)}forEach(e){this.forEachWithCtx(e,sb)}forEachWithCtx(e,n){let r=this.pureOps;if(r.length>0){let s=0,o=0;for(let[i,a]of this.dirty){for(;s<r.length&&r[s][0]<=o;){let c=r[s++][1];n(e,-c,c)}n(e,i,a),o++}for(;s<r.length;){let i=r[s++][1];n(e,-i,i)}}else for(let[s,o]of this.dirty)n(e,s,o)}size(){return this.dirty.size+this.pureOps.length}has(){return this.dirty.size>0||this.pureOps.length>0}reset(){this.dirty.clear(),this.pureOps.length=0}shift(e){let n=new Map;for(let[r,s]of this.dirty)n.set(r+e,s);this.dirty=n}};ib=(t,e)=>{t.isFieldUnreliable(e)?t.ensureUnreliableRecorder().record(e,N.ADD):t.record(e,N.ADD)},AA=(t,e)=>t(e);ub=1,Hu=2,$u=4,vA=ub|Hu|$u;MA=(t,e,n)=>{op(e)};Jy=[],Bu=0;zA=(t,e,n)=>t(e,n);Hf=1,$f=2,Sa=4,jf=8,_a=16,Qo=32,Fu=64,Lu=128,Ea=256,ip=512,UA=_a|Qo,fs=class{constructor(e,n=e){m(this,"ref");m(this,"refTarget");m(this,"metadata");m(this,"encDescriptor");m(this,"root");m(this,"parentRef");m(this,"_parentIndex");m(this,"extraParents");m(this,"flags",Sa);m(this,"_fullSyncGen",0);m(this,"_isSchema",!1);m(this,"dirtyLow",0);m(this,"dirtyHigh",0);m(this,"opsLow",0);m(this,"opsHigh",0);m(this,"ops");m(this,"collDirty");m(this,"collPureOps");m(this,"unreliableRecorder");m(this,"paused",!1);m(this,"changesNode");m(this,"unreliableChangesNode");m(this,"visibleViews");m(this,"tagViews");m(this,"subscribedViews");this.ref=e,this.refTarget=n;let r=rp(e);this.encDescriptor=r,this.metadata=r.metadata;let s=r.isSchema;if(this._isSchema=s,this.ops=void 0,this.collDirty=void 0,this.collPureOps=void 0,s){let o=this.metadata?.[kt]??0;o>7&&(this.ops=new Uint8Array(o+1))}else this.collDirty=new Map}get isArray(){return this.refTarget!==this.ref}get isFiltered(){return(this.flags&Hf)!==0}set isFiltered(e){this.flags=e?this.flags|Hf:this.flags&~Hf}get isVisibilitySharedWithParent(){return(this.flags&$f)!==0}set isVisibilitySharedWithParent(e){this.flags=e?this.flags|$f:this.flags&~$f}get isNew(){return(this.flags&Sa)!==0}set isNew(e){this.flags=e?this.flags|Sa:this.flags&~Sa}get isUnreliable(){return(this.flags&jf)!==0}set isUnreliable(e){this.flags=e?this.flags|jf:this.flags&~jf}get isPatchOnly(){return(this.flags&_a)!==0}set isPatchOnly(e){this.flags=e?this.flags|_a:this.flags&~_a}get isFullStateOnly(){return(this.flags&Qo)!==0}set isFullStateOnly(e){this.flags=e?this.flags|Qo:this.flags&~Qo}get isStreamCollection(){return(this.flags&Fu)!==0}set isStreamCollection(e){this.flags=e?this.flags|Fu:this.flags&~Fu}get needsRestage(){return(this.flags&Lu)!==0}set needsRestage(e){this.flags=e?this.flags|Lu:this.flags&~Lu}get hasFilteredFields(){return this.isFiltered||this.encDescriptor.hasAnyView}ensureUnreliableRecorder(){return this.unreliableRecorder===void 0&&(this.unreliableRecorder=this._isSchema?new Yf(this.metadata?.[kt]??0):new Kf),this.unreliableRecorder}isFieldUnreliable(e){let n=this.encDescriptor;return n.hasAnyUnreliable?e<32?(n.unreliableBitmask&1<<e)!==0:Ie.hasUnreliableAtIndex(this.metadata,e):!1}isFieldFullStateOnly(e){if(this.isFullStateOnly)return!0;let n=this.encDescriptor;return n.hasAnyFullStateOnly?e<32?(n.fullStateOnlyBitmask&1<<e)!==0:Ie.hasFullStateOnlyAtIndex(this.metadata,e):!1}isFieldStream(e){let n=this.encDescriptor;return n.hasAnyStream?e<32?(n.streamBitmask&1<<e)!==0:Ie.hasStreamAtIndex(this.metadata,e):!1}_opAt(e){let n=this.ops;if(n!==void 0)return n[e];let r=(e&3)<<3;return e<4?this.opsLow>>>r&255:this.opsHigh>>>r&255}_opPut(e,n){let r=this.ops;if(r!==void 0){r[e]=n;return}let s=(e&3)<<3,o=~(255<<s);e<4?this.opsLow=this.opsLow&o|n<<s:this.opsHigh=this.opsHigh&o|n<<s}_markDirty(e){e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}record(e,n){if(this._isSchema){let r=this._opAt(e);r===0?this._opPut(e,n):r===N.DELETE?this._opPut(e,N.DELETE_AND_ADD):r===N.ADD&&n===N.DELETE_AND_ADD&&this._opPut(e,N.DELETE_AND_ADD),this._markDirty(e)}else{let r=this.collDirty,s=r.get(e),o;s===void 0?o=n:s===N.DELETE||s===N.ADD&&n===N.DELETE_AND_ADD?o=N.DELETE_AND_ADD:o=s,r.set(e,o)}}recordDelete(e,n){this._isSchema?(this._opPut(e,n),this._markDirty(e)):this.collDirty.set(e,n)}recordRaw(e,n){this._isSchema?(this._opPut(e,n),this._markDirty(e)):this.collDirty.set(e,n)}recordPure(e){if(this._isSchema)throw new Error("ChangeTree (Schema): pure operations are not supported");(this.collPureOps??(this.collPureOps=[])).push([this.collDirty.size,e])}operationAt(e){if(this._isSchema){let n=this._opAt(e);return n===0?void 0:n}return this.collDirty.get(e)}setOperationAt(e,n){if(this._isSchema)this._opPut(e,n);else{let r=this.collDirty;r.has(e)&&r.set(e,n)}}forEach(e){this.forEachWithCtx(e,zA)}forEachWithCtx(e,n){if(this._isSchema){let o=this.dirtyLow,i=this.dirtyHigh,a=this.ops;if(a!==void 0){for(;o!==0;){let c=o&-o,u=31-Math.clz32(c);o^=c,n(e,u,a[u])}for(;i!==0;){let c=i&-i,u=31-Math.clz32(c)+32;i^=c,n(e,u,a[u])}}else{let c=this.opsLow,u=this.opsHigh;for(;o!==0;){let l=o&-o,d=31-Math.clz32(l);o^=l,n(e,d,FA(c,u,d))}}return}let r=this.collDirty,s=this.collPureOps;if(s!==void 0&&s.length>0){let o=0,i=0;for(let[a,c]of r){for(;o<s.length&&s[o][0]<=i;){let u=s[o++][1];n(e,-u,u)}n(e,a,c),i++}for(;o<s.length;){let a=s[o++][1];n(e,-a,a)}}else for(let[o,i]of r)n(e,o,i)}size(){return this._isSchema?Vu(this.dirtyLow)+Vu(this.dirtyHigh):this.collDirty.size+(this.collPureOps?.length??0)}has(){return this._isSchema?(this.dirtyLow|this.dirtyHigh)!==0:this.collDirty.size>0||this.collPureOps!==void 0&&this.collPureOps.length>0}reset(){if(this._isSchema){this.dirtyLow=0,this.dirtyHigh=0,this.ops!==void 0?this.ops.fill(0):(this.opsLow=0,this.opsHigh=0);return}this.collDirty.clear(),this.collPureOps!==void 0&&(this.collPureOps.length=0),this.flags&=~ip}recycle(){if(this.root!==void 0)throw new Error(`@colyseus/schema: cannot recycle an attached ChangeTree (${this.ref?.constructor?.name}). Remove the instance from its parent collection before releasing it to a pool.`);this.reset(),this.unreliableRecorder?.reset(),this.flags=Sa|Lu,this._fullSyncGen=0,this.parentRef=void 0,this._parentIndex=void 0,this.extraParents=void 0,this.changesNode=void 0,this.unreliableChangesNode=void 0,this.paused=!1,this.visibleViews=void 0,this.tagViews=void 0,this.subscribedViews=void 0}insertAt(e,n){if(this._isSchema)throw new Error("ChangeTree (Schema): insertAt is not supported");let r=this.collDirty,s=new Map,o=!this.paused&&!this.isFullStateOnly;if(e>0)for(let[i,a]of r)i<e&&s.set(i,a);if(o)for(let i=0;i<n;i++)s.set(e+i,N.ADD);for(let[i,a]of r)i>=e&&s.set(i+n,a);this.collDirty=s,o&&this.root?.enqueueChangeTree(this)}removeAt(e,n){if(this._isSchema)throw new Error("ChangeTree (Schema): removeAt is not supported");let r=this.collDirty,s=e+n,o=!1;for(let a of r.keys())if(a>=s){o=!0;break}if(!o){for(let a=e;a<s;a++)r.delete(a);return}let i=new Map;for(let[a,c]of r)a<e?i.set(a,c):a>=s&&i.set(a-n,c);this.collDirty=i}unshift(e){this.insertAt(0,e)}setRoot(e){OA(this,e)}setParent(e,n,r){IA(this,e,n,r)}forEachChild(e){DA(this,e)}forEachChildWithCtx(e,n){Ca(this,e,n)}forEachLive(e){PA(this,e)}forEachLiveWithCtx(e,n){sp(this,e,n)}operation(e){this.paused||this.isFullStateOnly||(this.recordPure(e),this.root?.enqueueChangeTree(this))}_routeAndRecord(e,n,r){if(!(this.paused||this.isFieldFullStateOnly(e))){if(this.isFieldUnreliable(e)&&!this.isNew){let s=this.ensureUnreliableRecorder();r?s.recordRaw(e,n):s.record(e,n),this.root?.enqueueUnreliable(this);return}r?this.recordRaw(e,n):this.record(e,n),this.root?.enqueueChangeTree(this)}}change(e,n=N.ADD){this._routeAndRecord(e,n,!1)}indexedOperation(e,n){this._routeAndRecord(e,n,!0)}getChange(e){return this.operationAt(e)}pause(){this.paused=!0}resume(){this.paused=!1}untracked(e){let n=this.paused;this.paused=!0;try{return e()}finally{this.paused=n}}markDirty(e,n=N.ADD){let r=this.paused;this.paused=!1;try{this.change(e,n)}finally{this.paused=r}}getValue(e,n=!1){return this.refTarget[st](e,n)}delete(e,n){if(e===void 0){try{throw new Error(`@colyseus/schema ${this.ref.constructor.name}: trying to delete non-existing index '${e}'`)}catch(o){console.warn(o)}return}if(this.paused||this.isFieldFullStateOnly(e))return this.getValue(e);let r=this.isFieldUnreliable(e)&&!this.isNew;r?this.ensureUnreliableRecorder().recordDelete(e,n??N.DELETE):this.recordDelete(e,n??N.DELETE);let s=this.getValue(e);return s&&s[I]&&this.root?.remove(s[I]),r?this.root?.enqueueUnreliable(this):this.root?.enqueueChangeTree(this),s}endEncode(){this.reset(),this.changesNode=void 0,this._isSchema||this.refTarget[cs]?.(),this.isNew=!1}endEncodeUnreliable(){this.unreliableRecorder?.reset(),this.unreliableChangesNode=void 0,this._isSchema||this.refTarget[cs]?.()}discard(){this._isSchema||this.refTarget[cs]?.(),this.reset(),this.unreliableRecorder?.reset()}discardAll(){let e=n=>{if(n<0)return;let r=this.getValue(n);r&&r[I]&&r[I].discardAll()};this.forEach(e),this.unreliableRecorder?.forEach(e),this.discard()}get changed(){return this.has()||(this.unreliableRecorder?.has()??!1)}get parent(){return this.parentRef}get parentIndex(){return this._parentIndex}addParent(e,n){wA(this,e,n)}setParentIndex(e,n){SA(this,e,n)}removeParent(e=this.parent){return xA(this,e)}findParent(e){return _A(this,e)}hasParent(e){return ob(this,e)}indexInParent(e){return RA(this,e)}getAllParents(){return EA(this)}},Xf=class{constructor(e){m(this,"ref");m(this,"root");m(this,"parentRef");m(this,"paused",!1);m(this,"isNew",!1);m(this,"flags",0);this.ref=e}change(){}delete(){}indexedOperation(){}operation(){}setParent(){}addParent(){}setParentIndex(){}removeParent(){return!1}getChange(){return 0}discard(){}discardAll(){}pause(){}resume(){}untracked(e){return e()}markDirty(){}forEachChild(e){let n=this.ref;if(n[ge]){if(typeof n[ge]!="string")for(let[i,a]of n.entries())a&&e(a[I],n._collectionIndexes?.[i]??i);return}let s=n.constructor?.[Symbol.metadata];if(!s)return;let o=s[us]??[];for(let i=0;i<o.length;i++){let a=o[i],c=n[s[a].name];c&&e(c[I],a)}}forEachChildWithCtx(e,n){this.forEachChild((r,s)=>n(e,r,s))}forEachLive(){}forEachLiveWithCtx(){}forEach(){}};HA=function(t,e,n,r,s,o,i,a){if(e[o.offset++]=(r|s)&255,s===N.DELETE)return;let c=n.encDescriptor,u=n.ref,l=u[vt][r]??u[c.names[r]];el(t,e,c.types[r],l,s,o,c.encoders[r])},$A=function(t,e,n,r,s,o){if(e[o.offset++]=s&255,Se.number(e,r,o),s===N.DELETE)return;let i=n.ref;if((s&N.ADD)===N.ADD){let a=i.$indexes.get(r);Se.string(e,a,o)}el(t,e,i[ge],i[st](r),s,o)},ap=function(t,e,n,r,s,o){if(e[o.offset++]=s&255,Se.number(e,r,o),s===N.DELETE)return;let i=n.ref;el(t,e,i[ge],i[st](r),s,o)},jA=function(t,e,n,r,s,o,i,a){let c=n.refTarget,u=c[ge],l=typeof u!="string",d=a&&n.isFiltered&&l,f;if(d){let p=c.tmpItems[r];if(!p)return;if(f=p[ee],s===N.DELETE)s=N.DELETE_BY_REFID;else if((s&N.ADD)===N.ADD)s=N.ADD_BY_REFID;else if((s&N.MOVE)===N.MOVE)return}else if(s===N.DELETE&&l){let p=c.tmpItems[r];if(!p)return;f=p[ee],s=N.DELETE_BY_REFID}else f=r;if(e[o.offset++]=s&255,Se.number(e,f,o),s===N.DELETE||s===N.DELETE_BY_REFID)return;let h=c[st](r,i);el(t,e,u,h,s,o)};db=-1,On={Map:1,Array:2,Set:3,Collection:4,Stream:5};YA=function(t,e,n,r,s){let o=e[n.offset++],i=r.constructor[Symbol.metadata],a=o>>6<<6,c=o%(a||255),u=i[c];if(u===void 0)return console.warn("@colyseus/schema: field not defined at",{index:c,ref:r.constructor.name,metadata:i}),db;let l=u.deprecated===!0,d=l?void 0:r[st](c),f=up(t,a,r,c,d,u.type,e,n,s);l||(f!=null&&(r[u.name]=f),d!==f&&s?.push({ref:r,refId:t.currentRefId,op:a,field:u.name,value:f,previousValue:d}))},tl=function(t,e,n,r,s){let o=r[lt]??r,i=e[n.offset++];if(i===N.CLEAR){t.removeChildRefs(o,s),o.clear();return}let a=Ae.number(e,n),c=o[ge],u=o.constructor.COLLECTION_KIND,l;(i&N.ADD)===N.ADD?u===On.Map?(l=Ae.string(e,n),o.setIndex(a,l)):l=a:l=o.getIndex(a);let d=o[st](a),f=up(t,i,r,a,d,c,e,n,s);if(t.resyncVisited!==null&&lb(t,r,i,l,d,f,s),f!=null)switch(u){case On.Map:o.$items.set(l,f);break;case On.Array:o.$setAt(a,f,t.resyncVisited!==null&&i===N.ADD?N.REPLACE:i);break;case On.Set:case On.Collection:case On.Stream:o.$items.has(a)||(o.$items.set(a,f),typeof o.$refId=="number"&&a>=o.$refId&&(o.$refId=a+1));break;default:console.warn(`@colyseus/schema: missing COLLECTION_KIND on ${o.constructor?.name} \u2014 item at index ${a} was not stored.`);break}d!==f&&s?.push({ref:r,refId:t.currentRefId,op:i,dynamicIndex:l,value:f,previousValue:d})},KA=function(t,e,n,r,s){let o=r[lt]??r,i=e[n.offset++],a;if(i===N.CLEAR){t.removeChildRefs(o,s),o.clear();return}else if(i===N.REVERSE){o.items.reverse();return}else if(i===N.DELETE_BY_REFID){let f=Ae.number(e,n),h=t.root.refs.get(f);if(h===void 0||(t.root.removeRef(f),a=o.findIndex(p=>p===h),a===-1))return;o[Nn](a),s?.push({ref:r,refId:t.currentRefId,op:N.DELETE,dynamicIndex:a,value:void 0,previousValue:h});return}else if(i===N.ADD_BY_REFID){let f=Ae.number(e,n),h=t.root.refs.get(f);h&&(a=o.findIndex(p=>p===h)),(a===-1||a===void 0)&&(a=o.length)}else a=Ae.number(e,n);let c=o[ge],u=a,l=o.items[a],d=up(t,i,r,a,l,c,e,n,s);t.resyncVisited!==null&&lb(t,r,i,a,l,d,s),d!=null&&d!==l&&o.$setAt(a,d,t.resyncVisited!==null&&i===N.ADD?N.REPLACE:i),l!==d&&s?.push({ref:r,refId:t.currentRefId,op:i,dynamicIndex:u,value:d,previousValue:l})},ka=class extends Error{};XA=(t,e)=>{let n=t.toString(),r=e.toString();return n<r?-1:n>r?1:0},Qy={get:(t,e)=>typeof e!="symbol"&&!isNaN(e)?t.items[e]:Reflect.get(t,e),set:(t,e,n)=>{if(typeof e!="symbol"&&!isNaN(e)){if(n==null)t.$deleteAt(e);else{let r;if(n[I]){nl(n,t[ge],t,e);let s=t.items[e];t.isMovingItems?(r=t.$wireIndex(Number(e)),s!==void 0?n[I].isNew?t[I].indexedOperation(r,N.MOVE_AND_ADD):(t[I].getChange(r)&N.DELETE)===N.DELETE?t[I].indexedOperation(r,N.DELETE_AND_MOVE):t[I].indexedOperation(r,N.MOVE):n[I].isNew&&t[I].indexedOperation(r,N.ADD),n[I].setParent(t,t[I].root,r)):r=t.$changeAt(Number(e),n),s!==void 0&&s[I].root?.remove(s[I])}else r=t.$changeAt(Number(e),n);t.items[e]=n,r!==void 0&&(t.tmpItems[r]=n)}return!0}return Reflect.set(t,e,n)},deleteProperty:(t,e)=>(typeof e=="number"?t.$deleteAt(e):delete t[e],!0),has:(t,e)=>typeof e!="symbol"&&!isNaN(Number(e))?Reflect.has(t.items,e):Reflect.has(t,e)},on=class on{constructor(...e){m(this,lg);m(this,ug);m(this,cg);m(this,ag);m(this,"items",[]);m(this,"tmpItems",[]);m(this,"deletedIndexes",[]);m(this,"isMovingItems",!1);m(this,"_needsCompaction",!1);m(this,sg);this[ge]=void 0,this[lt]=this;let n=new Proxy(this,Qy);return Object.defineProperty(this,I,{value:new fs(n,this),enumerable:!1,writable:!0}),e.length>0&&this.push(...e),n}static[(lg=I,ug=ee,cg=lt,ag=ge,ig=ir,og=In,Xs)](e,n,r){if(!r)return!0;let s=e[lt]??e;return typeof s[ge]=="string"||r.isChangeTreeVisible(s.tmpItems[n]?.[I])}static is(e){return Array.isArray(e)||e.array!==void 0}static from(e){return new on(...Array.from(e))}static initializeForDecoder(){let e=Object.create(on.prototype);e.items=[],e.isMovingItems=!1,e._needsCompaction=!1,e[ge]=void 0,e[lt]=e;let n=new Proxy(e,Qy);return si(e,n),n}set length(e){e===0?this.clear():e<this.items.length?this.splice(e,this.length-e):console.warn("ArraySchema: can't set .length to a higher value than its length.")}get length(){return this.items.length}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}push(...e){let n=this[lt],r=n.items,s=n.tmpItems,o=n[I],i=n[ge],a=s.length;for(let c=0,u=e.length;c<u;c++,a++){let l=e[c];if(l==null)return;typeof l=="object"&&i&&nl(l,i,n,c),o.indexedOperation(a,N.ADD),r.push(l),s.push(l),l[I]?.setParent(this,o.root,a)}return a}pop(){let e=this[lt],n=e.tmpItems,r=e.deletedIndexes,s=-1;for(let i=n.length-1;i>=0;i--)if(r[i]!==!0){s=i;break}if(s<0)return;let o=e.$isUnsentAdd(s);return e[I].delete(s),o?e.$cancelAdd(s):r[s]=!0,e.items.pop()}at(e){return e<0&&(e+=this.length),this.items[e]}$wireIndex(e){let n=this.deletedIndexes;if(n.length===0)return e;let r=this.tmpItems,s=0;for(let o=0;o<r.length;o++)if(n[o]!==!0){if(s===e)return o;s++}return r.length+(e-s)}$isUnsentAdd(e){let n=this[I];return(n.flags&(ip|Fu))===0&&!n.paused&&typeof this[ge]!="string"&&n.operationAt(e)===N.ADD}$cancelAdd(e,n=!0){let r=this[I],s=this.tmpItems[e];this.tmpItems.splice(e,1),this.deletedIndexes.length>0&&this.deletedIndexes.splice(e,1),r.removeAt(e,1);let o=s?.[I];o!==void 0&&o.root===void 0&&o.removeParent(this),n&&this.$reindexChildren(e)}$reindexChildren(e,n){if(!this[I].hasFilteredFields||typeof this[ge]=="string")return;let r=this.tmpItems,s=r.length;if(n!==void 0)for(;e<s&&r[e]===n[e];)e++;for(let o=e;o<s;o++)r[o]?.[I]?.setParentIndex(this,o)}$changeAt(e,n){if(n==null){console.error("ArraySchema items cannot be null nor undefined; Use `splice(index, 1)` instead.");return}if(this.items[e]===n)return;let r=this.items[e]!==void 0?typeof n=="object"?N.DELETE_AND_ADD:N.REPLACE:N.ADD,s=this.$wireIndex(e),o=this[I];return o.change(s,r),n[I]?.setParent(this,o.root,s),s}$deleteAt(e,n){this[I].delete(this.$wireIndex(e),n)}$setAt(e,n,r){r===N.ADD&&this.items[e]!==void 0?this.items.splice(e,0,n):r===N.DELETE_AND_MOVE?(this.items.splice(e,1),this.items[e]=n):(e>this.items.length&&(this._needsCompaction=!0),this.items[e]=n)}clear(){let e=this[lt];if(e.items.length===0)return;let n=e[I];n.forEachChild((r,s)=>{n.root?.remove(r)}),n.discard(),n.operation(N.CLEAR),e.items.length=0,e.tmpItems.length=0}[Dn](){let e=this[lt]??this,n=e[I];if(n.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed ArraySchema (pooling not supported).");let r=e.items;for(let s=0;s<r.length;s++)r[s]?.[Dn]?.();e.items.length=0,e.tmpItems.length=0,e.deletedIndexes.length=0,n.recycle(),e[ee]=void 0}concat(...e){return new on(...this.items.concat(...e))}join(e){return this.items.join(e)}reverse(){let e=this[lt],n=e[I];if(n.has()||e.deletedIndexes.length>0){let r=e.items.slice().reverse();return this.clear(),this.push(...r),this}return n.operation(N.REVERSE),e.items.reverse(),e.tmpItems.reverse(),e.$reindexChildren(0),this}shift(){let e=this[lt],n=e.items;if(n.length===0)return;let r=e[I],s=e.deletedIndexes,o=0;for(;s[o]===!0;)o++;let i=e.$isUnsentAdd(o);return r.delete(o,N.DELETE),i?e.$cancelAdd(o):s[o]=!0,n.shift()}slice(e,n){let r=new on;return r.push(...this.items.slice(e,n)),r}sort(e=XA){let n=this[lt];n.isMovingItems=!0;let r=n[I];return n.items.sort(e).forEach((o,i)=>r.change(i,N.REPLACE)),n.tmpItems.sort(e),n.$reindexChildren(0),n.isMovingItems=!1,this}splice(e,n,...r){let s=this[lt],o=s[I],i=s.items,a=s.tmpItems,c=s.deletedIndexes,u=i.length,l=a.length,d=r.length,f=[];for(let p=0;p<l;p++)c[p]!==!0&&f.push(p);let h;if(u>e){n===void 0&&(n=u-e);for(let p=e;p<e+n;p++){let y=f[p],S=s.$isUnsentAdd(y);o.delete(y,N.DELETE),S?(h??(h=[])).push(y):c[y]=!0}}else n=0;if(d>0){let p=f[e]??u,y=Math.min(d,n);for(let w=0;w<y;w++){let x=p+w,R,A=h!==void 0?h.indexOf(x):-1;A!==-1?(h.splice(A,1),R=N.ADD):R=c[x]?N.DELETE_AND_ADD:N.ADD,o.indexedOperation(x,R),a[x]=r[w],c[x]=!1,r[w][I]?.setParent(this,o.root,x)}let S=d-y;if(S>0){let w=p+y;o.insertAt(w,S);for(let x=0;x<S;x++)r[y+x][I]?.setParent(this,o.root,w+x);c.length>0&&c.splice(w,0,...new Array(S).fill(!1)),a.splice(w,0,...r.slice(y)),s.$reindexChildren(w+S)}}if(h!==void 0&&h.length>0){for(let p=h.length-1;p>=0;p--)s.$cancelAdd(h[p],!1);s.$reindexChildren(h[0])}return o.root?.enqueueChangeTree(o),i.splice(e,n,...r)}unshift(...e){let n=this[lt],r=n[I];r.unshift(e.length);for(let o=0;o<e.length;o++)e[o]?.[I]?.setParent(this,r.root,o);let s=n.deletedIndexes;return s.length>0&&s.unshift(...new Array(e.length).fill(!1)),n.tmpItems.unshift(...e),n.$reindexChildren(e.length),n.items.unshift(...e)}indexOf(e,n){return this.items.indexOf(e,n)}lastIndexOf(e,n=this.length-1){return this.items.lastIndexOf(e,n)}every(e,n){return this.items.every(e,n)}some(e,n){return this.items.some(e,n)}forEach(e,n){return this.items.forEach(e,n)}map(e,n){return this.items.map(e,n)}filter(e,n){return this.items.filter(e,n)}reduce(e,n){return this.items.reduce.apply(this.items,arguments)}reduceRight(e,n){return this.items.reduceRight.apply(this.items,arguments)}find(e,n){return this.items.find(e,n)}findIndex(e,n){return this.items.findIndex(e,n)}fill(e,n,r){throw new Error("ArraySchema#fill() not implemented")}copyWithin(e,n,r){throw new Error("ArraySchema#copyWithin() not implemented")}toString(){return this.items.toString()}toLocaleString(){return this.items.toLocaleString()}[Symbol.iterator](){return this.items[Symbol.iterator]()}static get[Symbol.species](){return on}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}includes(e,n){return this.items.includes(e,n)}flatMap(e,n){throw new Error("ArraySchema#flatMap() is not supported.")}flat(e){throw new Error("ArraySchema#flat() is not supported.")}findLast(){return this.items.findLast.apply(this.items,arguments)}findLastIndex(...e){return this.items.findLastIndex.apply(this.items,arguments)}with(e,n){let r=this.items.slice();return e<0&&(e+=this.length),r[e]=n,new on(...r)}toReversed(){return this.items.slice().reverse()}toSorted(e){return this.items.slice().sort(e)}toSpliced(e,n,...r){let s=this.items.slice();return s.splice.apply(s,arguments),s}shuffle(){return this.move(e=>{let n=this.items.length;for(;n!=0;){let r=Math.floor(Math.random()*n);n--,[this[n],this[r]]=[this[r],this[n]]}})}move(e){return this.isMovingItems=!0,e(this),this.isMovingItems=!1,this}[(sg=Symbol.unscopables,st)](e,n=!1){let r=this[lt]??this;return n||r.deletedIndexes[e]?r.items[e]:r.tmpItems[e]||r.items[e]}[Nn](e){let n=this[lt]??this;n.items[e]=void 0,n._needsCompaction=!0}[cs](){let e=this.tmpItems;this.tmpItems=this.items.slice(),this.deletedIndexes.length>0&&(this.$reindexChildren(0,e),this.deletedIndexes.length=0)}[zu](){let e=this[lt]??this;e._needsCompaction&&(e._needsCompaction=!1,e.items=e.items.filter(n=>n!==void 0))}[ri](e,n,r){let s=this[lt]??this,o=s.items,i=!1;for(let a=0;a<o.length;a++){let c=o[a];if(e.has(a)){r(c);continue}i=!0,n(c,a),s[Nn](a)}i&&s[zu]()}toArray(){return this.items.slice(0)}toJSON(){return this.toArray().map(e=>typeof e.toJSON=="function"?e.toJSON():e)}clone(e){let n;return e?(n=new on,n.push(...this.items)):n=new on(...this.map(r=>r[I]?r.clone():r)),n}};m(on,ig,jA),m(on,og,KA),m(on,"COLLECTION_KIND",On.Array);ls=on;Or("array",{constructor:ls});ju=class{constructor(){m(this,"keyByIndex",new Map);m(this,"indexByKey",Object.create(null));m(this,"nextIndex",0);m(this,"snapshots")}indexOf(e){let n=this.indexByKey[e];return n===void 0?void 0:n}assign(e){let n=this.nextIndex++;return this.indexByKey[e]=n,this.keyByIndex.set(n,e),n}snapshot(e,n){(this.snapshots??(this.snapshots=new Map)).set(e,n)}forgetSnapshot(e){this.snapshots?.delete(e)}snapshotAt(e){return this.snapshots?.get(e)}setIndex(e,n){this.keyByIndex.set(e,n),this.indexByKey[n]=e}keyOf(e){return this.keyByIndex.get(e)}cleanupAfterEncode(){if(this.snapshots!==void 0){for(let[e]of this.snapshots){let n=this.keyByIndex.get(e);n!==void 0&&(delete this.indexByKey[n],this.keyByIndex.delete(e))}this.snapshots.clear()}}reset(){this.indexByKey=Object.create(null),this.keyByIndex.clear(),this.snapshots?.clear(),this.nextIndex=0}},rr=class rr{constructor(e){m(this,mg);m(this,hg);m(this,"childType");m(this,pg);m(this,"$items",new Map);m(this,"journal",new ju);m(this,"_stream");if(Object.defineProperty(this,I,{value:new fs(this),enumerable:!1,writable:!0}),this[ge]=void 0,e)if(e instanceof Map||e instanceof rr)e.forEach((n,r)=>this.set(r,n));else for(let n in e)this.set(n,e[n])}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Cr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Cr())).priority=e}get $indexes(){return this.journal.keyByIndex}get _collectionIndexes(){return this.journal.indexByKey}static[(mg=I,hg=ee,pg=ge,fg=ir,dg=In,Xs)](e,n,r){if(!r||typeof e[ge]=="string")return!0;let s=e[st](n)??e.journal.snapshotAt(n);return r.isChangeTreeVisible(s[I])}static is(e){return e.map!==void 0}static initializeForDecoder(){let e=Object.create(rr.prototype);return e.$items=new Map,e.journal=new ju,e[ge]=void 0,si(e),e}[Symbol.iterator](){return this.$items[Symbol.iterator]()}get[Symbol.toStringTag](){return this.$items[Symbol.toStringTag]}static get[Symbol.species](){return rr}set(e,n){if(n==null)throw new Error(`MapSchema#set('${e}', ${n}): trying to set ${n} value on '${e}'.`);typeof n=="object"&&this[ge]&&nl(n,this[ge],this,e),e=e.toString();let r=this[I],s=n[I]!==void 0,o=this.journal,i=o.indexOf(e),a;if(i!==void 0){a=N.REPLACE;let c=this.$items.get(e);if(c===n)return;s&&(a=N.DELETE_AND_ADD,c!==void 0&&c[I].root?.remove(c[I])),o.snapshotAt(i)!==void 0&&o.forgetSnapshot(i)}else i=o.assign(e),a=N.ADD;return this.$items.set(e,n),a===N.ADD&&r.isStreamCollection?r.root!==void 0&&Ju(this,r.root,i):r.change(i,a),s&&n[I].setParent(this,r.root,i),this}get(e){return this.$items.get(e)}getOrInsert(e,n){return this.$items.has(e)?this.$items.get(e):(this.set(e,n),n)}getOrInsertComputed(e,n){if(this.$items.has(e))return this.$items.get(e);let r=n(e);return this.set(e,r),r}delete(e){if(!this.$items.has(e))return!1;let n=this.journal.indexOf(e),r=this.$items.get(e),s=this[I];if(s.isStreamCollection){let o=s.root,i=!1;return o!==void 0&&(i=Zu(this,o,this[ee],n)),r?.[I]!==void 0&&o?.remove(r[I]),this.$items.delete(e),i||this.journal.snapshot(n,r),!0}return this.journal.snapshot(n,r),s.delete(n),this.$items.delete(e)}clear(){let e=this[I];e.discard(),e.forEachChild((n,r)=>{e.root?.remove(n)}),this.journal.reset(),this.$items.clear(),e.operation(N.CLEAR)}[Dn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed MapSchema (pooling not supported).");this.$items.forEach(n=>n?.[Dn]?.()),this.$items.clear(),this.journal.reset(),e.recycle(),this[ee]=void 0}has(e){return this.$items.has(e)}forEach(e){this.$items.forEach(e)}entries(){return this.$items.entries()}keys(){return this.$items.keys()}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}setIndex(e,n){this.journal.setIndex(e,n)}getIndex(e){return this.journal.keyOf(e)}[st](e){let n=this.journal.keyOf(e);return n!==void 0?this.$items.get(n):void 0}[Nn](e){let n=this.journal.keyOf(e);n!==void 0&&(this.$items.delete(n),this.journal.keyByIndex.delete(e))}[ri](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=new Set)).add(i),n(o,i)}),s!==null){s.forEach(i=>{this.$items.delete(i),delete this.journal.indexByKey[i]});let o=[];this.journal.keyByIndex.forEach((i,a)=>{s.has(i)&&o.push(a)});for(let i=0;i<o.length;i++)this.journal.keyByIndex.delete(o[i])}}[cs](){this.journal.cleanupAfterEncode()}_dropView(e){Qu(this,e)}_unregister(){}toJSON(){return Object.fromEntries(Array.from(this,([n,r])=>[n,typeof r.toJSON=="function"?r.toJSON():r]))}clone(e){let n;return e?n=Object.assign(new rr,this):(n=new rr,this.forEach((r,s)=>{r[I]?n.set(s,r.clone()):n.set(s,r)})),n}};m(rr,fg,$A),m(rr,dg,tl),m(rr,"COLLECTION_KIND",On.Map);ds=rr;Or("map",{constructor:ds});is=class is{constructor(e){m(this,Sg);m(this,wg);m(this,bg);m(this,"$items",new Map);m(this,"deletedItems",{});m(this,"$refId",0);m(this,"_stream");Object.defineProperty(this,I,{value:new fs(this),enumerable:!1,writable:!0}),this[ge]=void 0,e&&e.forEach(n=>this.add(n))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Cr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Cr())).priority=e}static[(Sg=I,wg=ee,bg=ge,gg=ir,yg=In,Xs)](e,n,r){return!r||typeof e[ge]=="string"||r.isChangeTreeVisible((e[st](n)??e.deletedItems[n])[I])}static is(e){return e.collection!==void 0}static initializeForDecoder(){let e=Object.create(is.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[ge]=void 0,si(e),e}add(e){let n=this.$refId++,r=this[I];return this.$items.set(n,e),r.isStreamCollection?r.root!==void 0&&Ju(this,r.root,n):r.change(n),e[I]!==void 0&&e[I].setParent(this,r.root,n),n}at(e){let n=Array.from(this.$items.keys())[e];return this.$items.get(n)}entries(){return this.$items.entries()}delete(e){let n=this.$items.entries(),r,s;for(;(s=n.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let o=this[I];if(o.isStreamCollection){let i=o.root,a=this.$items.get(r);return i!==void 0&&Zu(this,i,this[ee],r),a?.[I]!==void 0&&i?.remove(a[I]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=o.delete(r),this.$items.delete(r)}clear(){let e=this[I];e.discard(),e.forEachChild((n,r)=>{e.root?.remove(n)}),this.$items.clear(),e.operation(N.CLEAR)}[Dn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed CollectionSchema (pooling not supported).");this.$items.forEach(n=>n?.[Dn]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[ee]=void 0}has(e){return Array.from(this.$items.values()).some(n=>n===e)}forEach(e){this.$items.forEach((n,r,s)=>e(n,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,n){}getIndex(e){return e}[st](e){return this.$items.get(e)}[Nn](e){this.$items.delete(e)}[ri](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=[])).push(i),n(o,i)}),s!==null)for(let o=0;o<s.length;o++)this[Nn](s[o])}[cs](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){Qu(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((n,r)=>{e.push(typeof n.toJSON=="function"?n.toJSON():n)}),e}clone(e){let n;return e?n=Object.assign(new is,this):(n=new is,this.forEach(r=>{r[I]?n.add(r.clone()):n.add(r)})),n}};m(is,gg,ap),m(is,yg,tl),m(is,"COLLECTION_KIND",On.Collection);Aa=is;Or("collection",{constructor:Aa});as=class as{constructor(e){m(this,kg);m(this,Eg);m(this,Rg);m(this,"$items",new Map);m(this,"deletedItems",{});m(this,"$refId",0);m(this,"_stream");Object.defineProperty(this,I,{value:new fs(this),enumerable:!1,writable:!0}),this[ge]=void 0,e&&e.forEach(n=>this.add(n))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Cr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Cr())).priority=e}static[(kg=I,Eg=ee,Rg=ge,_g=ir,xg=In,Xs)](e,n,r){return!r||typeof e[ge]=="string"||r.isVisible((e[st](n)??e.deletedItems[n])[I])}static is(e){return e.set!==void 0}static initializeForDecoder(){let e=Object.create(as.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[ge]=void 0,si(e),e}add(e){if(this.has(e))return!1;let n=this.$refId++,r=this[I];return this.$items.set(n,e),r.isStreamCollection?r.root!==void 0&&Ju(this,r.root,n):r.change(n,N.ADD),e[I]!==void 0&&e[I].setParent(this,r.root,n),n}entries(){return this.$items.entries()}delete(e){let n=this.$items.entries(),r,s;for(;(s=n.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let o=this[I];if(o.isStreamCollection){let i=o.root,a=this.$items.get(r);return i!==void 0&&Zu(this,i,this[ee],r),a?.[I]!==void 0&&i?.remove(a[I]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=o.delete(r),this.$items.delete(r)}clear(){let e=this[I];e.discard(),this.$items.clear(),e.operation(N.CLEAR)}[Dn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed SetSchema (pooling not supported).");this.$items.forEach(n=>n?.[Dn]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[ee]=void 0}has(e){let n=this.$items.values(),r=!1,s;for(;(s=n.next())&&!s.done;)if(e===s.value){r=!0;break}return r}forEach(e){this.$items.forEach((n,r,s)=>e(n,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,n){}getIndex(e){return e}[st](e){return this.$items.get(e)}[Nn](e){this.$items.delete(e)}[ri](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=[])).push(i),n(o,i)}),s!==null)for(let o=0;o<s.length;o++)this[Nn](s[o])}[cs](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){Qu(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((n,r)=>{e.push(typeof n.toJSON=="function"?n.toJSON():n)}),e}clone(e){let n;return e?n=Object.assign(new as,this):(n=new as,this.forEach(r=>{r[I]?n.add(r.clone()):n.add(r)})),n}};m(as,_g,ap),m(as,xg,tl),m(as,"COLLECTION_KIND",On.Set);Pa=as;Or("set",{constructor:Pa});vr=class vr{constructor(){m(this,Mg);m(this,vg);m(this,Tg);m(this,"$items",new Map);m(this,"$nextPosition",0);m(this,"_itemIndex",new Map);m(this,"_stream");Object.defineProperty(this,I,{value:new fs(this),enumerable:!1,writable:!0}),this[ge]=void 0}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Cr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Cr())).priority=e}static[(Mg=I,vg=ee,Tg=ge,Pg=ir,Ag=In,Xs)](e,n,r){if(!r)return!0;let s=e[st](n);return s===void 0?!1:r.isVisible(s[I])}static is(e){return e&&e.stream!==void 0}static initializeForDecoder(){let e=Object.create(vr.prototype);return e.$items=new Map,e.$nextPosition=0,e._itemIndex=new Map,e[ge]=void 0,si(e),e}add(e){if(this._itemIndex.has(e))return-1;let n=this.$nextPosition++;this.$items.set(n,e),this._itemIndex.set(e,n);let s=this[I].root;return e[I]!==void 0&&e[I].setParent(this,s,n),s!==void 0&&Ju(this,s,n),n}remove(e){let n=this._itemIndex.get(e);if(n===void 0)return!1;this._itemIndex.delete(e),this.$items.delete(n);let r=this[I].root;return r!==void 0&&(Zu(this,r,this[ee],n),e[I]!==void 0&&r.remove(e[I])),!0}has(e){return this._itemIndex.has(e)}clear(){let e=this[I].root;if(e!==void 0){cA(this,e,this[ee]);for(let n of this.$items.values())n[I]!==void 0&&e.remove(n[I])}this.$items.clear(),this._itemIndex.clear()}forEach(e){for(let[n,r]of this.$items)e(r,n,this)}values(){return this.$items.values()}entries(){return this.$items.entries()}[Symbol.iterator](){return this.$items.values()}get size(){return this.$items.size}get length(){return this.$items.size}setIndex(e,n){}getIndex(e){return e}[st](e){return this.$items.get(e)}[Nn](e){let n=this.$items.get(e);n!==void 0&&(this._itemIndex.delete(n),this.$items.delete(e))}[ri](){}[cs](){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach(n=>{e.push(typeof n?.toJSON=="function"?n.toJSON():n)}),e}clone(e){if(e)return Object.assign(new vr,this);let n=new vr;return n.maxPerTick=this.maxPerTick,this.forEach(r=>{n.add(typeof r?.clone=="function"?r.clone():r)}),n}_dropView(e){Qu(this,e)}_unregister(){}};m(vr,"$isStream",!0),m(vr,Pg,ap),m(vr,Ag,tl),m(vr,"COLLECTION_KIND",On.Stream);Wu=vr;Or("stream",{constructor:Wu});Cg=Lg;ar=class{constructor(e){m(this,Cg,!0);m(this,"_type");m(this,"_default");m(this,"_hasDefault",!1);m(this,"_view");m(this,"_unreliable",!1);m(this,"_patchOnly",!1);m(this,"_deprecated",!1);m(this,"_deprecatedThrows",!0);m(this,"_fullStateOnly",!1);m(this,"_stream",!1);m(this,"_optional",!1);m(this,"_noSync",!1);m(this,"_streamPriority");this._type=e}default(e){return this._default=e,this._hasDefault=!0,this}view(e){return this._view=e??-1,this}unreliable(){return this._unreliable=!0,this}patchOnly(){return this._patchOnly=!0,this}fullStateOnly(){return this._fullStateOnly=!0,this}noSync(){return this._noSync=!0,this}stream(){let e=this._type;if(e&&typeof e=="object"&&e.array!==void 0)throw new Error(tb);return this._stream=!0,this}priority(e){return this._streamPriority=e,this}deprecated(e=!0){return this._deprecated=!0,this._deprecatedThrows=e,this}optional(){return this._optional=!0,this}toDefinition(){return{type:this._type,default:this._default,hasDefault:this._hasDefault,view:this._view,unreliable:this._unreliable,patchOnly:this._patchOnly,deprecated:this._deprecated,deprecatedThrows:this._deprecatedThrows,fullStateOnly:this._fullStateOnly,stream:this._stream,optional:this._optional,noSync:this._noSync,streamPriority:this._streamPriority}}};JA=(t=>new ar({array:Oa(t)})),ZA=(t=>new ar({map:Oa(t)})),QA=(t=>new ar({set:Oa(t)})),eP=(t=>new ar({collection:Oa(t)})),tP=(t=>{let e=new ar({stream:Oa(t)});return e._stream=!0,e}),nP=(t=>new ar(t));X=Object.freeze({string:Bt("string"),number:Bt("number"),boolean:Bt("boolean"),int8:Bt("int8"),uint8:Bt("uint8"),int16:Bt("int16"),uint16:Bt("uint16"),int32:Bt("int32"),uint32:Bt("uint32"),int64:Bt("int64"),uint64:Bt("uint64"),float32:Bt("float32"),float64:Bt("float64"),bigint64:Bt("bigint64"),biguint64:Bt("biguint64"),ref:nP,array:JA,map:ZA,set:QA,collection:eP,stream:tP,quantized:eg,angle:t=>eg({min:0,max:Math.PI*2,mode:"wrap",bits:t?.bits??16})}),rl=-1;iP={number:"number",int8:"number",uint8:"number",int16:"number",uint16:"number",int32:"number",uint32:"number",int64:"number",uint64:"number",float32:"number",float64:"number",bigint64:"bigint",biguint64:"bigint",string:"string",boolean:"boolean"};Mn=class Mn{constructor(e){m(this,Ig);m(this,Og);Mn.initialize(this),e&&Mn.assignProps(this,e)}static initialize(e){Object.defineProperty(e,I,{value:new fs(e),enumerable:!1,writable:!0}),e[vt]=[]}static initializeForDecoder(){let e=Object.create(this.prototype);return si(e),e[vt]=[],e}static reset(e){let n=e?.[I];if(n===void 0||typeof n.recycle!="function")throw new Error("@colyseus/schema: Schema.reset() requires a tracked (encoder-side) instance.");if(n.extraParents!==void 0)throw new Error(`@colyseus/schema: cannot reset a shared instance (${e.constructor.name}) with multiple parents.`);e[Dn]()}[(Ng=ir,Dg=In,Ig=ee,Og=vt,Dn)](){let n=this.constructor[Symbol.metadata]?.[us]??[],r=this[vt];for(let s=0;s<n.length;s++)r[n[s]]?.[Dn]?.();this[I].recycle(),this[ee]=void 0}static is(e){let n=e[Symbol.metadata];return typeof n=="object"&&n!==null}static isSchema(e){return typeof e?.assign=="function"}static[or](e,n,r=N.ADD){e.change(n,r)}static[Xs](e,n,r){let o=e.constructor[Symbol.metadata][n]?.tag;return r===void 0?o===void 0:o===void 0?!0:o===rl?r.isChangeTreeVisible(e[I]):r.hasTagOnTree(e[I],o)}assign(e){return Mn.assignProps(this,e),this}static assignProps(e,n){let r=e.constructor[Symbol.metadata];if(r&&r[kt]!==void 0)for(let o=0;o<=r[kt];o++){let i=r[o];if(!i)continue;let a=n[i.name];a!==void 0&&(e[i.name]=a)}let s=Object.keys(n);for(let o=0;o<s.length;o++){let i=s[o];r&&r[i]!==void 0||(e[i]=n[i])}}restore(e){let n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r],o=s.name,i=s.type,a=e[o];if(a!=null){if(typeof i=="string")this[o]=a;else if(Mn.is(i)){let c=new i;c.restore(a),this[o]=c}else if(typeof i=="object"){let c=Object.keys(i)[0],u=i[c];if(c==="map"){let l=this[o];for(let d in a)if(Mn.is(u)){let f=new u;f.restore(a[d]),l.set(d,f)}else l.set(d,a[d])}else if(c==="array"){let l=this[o];for(let d=0;d<a.length;d++)if(Mn.is(u)){let f=new u;f.restore(a[d]),l.push(f)}else l.push(a[d])}}}}return this}setDirty(e,n){let r=this.constructor[Symbol.metadata];this[I].change(r[r[e]].index,n)}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}clone(){let e=Object.create(this.constructor.prototype);Mn.initialize(e);let n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r].name;typeof this[s]=="object"&&typeof this[s]?.clone=="function"?e[s]=this[s].clone():e[s]=this[s]}return e}toJSON(){let e={},n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r],o=s.name;!s.deprecated&&this[o]!==null&&typeof this[o]<"u"&&(e[o]=typeof this[o].toJSON=="function"?this[o].toJSON():this[o])}return e}discardAllChanges(){this[I].discardAll()}[st](e){let n=this.constructor[Symbol.metadata];return this[n[e].name]}[Nn](e){let n=this.constructor[Symbol.metadata];this[n[e].name]=void 0}static debugRefIds(e,n=!1,r=0,s,o=""){let i=n?` - ${JSON.stringify(e.toJSON())}`:"",a=e[I],c=e[ee],u=s?s.root:a.root,l=u?.refCount?.[c]>1?` [\xD7${u.refCount[c]}]`:"",d=`${hP(r)}${o}${e.constructor.name} (refId: ${c})${l}${i}
|
|
5
|
-
`;return a.forEachChild((f,h)=>{let p=h;typeof h=="number"&&e.$indexes&&(p=e.$indexes.get(h)??h);let y=e.forEach!==void 0&&p!==void 0?`["${p}"]: `:"";d+=this.debugRefIds(f.ref,n,r+1,s,y)}),d}static debugRefIdEncodingOrder(e,n="allChanges"){let r=[],s=e[I];if(n==="changes"){let c=s.root.changes?.next;for(;c;)c.changeTree&&r.push(c.changeTree.ref[
|
|
3
|
+
hasFilters: ${this.hasFilters}`}};m(sr,"inheritedTypes",new WeakMap),m(sr,"cachedContexts",new WeakMap);Ks=sr,Ky=63;wA=[ls,js,Ra,Uu,ei,un,vr];De={addField(t,e,n,r,s){if(e>=Ky)throw new Error(`Can't define field '${n}'.
|
|
4
|
+
Schema instances may only have up to ${Ky} fields.`);t[e]=Object.assign(t[e]||{},{type:ni(r),index:e,name:n}),Object.defineProperty(t,cn,{value:t[cn]||{},enumerable:!1,configurable:!0}),s?t[cn][n]=s:t[cn][n]={value:void 0,writable:!0,enumerable:!0,configurable:!0},Object.defineProperty(t,At,{value:e,enumerable:!1,configurable:!0}),Object.defineProperty(t,n,{value:e,enumerable:!1,configurable:!0}),typeof t[e].type!="string"&&!Ys(t[e].type)&&(t[ls]===void 0&&Object.defineProperty(t,ls,{value:[],enumerable:!1,configurable:!0}),t[ls].push(e));let o=t[e].type;if(o&&typeof o=="object"&&o.stream!==void 0){if(o.array!==void 0)throw new Error(nb);t[e].stream=!0,t[un]||Object.defineProperty(t,un,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[un].includes(e)||t[un].push(e);let i=r?.priority;typeof i=="function"&&De.setStreamPriority(t,n,i)}},setTag(t,e,n){let r=t[e],s=t[r];if(s.tag=n,t[On]||(Object.defineProperty(t,On,{value:[],enumerable:!1,configurable:!0}),Object.defineProperty(t,Tr,{value:{},enumerable:!1,configurable:!0})),t[On].push(r),n<0)t[Tr][n]||(t[Tr][n]=[]),t[Tr][n].push(r);else for(let o=n;o>0;o&=o-1){let i=o&-o;t[Tr][i]||(t[Tr][i]=[]),t[Tr][i].push(r)}},setUnreliable(t,e){let n=t[e];if(typeof t[n].type!="string")throw new Error(`@unreliable cannot be applied to ref-type field "${e}". For ref-type fields, mark each primitive sub-field with @unreliable instead. See README "Limitations and best practices".`);t[n].unreliable=!0,t[js]||Object.defineProperty(t,js,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[js].push(n)},setPatchOnly(t,e){let n=t[e];if(t[n].fullStateOnly)throw new Error(`field "${e}" cannot be both patchOnly and fullStateOnly \u2014 those are the only two delivery channels, so the field would never reach a client.`);t[n].patchOnly=!0,Du(t,Ra,n),Du(t,Uu,n)},setDeprecated(t,e){let n=t[e];t[n].deprecated=!0,Du(t,Uu,n),Object.defineProperty(t,n,{value:t[n],enumerable:!1,configurable:!0})},setFullStateOnly(t,e){let n=t[e];if(t[n].patchOnly)throw new Error(`field "${e}" cannot be both patchOnly and fullStateOnly \u2014 those are the only two delivery channels, so the field would never reach a client.`);t[n].fullStateOnly=!0,Du(t,ei,n)},setStream(t,e){let n=t[e];t[n].stream=!0,t[un]||Object.defineProperty(t,un,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[un].push(n)},setStreamPriority(t,e,n){let r=t[e];t[Iu]||Object.defineProperty(t,Iu,{value:{},enumerable:!1,configurable:!0,writable:!0}),t[Iu][r]=n},getStreamPriority(t,e){return t?.[Iu]?.[e]},defineField(t,e,n,r,s){let o=ni(s),{complexTypeKlass:i,childType:a}=gA(o);De.addField(e,n,r,o,pP(r,n,a,i)),e[cn][r]&&Object.defineProperty(t.prototype,r,e[cn][r]),(typeof o=="string"||Ys(o))&&(e[vr]||Object.defineProperty(e,vr,{value:[],enumerable:!1,configurable:!0,writable:!0}),e[vr][n]=typeof o=="string"?Se[o]:mA(o.quantized))},setFields(t,e){let n=t.prototype.constructor;Ks.register(n);let r=Object.getPrototypeOf(n),s=r&&r[Symbol.metadata],o=De.initialize(n);n[ar]||(n[ar]=Xe[ar]),n[cr]||(n[cr]=Xe[cr]),n[Dn]||(n[Dn]=Xe[Dn]),n.prototype.toJSON||(n.prototype.toJSON=Xe.prototype.toJSON);let i=o[At]??(s&&s[At])??-1;i++,o[vr]||Object.defineProperty(o,vr,{value:s?.[vr]?[...s[vr]]:[],enumerable:!1,configurable:!0,writable:!0});for(let a in e){if(o[a]!==void 0)throw new Error(`@colyseus/schema: Duplicate '${a}' definition on '${n.name||"(anonymous)"}'.`);De.defineField(n,o,i,a,e[a]),i++}return t},isDeprecated(t,e){return t[e].deprecated===!0},initialize(t){let e=Object.getPrototypeOf(t),n=e[Symbol.metadata],r=t[Symbol.metadata]??Object.create(null);if(e!==Xe&&r===n&&(r=Object.create(null),n)){Object.setPrototypeOf(r,n),Object.defineProperty(r,At,{value:n[At],enumerable:!1,configurable:!0,writable:!0}),n[On]!==void 0&&(Object.defineProperty(r,On,{value:[...n[On]],enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(r,Tr,{value:{...n[Tr]},enumerable:!1,configurable:!0,writable:!0}));for(let s of wA){let o=n[s];o!==void 0&&Object.defineProperty(r,s,{value:[...o],enumerable:!1,configurable:!0,writable:!0})}Object.defineProperty(r,cn,{value:{...n[cn]},enumerable:!1,configurable:!0,writable:!0})}return Object.defineProperty(t,Symbol.metadata,{value:r,writable:!1,configurable:!0}),r},isValidInstance(t){return t.constructor[Symbol.metadata]&&Object.prototype.hasOwnProperty.call(t.constructor[Symbol.metadata],At)},getFields(t){let e=t[Symbol.metadata],n={};for(let r=0;r<=e[At];r++)n[e[r].name]=e[r].type;return n},hasViewTagAtIndex(t,e){return t?.[On]?.includes(e)},hasUnreliableAtIndex(t,e){return t?.[js]?.includes(e)},hasPatchOnlyAtIndex(t,e){return t?.[Ra]?.includes(e)},hasFullStateOnlyAtIndex(t,e){return t?.[ei]?.includes(e)},hasStreamAtIndex(t,e){return t?.[un]?.includes(e)}},ob=(t,e,n)=>t(e,n),Kf=class{constructor(e){m(this,"dirtyLow",0);m(this,"dirtyHigh",0);m(this,"ops");this.ops=new Uint8Array(Math.max(e+1,1))}record(e,n){let r=this.ops[e];r===0?this.ops[e]=n:r===N.DELETE?this.ops[e]=N.DELETE_AND_ADD:r===N.ADD&&n===N.DELETE_AND_ADD&&(this.ops[e]=N.DELETE_AND_ADD),e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordDelete(e,n){this.ops[e]=n,e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordRaw(e,n){this.record(e,n)}operationAt(e){let n=this.ops[e];return n===0?void 0:n}setOperationAt(e,n){this.ops[e]=n}forEach(e){this.forEachWithCtx(e,ob)}forEachWithCtx(e,n){let r=this.dirtyLow,s=this.dirtyHigh,o=this.ops;for(;r!==0;){let i=r&-r,a=31-Math.clz32(i);r^=i,n(e,a,o[a])}for(;s!==0;){let i=s&-s,a=31-Math.clz32(i)+32;s^=i,n(e,a,o[a])}}size(){return Vu(this.dirtyLow)+Vu(this.dirtyHigh)}has(){return(this.dirtyLow|this.dirtyHigh)!==0}reset(){this.dirtyLow=0,this.dirtyHigh=0,this.ops.fill(0)}},Xf=class{constructor(){m(this,"dirty",new Map);m(this,"pureOps",[])}record(e,n){let r=this.dirty.get(e);r===void 0?this.dirty.set(e,n):r===N.DELETE?this.dirty.set(e,N.DELETE_AND_ADD):r===N.ADD&&n===N.DELETE_AND_ADD&&this.dirty.set(e,N.DELETE_AND_ADD)}recordDelete(e,n){this.dirty.set(e,n)}recordRaw(e,n){this.dirty.set(e,n)}recordPure(e){this.pureOps.push([this.dirty.size,e])}operationAt(e){return this.dirty.get(e)}setOperationAt(e,n){this.dirty.has(e)&&this.dirty.set(e,n)}forEach(e){this.forEachWithCtx(e,ob)}forEachWithCtx(e,n){let r=this.pureOps;if(r.length>0){let s=0,o=0;for(let[i,a]of this.dirty){for(;s<r.length&&r[s][0]<=o;){let c=r[s++][1];n(e,-c,c)}n(e,i,a),o++}for(;s<r.length;){let i=r[s++][1];n(e,-i,i)}}else for(let[s,o]of this.dirty)n(e,s,o)}size(){return this.dirty.size+this.pureOps.length}has(){return this.dirty.size>0||this.pureOps.length>0}reset(){this.dirty.clear(),this.pureOps.length=0}shift(e){let n=new Map;for(let[r,s]of this.dirty)n.set(r+e,s);this.dirty=n}};ab=(t,e)=>{t.isFieldUnreliable(e)?t.ensureUnreliableRecorder().record(e,N.ADD):t.record(e,N.ADD)},TA=(t,e)=>t(e);lb=1,Hu=2,$u=4,CA=lb|Hu|$u;OA=(t,e,n)=>{ip(e)};Zy=[],Bu=0;VA=(t,e,n)=>t(e,n);$f=1,jf=2,Sa=4,Wf=8,_a=16,Qo=32,Fu=64,Lu=128,Ea=256,ap=512,HA=_a|Qo,ps=class{constructor(e,n=e){m(this,"ref");m(this,"refTarget");m(this,"metadata");m(this,"encDescriptor");m(this,"root");m(this,"parentRef");m(this,"_parentIndex");m(this,"extraParents");m(this,"flags",Sa);m(this,"_fullSyncGen",0);m(this,"_isSchema",!1);m(this,"dirtyLow",0);m(this,"dirtyHigh",0);m(this,"opsLow",0);m(this,"opsHigh",0);m(this,"ops");m(this,"collDirty");m(this,"collPureOps");m(this,"unreliableRecorder");m(this,"paused",!1);m(this,"changesNode");m(this,"unreliableChangesNode");m(this,"visibleViews");m(this,"tagViews");m(this,"subscribedViews");this.ref=e,this.refTarget=n;let r=sp(e);this.encDescriptor=r,this.metadata=r.metadata;let s=r.isSchema;if(this._isSchema=s,this.ops=void 0,this.collDirty=void 0,this.collPureOps=void 0,s){let o=this.metadata?.[At]??0;o>7&&(this.ops=new Uint8Array(o+1))}else this.collDirty=new Map}get isArray(){return this.refTarget!==this.ref}get isFiltered(){return(this.flags&$f)!==0}set isFiltered(e){this.flags=e?this.flags|$f:this.flags&~$f}get isVisibilitySharedWithParent(){return(this.flags&jf)!==0}set isVisibilitySharedWithParent(e){this.flags=e?this.flags|jf:this.flags&~jf}get isNew(){return(this.flags&Sa)!==0}set isNew(e){this.flags=e?this.flags|Sa:this.flags&~Sa}get isUnreliable(){return(this.flags&Wf)!==0}set isUnreliable(e){this.flags=e?this.flags|Wf:this.flags&~Wf}get isPatchOnly(){return(this.flags&_a)!==0}set isPatchOnly(e){this.flags=e?this.flags|_a:this.flags&~_a}get isFullStateOnly(){return(this.flags&Qo)!==0}set isFullStateOnly(e){this.flags=e?this.flags|Qo:this.flags&~Qo}get isStreamCollection(){return(this.flags&Fu)!==0}set isStreamCollection(e){this.flags=e?this.flags|Fu:this.flags&~Fu}get needsRestage(){return(this.flags&Lu)!==0}set needsRestage(e){this.flags=e?this.flags|Lu:this.flags&~Lu}get hasFilteredFields(){return this.isFiltered||this.encDescriptor.hasAnyView}ensureUnreliableRecorder(){return this.unreliableRecorder===void 0&&(this.unreliableRecorder=this._isSchema?new Kf(this.metadata?.[At]??0):new Xf),this.unreliableRecorder}isFieldUnreliable(e){let n=this.encDescriptor;return n.hasAnyUnreliable?e<32?(n.unreliableBitmask&1<<e)!==0:De.hasUnreliableAtIndex(this.metadata,e):!1}isFieldFullStateOnly(e){if(this.isFullStateOnly)return!0;let n=this.encDescriptor;return n.hasAnyFullStateOnly?e<32?(n.fullStateOnlyBitmask&1<<e)!==0:De.hasFullStateOnlyAtIndex(this.metadata,e):!1}isFieldStream(e){let n=this.encDescriptor;return n.hasAnyStream?e<32?(n.streamBitmask&1<<e)!==0:De.hasStreamAtIndex(this.metadata,e):!1}_opAt(e){let n=this.ops;if(n!==void 0)return n[e];let r=(e&3)<<3;return e<4?this.opsLow>>>r&255:this.opsHigh>>>r&255}_opPut(e,n){let r=this.ops;if(r!==void 0){r[e]=n;return}let s=(e&3)<<3,o=~(255<<s);e<4?this.opsLow=this.opsLow&o|n<<s:this.opsHigh=this.opsHigh&o|n<<s}_markDirty(e){e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}record(e,n){if(this._isSchema){let r=this._opAt(e);r===0?this._opPut(e,n):r===N.DELETE?this._opPut(e,N.DELETE_AND_ADD):r===N.ADD&&n===N.DELETE_AND_ADD&&this._opPut(e,N.DELETE_AND_ADD),this._markDirty(e)}else{let r=this.collDirty,s=r.get(e),o;s===void 0?o=n:s===N.DELETE||s===N.ADD&&n===N.DELETE_AND_ADD?o=N.DELETE_AND_ADD:o=s,r.set(e,o)}}recordDelete(e,n){this._isSchema?(this._opPut(e,n),this._markDirty(e)):this.collDirty.set(e,n)}recordRaw(e,n){this._isSchema?(this._opPut(e,n),this._markDirty(e)):this.collDirty.set(e,n)}recordPure(e){if(this._isSchema)throw new Error("ChangeTree (Schema): pure operations are not supported");(this.collPureOps??(this.collPureOps=[])).push([this.collDirty.size,e])}operationAt(e){if(this._isSchema){let n=this._opAt(e);return n===0?void 0:n}return this.collDirty.get(e)}setOperationAt(e,n){if(this._isSchema)this._opPut(e,n);else{let r=this.collDirty;r.has(e)&&r.set(e,n)}}forEach(e){this.forEachWithCtx(e,VA)}forEachWithCtx(e,n){if(this._isSchema){let o=this.dirtyLow,i=this.dirtyHigh,a=this.ops;if(a!==void 0){for(;o!==0;){let c=o&-o,u=31-Math.clz32(c);o^=c,n(e,u,a[u])}for(;i!==0;){let c=i&-i,u=31-Math.clz32(c)+32;i^=c,n(e,u,a[u])}}else{let c=this.opsLow,u=this.opsHigh;for(;o!==0;){let l=o&-o,d=31-Math.clz32(l);o^=l,n(e,d,UA(c,u,d))}}return}let r=this.collDirty,s=this.collPureOps;if(s!==void 0&&s.length>0){let o=0,i=0;for(let[a,c]of r){for(;o<s.length&&s[o][0]<=i;){let u=s[o++][1];n(e,-u,u)}n(e,a,c),i++}for(;o<s.length;){let a=s[o++][1];n(e,-a,a)}}else for(let[o,i]of r)n(e,o,i)}size(){return this._isSchema?Vu(this.dirtyLow)+Vu(this.dirtyHigh):this.collDirty.size+(this.collPureOps?.length??0)}has(){return this._isSchema?(this.dirtyLow|this.dirtyHigh)!==0:this.collDirty.size>0||this.collPureOps!==void 0&&this.collPureOps.length>0}reset(){if(this._isSchema){this.dirtyLow=0,this.dirtyHigh=0,this.ops!==void 0?this.ops.fill(0):(this.opsLow=0,this.opsHigh=0);return}this.collDirty.clear(),this.collPureOps!==void 0&&(this.collPureOps.length=0),this.flags&=~ap}recycle(){if(this.root!==void 0)throw new Error(`@colyseus/schema: cannot recycle an attached ChangeTree (${this.ref?.constructor?.name}). Remove the instance from its parent collection before releasing it to a pool.`);this.reset(),this.unreliableRecorder?.reset(),this.flags=Sa|Lu,this._fullSyncGen=0,this.parentRef=void 0,this._parentIndex=void 0,this.extraParents=void 0,this.changesNode=void 0,this.unreliableChangesNode=void 0,this.paused=!1,this.visibleViews=void 0,this.tagViews=void 0,this.subscribedViews=void 0}insertAt(e,n){if(this._isSchema)throw new Error("ChangeTree (Schema): insertAt is not supported");let r=this.collDirty,s=new Map,o=!this.paused&&!this.isFullStateOnly;if(e>0)for(let[i,a]of r)i<e&&s.set(i,a);if(o)for(let i=0;i<n;i++)s.set(e+i,N.ADD);for(let[i,a]of r)i>=e&&s.set(i+n,a);this.collDirty=s,o&&this.root?.enqueueChangeTree(this)}removeAt(e,n){if(this._isSchema)throw new Error("ChangeTree (Schema): removeAt is not supported");let r=this.collDirty,s=e+n,o=!1;for(let a of r.keys())if(a>=s){o=!0;break}if(!o){for(let a=e;a<s;a++)r.delete(a);return}let i=new Map;for(let[a,c]of r)a<e?i.set(a,c):a>=s&&i.set(a-n,c);this.collDirty=i}unshift(e){this.insertAt(0,e)}setRoot(e){DA(this,e)}setParent(e,n,r){NA(this,e,n,r)}forEachChild(e){BA(this,e)}forEachChildWithCtx(e,n){Ca(this,e,n)}forEachLive(e){vA(this,e)}forEachLiveWithCtx(e,n){op(this,e,n)}operation(e){this.paused||this.isFullStateOnly||(this.recordPure(e),this.root?.enqueueChangeTree(this))}_routeAndRecord(e,n,r){if(!(this.paused||this.isFieldFullStateOnly(e))){if(this.isFieldUnreliable(e)&&!this.isNew){let s=this.ensureUnreliableRecorder();r?s.recordRaw(e,n):s.record(e,n),this.root?.enqueueUnreliable(this);return}r?this.recordRaw(e,n):this.record(e,n),this.root?.enqueueChangeTree(this)}}change(e,n=N.ADD){this._routeAndRecord(e,n,!1)}indexedOperation(e,n){this._routeAndRecord(e,n,!0)}getChange(e){return this.operationAt(e)}pause(){this.paused=!0}resume(){this.paused=!1}untracked(e){let n=this.paused;this.paused=!0;try{return e()}finally{this.paused=n}}markDirty(e,n=N.ADD){let r=this.paused;this.paused=!1;try{this.change(e,n)}finally{this.paused=r}}getValue(e,n=!1){return this.refTarget[st](e,n)}delete(e,n){if(e===void 0){try{throw new Error(`@colyseus/schema ${this.ref.constructor.name}: trying to delete non-existing index '${e}'`)}catch(o){console.warn(o)}return}if(this.paused||this.isFieldFullStateOnly(e))return this.getValue(e);let r=this.isFieldUnreliable(e)&&!this.isNew;r?this.ensureUnreliableRecorder().recordDelete(e,n??N.DELETE):this.recordDelete(e,n??N.DELETE);let s=this.getValue(e);return s&&s[I]&&this.root?.remove(s[I]),r?this.root?.enqueueUnreliable(this):this.root?.enqueueChangeTree(this),s}endEncode(){this.reset(),this.changesNode=void 0,this._isSchema||this.refTarget[us]?.(),this.isNew=!1}endEncodeUnreliable(){this.unreliableRecorder?.reset(),this.unreliableChangesNode=void 0,this._isSchema||this.refTarget[us]?.()}discard(){this._isSchema||this.refTarget[us]?.(),this.reset(),this.unreliableRecorder?.reset()}discardAll(){let e=n=>{if(n<0)return;let r=this.getValue(n);r&&r[I]&&r[I].discardAll()};this.forEach(e),this.unreliableRecorder?.forEach(e),this.discard()}get changed(){return this.has()||(this.unreliableRecorder?.has()??!1)}get parent(){return this.parentRef}get parentIndex(){return this._parentIndex}addParent(e,n){xA(this,e,n)}setParentIndex(e,n){_A(this,e,n)}removeParent(e=this.parent){return RA(this,e)}findParent(e){return EA(this,e)}hasParent(e){return ib(this,e)}indexInParent(e){return kA(this,e)}getAllParents(){return AA(this)}},Jf=class{constructor(e){m(this,"ref");m(this,"root");m(this,"parentRef");m(this,"paused",!1);m(this,"isNew",!1);m(this,"flags",0);this.ref=e}change(){}delete(){}indexedOperation(){}operation(){}setParent(){}addParent(){}setParentIndex(){}removeParent(){return!1}getChange(){return 0}discard(){}discardAll(){}pause(){}resume(){}untracked(e){return e()}markDirty(){}forEachChild(e){let n=this.ref;if(n[be]){if(typeof n[be]!="string")for(let[i,a]of n.entries())a&&e(a[I],n._collectionIndexes?.[i]??i);return}let s=n.constructor?.[Symbol.metadata];if(!s)return;let o=s[ls]??[];for(let i=0;i<o.length;i++){let a=o[i],c=n[s[a].name];c&&e(c[I],a)}}forEachChildWithCtx(e,n){this.forEachChild((r,s)=>n(e,r,s))}forEachLive(){}forEachLiveWithCtx(){}forEach(){}};jA=function(t,e,n,r,s,o,i,a){if(e[o.offset++]=(r|s)&255,s===N.DELETE)return;let c=n.encDescriptor,u=n.ref,l=u[Mt][r]??u[c.names[r]];el(t,e,c.types[r],l,s,o,c.encoders[r])},WA=function(t,e,n,r,s,o){if(e[o.offset++]=s&255,Se.number(e,r,o),s===N.DELETE)return;let i=n.ref;if((s&N.ADD)===N.ADD){let a=i.$indexes.get(r);Se.string(e,a,o)}el(t,e,i[be],i[st](r),s,o)},cp=function(t,e,n,r,s,o){if(e[o.offset++]=s&255,Se.number(e,r,o),s===N.DELETE)return;let i=n.ref;el(t,e,i[be],i[st](r),s,o)},qA=function(t,e,n,r,s,o,i,a){let c=n.refTarget,u=c[be],l=typeof u!="string",d=a&&n.isFiltered&&l,f;if(d){let p=c.tmpItems[r];if(!p)return;if(f=p[Q],s===N.DELETE)s=N.DELETE_BY_REFID;else if((s&N.ADD)===N.ADD)s=N.ADD_BY_REFID;else if((s&N.MOVE)===N.MOVE)return}else if(s===N.DELETE&&l){let p=c.tmpItems[r];if(!p)return;f=p[Q],s=N.DELETE_BY_REFID}else f=r;if(e[o.offset++]=s&255,Se.number(e,f,o),s===N.DELETE||s===N.DELETE_BY_REFID)return;let h=c[st](r,i);el(t,e,u,h,s,o)};fb=-1,In={Map:1,Array:2,Set:3,Collection:4,Stream:5};XA=function(t,e,n,r,s){let o=e[n.offset++],i=r.constructor[Symbol.metadata],a=o>>6<<6,c=o%(a||255),u=i[c];if(u===void 0)return console.warn("@colyseus/schema: field not defined at",{index:c,ref:r.constructor.name,metadata:i}),fb;let l=u.deprecated===!0,d=l?void 0:r[st](c),f=lp(t,a,r,c,d,u.type,e,n,s);l||(f!=null&&(r[u.name]=f),d!==f&&s?.push({ref:r,refId:t.currentRefId,op:a,field:u.name,value:f,previousValue:d}))},tl=function(t,e,n,r,s){let o=r[lt]??r,i=e[n.offset++];if(i===N.CLEAR){t.removeChildRefs(o,s),o.clear();return}let a=Pe.number(e,n),c=o[be],u=o.constructor.COLLECTION_KIND,l;(i&N.ADD)===N.ADD?u===In.Map?(l=Pe.string(e,n),o.setIndex(a,l)):l=a:l=o.getIndex(a);let d=o[st](a),f=lp(t,i,r,a,d,c,e,n,s);if(t.resyncVisited!==null&&db(t,r,i,l,d,f,s),f!=null)switch(u){case In.Map:o.$items.set(l,f);break;case In.Array:o.$setAt(a,f,t.resyncVisited!==null&&i===N.ADD?N.REPLACE:i);break;case In.Set:case In.Collection:case In.Stream:o.$items.has(a)||(o.$items.set(a,f),typeof o.$refId=="number"&&a>=o.$refId&&(o.$refId=a+1));break;default:console.warn(`@colyseus/schema: missing COLLECTION_KIND on ${o.constructor?.name} \u2014 item at index ${a} was not stored.`);break}d!==f&&s?.push({ref:r,refId:t.currentRefId,op:i,dynamicIndex:l,value:f,previousValue:d})},JA=function(t,e,n,r,s){let o=r[lt]??r,i=e[n.offset++],a;if(i===N.CLEAR){t.removeChildRefs(o,s),o.clear();return}else if(i===N.REVERSE){o.items.reverse();return}else if(i===N.DELETE_BY_REFID){let f=Pe.number(e,n),h=t.root.refs.get(f);if(h===void 0||(t.root.removeRef(f),a=o.findIndex(p=>p===h),a===-1))return;o[Bn](a),s?.push({ref:r,refId:t.currentRefId,op:N.DELETE,dynamicIndex:a,value:void 0,previousValue:h});return}else if(i===N.ADD_BY_REFID){let f=Pe.number(e,n),h=t.root.refs.get(f);h&&(a=o.findIndex(p=>p===h)),(a===-1||a===void 0)&&(a=o.length)}else a=Pe.number(e,n);let c=o[be],u=a,l=o.items[a],d=lp(t,i,r,a,l,c,e,n,s);t.resyncVisited!==null&&db(t,r,i,a,l,d,s),d!=null&&d!==l&&o.$setAt(a,d,t.resyncVisited!==null&&i===N.ADD?N.REPLACE:i),l!==d&&s?.push({ref:r,refId:t.currentRefId,op:i,dynamicIndex:u,value:d,previousValue:l})},ka=class extends Error{};ZA=(t,e)=>{let n=t.toString(),r=e.toString();return n<r?-1:n>r?1:0},eg={get:(t,e)=>typeof e!="symbol"&&!isNaN(e)?t.items[e]:Reflect.get(t,e),set:(t,e,n)=>{if(typeof e!="symbol"&&!isNaN(e)){if(n==null)t.$deleteAt(e);else{let r;if(n[I]){nl(n,t[be],t,e);let s=t.items[e];t.isMovingItems?(r=t.$wireIndex(Number(e)),s!==void 0?n[I].isNew?t[I].indexedOperation(r,N.MOVE_AND_ADD):(t[I].getChange(r)&N.DELETE)===N.DELETE?t[I].indexedOperation(r,N.DELETE_AND_MOVE):t[I].indexedOperation(r,N.MOVE):n[I].isNew&&t[I].indexedOperation(r,N.ADD),n[I].setParent(t,t[I].root,r)):r=t.$changeAt(Number(e),n),s!==void 0&&s[I].root?.remove(s[I])}else r=t.$changeAt(Number(e),n);t.items[e]=n,r!==void 0&&(t.tmpItems[r]=n)}return!0}return Reflect.set(t,e,n)},deleteProperty:(t,e)=>(typeof e=="number"?t.$deleteAt(e):delete t[e],!0),has:(t,e)=>typeof e!="symbol"&&!isNaN(Number(e))?Reflect.has(t.items,e):Reflect.has(t,e)},an=class an{constructor(...e){m(this,dg);m(this,lg);m(this,ug);m(this,cg);m(this,"items",[]);m(this,"tmpItems",[]);m(this,"deletedIndexes",[]);m(this,"isMovingItems",!1);m(this,"_needsCompaction",!1);m(this,og);this[be]=void 0,this[lt]=this;let n=new Proxy(this,eg);return Object.defineProperty(this,I,{value:new ps(n,this),enumerable:!1,writable:!0}),e.length>0&&this.push(...e),n}static[(dg=I,lg=Q,ug=lt,cg=be,ag=cr,ig=Dn,Xs)](e,n,r){if(!r)return!0;let s=e[lt]??e;return typeof s[be]=="string"||r.isChangeTreeVisible(s.tmpItems[n]?.[I])}static is(e){return Array.isArray(e)||e.array!==void 0}static from(e){return new an(...Array.from(e))}static initializeForDecoder(){let e=Object.create(an.prototype);e.items=[],e.isMovingItems=!1,e._needsCompaction=!1,e[be]=void 0,e[lt]=e;let n=new Proxy(e,eg);return si(e,n),n}set length(e){e===0?this.clear():e<this.items.length?this.splice(e,this.length-e):console.warn("ArraySchema: can't set .length to a higher value than its length.")}get length(){return this.items.length}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}push(...e){let n=this[lt],r=n.items,s=n.tmpItems,o=n[I],i=n[be],a=s.length;for(let c=0,u=e.length;c<u;c++,a++){let l=e[c];if(l==null)return;typeof l=="object"&&i&&nl(l,i,n,c),o.indexedOperation(a,N.ADD),r.push(l),s.push(l),l[I]?.setParent(this,o.root,a)}return a}pop(){let e=this[lt],n=e.tmpItems,r=e.deletedIndexes,s=-1;for(let i=n.length-1;i>=0;i--)if(r[i]!==!0){s=i;break}if(s<0)return;let o=e.$isUnsentAdd(s);return e[I].delete(s),o?e.$cancelAdd(s):r[s]=!0,e.items.pop()}at(e){return e<0&&(e+=this.length),this.items[e]}$wireIndex(e){let n=this.deletedIndexes;if(n.length===0)return e;let r=this.tmpItems,s=0;for(let o=0;o<r.length;o++)if(n[o]!==!0){if(s===e)return o;s++}return r.length+(e-s)}$isUnsentAdd(e){let n=this[I];return(n.flags&(ap|Fu))===0&&!n.paused&&typeof this[be]!="string"&&n.operationAt(e)===N.ADD}$cancelAdd(e,n=!0){let r=this[I],s=this.tmpItems[e];this.tmpItems.splice(e,1),this.deletedIndexes.length>0&&this.deletedIndexes.splice(e,1),r.removeAt(e,1);let o=s?.[I];o!==void 0&&o.root===void 0&&o.removeParent(this),n&&this.$reindexChildren(e)}$reindexChildren(e,n){if(!this[I].hasFilteredFields||typeof this[be]=="string")return;let r=this.tmpItems,s=r.length;if(n!==void 0)for(;e<s&&r[e]===n[e];)e++;for(let o=e;o<s;o++)r[o]?.[I]?.setParentIndex(this,o)}$changeAt(e,n){if(n==null){console.error("ArraySchema items cannot be null nor undefined; Use `splice(index, 1)` instead.");return}if(this.items[e]===n)return;let r=this.items[e]!==void 0?typeof n=="object"?N.DELETE_AND_ADD:N.REPLACE:N.ADD,s=this.$wireIndex(e),o=this[I];return o.change(s,r),n[I]?.setParent(this,o.root,s),s}$deleteAt(e,n){this[I].delete(this.$wireIndex(e),n)}$setAt(e,n,r){r===N.ADD&&this.items[e]!==void 0?this.items.splice(e,0,n):r===N.DELETE_AND_MOVE?(this.items.splice(e,1),this.items[e]=n):(e>this.items.length&&(this._needsCompaction=!0),this.items[e]=n)}clear(){let e=this[lt];if(e.items.length===0)return;let n=e[I];n.forEachChild((r,s)=>{n.root?.remove(r)}),n.discard(),n.operation(N.CLEAR),e.items.length=0,e.tmpItems.length=0}[Nn](){let e=this[lt]??this,n=e[I];if(n.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed ArraySchema (pooling not supported).");let r=e.items;for(let s=0;s<r.length;s++)r[s]?.[Nn]?.();e.items.length=0,e.tmpItems.length=0,e.deletedIndexes.length=0,n.recycle(),e[Q]=void 0}concat(...e){return new an(...this.items.concat(...e))}join(e){return this.items.join(e)}reverse(){let e=this[lt],n=e[I];if(n.has()||e.deletedIndexes.length>0){let r=e.items.slice().reverse();return this.clear(),this.push(...r),this}return n.operation(N.REVERSE),e.items.reverse(),e.tmpItems.reverse(),e.$reindexChildren(0),this}shift(){let e=this[lt],n=e.items;if(n.length===0)return;let r=e[I],s=e.deletedIndexes,o=0;for(;s[o]===!0;)o++;let i=e.$isUnsentAdd(o);return r.delete(o,N.DELETE),i?e.$cancelAdd(o):s[o]=!0,n.shift()}slice(e,n){let r=new an;return r.push(...this.items.slice(e,n)),r}sort(e=ZA){let n=this[lt];n.isMovingItems=!0;let r=n[I];return n.items.sort(e).forEach((o,i)=>r.change(i,N.REPLACE)),n.tmpItems.sort(e),n.$reindexChildren(0),n.isMovingItems=!1,this}splice(e,n,...r){let s=this[lt],o=s[I],i=s.items,a=s.tmpItems,c=s.deletedIndexes,u=i.length,l=a.length,d=r.length,f=[];for(let p=0;p<l;p++)c[p]!==!0&&f.push(p);let h;if(u>e){n===void 0&&(n=u-e);for(let p=e;p<e+n;p++){let y=f[p],S=s.$isUnsentAdd(y);o.delete(y,N.DELETE),S?(h??(h=[])).push(y):c[y]=!0}}else n=0;if(d>0){let p=f[e]??u,y=Math.min(d,n);for(let b=0;b<y;b++){let x=p+b,R,A=h!==void 0?h.indexOf(x):-1;A!==-1?(h.splice(A,1),R=N.ADD):R=c[x]?N.DELETE_AND_ADD:N.ADD,o.indexedOperation(x,R),a[x]=r[b],c[x]=!1,r[b][I]?.setParent(this,o.root,x)}let S=d-y;if(S>0){let b=p+y;o.insertAt(b,S);for(let x=0;x<S;x++)r[y+x][I]?.setParent(this,o.root,b+x);c.length>0&&c.splice(b,0,...new Array(S).fill(!1)),a.splice(b,0,...r.slice(y)),s.$reindexChildren(b+S)}}if(h!==void 0&&h.length>0){for(let p=h.length-1;p>=0;p--)s.$cancelAdd(h[p],!1);s.$reindexChildren(h[0])}return o.root?.enqueueChangeTree(o),i.splice(e,n,...r)}unshift(...e){let n=this[lt],r=n[I];r.unshift(e.length);for(let o=0;o<e.length;o++)e[o]?.[I]?.setParent(this,r.root,o);let s=n.deletedIndexes;return s.length>0&&s.unshift(...new Array(e.length).fill(!1)),n.tmpItems.unshift(...e),n.$reindexChildren(e.length),n.items.unshift(...e)}indexOf(e,n){return this.items.indexOf(e,n)}lastIndexOf(e,n=this.length-1){return this.items.lastIndexOf(e,n)}every(e,n){return this.items.every(e,n)}some(e,n){return this.items.some(e,n)}forEach(e,n){return this.items.forEach(e,n)}map(e,n){return this.items.map(e,n)}filter(e,n){return this.items.filter(e,n)}reduce(e,n){return this.items.reduce.apply(this.items,arguments)}reduceRight(e,n){return this.items.reduceRight.apply(this.items,arguments)}find(e,n){return this.items.find(e,n)}findIndex(e,n){return this.items.findIndex(e,n)}fill(e,n,r){throw new Error("ArraySchema#fill() not implemented")}copyWithin(e,n,r){throw new Error("ArraySchema#copyWithin() not implemented")}toString(){return this.items.toString()}toLocaleString(){return this.items.toLocaleString()}[Symbol.iterator](){return this.items[Symbol.iterator]()}static get[Symbol.species](){return an}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}includes(e,n){return this.items.includes(e,n)}flatMap(e,n){throw new Error("ArraySchema#flatMap() is not supported.")}flat(e){throw new Error("ArraySchema#flat() is not supported.")}findLast(){return this.items.findLast.apply(this.items,arguments)}findLastIndex(...e){return this.items.findLastIndex.apply(this.items,arguments)}with(e,n){let r=this.items.slice();return e<0&&(e+=this.length),r[e]=n,new an(...r)}toReversed(){return this.items.slice().reverse()}toSorted(e){return this.items.slice().sort(e)}toSpliced(e,n,...r){let s=this.items.slice();return s.splice.apply(s,arguments),s}shuffle(){return this.move(e=>{let n=this.items.length;for(;n!=0;){let r=Math.floor(Math.random()*n);n--,[this[n],this[r]]=[this[r],this[n]]}})}move(e){return this.isMovingItems=!0,e(this),this.isMovingItems=!1,this}[(og=Symbol.unscopables,st)](e,n=!1){let r=this[lt]??this;return n||r.deletedIndexes[e]?r.items[e]:r.tmpItems[e]||r.items[e]}[Bn](e){let n=this[lt]??this;n.items[e]=void 0,n._needsCompaction=!0}[us](){let e=this.tmpItems;this.tmpItems=this.items.slice(),this.deletedIndexes.length>0&&(this.$reindexChildren(0,e),this.deletedIndexes.length=0)}[zu](){let e=this[lt]??this;e._needsCompaction&&(e._needsCompaction=!1,e.items=e.items.filter(n=>n!==void 0))}[ri](e,n,r){let s=this[lt]??this,o=s.items,i=!1;for(let a=0;a<o.length;a++){let c=o[a];if(e.has(a)){r(c);continue}i=!0,n(c,a),s[Bn](a)}i&&s[zu]()}toArray(){return this.items.slice(0)}toJSON(){return this.toArray().map(e=>typeof e.toJSON=="function"?e.toJSON():e)}clone(e){let n;return e?(n=new an,n.push(...this.items)):n=new an(...this.map(r=>r[I]?r.clone():r)),n}};m(an,ag,qA),m(an,ig,JA),m(an,"COLLECTION_KIND",In.Array);ds=an;Ir("array",{constructor:ds});ju=class{constructor(){m(this,"keyByIndex",new Map);m(this,"indexByKey",Object.create(null));m(this,"nextIndex",0);m(this,"snapshots")}indexOf(e){let n=this.indexByKey[e];return n===void 0?void 0:n}assign(e){let n=this.nextIndex++;return this.indexByKey[e]=n,this.keyByIndex.set(n,e),n}snapshot(e,n){(this.snapshots??(this.snapshots=new Map)).set(e,n)}forgetSnapshot(e){this.snapshots?.delete(e)}snapshotAt(e){return this.snapshots?.get(e)}setIndex(e,n){this.keyByIndex.set(e,n),this.indexByKey[n]=e}keyOf(e){return this.keyByIndex.get(e)}cleanupAfterEncode(){if(this.snapshots!==void 0){for(let[e]of this.snapshots){let n=this.keyByIndex.get(e);n!==void 0&&(delete this.indexByKey[n],this.keyByIndex.delete(e))}this.snapshots.clear()}}reset(){this.indexByKey=Object.create(null),this.keyByIndex.clear(),this.snapshots?.clear(),this.nextIndex=0}},or=class or{constructor(e){m(this,yg);m(this,mg);m(this,"childType");m(this,hg);m(this,"$items",new Map);m(this,"journal",new ju);m(this,"_stream");if(Object.defineProperty(this,I,{value:new ps(this),enumerable:!1,writable:!0}),this[be]=void 0,e)if(e instanceof Map||e instanceof or)e.forEach((n,r)=>this.set(r,n));else for(let n in e)this.set(n,e[n])}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Or())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Or())).priority=e}get $indexes(){return this.journal.keyByIndex}get _collectionIndexes(){return this.journal.indexByKey}static[(yg=I,mg=Q,hg=be,pg=cr,fg=Dn,Xs)](e,n,r){if(!r||typeof e[be]=="string")return!0;let s=e[st](n)??e.journal.snapshotAt(n);return r.isChangeTreeVisible(s[I])}static is(e){return e.map!==void 0}static initializeForDecoder(){let e=Object.create(or.prototype);return e.$items=new Map,e.journal=new ju,e[be]=void 0,si(e),e}[Symbol.iterator](){return this.$items[Symbol.iterator]()}get[Symbol.toStringTag](){return this.$items[Symbol.toStringTag]}static get[Symbol.species](){return or}set(e,n){if(n==null)throw new Error(`MapSchema#set('${e}', ${n}): trying to set ${n} value on '${e}'.`);typeof n=="object"&&this[be]&&nl(n,this[be],this,e),e=e.toString();let r=this[I],s=n[I]!==void 0,o=this.journal,i=o.indexOf(e),a;if(i!==void 0){a=N.REPLACE;let c=this.$items.get(e);if(c===n)return;s&&(a=N.DELETE_AND_ADD,c!==void 0&&c[I].root?.remove(c[I])),o.snapshotAt(i)!==void 0&&o.forgetSnapshot(i)}else i=o.assign(e),a=N.ADD;return this.$items.set(e,n),a===N.ADD&&r.isStreamCollection?r.root!==void 0&&Ju(this,r.root,i):r.change(i,a),s&&n[I].setParent(this,r.root,i),this}get(e){return this.$items.get(e)}getOrInsert(e,n){return this.$items.has(e)?this.$items.get(e):(this.set(e,n),n)}getOrInsertComputed(e,n){if(this.$items.has(e))return this.$items.get(e);let r=n(e);return this.set(e,r),r}delete(e){if(!this.$items.has(e))return!1;let n=this.journal.indexOf(e),r=this.$items.get(e),s=this[I];if(s.isStreamCollection){let o=s.root,i=!1;return o!==void 0&&(i=Zu(this,o,this[Q],n)),r?.[I]!==void 0&&o?.remove(r[I]),this.$items.delete(e),i||this.journal.snapshot(n,r),!0}return this.journal.snapshot(n,r),s.delete(n),this.$items.delete(e)}clear(){let e=this[I];e.discard(),e.forEachChild((n,r)=>{e.root?.remove(n)}),this.journal.reset(),this.$items.clear(),e.operation(N.CLEAR)}[Nn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed MapSchema (pooling not supported).");this.$items.forEach(n=>n?.[Nn]?.()),this.$items.clear(),this.journal.reset(),e.recycle(),this[Q]=void 0}has(e){return this.$items.has(e)}forEach(e){this.$items.forEach(e)}entries(){return this.$items.entries()}keys(){return this.$items.keys()}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}setIndex(e,n){this.journal.setIndex(e,n)}getIndex(e){return this.journal.keyOf(e)}[st](e){let n=this.journal.keyOf(e);return n!==void 0?this.$items.get(n):void 0}[Bn](e){let n=this.journal.keyOf(e);n!==void 0&&(this.$items.delete(n),this.journal.keyByIndex.delete(e))}[ri](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=new Set)).add(i),n(o,i)}),s!==null){s.forEach(i=>{this.$items.delete(i),delete this.journal.indexByKey[i]});let o=[];this.journal.keyByIndex.forEach((i,a)=>{s.has(i)&&o.push(a)});for(let i=0;i<o.length;i++)this.journal.keyByIndex.delete(o[i])}}[us](){this.journal.cleanupAfterEncode()}_dropView(e){Qu(this,e)}_unregister(){}toJSON(){return Object.fromEntries(Array.from(this,([n,r])=>[n,typeof r.toJSON=="function"?r.toJSON():r]))}clone(e){let n;return e?n=Object.assign(new or,this):(n=new or,this.forEach((r,s)=>{r[I]?n.set(s,r.clone()):n.set(s,r)})),n}};m(or,pg,WA),m(or,fg,tl),m(or,"COLLECTION_KIND",In.Map);fs=or;Ir("map",{constructor:fs});as=class as{constructor(e){m(this,xg);m(this,Sg);m(this,wg);m(this,"$items",new Map);m(this,"deletedItems",{});m(this,"$refId",0);m(this,"_stream");Object.defineProperty(this,I,{value:new ps(this),enumerable:!1,writable:!0}),this[be]=void 0,e&&e.forEach(n=>this.add(n))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Or())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Or())).priority=e}static[(xg=I,Sg=Q,wg=be,bg=cr,gg=Dn,Xs)](e,n,r){return!r||typeof e[be]=="string"||r.isChangeTreeVisible((e[st](n)??e.deletedItems[n])[I])}static is(e){return e.collection!==void 0}static initializeForDecoder(){let e=Object.create(as.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[be]=void 0,si(e),e}add(e){let n=this.$refId++,r=this[I];return this.$items.set(n,e),r.isStreamCollection?r.root!==void 0&&Ju(this,r.root,n):r.change(n),e[I]!==void 0&&e[I].setParent(this,r.root,n),n}at(e){let n=Array.from(this.$items.keys())[e];return this.$items.get(n)}entries(){return this.$items.entries()}delete(e){let n=this.$items.entries(),r,s;for(;(s=n.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let o=this[I];if(o.isStreamCollection){let i=o.root,a=this.$items.get(r);return i!==void 0&&Zu(this,i,this[Q],r),a?.[I]!==void 0&&i?.remove(a[I]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=o.delete(r),this.$items.delete(r)}clear(){let e=this[I];e.discard(),e.forEachChild((n,r)=>{e.root?.remove(n)}),this.$items.clear(),e.operation(N.CLEAR)}[Nn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed CollectionSchema (pooling not supported).");this.$items.forEach(n=>n?.[Nn]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[Q]=void 0}has(e){return Array.from(this.$items.values()).some(n=>n===e)}forEach(e){this.$items.forEach((n,r,s)=>e(n,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,n){}getIndex(e){return e}[st](e){return this.$items.get(e)}[Bn](e){this.$items.delete(e)}[ri](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=[])).push(i),n(o,i)}),s!==null)for(let o=0;o<s.length;o++)this[Bn](s[o])}[us](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){Qu(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((n,r)=>{e.push(typeof n.toJSON=="function"?n.toJSON():n)}),e}clone(e){let n;return e?n=Object.assign(new as,this):(n=new as,this.forEach(r=>{r[I]?n.add(r.clone()):n.add(r)})),n}};m(as,bg,cp),m(as,gg,tl),m(as,"COLLECTION_KIND",In.Collection);Aa=as;Ir("collection",{constructor:Aa});cs=class cs{constructor(e){m(this,Ag);m(this,kg);m(this,Eg);m(this,"$items",new Map);m(this,"deletedItems",{});m(this,"$refId",0);m(this,"_stream");Object.defineProperty(this,I,{value:new ps(this),enumerable:!1,writable:!0}),this[be]=void 0,e&&e.forEach(n=>this.add(n))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Or())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Or())).priority=e}static[(Ag=I,kg=Q,Eg=be,Rg=cr,_g=Dn,Xs)](e,n,r){return!r||typeof e[be]=="string"||r.isVisible((e[st](n)??e.deletedItems[n])[I])}static is(e){return e.set!==void 0}static initializeForDecoder(){let e=Object.create(cs.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[be]=void 0,si(e),e}add(e){if(this.has(e))return!1;let n=this.$refId++,r=this[I];return this.$items.set(n,e),r.isStreamCollection?r.root!==void 0&&Ju(this,r.root,n):r.change(n,N.ADD),e[I]!==void 0&&e[I].setParent(this,r.root,n),n}entries(){return this.$items.entries()}delete(e){let n=this.$items.entries(),r,s;for(;(s=n.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let o=this[I];if(o.isStreamCollection){let i=o.root,a=this.$items.get(r);return i!==void 0&&Zu(this,i,this[Q],r),a?.[I]!==void 0&&i?.remove(a[I]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=o.delete(r),this.$items.delete(r)}clear(){let e=this[I];e.discard(),this.$items.clear(),e.operation(N.CLEAR)}[Nn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed SetSchema (pooling not supported).");this.$items.forEach(n=>n?.[Nn]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[Q]=void 0}has(e){let n=this.$items.values(),r=!1,s;for(;(s=n.next())&&!s.done;)if(e===s.value){r=!0;break}return r}forEach(e){this.$items.forEach((n,r,s)=>e(n,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,n){}getIndex(e){return e}[st](e){return this.$items.get(e)}[Bn](e){this.$items.delete(e)}[ri](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=[])).push(i),n(o,i)}),s!==null)for(let o=0;o<s.length;o++)this[Bn](s[o])}[us](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){Qu(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((n,r)=>{e.push(typeof n.toJSON=="function"?n.toJSON():n)}),e}clone(e){let n;return e?n=Object.assign(new cs,this):(n=new cs,this.forEach(r=>{r[I]?n.add(r.clone()):n.add(r)})),n}};m(cs,Rg,cp),m(cs,_g,tl),m(cs,"COLLECTION_KIND",In.Set);Pa=cs;Ir("set",{constructor:Pa});Mr=class Mr{constructor(){m(this,Cg);m(this,Mg);m(this,vg);m(this,"$items",new Map);m(this,"$nextPosition",0);m(this,"_itemIndex",new Map);m(this,"_stream");Object.defineProperty(this,I,{value:new ps(this),enumerable:!1,writable:!0}),this[be]=void 0}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Or())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Or())).priority=e}static[(Cg=I,Mg=Q,vg=be,Tg=cr,Pg=Dn,Xs)](e,n,r){if(!r)return!0;let s=e[st](n);return s===void 0?!1:r.isVisible(s[I])}static is(e){return e&&e.stream!==void 0}static initializeForDecoder(){let e=Object.create(Mr.prototype);return e.$items=new Map,e.$nextPosition=0,e._itemIndex=new Map,e[be]=void 0,si(e),e}add(e){if(this._itemIndex.has(e))return-1;let n=this.$nextPosition++;this.$items.set(n,e),this._itemIndex.set(e,n);let s=this[I].root;return e[I]!==void 0&&e[I].setParent(this,s,n),s!==void 0&&Ju(this,s,n),n}remove(e){let n=this._itemIndex.get(e);if(n===void 0)return!1;this._itemIndex.delete(e),this.$items.delete(n);let r=this[I].root;return r!==void 0&&(Zu(this,r,this[Q],n),e[I]!==void 0&&r.remove(e[I])),!0}has(e){return this._itemIndex.has(e)}clear(){let e=this[I].root;if(e!==void 0){lA(this,e,this[Q]);for(let n of this.$items.values())n[I]!==void 0&&e.remove(n[I])}this.$items.clear(),this._itemIndex.clear()}forEach(e){for(let[n,r]of this.$items)e(r,n,this)}values(){return this.$items.values()}entries(){return this.$items.entries()}[Symbol.iterator](){return this.$items.values()}get size(){return this.$items.size}get length(){return this.$items.size}setIndex(e,n){}getIndex(e){return e}[st](e){return this.$items.get(e)}[Bn](e){let n=this.$items.get(e);n!==void 0&&(this._itemIndex.delete(n),this.$items.delete(e))}[ri](){}[us](){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach(n=>{e.push(typeof n?.toJSON=="function"?n.toJSON():n)}),e}clone(e){if(e)return Object.assign(new Mr,this);let n=new Mr;return n.maxPerTick=this.maxPerTick,this.forEach(r=>{n.add(typeof r?.clone=="function"?r.clone():r)}),n}_dropView(e){Qu(this,e)}_unregister(){}};m(Mr,"$isStream",!0),m(Mr,Tg,cp),m(Mr,Pg,tl),m(Mr,"COLLECTION_KIND",In.Stream);Wu=Mr;Ir("stream",{constructor:Wu});Og=Fg;ur=class{constructor(e){m(this,Og,!0);m(this,"_type");m(this,"_default");m(this,"_hasDefault",!1);m(this,"_view");m(this,"_unreliable",!1);m(this,"_patchOnly",!1);m(this,"_deprecated",!1);m(this,"_deprecatedThrows",!0);m(this,"_fullStateOnly",!1);m(this,"_stream",!1);m(this,"_optional",!1);m(this,"_noSync",!1);m(this,"_streamPriority");this._type=e}default(e){return this._default=e,this._hasDefault=!0,this}view(e){return this._view=e??-1,this}unreliable(){return this._unreliable=!0,this}patchOnly(){return this._patchOnly=!0,this}fullStateOnly(){return this._fullStateOnly=!0,this}noSync(){return this._noSync=!0,this}stream(){let e=this._type;if(e&&typeof e=="object"&&e.array!==void 0)throw new Error(nb);return this._stream=!0,this}priority(e){return this._streamPriority=e,this}deprecated(e=!0){return this._deprecated=!0,this._deprecatedThrows=e,this}optional(){return this._optional=!0,this}toDefinition(){return{type:this._type,default:this._default,hasDefault:this._hasDefault,view:this._view,unreliable:this._unreliable,patchOnly:this._patchOnly,deprecated:this._deprecated,deprecatedThrows:this._deprecatedThrows,fullStateOnly:this._fullStateOnly,stream:this._stream,optional:this._optional,noSync:this._noSync,streamPriority:this._streamPriority}}};QA=(t=>new ur({array:Oa(t)})),eP=(t=>new ur({map:Oa(t)})),tP=(t=>new ur({set:Oa(t)})),nP=(t=>new ur({collection:Oa(t)})),rP=(t=>{let e=new ur({stream:Oa(t)});return e._stream=!0,e}),sP=(t=>new ur(t));Y=Object.freeze({string:Ft("string"),number:Ft("number"),boolean:Ft("boolean"),int8:Ft("int8"),uint8:Ft("uint8"),int16:Ft("int16"),uint16:Ft("uint16"),int32:Ft("int32"),uint32:Ft("uint32"),int64:Ft("int64"),uint64:Ft("uint64"),float32:Ft("float32"),float64:Ft("float64"),bigint64:Ft("bigint64"),biguint64:Ft("biguint64"),ref:sP,array:QA,map:eP,set:tP,collection:nP,stream:rP,quantized:tg,angle:t=>tg({min:0,max:Math.PI*2,mode:"wrap",bits:t?.bits??16})}),rl=-1;cP={number:"number",int8:"number",uint8:"number",int16:"number",uint16:"number",int32:"number",uint32:"number",int64:"number",uint64:"number",float32:"number",float64:"number",bigint64:"bigint",biguint64:"bigint",string:"string",boolean:"boolean"};Cn=class Cn{constructor(e){m(this,Dg);m(this,Ig);Cn.initialize(this),e&&Cn.assignProps(this,e)}static initialize(e){Object.defineProperty(e,I,{value:new ps(e),enumerable:!1,writable:!0}),e[Mt]=[]}static initializeForDecoder(){let e=Object.create(this.prototype);return si(e),e[Mt]=[],e}static reset(e){let n=e?.[I];if(n===void 0||typeof n.recycle!="function")throw new Error("@colyseus/schema: Schema.reset() requires a tracked (encoder-side) instance.");if(n.extraParents!==void 0)throw new Error(`@colyseus/schema: cannot reset a shared instance (${e.constructor.name}) with multiple parents.`);e[Nn]()}[(Bg=cr,Ng=Dn,Dg=Q,Ig=Mt,Nn)](){let n=this.constructor[Symbol.metadata]?.[ls]??[],r=this[Mt];for(let s=0;s<n.length;s++)r[n[s]]?.[Nn]?.();this[I].recycle(),this[Q]=void 0}static is(e){let n=e[Symbol.metadata];return typeof n=="object"&&n!==null}static isSchema(e){return typeof e?.assign=="function"}static[ar](e,n,r=N.ADD){e.change(n,r)}static[Xs](e,n,r){let o=e.constructor[Symbol.metadata][n]?.tag;return r===void 0?o===void 0:o===void 0?!0:o===rl?r.isChangeTreeVisible(e[I]):r.hasTagOnTree(e[I],o)}assign(e){return Cn.assignProps(this,e),this}static assignProps(e,n){let r=e.constructor[Symbol.metadata];if(r&&r[At]!==void 0)for(let o=0;o<=r[At];o++){let i=r[o];if(!i)continue;let a=n[i.name];a!==void 0&&(e[i.name]=a)}let s=Object.keys(n);for(let o=0;o<s.length;o++){let i=s[o];r&&r[i]!==void 0||(e[i]=n[i])}}restore(e){let n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r],o=s.name,i=s.type,a=e[o];if(a!=null){if(typeof i=="string")this[o]=a;else if(Cn.is(i)){let c=new i;c.restore(a),this[o]=c}else if(typeof i=="object"){let c=Object.keys(i)[0],u=i[c];if(c==="map"){let l=this[o];for(let d in a)if(Cn.is(u)){let f=new u;f.restore(a[d]),l.set(d,f)}else l.set(d,a[d])}else if(c==="array"){let l=this[o];for(let d=0;d<a.length;d++)if(Cn.is(u)){let f=new u;f.restore(a[d]),l.push(f)}else l.push(a[d])}}}}return this}setDirty(e,n){let r=this.constructor[Symbol.metadata];this[I].change(r[r[e]].index,n)}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}clone(){let e=Object.create(this.constructor.prototype);Cn.initialize(e);let n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r].name;typeof this[s]=="object"&&typeof this[s]?.clone=="function"?e[s]=this[s].clone():e[s]=this[s]}return e}toJSON(){let e={},n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r],o=s.name;!s.deprecated&&this[o]!==null&&typeof this[o]<"u"&&(e[o]=typeof this[o].toJSON=="function"?this[o].toJSON():this[o])}return e}discardAllChanges(){this[I].discardAll()}[st](e){let n=this.constructor[Symbol.metadata];return this[n[e].name]}[Bn](e){let n=this.constructor[Symbol.metadata];this[n[e].name]=void 0}static debugRefIds(e,n=!1,r=0,s,o=""){let i=n?` - ${JSON.stringify(e.toJSON())}`:"",a=e[I],c=e[Q],u=s?s.root:a.root,l=u?.refCount?.[c]>1?` [\xD7${u.refCount[c]}]`:"",d=`${yP(r)}${o}${e.constructor.name} (refId: ${c})${l}${i}
|
|
5
|
+
`;return a.forEachChild((f,h)=>{let p=h;typeof h=="number"&&e.$indexes&&(p=e.$indexes.get(h)??h);let y=e.forEach!==void 0&&p!==void 0?`["${p}"]: `:"";d+=this.debugRefIds(f.ref,n,r+1,s,y)}),d}static debugRefIdEncodingOrder(e,n="allChanges"){let r=[],s=e[I];if(n==="changes"){let c=s.root.changes?.next;for(;c;)c.changeTree&&r.push(c.changeTree.ref[Q]),c=c.next;return r}let o=n==="allFilteredChanges",i=new Set,a=c=>{i.has(c)||(i.add(c),c.isFiltered===o&&r.push(c.ref[Q]),c.forEachChild((u,l)=>a(u)))};return a(s),r}static debugRefIdsFromDecoder(e){return this.debugRefIds(e.state,!1,0,e)}static debugChanges(e,n=!1){let r=e[I],s=n?"allChanges":"changes",o=`${e.constructor.name} (${e[Q]}) -> .${s}:
|
|
6
6
|
`;return n?r.forEachLive(i=>{o+=`- [${i}]: ADD (${JSON.stringify(r.getValue(Number(i),!0))})
|
|
7
7
|
`}):r.forEach((i,a)=>{i<0||!a||(o+=`- [${i}]: ${N[a]} (${JSON.stringify(r.getValue(Number(i),!1))})
|
|
8
|
-
`)}),o}};m(
|
|
8
|
+
`)}),o}};m(Cn,Bg,jA),m(Cn,Ng,XA);Xe=Cn;Lg(Xe);ng={value:0,enumerable:!1,writable:!0},Zf=class{constructor(e,n=0){m(this,"types");m(this,"nextUniqueId",0);m(this,"refCount",{});m(this,"changeTrees",{});m(this,"changes",Qy());m(this,"unreliableChanges",Qy());m(this,"pendingFilterRefresh",[]);m(this,"_nodePool",[]);m(this,"_nextViewId",0);m(this,"_freeViewIds",[]);m(this,"activeViews",new Map);m(this,"streamTrees",new Set);this.types=e,this.nextUniqueId=n}enqueueFilterRefresh(e){this.types.hasFilters&&(e.flags&Ea||(e.flags|=Ea,this.pendingFilterRefresh.push(e)))}acquireViewId(){return this._freeViewIds.length>0?this._freeViewIds.pop():this._nextViewId++}releaseViewId(e){this._freeViewIds.push(e)}registerView(e){this.activeViews.set(e.id,new WeakRef(e))}unregisterView(e){this.activeViews.delete(e.id);let n=e.id;for(let r of this.streamTrees)r._dropView(n)}forEachActiveView(e){for(let[n,r]of this.activeViews){let s=r.deref();if(s===void 0){this.activeViews.delete(n);for(let o of this.streamTrees)o._dropView(n);continue}e(s)}}registerStream(e){this.streamTrees.add(e)}unregisterStream(e){this.streamTrees.delete(e)}add(e){let n=e.ref;n[Q]===void 0&&(ng.value=this.nextUniqueId++,Object.defineProperty(n,Q,ng));let r=n[Q],s=this.changeTrees[r]===void 0;s&&(this.changeTrees[r]=e);let o=this.refCount[r];return(o===0||e.needsRestage)&&(e.needsRestage=!1,e.forEachLiveWithCtx(e,ab)),this.refCount[r]=(o||0)+1,o>0&&this.enqueueFilterRefresh(e),s}remove(e){let n=e.ref[Q],r=this.refCount[n]-1;if(r<=0){if(e.root=void 0,delete this.changeTrees[n],e.isStreamCollection){let s=e.ref;s._unregister?.(),this.unregisterStream(s)}this.removeFromQueue(e),this.removeFromUnreliableQueue(e),this.refCount[n]=0,e.forEachChild((s,o)=>{s.removeParent(e.ref)&&(s.parentRef===void 0||s.parentRef&&this.refCount[s.ref[Q]]>0?this.remove(s):s.parentRef&&this.moveNextToParent(s))})}else this.refCount[n]=r,this.enqueueFilterRefresh(e),this.recursivelyMoveNextToParent(e);return r}recursivelyMoveNextToParent(e){this.moveNextToParent(e),e.forEachChild((n,r)=>this.recursivelyMoveNextToParent(n))}moveNextToParent(e){e.changesNode&&this._moveNextToParentInList(this.changes,e,e.changesNode,"changesNode"),e.unreliableChangesNode&&this._moveNextToParentInList(this.unreliableChanges,e,e.unreliableChangesNode,"unreliableChangesNode")}_moveNextToParentInList(e,n,r,s){let o=n.parent;if(!o||!o[I])return;let i=o[I][s];!i||i===r||r.position>i.position||(r.prev?r.prev.next=r.next:e.next=r.next,r.next?r.next.prev=r.prev:e.tail=r.prev,r.prev=e.tail,r.next=void 0,e.tail.next=r,e.tail=r,r.position=e.nextPosition++)}enqueueChangeTree(e,n=e.changesNode){n||(e.changesNode=this._appendToList(this.changes,e))}enqueueUnreliable(e,n=e.unreliableChangesNode){n||(e.unreliableChangesNode=this._appendToList(this.unreliableChanges,e))}_appendToList(e,n){let r=this._nodePool,s;return r.length>0?(s=r.pop(),s.changeTree=n,s.next=void 0,s.prev=void 0):s={changeTree:n,next:void 0,prev:void 0,position:0},e.next?(s.prev=e.tail,e.tail.next=s,e.tail=s):(e.nextPosition=0,e.next=s,e.tail=s),s.position=e.nextPosition++,s}releaseNode(e){e.changeTree=void 0,e.prev=void 0,e.next=void 0,this._nodePool.push(e)}removeFromQueue(e){return this._removeNode(this.changes,e,e.changesNode,"changesNode")}removeFromUnreliableQueue(e){return this._removeNode(this.unreliableChanges,e,e.unreliableChangesNode,"unreliableChangesNode")}_removeNode(e,n,r,s){return!r||r.changeTree!==n?!1:(r.prev?r.prev.next=r.next:e.next=r.next,r.next?r.next.prev=r.prev:e.tail=r.prev,n[s]=void 0,this.releaseNode(r),!0)}};HB=new FinalizationRegistry(({root:t,id:e,slot:n,bit:r})=>{bP(t,n,r),t.activeViews.delete(e);for(let s of t.streamTrees)s._dropView(e);t.releaseViewId(e)}),wP=-1;ir=class ir{constructor(e,n){m(this,"sharedBuffer",new Uint8Array(ir.BUFFER_SIZE));m(this,"context");m(this,"state");m(this,"root");m(this,"_encodeCtx",{self:void 0,buffer:void 0,it:void 0,changeTree:void 0,ref:void 0,encoder:void 0,filter:void 0,metadata:void 0,view:void 0,isEncodeAll:!1,hasView:!1,treeIsFiltered:!1,isSchema:!1,emitFiltered:!1,filterBitmask:0,tags:void 0,structSwitchEmitted:!1,isRootTree:!1,shouldEmitSwitch:!1,gen:0,initialOffset:0,rootChangeTree:void 0});m(this,"_fullSyncGen",0);this.context=Ks.cache(e.constructor),this.root=n??new Zf(this.context),this.setState(e)}setState(e){this.state=e,this.state[I].setRoot(this.root)}encode(e={offset:0},n,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,n,r,s,!1)}encodeUnreliable(e={offset:0},n,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,n,r,s,!0)}_encodeChannel(e,n,r,s,o){this.root.pendingFilterRefresh.length>0&&Xy(this.root);let i=n!==void 0,a=this.state[I],c=this._encodeCtx;c.self=this,c.buffer=r,c.it=e,c.view=n,c.isEncodeAll=!1,c.hasView=i,c.emitFiltered=i;let l=o?this.root.unreliableChanges:this.root.changes;for(;l=l.next;){let d=l.changeTree;if(i&&!n.isChangeTreeVisible(d))continue;let f=o?d.unreliableRecorder:d;if(!f||!f.has())continue;let h=d.encDescriptor;c.changeTree=d,c.ref=d.ref,c.encoder=h.encoder,c.filter=h.filter,c.metadata=h.metadata,c.treeIsFiltered=d.isFiltered,c.isSchema=h.isSchema,c.filterBitmask=h.filterBitmask,c.tags=h.tags,c.structSwitchEmitted=!1,c.isRootTree=d===a,c.shouldEmitSwitch=i||e.offset>s||!c.isRootTree,f.forEachWithCtx(c,mb)}return!o&&!i&&this._isStreamBroadcastMode&&this._emitStreamBroadcast(r,e),e.offset>r.byteLength?(r=this._resizeBuffer(r,e.offset),e.offset=s,this._encodeChannel(e,n,r,s,o)):r.subarray(0,e.offset)}encodeFullSync(e,n,r,s,o=e.offset){this.root.pendingFilterRefresh.length>0&&Xy(this.root);let i=s!==void 0,a=this.state[I],c=this._encodeCtx;return c.self=this,c.buffer=n,c.it=e,c.view=s,c.isEncodeAll=!0,c.hasView=i,c.emitFiltered=r,c.gen=++this._fullSyncGen,c.initialOffset=o,c.rootChangeTree=a,hb(c,a),e.offset>n.byteLength?(n=this._resizeBuffer(n,e.offset),e.offset=o,this.encodeFullSync(e,n,r,s,o)):n.subarray(0,e.offset)}_resizeBuffer(e,n){let r=Math.ceil(n/ir.BUFFER_SIZE)*ir.BUFFER_SIZE;console.warn(`@colyseus/schema buffer overflow. Encoded state is higher than default BUFFER_SIZE. Use the following to increase default BUFFER_SIZE:
|
|
9
9
|
|
|
10
10
|
import { Encoder } from "@colyseus/schema";
|
|
11
11
|
Encoder.BUFFER_SIZE = ${Math.round(r/1024)} * 1024; // ${Math.round(r/1024)} KB
|
|
12
|
-
`);let s=new Uint8Array(r);return s.set(e),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeAll(e={offset:0},n=this.sharedBuffer){return this.encodeFullSync(e,n,!1)}encodeAllView(e,n,r,s=this.sharedBuffer){let o=r.offset;return s=this.encodeFullSync(r,s,!0,e,o),Wf(s.subarray(0,n),s.subarray(o,r.offset))}ensureCapacity(e,n){if(n+sr.BUFFER_SIZE<=e.byteLength)return e;let r=Math.ceil((n+sr.BUFFER_SIZE)/sr.BUFFER_SIZE)*sr.BUFFER_SIZE,s=new Uint8Array(r);return s.set(e.subarray(0,n)),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeView(e,n,r,s=this.sharedBuffer){let o=r.offset;this._emitStreamPriority(e);for(let i of e.changes.keys()){let a=e.changes.get(i),c=this.root.changeTrees[i];if(c===void 0){e.changes.delete(i);continue}if(a.size===0)continue;let u=c.encDescriptor,l=u.encoder,d=u.metadata,f=c.ref,h=c.refTarget;s=this.ensureCapacity(s,r.offset),s[r.offset++]=255,Se.number(s,f[ee],r);for(let[p,y]of a){let S;if(p===gP){let R=h.tmpItems,A=h.deletedIndexes;for(let E=0;E<R.length;E++)R[E]===void 0||A[E]===!0||l(this,s,c,E,N.ADD,r,!1,!0,d);continue}if(typeof p=="number")S=p;else{let R=p.indexInParent(f);if(R===void 0)continue;if(S=R,y===N.ADD&&c.getChange(S)===N.DELETE){e.changes.delete(p.ref[ee]);continue}}let x=h[st](S)!==void 0&&y||N.DELETE;l(this,s,c,S,x,r,!1,!0,d)}}return e.changes.clear(),s=this.encode(r,e,s),Wf(s.subarray(0,n),s.subarray(o,r.offset))}encodeUnreliableView(e,n,r,s=this.sharedBuffer){let o=r.offset;return s=this.encodeUnreliable(r,e,s,o),Wf(s.subarray(0,n),s.subarray(o,r.offset))}_emitStreamBroadcast(e,n){let r=this.root.streamTrees;for(let s of r){let o=s,i=o[I],a=o[ee];if(a===void 0)continue;let c=o._stream,u=c.broadcastDeletes,l=c.broadcastPending,d=c.sentBroadcast,f=u.size>0,h=l.size>0,p=i.encDescriptor,y=p.encoder,S=p.metadata;if(f||h){if(e[n.offset++]=255,Se.number(e,a,n),f){for(let E of u)y(this,e,i,E,N.DELETE,n,!1,!1,S);u.clear()}let w=c.maxPerTick,x=[],R=0,A=[];for(let E of l){if(R>=w)break;let P=o[st](E);if(P===void 0){A.push(E);continue}y(this,e,i,E,N.ADD,n,!1,!1,S),d.add(E),x.push(P),A.push(E),R++}for(let E of A)l.delete(E);for(let E of x){let P=E[I];if(P===void 0)continue;let k=E[ee];if(k===void 0)continue;e[n.offset++]=255,Se.number(e,k,n);let M=P.encDescriptor,L=M.encoder,K=M.metadata;P.forEachLive(W=>{Ie.hasUnreliableAtIndex(K,W)||L(this,e,P,W,N.ADD,n,!1,!1,K)})}}for(let w of d){let x=o[st](w);if(x===void 0)continue;let R=x[I];if(R===void 0||!R.has())continue;let A=x[ee];if(A===void 0)continue;e[n.offset++]=255,Se.number(e,A,n);let E=R.encDescriptor,P=E.encoder,k=E.metadata;R.forEach((M,L)=>{M<0||Ie.hasUnreliableAtIndex(k,M)||P(this,e,R,M,L,n,!1,!1,k)})}}}_emitStreamPriority(e){let n=this.root.streamTrees;if(n.size===0)return;let r=e.id;for(let s of n){let o=s,i=o._stream,a=i.pendingByView.get(r);if(a===void 0||a.size===0)continue;let c=i.priorityByView?.get(r),u=c!==void 0,l=i.priority,d=i.maxPerTick,f=[],h=[];if(u||l!==void 0){let S=[],w=[],x=0;for(let R of a){let A=o[st](R);if(A===void 0){h.push(R);continue}let E=u?c(A):l(e,A);if(x<d){let P=x++;for(;P>0&&w[P-1]<E;)w[P]=w[P-1],S[P]=S[P-1],P--;w[P]=E,S[P]=R}else if(E>w[d-1]){let P=d-1;for(;P>0&&w[P-1]<E;)w[P]=w[P-1],S[P]=S[P-1],P--;w[P]=E,S[P]=R}}for(let R=0;R<x;R++)f.push(S[R])}else for(let S of a){if(f.length>=d)break;f.push(S)}for(let S of h)a.delete(S);let p=f.length,y=i.sentByView.get(r);y===void 0&&(y=new Set,i.sentByView.set(r,y));for(let S=0;S<p;S++){let w=f[S],x=o[st](w);if(x===void 0){a.delete(w);continue}e._addImmediate(x);let R=x[I];if(R!==void 0){let A=x[ee],E=e.changes.get(A);E===void 0&&(E=new Map,e.changes.set(A,E));let P=R.metadata;R.forEachLive(k=>{Ie.hasUnreliableAtIndex(P,k)||E.set(k,N.ADD)})}a.delete(w),y.add(w)}}}discardChanges(){let e=this.root.changes,n=e.next,r=this.root;for(;n;){let s=n.next;n.changeTree.endEncode(),r.releaseNode(n),n=s}e.next=void 0,e.tail=void 0}discardUnreliableChanges(){let e=this.root.unreliableChanges,n=e.next,r=this.root;for(;n;){let s=n.next;n.changeTree.endEncodeUnreliable(),r.releaseNode(n),n=s}e.next=void 0,e.tail=void 0}tryEncodeTypeId(e,n,r,s){let o=this.context.getTypeId(n),i=this.context.getTypeId(r);if(i===void 0){console.warn(`@colyseus/schema WARNING: Class "${r.name}" is not registered on TypeRegistry - Please either tag the class with @entity or define a @type() field.`);return}o!==i&&(e[s.offset++]=213,Se.number(e,i,s))}get hasChanges(){return this.root.changes.next!==void 0||this._hasStreamBacklog()}get _isStreamBroadcastMode(){return this.root.activeViews.size===0&&this.root.streamTrees.size>0}_hasStreamBacklog(){let e=this.root;if(e.streamTrees.size===0)return!1;let n=e.activeViews.size===0;for(let r of e.streamTrees)if(n?lA(r):uA(r,e))return!0;return!1}get hasUnreliableChanges(){return this.root.unreliableChanges.next!==void 0}};m(sr,"BUFFER_SIZE",16*1024);Ta=sr,qu=class extends Error{constructor(e){super(e),this.name="DecodingWarning"}},rg={value:0,enumerable:!1,writable:!0},Zf=class{constructor(){m(this,"refs",new Map);m(this,"refCount",{});m(this,"deletedRefs",new Set);m(this,"callbacks",{});m(this,"nextUniqueId",0)}getNextUniqueId(){return this.nextUniqueId++}addRef(e,n,r=!0){this.refs.set(e,n),n[ee]===void 0?(rg.value=e,Object.defineProperty(n,ee,rg)):n[ee]!==e&&(n[ee]=e),r&&(this.refCount[e]=(this.refCount[e]||0)+1),this.deletedRefs.has(e)&&this.deletedRefs.delete(e)}removeRef(e){let n=this.refCount[e];if(n===void 0){try{throw new qu("trying to remove refId that doesn't exist: "+e)}catch(r){console.warn(r)}return}if(n===0){try{let r=this.refs.get(e);throw new qu(`trying to remove refId '${e}' with 0 refCount (${r.constructor.name}: ${JSON.stringify(r)})`)}catch(r){console.warn(r)}return}(this.refCount[e]=n-1)<=0&&this.deletedRefs.add(e)}clearRefs(){this.refs.clear(),this.deletedRefs.clear(),this.callbacks={},this.refCount={}}garbageCollectDeletedRefs(){this.deletedRefs.forEach(e=>{if(this.refCount[e]>0)return;let n=this.refs.get(e),r=n.constructor[Symbol.metadata];if(r!=null)for(let s in r){let o=r[s].name,i=n[o];if(typeof i=="object"&&i){let a=i[ee];a!==void 0&&!this.deletedRefs.has(a)&&this.removeRef(a)}}else typeof n[ge]=="function"&&Array.from(n.values()).forEach(s=>{let o=s[ee];o!==void 0&&!this.deletedRefs.has(o)&&this.removeRef(o)});this.refs.delete(e),delete this.refCount[e],delete this.callbacks[e]}),this.deletedRefs.clear()}addCallback(e,n,r){if(e===void 0){let s=typeof n=="number"?N[n]:n;throw new Error(`Can't addCallback on '${s}' (refId is undefined)`)}return this.callbacks[e]||(this.callbacks[e]={}),this.callbacks[e][n]||(this.callbacks[e][n]=[]),this.callbacks[e][n].push(r),()=>this.removeCallback(e,n,r)}removeCallback(e,n,r){let s=this.callbacks?.[e]?.[n]?.indexOf(r);s!==void 0&&s!==-1&&mP(this.callbacks[e][n],s)}},Ln=class{constructor(e,n){m(this,"context");m(this,"state");m(this,"root");m(this,"currentRefId",0);m(this,"triggerChanges");m(this,"resyncVisited",null);m(this,"resyncDamaged",!1);this.setState(e),this.context=n||new Ks(e.constructor)}setState(e){this.state=e,this.root=new Zf,this.root.addRef(0,e)}decode(e,n={offset:0},r=this.state){let s=this.triggerChanges!==void 0?[]:null,o=this.root,i=e.byteLength,a=r.constructor[In];for(this.currentRefId=0;n.offset<i;){if(e[n.offset]==255){n.offset++,r[zu]?.();let u=Ae.number(e,n),l=o.refs.get(u);l?(r=l,a=r.constructor[In],this.currentRefId=u):(console.error(`"refId" not found: ${u}`,{previousRef:r,previousRefId:this.currentRefId}),console.warn("Please report this issue to the developers."),this.skipCurrentStructure(e,n,i));continue}if(a(this,e,n,r,s)===db){console.warn("@colyseus/schema: definition mismatch"),this.skipCurrentStructure(e,n,i);continue}}return r[zu]?.(),this.resyncVisited!==null&&qA(this,s),s!==null&&this.triggerChanges?.(s),o.garbageCollectDeletedRefs(),s}decodeResync(e,n={offset:0}){this.resyncVisited=new Map,this.resyncDamaged=!1;try{return this.decode(e,n)}finally{this.resyncVisited=null}}skipCurrentStructure(e,n,r){this.resyncVisited!==null&&(this.resyncDamaged=!0);let s={offset:n.offset};for(;n.offset<r&&!(e[n.offset]===255&&(s.offset=n.offset+1,this.root.refs.has(Ae.number(e,s))));)n.offset++}getInstanceType(e,n,r){let s;if(e[n.offset]===213){n.offset++;let o=Ae.number(e,n);s=this.context.get(o)}return s||r}createInstanceOfType(e){return e.initializeForDecoder()}removeChildRefs(e,n){let r=typeof e[ge]!="string",s=e[ee];e.forEach((o,i)=>{n?.push({ref:e,refId:s,op:N.DELETE,field:i,value:void 0,previousValue:o}),r&&this.root.removeRef(o[ee])})}},mb=Lt({min:X.float64(),max:X.float64(),bits:X.uint8(),mode:X.uint8()},"QuantizedDescriptor"),yb=Lt({name:X.string(),type:X.string(),referencedType:X.number(),childPrimitive:X.string(),quantized:X.ref(mb).optional()},"ReflectionField"),gb=Lt({id:X.number(),extendsId:X.number(),fields:X.array(yb)},"ReflectionType"),Fn=Lt({types:X.array(gb),rootType:X.number()},"Reflection");Fn.encode=function(t,e={offset:0}){let n=t.context,r=new Fn,s=new Ta(r),o=n.schemas.get(t.state.constructor);o>0&&(r.rootType=o);let i=new Set,a={},c=l=>{if(l.extendsId===void 0||i.has(l.extendsId)){i.add(l.id),r.types.push(l);let d=a[l.id];d!==void 0&&(delete a[l.id],d.forEach(f=>c(f)))}else a[l.extendsId]===void 0&&(a[l.extendsId]=[]),a[l.extendsId].push(l)};n.schemas.forEach((l,d)=>{let f=new gb;f.id=Number(l);let h=Object.getPrototypeOf(d);h!==Xe&&(f.extendsId=n.schemas.get(h));let p=d[Symbol.metadata];if(p!==h[Symbol.metadata]){let y=p[kt]??-1;for(let S=0;S<=y;S++){let w=p[S];if(w===void 0)continue;let x=w.name;if(!Object.prototype.hasOwnProperty.call(p,x))continue;let R=new yb;R.name=x;let A;if(typeof w.type=="string")A=w.type;else if(Ys(w.type)){let E=w.type.quantized;A="quantized";let P=new mb;P.min=E.min,P.max=E.max,P.bits=E.bits,P.mode=E.wrap?1:0,R.quantized=P}else{let E;Xe.is(w.type)?(A="ref",E=w.type):(A=Object.keys(w.type)[0],typeof w.type[A]=="string"?R.childPrimitive=w.type[A]:E=w.type[A]),R.referencedType=E?n.getTypeId(E):-1}R.type=A,f.fields.push(R)}}c(f)});for(let l in a)a[l].forEach(d=>r.types.push(d));return s.encodeAll(e).slice(0,e.offset)};Fn.decode=function(t,e){let n=new Fn;new Ln(n).decode(t,e);let s=new Ks;n.types.forEach(a=>{let c=s.get(a.extendsId)??Xe,u=class extends c{};Ks.register(u),s.add(u,a.id)},{});let o=(a,c,u)=>{c.fields.forEach((l,d)=>{let f=u+d;if(l.quantized!==void 0){let h=l.quantized;Ie.addField(a,f,l.name,{quantized:np({min:h.min,max:h.max,bits:h.bits,mode:h.mode===1?"wrap":"clamp"})})}else if(l.referencedType!==void 0){let h=l.type,p=s.get(l.referencedType)??l.childPrimitive;h==="ref"?Ie.addField(a,f,l.name,p):Ie.addField(a,f,l.name,{[h]:p})}else Ie.addField(a,f,l.name,l.type)})};n.types.forEach(a=>{let c=s.get(a.id),u=Ie.initialize(c),l=[],d=a;do l.push(d),d=n.types.find(h=>h.id===d.extendsId);while(d);let f=0;l.reverse().forEach(h=>{o(u,h,f),f+=h.fields.length})});let i=new(s.get(n.rootType||0));return new Ln(i,s)};Fn.makeEncodable=function(t){let e=t[Symbol.metadata];if(!e)return t;let n=e[kt];if(n===void 0)return t;for(let r=0;r<=n;r++){let s=e[r];s&&Ie.defineField(t,e,r,s.name,s.type)}return Object.prototype.hasOwnProperty.call(t,xa)&&delete t[xa],t};Yu=class{constructor(e){m(this,"decoder");m(this,"uniqueRefIds",new Set);m(this,"isTriggering",!1);this.decoder=e,this.decoder.triggerChanges=this.triggerChanges.bind(this)}get callbacks(){return this.decoder.root.callbacks}get state(){return this.decoder.state}addCallback(e,n,r){return this.decoder.root.addCallback(e,n,r)}addCallbackOrWaitCollectionAvailable(e,n,r,s,o=!0){let i=()=>{},a=()=>i(),c=e[n];if(!c||c[ee]===void 0){let u;return u=this.addCallback(e[ee],n,(l,d)=>{l!=null&&(u(),i=this.addCallback(l[ee],r,s))}),i=u,a}else return o=o&&this.isTriggering===!1,r===N.ADD&&o&&c.forEach((u,l)=>{s(u,l)}),this.addCallback(c[ee],r,s)}listen(...e){return typeof e[0]=="string"?this.listenInstance(this.state,e[0],e[1],e[2]):this.listenInstance(e[0],e[1],e[2],e[3])}listenInstance(e,n,r,s=!0){s=s&&this.isTriggering===!1;let o=e[n];return s&&o!==null&&o!==void 0&&r(o,void 0),this.addCallback(e[ee],n,r)}onChange(...e){if(e.length===2&&typeof e[0]!="string"){let n=e[0],r=e[1];return this.addCallback(n[ee],N.REPLACE,r)}return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],N.REPLACE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],N.REPLACE,e[2])}onAdd(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],N.ADD,e[1],e[2]!==!1):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],N.ADD,e[2],e[3]!==!1)}onRemove(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],N.DELETE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],N.DELETE,e[2])}bindTo(e,n,r,s=!0){let o=e.constructor[Symbol.metadata];r||(r=Object.keys(o).filter(a=>!isNaN(Number(a))).map(a=>o[a].name));let i=()=>{for(let a of r){let c=e[a];c!==void 0&&(n[a]=c)}};return s&&i(),this.addCallback(e[ee],N.REPLACE,i)}triggerChanges(e){this.uniqueRefIds.clear(),this.isTriggering=!0;for(let n=0,r=e.length;n<r;n++){let s=e[n],o=s.refId,i=s.ref,a=this.callbacks[o];if(a){if((s.op&N.DELETE)===N.DELETE&&Xe.isSchema(s.previousValue)){let c=s.previousValue[ee],u=this.callbacks[c]?.[N.DELETE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l]()}catch(d){console.error(d)}}if(Xe.isSchema(i)){if(!this.uniqueRefIds.has(o)){let u=a[N.REPLACE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l]()}catch(d){console.error(d)}}let c=a[s.field];if(c)for(let u=c.length-1;u>=0;u--)try{c[u](s.value,s.previousValue)}catch(l){console.error(l)}}else{let c=s.dynamicIndex??s.field;if((s.op&N.DELETE)===N.DELETE){if(s.previousValue!==void 0){let u=a[N.DELETE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.previousValue,c)}catch(d){console.error(d)}}if((s.op&N.ADD)===N.ADD){let u=a[N.ADD];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.value,c)}catch(d){console.error(d)}}}else if((s.op&N.ADD)===N.ADD&&s.previousValue!==s.value){let u=a[N.ADD];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.value,c)}catch(d){console.error(d)}}if(s.value!==s.previousValue){let u=a[N.REPLACE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](c,s.value)}catch(d){console.error(d)}}}this.uniqueRefIds.add(o)}}this.isTriggering=!1}},lp={get(t){if(t instanceof Ln)return new Yu(t);if("decoder"in t.serializer)return new Yu(t.serializer.decoder);throw new Error("Invalid room or decoder")},getLegacy(t){if(t instanceof Ln)return Gu(t);if("decoder"in t.serializer)return Gu(t.serializer.decoder);throw new Error("Invalid room or decoder")},getRawChanges(t,e){return SP(t,e)}};Or("map",{constructor:ds});Or("array",{constructor:ls});Or("set",{constructor:Pa});Or("collection",{constructor:Aa})});function Mt(){return typeof performance<"u"?performance.now():Date.now()}var Ia=pt(()=>{"use strict"});function ol(t,e){let n=globalThis,r=n.__colyseusDebug;if(!r){let s=[];r=n.__colyseusDebug={__buffer:s,publish(o,i){s.push([o,xP(i)]),s.length>_P&&s.shift()}}}r.publish(t,e)}function il(){if(typeof globalThis>"u")return!1;let t=globalThis.__colyseusDebug;return t!=null&&t.__buffer===void 0}var xP,_P,Da=pt(()=>{"use strict";xP=typeof WeakRef<"u"?t=>new WeakRef(t):t=>({deref:()=>t}),_P=64});function jt(t){return t[ee]}function cr(t){return t.constructor[RP]}function Na(t,e){let n=cr(t)?.[e];return typeof n=="number"?n:-1}function wb(t){let e=cr(t);if(!e)return[];let n=[];for(let r=0;;r++){let s=e[r];if(!s||typeof s.name!="string")break;typeof s.type=="string"&&n.push(s.name)}return n}function Ba(t){let e=cr(t),n=[],r=[];if(e)for(let s=0;;s++){let o=e[s];if(!o||typeof o.name!="string")break;typeof o.type=="string"&&(n.push(o.name),EP[o.type]===void 0&&r.push(o.name))}return{fields:n,numeric:r}}function AP(t){if(Number.isNaN(t))return 0;if(!Number.isFinite(t))return t>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER;if(t!==(t|0)&&Math.abs(t)<=34028235e31){let e=Math.fround(t);if(Math.abs(Math.abs(e)-Math.abs(t))<1e-4)return e}return t}function Sb(t,e){let n=cr(t),r=n?.[e];switch((typeof r=="number"?n[r]:void 0)?.type){case"float32":return Math.fround;case"number":return AP;default:return kP}}function xb(t){if(t.length>PP){let w=t;return x=>{let R={};for(let A=0;A<w.length;A++)R[w[A]]=x[w[A]];return R}}let e=t[0],n=t[1],r=t[2],s=t[3],o=t[4],i=t[5],a=t[6],c=t[7],u=t[8],l=t[9],d=t[10],f=t[11],h=t[12],p=t[13],y=t[14],S=t[15];return w=>{let x={};return e!==void 0&&(x[e]=w[e]),n!==void 0&&(x[n]=w[n]),r!==void 0&&(x[r]=w[r]),s!==void 0&&(x[s]=w[s]),o!==void 0&&(x[o]=w[o]),i!==void 0&&(x[i]=w[i]),a!==void 0&&(x[a]=w[a]),c!==void 0&&(x[c]=w[c]),u!==void 0&&(x[u]=w[u]),l!==void 0&&(x[l]=w[l]),d!==void 0&&(x[d]=w[d]),f!==void 0&&(x[f]=w[f]),h!==void 0&&(x[h]=w[h]),p!==void 0&&(x[p]=w[p]),y!==void 0&&(x[y]=w[y]),S!==void 0&&(x[S]=w[S]),x}}var RP,al,EP,kP,PP,La=pt(()=>{"use strict";At();RP=Symbol.metadata??Symbol.for("Symbol.metadata"),al=vt;EP={string:!0,boolean:!0,bigint64:!0,biguint64:!0};kP=t=>t;PP=16});var fp,TP,vP,Wt,oi,pp=pt(()=>{"use strict";At();Ar();Ia();Da();La();fp=9,TP=fp,vP=(t,e)=>(e?2:1)*(fp+4+fp*t),Wt=class Wt{constructor(e,n,r,s){m(this,"data");m(this,"_host");m(this,"_encoder");m(this,"_scratch",new Uint8Array(2048));m(this,"_framed",null);m(this,"_sentCount",0);m(this,"_lastProcessed",0);m(this,"_epoch",0);m(this,"_sendTimes");m(this,"_inputBufferSize");m(this,"_inputBuffer",null);m(this,"_reckonTimes",null);m(this,"_pendingReckon",0);m(this,"_lastStamp",0);m(this,"_stampRing",null);m(this,"_renderDeltaRing",null);m(this,"_ringSlots",0);m(this,"_warnedUnknownKeys",null);m(this,"_stampRender",!1);m(this,"_stampReckon",!1);m(this,"_allowRewind");m(this,"_sendListeners",null);m(this,"_renderDelay",0);m(this,"_renderDelayExplicit",!1);m(this,"_renderDelayProvider");m(this,"_tickRate");m(this,"_patchRate");m(this,"_subSteps",1);this._host=e,this.data=n,this._encoder=r,this._stampRender=s?.stampRender??!1,this._stampReckon=s?.stampReckon??!1,this._allowRewind=s?.allowRewind,this._allowRewind!==void 0&&r.mode==="unreliable"&&!Wt._warnedAllowRewindIgnored&&(Wt._warnedAllowRewindIgnored=!0,console.warn('@colyseus/sdk: `allowRewind` is ignored on `mode:"unreliable"` \u2014 a packet stamps its whole redundancy ring or none of it, so excluding one input would cost bandwidth rather than save it. Use `mode:"reliable"` to gate the lag-comp stamp per input.')),this._renderDelay=s?.renderDelay??0,this._renderDelayExplicit=s?.renderDelay!==void 0,this._tickRate=s?.tickRate,this._patchRate=s?.patchRate,this._subSteps=s?.subSteps??1;let o=this._tickRate?1e3/this._tickRate:1e3/60,i=Wt.BUFFER_RTT_BUDGET_MS+(this._patchRate??0);this._inputBufferSize=Math.max(Wt.BUFFER_FLOOR,Math.ceil(i/o*Wt.BUFFER_HEADROOM)),this._sendTimes=new Float64Array(this._inputBufferSize)}get mode(){return this._encoder.mode}get tickRate(){return this._tickRate}get stepSeconds(){return this._tickRate?1/this._tickRate:void 0}get stepMs(){return this._tickRate?1e3/this._tickRate:void 0}get patchRate(){return this._patchRate}get subSteps(){return this._subSteps}get subStepSeconds(){return this._tickRate?1/this._tickRate/this._subSteps:void 0}get subStepMs(){return this._tickRate?1e3/this._tickRate/this._subSteps:void 0}get lastProcessed(){return this._lastProcessed}get sentCount(){return this._sentCount}get pendingCount(){return this._sentCount-this._lastProcessed}get replayBufferSize(){return this._inputBufferSize}get epoch(){return this._epoch}at(e){if(this._inputBuffer!==null&&!(e<=this._lastProcessed||e>this._sentCount)){if(this._sentCount-e>=this._inputBufferSize){Wt._warnedBufferOverflow||(Wt._warnedBufferOverflow=!0,console.warn(`@colyseus/sdk: input replay buffer (${this._inputBufferSize}) overflowed \u2014 RTT exceeds its budget at this input rate; reconciliation may drift.`));return}return this._inputBuffer[e%this._inputBufferSize]}}reckonTimeAt(e){return this._reckonTimes===null||e<=this._lastProcessed||e>this._sentCount||this._sentCount-e>=this._inputBufferSize?0:this._reckonTimes[e%this._inputBufferSize]}reset(){this._encoder.reset(),this._sentCount=this._lastProcessed=this._encoder.seq,this._framed=null,this._lastStamp=0,this._ringSlots=0,this._sendTimes.fill(0),this._epoch++}bindRenderDelay(e){this._renderDelayExplicit||(this._renderDelayProvider=e)}_resolveRenderDelay(){return this._renderDelayProvider?this._renderDelayProvider():this._renderDelay}_warnUnknownFields(){let e=cr(this.data);if(e)for(let n of Object.keys(this.data))e[n]!==void 0||this._warnedUnknownKeys?.has(n)||((this._warnedUnknownKeys??(this._warnedUnknownKeys=new Set)).add(n),console.warn(`@colyseus/sdk input: "${n}" is not a declared field on ${this.data.constructor.name} \u2014 the write is never encoded or sent. Declare it with @type(...) on the input schema, or remove the write.`))}send(){let e=this._host.connection;if(!e?.isOpen)return 0;il()&&this._warnUnknownFields();let n=this._encoder.encode(),r=this._encoder.mode==="reliable",s=this._stampReckon||this._stampRender,o=s&&r&&(this._allowRewind===void 0||this._allowRewind(this.data)),i=s&&!r,a=this._stampReckon&&this._stampRender,u=1+(o?TP+(a?2:0):i?vP(this._encoder.historySize,a):0)+n.length;u>this._scratch.byteLength&&(this._scratch=new Uint8Array(Math.max(u,this._scratch.byteLength*2)),this._framed=null),this._scratch[0]=(r?Ke.ROOM_INPUT_RELIABLE:Ke.ROOM_INPUT_UNRELIABLE)|(o||i?Zo.TIMED:0);let l={offset:1};if(i)this._writeRingStamps(l);else if(o){let{stamp:p,renderDelta:y}=this._sampleStamp();Se.number(this._scratch,p-this._lastStamp,l),this._lastStamp=p,a&&Se.uint16(this._scratch,y,l)}else this._pendingReckon=0;this._scratch.set(n,l.offset);let d=l.offset+n.length;(this._framed===null||this._framed.byteLength!==d)&&(this._framed=this._scratch.subarray(0,d));let f=this._framed,h;return r?(e.send(f),h=++this._sentCount):(e.sendUnreliable(f),h=this._sentCount=this._encoder.seq),this._recordSent(h),h}_writeRingStamps(e){let{stamp:n,renderDelta:r}=this._sampleStamp(),s=this._encoder.historySize,o=this._encoder.seq,i=this._ringSlots=Math.min(this._ringSlots+1,s),a=this._stampRing??(this._stampRing=new Float64Array(s));if(a[o%s]=n,Se.number(this._scratch,i,e),Se.uint32(this._scratch,n,e),this._writeSeriesDeltas(a,o,i,e),this._stampReckon&&this._stampRender){let c=this._renderDeltaRing??(this._renderDeltaRing=new Uint16Array(s));c[o%s]=r,Se.uint16(this._scratch,r,e),this._writeSeriesDeltas(c,o,i,e)}}_writeSeriesDeltas(e,n,r,s){let o=e.length;for(let i=1;i<r;i++)Se.number(this._scratch,e[(n-i+1)%o]-e[(n-i)%o],s)}_sampleStamp(){let e=this._host.clock,n=(e?.lastServerTime?.()??0)>0,r=n?Math.max(0,Math.round(e.serverNow()))>>>0:0,s=n?Math.min(65535,Math.max(0,Math.round(this._resolveRenderDelay()+(e.smoothedRtt?.()??0)/2))):0;return this._pendingReckon=r,{stamp:this._stampReckon?r:r>s?r-s:0,renderDelta:s}}_recordSent(e){if(this._inputBuffer===null){let r=this.data.constructor;this._inputBuffer=Array.from({length:this._inputBufferSize},()=>new r)}this._encoder.copyInto(this._inputBuffer[e%this._inputBufferSize]),this._sendTimes[e%this._inputBufferSize]=Mt(),this._stampReckon&&((this._reckonTimes??(this._reckonTimes=new Float64Array(this._inputBufferSize)))[e%this._inputBufferSize]=this._pendingReckon);let n=this._sendListeners;if(n!==null)for(let r=0;r<n.length;r++)n[r](e)}onSend(e){let n=this._sendListeners;return this._sendListeners=n!==null?[...n,e]:[e],()=>{let r=this._sendListeners;if(r===null)return;let s=r.indexOf(e);if(s<0)return;let o=r.slice();o.splice(s,1),this._sendListeners=o.length>0?o:null}}ackInput(e){if(e<=this._lastProcessed)return-1;let n=this._sentCount-e>=this._inputBufferSize;if(this._lastProcessed=e,n)return-1;let r=this._sendTimes[e%this._inputBufferSize];return r>0?Mt()-r:-1}};m(Wt,"BUFFER_FLOOR",64),m(Wt,"BUFFER_RTT_BUDGET_MS",1e3),m(Wt,"BUFFER_HEADROOM",1.5),m(Wt,"_warnedBufferOverflow",!1),m(Wt,"_warnedAllowRewindIgnored",!1);oi=Wt});var ii,dt,cl,ul=pt(()=>{"use strict";Ia();ii=Object.freeze({now:()=>Mt(),serverNow:()=>Mt(),renderNow:()=>Mt(),rtt:()=>0,smoothedRtt:()=>0,jitter:()=>0,lastServerTime:()=>0,patchInterval:()=>0,setPatchInterval:t=>{},sample:(t,e)=>{}}),dt=class dt{constructor(){m(this,"_clockOffset",0);m(this,"_clockHasSample",!1);m(this,"_offsetCount",0);m(this,"_rttFloorT",[]);m(this,"_rttFloorV",[]);m(this,"_rtt",0);m(this,"_smoothedRtt",0);m(this,"_rttHasSample",!1);m(this,"_jitter",0);m(this,"_lastRecvTime",-1);m(this,"_lastServerTime",0);m(this,"_patchInterval",0);m(this,"_renderTau",dt.RENDER_TAU);m(this,"_renderSn",0);m(this,"_renderSnAt",0)}serverNow(){return Mt()+this._clockOffset}renderNow(){let e=this.serverNow();if(this._renderTau<=0)return e;let n=Mt();if(this._renderSn===0)return this._renderSn=e,this._renderSnAt=n,this._renderSn;let r=Math.min(n-this._renderSnAt,100);return r<.5?this._renderSn:(this._renderSnAt=n,this._renderSn+=r,Math.abs(e-this._renderSn)>dt.RENDER_SNAP?(this._renderSn=e,this._renderSn):(this._renderSn+=(e-this._renderSn)*(1-Math.exp(-r/this._renderTau)),this._renderSn))}setRenderTau(e){this._renderTau=e>0?e:0}now(){return Mt()}rtt(){return this._rtt}smoothedRtt(){return this._smoothedRtt}jitter(){return this._jitter}lastServerTime(){return this._lastServerTime}patchInterval(){return this._patchInterval}setPatchInterval(e){this._patchInterval=e>0?e:0}sample(e,n){let r=Mt(),s=dt.EMA_ALPHA,o=this._patchInterval;if(this._lastRecvTime>=0&&o>0){let a=r-this._lastRecvTime,c=Math.round(a/o);c>=1&&c<=dt.JITTER_STALL_X&&(this._jitter+=(Math.abs(a-c*o)-this._jitter)*dt.JITTER_GAIN)}this._lastRecvTime=r,this._lastServerTime=e,(n<0||this._smoothedRtt>0&&n>this._smoothedRtt*dt.RTT_OUTLIER_X)&&(n=-1);let i=n>=0?e+n/2-r:e-r;if(!this._clockHasSample)this._clockOffset=i,this._clockHasSample=!0,n>=0&&(this.pushRttFloor(n,r),this._offsetCount=1);else if(n>=0){let a=this.pushRttFloor(n,r),c=this._offsetCount<dt.RTT_GATE_WARMUP;this._offsetCount++,(c||n<=a*dt.RTT_GATE_FACTOR)&&(this._clockOffset=this._clockOffset*(1-s)+i*s)}n>=0&&(this._rtt=n,this._rttHasSample?this._smoothedRtt=this._smoothedRtt*(1-s)+n*s:(this._smoothedRtt=n,this._rttHasSample=!0))}pushRttFloor(e,n){let r=this._rttFloorT,s=this._rttFloorV;for(;s.length>0&&s[s.length-1]>=e;)s.pop(),r.pop();s.push(e),r.push(n);let o=n-dt.RTT_GATE_WINDOW;for(;r.length>0&&r[0]<o;)r.shift(),s.shift();return s[0]}reset(){this._clockOffset=0,this._clockHasSample=!1,this._offsetCount=0,this._rtt=0,this._smoothedRtt=0,this._rttHasSample=!1,this._jitter=0,this._lastRecvTime=-1,this._lastServerTime=0,this._rttFloorT.length=0,this._rttFloorV.length=0,this._renderSn=0,this._renderSnAt=0}};m(dt,"EMA_ALPHA",.1),m(dt,"RENDER_TAU",250),m(dt,"RENDER_SNAP",250),m(dt,"RTT_OUTLIER_X",4),m(dt,"JITTER_GAIN",1/16),m(dt,"JITTER_STALL_X",4),m(dt,"RTT_GATE_FACTOR",1.2),m(dt,"RTT_GATE_WINDOW",1e4),m(dt,"RTT_GATE_WARMUP",30);cl=dt});var Gb=iE((HL,qb)=>{"use strict";qb.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});function eT(t,e){return{now:()=>t?.serverNow()??performance.now(),ttlMs:typeof e=="function"?()=>e(t?.smoothedRtt()??0):e}}var rc,Tl,Np=pt(()=>{"use strict";rc=t=>Math.max(t*2,600),Tl=class t{constructor(){m(this,"entries",new Map);m(this,"accepted",new Set);m(this,"cfg",{});m(this,"dead",!1)}static get(e,n={}){let r=new t;return r.configure(eT(e.clock??null,n.ttlMs??rc)),n.onReject&&r.configure({onReject:n.onReject}),r}configure(e){this.cfg={...this.cfg,...e}}predict(e,n){return this.entries.set(e,n??this.cfg.now?.()??performance.now()),{key:e,cancel:()=>{this.entries.delete(e),this.accepted.delete(e)},accept:()=>{this.entries.has(e)&&this.accepted.add(e)}}}has(e){return this.entries.has(e)}confirm(e){this.entries.delete(e),this.accepted.delete(e)}reject(e){this.entries.delete(e)&&(this.accepted.delete(e),this.cfg.onReject?.(e))}prune(e,n){let r=e??this.cfg.now?.()??performance.now(),s=this.cfg.ttlMs,o=n??(typeof s=="function"?s():s)??1/0;for(let[i,a]of this.entries)this.accepted.has(i)||r-a>o&&(this.entries.delete(i),this.cfg.onReject?.(i))}clear(){this.entries.clear(),this.accepted.clear()}get size(){return this.entries.size}dispose(){this.dead=!0,this.entries.clear(),this.accepted.clear()}}});function d0(){return{ema:0,peak:0}}function Bp(t,e){t.ema+=(e-t.ema)*.1,t.peak=Math.max(e,t.peak*.9)}function f0(t){t.ema=0,t.peak=0}function bi(t,e){let n=e!==void 0&&e>l0?e:l0;return t.ema>=n?"diverging":t.peak>=n?"jitter":"matched"}var l0,vl=pt(()=>{"use strict";l0=.001});function sc(){return il()}function h0(){console.warn("@colyseus/sdk predict: a predicted value was read BEFORE this frame's input.send() calls. Reads between predict.tick() and the frame's sends are one fixed step stale and stutter on late frames. Send the frame's due inputs right after predict.tick(now) \u2014 tick and pump in your earliest per-frame callback, before anything reads value()/pose(). For game logic (zone checks, hit-reg) read .state/.world instead. See PREDICTION.md \xA74 (frame order).")}function m0(t,e){console.warn(e===""?`@colyseus/sdk predict: two key-less ctx.memo calls ran in one step (input seq ${t}) \u2014 the key-less form is ONE shared slot per step, so replay returns one frozen value for both (silent re-simulation corruption). Pass distinct keys: ctx.memo("a", \u2026) / ctx.memo("b", \u2026).`:`@colyseus/sdk predict: ctx.memo("${e}") ran twice in one step (input seq ${t}) \u2014 both calls share one slot on replay. Give each call site its own key (include the loop index for a per-iteration memo).`)}function y0(t,e,n,r){let s=Mt();if(s-p0<tT)return;p0=s;let o="",i=-1;for(let c in e){let u=e[c],l=u<0?-u:u;l>i&&(i=l,o=c)}let a=o?e[o]:n;console.warn(`@colyseus/sdk predict: prediction is diverging at input seq ${t} \u2014 rolling drift ${n.toFixed(3)} \u2265 tolerance ${r}; "${o}" currently off by ${a.toFixed(3)}. Most likely the client and server simulations disagree: a different fixed dt, mismatched constants, a step function that isn't shared, or an input the server skipped. See PREDICTION.md \xA75 (Determinism).`)}var p0,tT,Lp=pt(()=>{"use strict";Ia();Da();p0=-1/0,tT=1e3});function g0(){return zp>0}var Fp,zp,wi,Ml=pt(()=>{"use strict";vl();Lp();Fp=class{constructor(){m(this,"byTick",new Map);m(this,"diagTick",-1);m(this,"diagKeys",new Set);m(this,"warnedKeys",new Set)}run(e,n,r,s){if(n)return this.byTick.get(e)?.get(r);sc()&&(e!==this.diagTick?(this.diagTick=e,this.diagKeys.clear()):this.diagKeys.has(r)&&!this.warnedKeys.has(r)&&(this.warnedKeys.add(r),m0(e,r)),this.diagKeys.add(r));let o=s();if(o!==void 0){let i=this.byTick.get(e);i===void 0&&(i=new Map,this.byTick.set(e,i)),i.set(r,o)}return o}prune(e){for(let n of this.byTick.keys())n<=e&&this.byTick.delete(n)}clear(){this.byTick.clear(),this.diagTick=-1,this.diagKeys.clear()}},zp=0;wi=class{constructor(e){m(this,"lastCorrection",{});m(this,"lastCorrectionMag",0);m(this,"reconcileSeq",0);m(this,"drift",d0());m(this,"error",{});m(this,"prev",{});m(this,"renderedBefore",{});m(this,"lastTick",-1);m(this,"lastAcked",0);m(this,"lastEpoch");m(this,"replayFrom",0);m(this,"predictedSeq",0);m(this,"catching",!1);m(this,"unsubscribeSend",()=>{});m(this,"renderAcc",0);m(this,"tickSeq",0);m(this,"clampedReadTick",-1);m(this,"warnedStaleRead",!1);m(this,"stepCtx");m(this,"ackWatermark",()=>this.input_.lastProcessed);m(this,"memos",new Fp);m(this,"smoothMs");m(this,"snapThreshold");m(this,"stepMs");m(this,"input_");m(this,"onReconcile");m(this,"warnTolerance");m(this,"clock");m(this,"dead",!1);m(this,"disposedHooks",[]);this.input_=e.input,this.clock=e.clock,this.smoothMs=e.smoothMs??(this.input_.patchRate?this.input_.patchRate:50),this.snapThreshold=e.snap??0;let n=e.stepMs??this.input_.stepMs??(e.stepSeconds!==void 0?e.stepSeconds*1e3:void 0);if(n===void 0)throw new Error("@colyseus/sdk reconciler: fixed simulation step is unknown. The server room must call setFixedTimestep() (or setTimestep()) so the input handle advertises a tick rate, or pass stepMs/stepSeconds explicitly \u2014 a wrong dt silently diverges rollback-replay.");this.stepMs=n;let r=e.stepSeconds??this.input_.stepSeconds??n/1e3,s=e.subSteps??this.input_.subSteps??1;this.stepCtx={dt:r,dtMs:n,tick:0,isReplay:!1,reckonTime:0,lagCompActive:!1,subSteps:s,subDt:r/s,subDtMs:n/s,memo:(o,i)=>typeof o=="string"?this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,o,i):this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,"",o),predict:(o,i)=>{this.stepCtx.isReplay||o._predictFromSim(this.stepCtx.tick,i,this.ackWatermark)}},this.onReconcile=e.onReconcile,this.warnTolerance=e.warnOnDivergence,this.lastAcked=this.input_.lastProcessed,this.lastEpoch=this.input_.epoch,this.predictedSeq=this.input_.sentCount,this.unsubscribeSend=this.input_.onSend(()=>this.catchUp())}tick(e){this.tickSeq++;let n=this.lastTick<0?0:e-this.lastTick;this.lastTick=e,n>0&&this.stepMs>0&&(this.renderAcc+=n);let r=this.input_.epoch;r!==this.lastEpoch&&(this.lastEpoch=r,this.reset());let s=this.input_.lastProcessed;if(s>this.lastAcked&&(this.lastAcked=s,this.reconcile(s)),this.markDirty(),n<=0)return;let o=this.smoothMs<=0?1:1-Math.exp(-n/this.smoothMs);for(let i of this.smoothedFields())this.error[i]-=this.error[i]*o}renderAlpha(){if(this.stepMs<=0)return 1;let e=this.renderAcc/this.stepMs;return e<0?0:e>1?1:e}noteRenderRead(){this.catching||this.stepMs<=0||this.renderAcc<this.stepMs||(this.clampedReadTick=this.tickSeq)}catchUp(){let e=this.input_.sentCount;if(!(this.predictedSeq>=e||this.catching)){this.clampedReadTick===this.tickSeq&&!this.warnedStaleRead&&(this.warnedStaleRead=!0,h0()),this.catching=!0,this.stepCtx.isReplay=!1;for(let n=this.predictedSeq+1;n<=e;n++){let r=this.input_.at(n);r!==void 0&&(this.snapshotPrev(),this.runStep(n,r),this.refreshRender(),this.renderAcc-=this.stepMs,this.renderAcc<0?this.renderAcc=0:this.renderAcc>=this.stepMs&&(this.renderAcc%=this.stepMs)),this.predictedSeq=n}this.catching=!1}}runStep(e,n){this.stepCtx.tick=e;let r=this.input_.reckonTimeAt(e);this.stepCtx.lagCompActive=r>0,this.stepCtx.reckonTime=r>0?r:this.clock!==void 0?this.clock.serverNow():0,this.applyStep(n)}reconcile(e){let n=this.warnTolerance!==void 0||sc();if(this.truthMatchesAt(e)){if(n){for(let u of this.smoothedFields())this.lastCorrection[u]=0;this.lastCorrectionMag=0,Bp(this.drift,0)}this.reconcileSeq++,this.memos.prune(e),this.onReconcile?.(e);return}let r=this.renderedBefore;for(let u of this.smoothedFields())r[u]=this.readCurrent(u)+this.error[u];this.adoptTruth();let s=Math.max(e,this.replayFrom);this.stepCtx.isReplay=!0,this.catching=!0,zp++;try{for(let u=s+1;u<=this.input_.sentCount;u++){let l=this.input_.at(u);l!==void 0&&this.runStep(u,l)}}finally{zp--}this.catching=!1,this.refreshRender(),this.predictedSeq=this.input_.sentCount;let o=this.smoothMs<=0,i=n||this.snapThreshold>0,a=0;for(let u of this.smoothedFields()){let l=r[u]-this.readCurrent(u);if(this.error[u]=o?0:l,i){let d=l<0?-l:l;d>a&&(a=d)}n&&(this.lastCorrection[u]=l)}let c=this.snapThreshold>0&&a>this.snapThreshold;if(c)for(let u of this.smoothedFields())this.error[u]=0,this.prev[u]=this.readCurrent(u);this.reconcileSeq++,n&&(this.lastCorrectionMag=a,c||(Bp(this.drift,a),this.warnTolerance!==void 0&&bi(this.drift,this.warnTolerance)==="diverging"&&y0(e,this.lastCorrection,this.drift.ema,this.warnTolerance))),this.memos.prune(e),this.onReconcile?.(e)}get pendingCount(){return this.input_.pendingCount}reset(){this.reseedState(),f0(this.drift),this.replayFrom=this.input_.sentCount,this.predictedSeq=this.input_.sentCount,this.lastAcked=this.input_.lastProcessed,this.renderAcc=0,this.memos.clear(),this.markDirty()}onDisposed(e){this.disposedHooks.push(e)}dispose(){this.dead=!0,this.unsubscribeSend();for(let e of this.disposedHooks.splice(0))e()}truthMatchesAt(e){return!1}refreshRender(){}markDirty(){}}});var nT,Up,Si,Vp=pt(()=>{"use strict";Np();Ml();nT=0,Up=10,Si=class{constructor(e,n){m(this,"opts");m(this,"store");m(this,"entries",new Map);m(this,"now");m(this,"cooldownUntil",-1/0);m(this,"warnedReplayPredict",!1);m(this,"dead",!1);m(this,"teardowns",[]);this.opts=e,this.now=()=>n?.serverNow()??performance.now(),this.store=Tl.get({clock:n},{ttlMs:e.ttlMs??rc,onReject:r=>{let s=this.entries.get(r);this.entries.delete(r),s&&this.opts.onReject?.(s.payload)}})}_predictFromSim(e,n,r){this.add(e,n,r)}predict(e){if(g0()){this.warnedReplayPredict||(this.warnedReplayPredict=!0,console.warn(`@colyseus/sdk: PredictedEventChannel${this.opts.label?` "${this.opts.label}"`:""}.predict() was called during a rollback replay and ignored. Inside a reconciler step, use ctx.predict(channel, payload).`));return}this.add(-1,e)}add(e,n,r){let s=this.opts.uniqueBy!==void 0?this.opts.uniqueBy(n):typeof n=="string"||typeof n=="number"?n:nT;if(this.entries.has(s))return;let o=this.now();if(this.opts.cooldownMs!==void 0){if(o<this.cooldownUntil)return;this.cooldownUntil=o+this.opts.cooldownMs}let i=this.store.predict(s,o);r!==void 0&&i.accept(),this.entries.set(s,{payload:n,seq:e,acked:r}),this.opts.onPredict?.(n)}has(e){return e===void 0?this.entries.size>0:this.entries.has(e)}get pendingCount(){return this.entries.size}confirm(e){let n=0;for(let r of this.settleKeys(e)){let s=this.entries.get(r);s!==void 0&&(this.entries.delete(r),this.store.confirm(r),this.opts.onConfirm?.(s.payload),n++)}return n===0&&this.opts.onUnpredicted?.(e),n}reject(e){let n=0;for(let r of this.settleKeys(e))this.entries.has(r)&&(this.store.reject(r),n++);return n}settleKeys(e){return e!==void 0?[e]:[...this.entries.keys()]}clear(){this.entries.clear(),this.store.clear()}prune(){if(this.entries.size>0){let e=this.opts.graceTicks??Up;for(let[n,r]of[...this.entries])r.acked!==void 0&&r.acked()>=r.seq+e&&this.store.reject(n)}this.store.prune()}_addTeardown(e){this.teardowns.push(e)}dispose(){for(let e of this.teardowns.splice(0))e();this.dead=!0,this.clear(),this.store.dispose()}}});var no,Cl=pt(()=>{"use strict";Np();no=class{constructor(e={},n=null){m(this,"opts");m(this,"clock");m(this,"correlate");m(this,"ttl");m(this,"byId",new Map);m(this,"byServer",new Map);m(this,"nextId",1);m(this,"lastTickAt");m(this,"detach");m(this,"dead",!1);m(this,"handleAdd",(e,n)=>{if(this.byServer.has(e))return;let r=this.isOwned(e)?this.takeMatch(e):void 0;if(r)this.confirmEntry(r,e);else{let s={id:this.nextId++,server:e,local:void 0,state:"confirmed",at:void 0,leadMs:0,accepted:!1,data:this.makeData()};this.byId.set(s.id,s),this.byServer.set(e,s)}});m(this,"handleRemove",(e,n)=>{let r=this.byServer.get(e);r&&(this.byServer.delete(e),this.byId.delete(r.id))});m(this,"readServer",(e,n)=>e[n]);this.opts=e,this.clock=n,this.correlate=e.correlate??"fifo",this.ttl=e.ttl??rc}attach(e){this.detach?.(),this.detach=e(this.handleAdd,this.handleRemove)}spawn(e){let n=this.nextId++,r=this.makeData(),s={id:n,server:void 0,local:e,state:"pending",at:this.now(),leadMs:0,accepted:!1,data:r};return this.byId.set(n,s),{id:n,local:e,data:r,cancel:()=>{let o=this.byId.get(n);o&&o.state==="pending"&&this.byId.delete(n)},accept:()=>{let o=this.byId.get(n);o&&(o.accepted=!0)}}}confirmEntry(e,n){e.server=n,e.state="confirmed";let r=this.opts.spawnTime;r!==void 0&&e.at!==void 0&&(e.leadMs=r(n)-e.at),this.byServer.set(n,e)}takeMatch(e){let n=this.correlate;if(typeof n!="function"){for(let r of this.byId.values())if(r.state==="pending")return r;return}for(let r of this.byId.values())if(r.state==="pending"&&n(r.local,e))return r}isOwned(e){return this.opts.owned?this.opts.owned(e):!0}makeData(){return this.opts.data?this.opts.data():void 0}tick(e=performance.now()){let n=this.opts.step,r=this.clock!==null?this.clock.serverNow():e;if(n!==void 0&&this.lastTickAt!==void 0){let s=Math.max(0,(r-this.lastTickAt)/1e3);if(s>0)for(let o of this.byId.values())o.state==="pending"&&n(o.local,s)}this.lastTickAt=r}prune(){if(this.byId.size===0)return;let e=this.now(),n=this.ttl(this.clock?.smoothedRtt()??0);for(let r of this.byId.values())r.state==="pending"&&!r.accepted&&r.at!==void 0&&e-r.at>n&&(this.byId.delete(r.id),this.opts.onReject?.(r.local,r.id))}entries(){return this.byId.values()}entryFor(e){return this.byServer.get(e)}value(e,n){return e.server!==void 0?this.readServer(e.server,n):e.local[n]}bindReader(e){this.readServer=e}alive(e){return this.byId.has(e)}get size(){return this.byId.size}clear(){this.byId.clear(),this.byServer.clear()}dispose(){this.dead=!0,this.detach?.(),this.detach=void 0,this.clear()}now(){return this.clock?.serverNow()??performance.now()}}});var b0,ro,Ol=pt(()=>{"use strict";Ml();La();Lp();b0=t=>typeof t=="number"?t:typeof t=="boolean"?t?1:0:NaN,ro=class extends wi{constructor(n,r){super(r);m(this,"local",{});m(this,"fields");m(this,"numericFields",[]);m(this,"step");m(this,"instance");m(this,"wireRound",[]);m(this,"history");m(this,"historySeq");m(this,"historySize");m(this,"historyOn");m(this,"undeclared",null);m(this,"devView",null);this.instance=n;let s=r.fields,o=s??Ba(n).fields;if(s===void 0&&o.length===0)throw new Error("predict.reconciler(): no `fields` given and none derivable \u2014 the instance has no schema metadata (a plain object, or a schema with no scalar fields). Pass the decoded instance from room.state, or list `fields` explicitly.");this.fields=o,this.step=r.step;let i=this.fields.length>0;for(let a of this.fields){let c=n[a];this.local[a]=c,typeof c=="number"?(this.numericFields.push(a),this.prev[a]=c,this.error[a]=0):typeof c!="boolean"&&(i=!1),this.wireRound.push(Sb(n,a))}if(this.historyOn=i,this.historySize=this.input_.replayBufferSize??64,this.history=new Float64Array(this.historyOn?this.historySize*this.fields.length:0),this.historySeq=new Float64Array(this.historyOn?this.historySize:0).fill(-1),s!==void 0){let a=new Set(this.fields),c=Ba(n).fields.filter(u=>!a.has(u));c.length>0&&(this.undeclared=new Set(c))}}get state(){return this.local}get boundRegistrations(){return[{source:this.instance,fields:this.numericFields,poseKeys:this.numericFields}]}value(n){this.noteRenderRead();let r=this.local[n];if(typeof r!="number")return r;let s=r+(this.error[n]??0),o=this.prev[n]??s;return o+(s-o)*this.renderAlpha()}smoothedFields(){return this.numericFields}readCurrent(n){return this.local[n]}applyStep(n){let r=this.undeclared!==null&&sc()?this.stepView():this.local;if(this.step(this.stepCtx,r,n),this.historyOn){let s=this.stepCtx.tick,o=s%this.historySize,i=o*this.fields.length;for(let a=0;a<this.fields.length;a++)this.history[i+a]=b0(this.local[this.fields[a]]);this.historySeq[o]=s}}stepView(){if(this.devView!==null)return this.devView;let n=this.undeclared,r=new Set,s=(o,i)=>{typeof i!="string"||!n.has(i)||r.has(i)||(r.add(i),console.warn(`@colyseus/sdk predict: step ${o} "${i}" \u2014 a schema field NOT in this reconciler's \`fields\` list, so it is never mirrored or replayed: prediction integrates on top of a stale value and rubber-bands under latency. Add "${i}" to \`fields\`, or omit \`fields\` to mirror every scalar field. Read adopt-only fields off the raw instance instead of the predicted state.`))};return this.devView=new Proxy(this.local,{get(o,i,a){return s("read",i),Reflect.get(o,i,a)},set(o,i,a,c){return s("wrote",i),Reflect.set(o,i,a,c)}}),this.devView}truthMatchesAt(n){if(!this.historyOn)return!1;let r=n%this.historySize;if(this.historySeq[r]!==n)return!1;let s=r*this.fields.length,o=this.instance;for(let i=0;i<this.fields.length;i++)if(this.wireRound[i](this.history[s+i])!==b0(o[this.fields[i]]))return!1;return!0}snapshotPrev(){for(let n of this.numericFields)this.prev[n]=this.local[n]+this.error[n]}adoptTruth(){let n=this.instance;for(let r of this.fields)this.local[r]=n[r]}reseedState(){let n=this.instance;for(let r of this.fields)this.local[r]=n[r];for(let r of this.numericFields)this.prev[r]=this.local[r],this.error[r]=0;this.historySeq.fill(-1)}}});var so,Il=pt(()=>{"use strict";Ml();La();so=class extends wi{constructor(n){super(n);m(this,"worldHandle");m(this,"bindings",[]);m(this,"curPose",{});m(this,"poseFields",[]);m(this,"customFields",[]);m(this,"fieldsReady",!1);m(this,"poseA",{});m(this,"poseB",{});m(this,"renderPose",{});m(this,"poseDirty",!0);m(this,"step");m(this,"adopt");m(this,"readPose");m(this,"interpolate");let r=n.world;for(let s of Object.keys(r)){let o=r[s];if(o===null||typeof o!="object")continue;if(jt(o)===void 0){if(cr(o)!==void 0)throw new Error(`predict.sim(): world.${s} is a schema instance that hasn't been decoded (no refId). Pass the decoded instance from room.state (e.g. inside onAdd), or a plain object for opaque scratch.`);continue}let{fields:i,numeric:a}=Ba(o);if(i.length===0)throw new Error(`predict.sim(): world.${s} is a decoded ref with no scalar fields to bind. Binding a whole COLLECTION isn't supported (yet) \u2014 spread its children into world parts (one entry per entity, fixed at construction). Nest a scalar-less instance below a plain wrapper if you meant it as an opaque handle.`);let c={};for(let l of i)c[l]=o[l];r[s]=c;let u=a.map(l=>`${s}.${l}`);this.bindings.push({source:o,mirror:c,fields:i,numeric:a,poseKeys:u})}if(this.bindings.length===0&&n.adopt===void 0)throw new Error("predict.sim(): no restore point \u2014 world has no schema-bound entries and no adopt() was provided. Put decoded schema instances in world (auto-bound), or provide adopt().");this.worldHandle=n.world,this.step=n.step,this.adopt=n.adopt,this.readPose=n.pose,this.interpolate=n.interpolate,this.refreshPose();for(let s of this.poseFields)this.prev[s]=this.curPose[s],this.error[s]=0}refreshPose(){let n=this.curPose;for(let r of this.bindings){let{mirror:s,numeric:o,poseKeys:i}=r;for(let a=0;a<o.length;a++)n[i[a]]=s[o[a]]}if(this.readPose!==void 0){let r=this.readPose(this.worldHandle);this.fieldsReady||(this.customFields=Object.keys(r));for(let s of this.customFields)n[s]=r[s]}if(!this.fieldsReady){let r=[];for(let s of this.bindings)for(let o of s.poseKeys)r.push(o);for(let s of this.customFields)r.includes(s)||r.push(s);this.poseFields=r,this.fieldsReady=!0}this.poseDirty=!0}get world(){return this.worldHandle}get boundRegistrations(){return this.bindings.map(n=>({source:n.source,fields:n.numeric,poseKeys:n.poseKeys}))}value(n){if(this.noteRenderRead(),this.interpolate)return this.pose()[n];let r=this.curPose[n]+(this.error[n]??0),s=this.prev[n]??r;return s+(r-s)*this.renderAlpha()}pose(){if(this.noteRenderRead(),!this.poseDirty)return this.renderPose;let n=this.renderAlpha(),r=this.poseA,s=this.poseB;for(let o of this.poseFields)r[o]=this.prev[o]??this.curPose[o],s[o]=this.curPose[o]+(this.error[o]??0);if(this.interpolate){let o=this.interpolate(r,s,n);for(let i of this.poseFields)this.renderPose[i]=o[i]}else for(let o of this.poseFields)this.renderPose[o]=r[o]+(s[o]-r[o])*n;return this.poseDirty=!1,this.renderPose}smoothedFields(){return this.poseFields}readCurrent(n){return this.curPose[n]}applyStep(n){this.step(this.stepCtx,this.worldHandle,n)}adoptTruth(){for(let n of this.bindings){let{source:r,mirror:s,fields:o}=n;for(let i=0;i<o.length;i++)s[o[i]]=r[o[i]]}this.adopt?.(this.worldHandle)}refreshRender(){this.refreshPose()}markDirty(){this.poseDirty=!0}snapshotPrev(){for(let n of this.poseFields)this.prev[n]=this.curPose[n]+this.error[n]}reseedState(){this.adoptTruth(),this.refreshPose();for(let n of this.poseFields)this.prev[n]=this.curPose[n],this.error[n]=0}}});function w0(t,e,n,r){let s=[];if(n.field!==void 0){let o=new Map;s.push(t.onAdd(n.collection,(i,a)=>{o.has(i)||o.set(i,t.listen(i,n.field,c=>{c===n.equals&&e.confirm(a)},!1))})),s.push(t.onRemove(n.collection,i=>{o.get(i)?.(),o.delete(i)})),s.push(()=>{for(let i of o.values())i();o.clear()})}else n.event==="remove"?s.push(t.onRemove(n.collection,(o,i)=>{e.confirm(i)})):s.push(t.onAdd(n.collection,o=>{n.mine!==void 0&&o[n.mine]!==r?.()||e.confirm()},!1));return()=>{for(let o of s.splice(0))o?.()}}var S0=pt(()=>{"use strict"});function _0(t){return t===null||typeof t!="object"?!1:Array.isArray(t.fields)}function aT(){R0||(R0=!0,console.warn("@colyseus/sdk Predict: room.clock isn't server-synced because the server room didn't call defineInput(). Server-time interpolation and lag compensation fall back to local time. Add defineInput() on the server room to enable them \u2014 or ignore this if you only need local smoothing."))}var ht,un,xn,Br,Un,oc,ic,xi,_i,Ri,ac,Ot,rT,sT,x0,Gt,Ei,oo,io,ki,Ai,Pi,Ti,pr,uc,Bl,Ll,Fl,oT,Dl,Hp,gs,Nl,iT,R0,vi,ao,$p=pt(()=>{"use strict";At();Vp();Cl();Ol();Il();pp();vl();ul();Da();La();S0();ht=16,un=0,xn=1,Br=2,Un=3,oc=4,ic=5,xi=6,_i=7,Ri=8,ac=9,Ot=ac+ht*2,rT=3,sT=1.5,x0=250,Gt=7,Ei=0,oo=1,io=2,ki=3,Ai=4,Pi=5,Ti=6,pr=0,uc=0,Bl=1,Ll=2,Fl=3,oT=4,Dl=5,Hp={lerp:uc,extrapolate:Bl,damped:Ll,reckon:Fl,raw:oT},gs={mode:"lerp",delay:100,smoothMs:50,maxExtrapolate:200,tickInterval:0,snap:0,angle:!1},Nl={step:void 0,smoothMs:50,substep:16,snap:0};iT=0,R0=!1;vi=class vi{constructor(e,n){m(this,"callbacks");m(this,"sessionSource");m(this,"slotBuf",new Float64Array(64*Ot));m(this,"slotCount",0);m(this,"slotDetach",[]);m(this,"slotAngle",[]);m(this,"freeSlots",[]);m(this,"slotByRef",new Map);m(this,"simByRef",new Map);m(this,"boundBySlot",new Map);m(this,"boundProfileIdx",-1);m(this,"renderTime",0);m(this,"defaultMode");m(this,"reckonDefaults");m(this,"clock");m(this,"useRenderClock",!1);m(this,"fixedStepMs");m(this,"stepAcc",0);m(this,"lastFrameNow",-1);m(this,"profileBuf",new Float64Array(8*Gt));m(this,"profileCount",0);m(this,"profileKeys",new Map);m(this,"profileLabels",[]);m(this,"profileComputers",[]);m(this,"trackListeners",[]);m(this,"name");m(this,"disposeListeners",[]);m(this,"driven",[]);m(this,"computeDamped",e=>{let n=this.slotBuf,r=e*Ot,s=this.profileBuf,o=(n[r+Un]|0)*Gt,i=this.renderTime,a=n[r+un],c=n[r+Br],u=i-c;n[r+Br]=i;let l=n[r+xn];if(u>0){let d=s[o+io],f=d>0?1-Math.exp(-u/d):1;l+=(a-l)*f,n[r+xn]=l}return l});m(this,"computeLerp",e=>{let n=this.computeLerpRaw(e),r=this.slotBuf,s=e*Ot,o=this.profileBuf[(r[s+Un]|0)*Gt+Ti],i=this.renderTime;if(o<=0)return r[s+xn]=n,r[s+Ri]=n,r[s+Br]=i,n;let a=r[s+Br],c=i-a;if(c<=0)return r[s+xn];let u=r[s+Ri],l=r[s+xn],d=c/o,f=(n-u)/d,h=n-f+(l-u+f)*Math.exp(-d);return r[s+xn]=h,r[s+Ri]=n,r[s+Br]=i,h});m(this,"computeExtrapolate",e=>{let n=this.slotBuf,r=e*Ot,s=this.profileBuf,o=(n[r+Un]|0)*Gt,i=this.renderTime,a=n[r+_i]|0;if(a===0)return n[r+un];let c=n[r+xi]|0,u=r+ac,l=(c-a+ht)%ht,d=(l+a-1)%ht,f=u+d*2,h=n[f],p=n[f+1],y;if(a===1)y=p;else{let A=a>=3?2:1,E=(l+a-1-A+ht)%ht,P=u+E*2,k=n[P],M=n[P+1],L=h-k;if(L<=0)y=p;else{let K=(p-M)/L,W=s[o+ki],B=i-h;B<0?B=0:B>W&&(B=W),y=p+K*B}}let S=n[r+Br];n[r+Br]=i;let w=s[o+io];if(w<=0)return n[r+xn]=y,y;let x=i-S,R=n[r+xn];if(x>0){let A=1-Math.exp(-x/w);R+=(y-R)*A,n[r+xn]=R}return R});m(this,"computeReckon",e=>{let n=this.slotBuf,r=e*Ot,s=n[r+oc],o=n[r+ic]|0,i=this.simByRef.get(s);if(i!==void 0){let a=o<i.posOf.length?i.posOf[o]:-1;if(a>=0)return this.applySimulation(i,a)}return n[r+un]});m(this,"computeRaw",e=>this.slotBuf[e*Ot+un]);m(this,"computeBound",e=>{let n=this.boundBySlot.get(e);return n!==void 0?n.ctrl.value(n.key):this.slotBuf[e*Ot+un]});this.callbacks=lp.get(e),this.sessionSource=e;let{clock:r,...s}=n;this.defaultMode=s.mode??"lerp";let o=this.defaultMode!=="reckon"&&this.defaultMode!=="raw",i=o?(()=>{let u=s;return{mode:u.mode??gs.mode,delay:u.delay??gs.delay,smoothMs:u.smoothMs??gs.smoothMs,maxExtrapolate:u.maxExtrapolate??gs.maxExtrapolate,tickInterval:u.tickInterval??gs.tickInterval,snap:u.snap??gs.snap,angle:u.angle??gs.angle}})():{...gs},a=o?s.smoothMs??0:0;if(this.allocProfile(this.defaultMode,i.delay,i.smoothMs,a,i.maxExtrapolate,i.tickInterval,i.snap,!1)!==pr)throw new Error("Predict: defaults profile must be at index 0");if(this.defaultMode==="reckon"){let u=s;this.reckonDefaults={step:u.step,smoothMs:u.smoothMs??Nl.smoothMs,substep:u.substep??Nl.substep,snap:u.snap??Nl.snap}}else this.reckonDefaults={...Nl};this.clock=r??e.clock??void 0,this.useRenderClock=s.renderPresent!==!1,this.clock===ii&&aT(),this.name=s.name??`predict#${++iT}`,ol("predict",this.makeCoreHandle())}static get(e,n={}){return new vi(e,n)}get mode(){return this.defaultMode}presentFn(){let e=this.clock;if(e)return this.useRenderClock&&e.renderNow?e.renderNow.bind(e):e.serverNow.bind(e)}makeCoreHandle(){return{name:this.name,mode:()=>this.defaultMode,smoothingDefaults:()=>this.readSmoothingDefaults(),reckonDefaults:()=>({...this.reckonDefaults}),reconcilers:()=>this.snapshotReconcilers(),attachedCount:()=>this.slotByRef.size,setDefaults:e=>this.setDefaults(e),profiles:()=>this.snapshotProfiles(),setProfile:(e,n)=>this.setProfile(e,n),onTrack:e=>(this.trackListeners.push(e),()=>{let n=this.trackListeners.indexOf(e);n>=0&&this.trackListeners.splice(n,1)}),onDispose:e=>(this.disposeListeners.push(e),()=>{let n=this.disposeListeners.indexOf(e);n>=0&&this.disposeListeners.splice(n,1)})}}snapshotReconcilers(){let e=[],n=0;for(let r of this.driven){let s=r;if(!s.drift)continue;let o=s.warnTolerance;e.push({label:`reconciler #${n++}`,status:bi(s.drift,o),severity:o!==void 0&&o>0?s.drift.ema/o:void 0,ema:s.drift.ema,peak:s.drift.peak,lastCorrectionMag:s.lastCorrectionMag??0,reconcileSeq:s.reconcileSeq??0})}return e}readSmoothingDefaults(){let e=this.profileBuf,n=pr*Gt,r=e[n+Ei]|0;return{mode:r===uc?"lerp":r===Bl?"extrapolate":r===Ll?"damped":r===Fl?"reckon":"raw",delay:e[n+oo],smoothMs:e[n+io],lerpSmoothMs:e[n+Ti],maxExtrapolate:e[n+ki],tickInterval:e[n+Ai],snap:e[n+Pi]}}allocProfile(e,n,r,s,o,i,a,c,u){let l=typeof e=="number"?e:Hp[e],d="";if(c){d=`${u??""}|${l}|${n}|${r}|${s}|${o}|${i}|${a}`;let y=this.profileKeys.get(d);if(y!==void 0)return y}let f=this.profileCount++;if((f+1)*Gt>this.profileBuf.length){let y=new Float64Array(this.profileBuf.length*2);y.set(this.profileBuf),this.profileBuf=y}let p=f*Gt;return this.profileBuf[p+Ei]=l,this.profileBuf[p+oo]=n,this.profileBuf[p+io]=r,this.profileBuf[p+Ti]=s,this.profileBuf[p+ki]=o,this.profileBuf[p+Ai]=i,this.profileBuf[p+Pi]=a,this.profileLabels[f]=u,this.profileComputers[f]=this.computerForMode(l),c&&this.profileKeys.set(d,f),f}computerForMode(e){return e===uc?this.computeLerp:e===Bl?this.computeExtrapolate:e===Ll?this.computeDamped:e===Fl?this.computeReckon:e===Dl?this.computeBound:this.computeRaw}profileFromOpts(e){if(e.mode===void 0&&e.delay===void 0&&e.smoothMs===void 0&&e.maxExtrapolate===void 0&&e.tickInterval===void 0&&e.snap===void 0)return pr;let n=this.readSmoothingDefaults(),r=e.mode??n.mode,s=e.delay??n.delay,o=e.smoothMs??n.smoothMs,i=e.smoothMs??n.lerpSmoothMs,a=e.maxExtrapolate??n.maxExtrapolate,c=e.tickInterval??n.tickInterval,u=e.snap??n.snap;return r===n.mode&&s===n.delay&&o===n.smoothMs&&i===n.lerpSmoothMs&&a===n.maxExtrapolate&&c===n.tickInterval&&u===n.snap?pr:this.allocProfile(r,s,o,i,a,c,u,!0)}groupProfile(e,n){let r=this.readSmoothingDefaults(),s=e.mode??this.defaultMode;return this.allocProfile(s,e.delay??r.delay,e.smoothMs??r.smoothMs,e.smoothMs??r.lerpSmoothMs,e.maxExtrapolate??r.maxExtrapolate,e.tickInterval??r.tickInterval,e.snap??r.snap,!0,n)}setDefaults(e){let n=e.mode;if(n!==void 0){this.defaultMode=n;let a=pr*Gt,c=Hp[n];this.profileBuf[a+Ei]=c,this.profileComputers[pr]=this.computerForMode(c)}let r=e,s=pr*Gt,o=this.profileBuf;r.delay!==void 0&&(o[s+oo]=r.delay),r.smoothMs!==void 0&&(o[s+io]=r.smoothMs,o[s+Ti]=r.smoothMs),r.maxExtrapolate!==void 0&&(o[s+ki]=r.maxExtrapolate),r.tickInterval!==void 0&&(o[s+Ai]=r.tickInterval),r.snap!==void 0&&(o[s+Pi]=r.snap,this.reckonDefaults.snap=r.snap);let i=e;i.step!==void 0&&(this.reckonDefaults.step=i.step),i.smoothMs!==void 0&&(this.reckonDefaults.smoothMs=i.smoothMs),i.substep!==void 0&&(this.reckonDefaults.substep=i.substep)}snapshotProfiles(){let e=[];for(let n=0;n<this.profileCount;n++){let r=n*Gt,s=this.profileBuf[r+Ei]|0;if(s===Dl)continue;let o=s===uc?"lerp":s===Bl?"extrapolate":s===Ll?"damped":s===Fl?"reckon":"raw";e.push({id:n,isDefault:n===pr,label:this.profileLabels[n],mode:o,delay:this.profileBuf[r+oo],smoothMs:this.profileBuf[r+(s===uc?Ti:io)],maxExtrapolate:this.profileBuf[r+ki],tickInterval:this.profileBuf[r+Ai],snap:this.profileBuf[r+Pi]})}return e}setProfile(e,n){if(e<0||e>=this.profileCount)return;let r=e*Gt,s=this.profileBuf;if((s[r+Ei]|0)!==Dl){if(n.mode!==void 0){let o=Hp[n.mode];s[r+Ei]=o,this.profileComputers[e]=this.computerForMode(o),e===pr&&(this.defaultMode=n.mode)}n.delay!==void 0&&(s[r+oo]=n.delay),n.smoothMs!==void 0&&(s[r+io]=n.smoothMs,s[r+Ti]=n.smoothMs),n.maxExtrapolate!==void 0&&(s[r+ki]=n.maxExtrapolate),n.tickInterval!==void 0&&(s[r+Ai]=n.tickInterval),n.snap!==void 0&&(s[r+Pi]=n.snap)}}dispose(){for(let e of new Set([...this.slotByRef.keys(),...this.simByRef.keys()]))this.detachByRef(e);this.trackListeners.length=0;for(let e of this.driven.splice(0))e.dispose?.();for(let e of this.disposeListeners.splice(0))e()}track(e,n,r={}){return this.trackWithProfile(e,n,this.profileFromOpts(r),r.angle??!1)}trackWithProfile(e,n,r,s=!1){let o=jt(e);if(o===void 0)throw new Error("Predict.track(): instance has no refId \u2014 track/attach must run AFTER the decoder delivers the instance (e.g. inside onAdd).");let i=Na(e,n),a=e[n]??0,c,u=this.slotByRef.get(o)?.get(n);u!==void 0&&(c=this.boundBySlot.get(u),c!==void 0?this.freeStash(c):this.untrackSlot(o,n));let l=this.allocSlot(),d=this.slotBuf,f=l*Ot;if(d[f+un]=a,d[f+xn]=a,d[f+Br]=performance.now(),d[f+Ri]=a,d[f+Un]=r,d[f+oc]=o,d[f+ic]=i,d[f+xi]=0,d[f+_i]=0,this.slotAngle[l]=s,c!==void 0)c.stash=l;else{let p=this.slotByRef.get(o);p===void 0&&(p=new Map,this.slotByRef.set(o,p)),p.set(n,l)}for(let p=0;p<this.trackListeners.length;p++)this.trackListeners[p](r,n);let h=this.callbacks.listen(e,n,p=>{let y=this.clock&&this.clock.lastServerTime()>0?this.clock.lastServerTime():performance.now(),S=this.slotBuf,w=l*Ot;if(s){let W=S[w+un];p=W+Math.atan2(Math.sin(p-W),Math.cos(p-W))}let x=(S[w+Un]|0)*Gt,R=this.profileBuf[x+Ai],A=S[w+xi]|0,E=S[w+_i]|0,P=this.profileBuf[x+Pi];P>0&&E>0&&Math.abs(p-S[w+un])>P&&(A=0,E=0,S[w+xn]=p,S[w+Ri]=p);let k=E===0?Number.NEGATIVE_INFINITY:S[w+ac+(A===0?ht-1:A-1)*2],M=y;if(R>0&&isFinite(k)){let W=y-k,B=W>0?Math.max(1,Math.round(W/R)):1;M=k+B*R;let se=y+R;M>se&&(M=se)}S[w+un]=p;let L=w+ac;if(E>=2&&isFinite(k)){let W=A===0?ht-1:A-1,B=W===0?ht-1:W-1,se=k-S[L+B*2],v=this.clock?.patchInterval?this.clock.patchInterval():0,$=v>0?v:se,Y=v>0?sT*v:rT*se;if($>0&&M-k>Y){let j=$<x0?$:x0,q=L+A*2;S[q]=M-j,S[q+1]=S[L+W*2+1],A=A+1>=ht?0:A+1,E<ht&&E++}}let K=L+A*2;S[K]=M,S[K+1]=p,S[w+xi]=A+1>=ht?0:A+1,E<ht&&(S[w+_i]=E+1)},!0);return this.slotDetach[l]=h,()=>this.untrackSlot(o,n)}untrack(e,n){let r=jt(e);r!==void 0&&this.untrackSlot(r,n)}untrackSlot(e,n){let r=this.slotByRef.get(e),s=r?.get(n);if(s===void 0)return;let o=this.boundBySlot.get(s);if(o!==void 0){this.freeStash(o);return}this.slotDetach[s]?.(),this.slotDetach[s]=void 0,this.freeSlots.push(s),r.delete(n),r.size===0&&this.slotByRef.delete(e)}freeStash(e){e.stash<0||(this.slotDetach[e.stash]?.(),this.slotDetach[e.stash]=void 0,this.freeSlots.push(e.stash),e.stash=-1)}allocSlot(){if(this.freeSlots.length>0)return this.freeSlots.pop();let e=this.slotCount++;if((e+1)*Ot>this.slotBuf.length){let r=new Float64Array(this.slotBuf.length*2);r.set(this.slotBuf),this.slotBuf=r}return e}registerBound(e,n,r,s,o){let i=jt(n),a=this.slotByRef.get(i);a===void 0&&(a=new Map,this.slotByRef.set(i,a));let c=[];for(let u=0;u<r.length;u++){let l=r[u],d=a.get(l),f=-1;if(d!==void 0){let w=this.boundBySlot.get(d);w!==void 0?(console.warn(`@colyseus/sdk Predict: "${l}" (refId ${i}) is already bound to a controller \u2014 the newer registration wins.`),f=w.stash,this.boundBySlot.delete(d),this.freeSlots.push(d)):f=d}let h=this.allocSlot(),p=this.slotBuf,y=h*Ot,S=n[l]??0;p[y+un]=S,p[y+xn]=S,p[y+Br]=0,p[y+Ri]=S,p[y+Un]=o,p[y+oc]=i,p[y+ic]=Na(n,l),p[y+xi]=0,p[y+_i]=0,this.slotAngle[h]=!1,this.boundBySlot.set(h,{ctrl:e,key:s[u],stash:f}),a.set(l,h),c.push(h);for(let w=0;w<this.trackListeners.length;w++)this.trackListeners[w](o,l)}return()=>{for(let u=0;u<c.length;u++){let l=c[u],d=this.boundBySlot.get(l);if(d===void 0||d.ctrl!==e)continue;this.boundBySlot.delete(l),this.freeSlots.push(l);let f=this.slotByRef.get(i);f?.get(r[u])===l&&(d.stash>=0?f.set(r[u],d.stash):(f.delete(r[u]),f.size===0&&this.slotByRef.delete(i)))}}}installBoundOverlay(e){let n=[];for(let r of e.boundRegistrations)r.fields.length===0||jt(r.source)===void 0||(this.boundProfileIdx<0&&(this.boundProfileIdx=this.allocProfile(Dl,0,0,0,0,0,0,!1,"bound")),n.push(this.registerBound(e,r.source,r.fields,r.poseKeys,this.boundProfileIdx)));n.length>0&&e.onDisposed(()=>{for(let r of n)r()})}trackStepped(e,n){let r=n.substep??16,s=n.fields,o=s.map(p=>Na(e,p)),i=n.step,a=this.clock,c=this.presentFn(),u=n.forwardMs??(c?()=>{let p=a.lastServerTime();return p>0?Math.max(0,c()-p):0}:()=>0),l=n.elapsedMs??c??(()=>performance.now()),d=e[al],f=n.snapshot===void 0&&Array.isArray(d)&&o.every(p=>p>=0&&p<d.length),h;if(f){let p=new e.constructor,y=p[al];h=(S,w,x,R)=>{let A=S[al];for(let k=0;k<A.length;k++)y[k]=A[k];let E=w,P=R-w;for(;E>0;){let k=E<r?E:r;P+=k,i(p,k/1e3,P),E-=k}for(let k=0;k<o.length;k++)x[k]=y[o[k]]}}else{let p=wb(e),y=n.snapshot??(p.length>0?xb(p):w=>({...w})),S=[...s];h=(w,x,R,A)=>{let E=y(w),P=x,k=A-x;for(;P>0;){let M=P<r?P:r;k+=M,i(E,M/1e3,k),P-=M}for(let M=0;M<S.length;M++)R[M]=E[S[M]]}}return this.trackSimulated(e,{fields:s,forwardMs:u,elapsedMs:l,smoothMs:n.smoothMs,snap:n.snap,advance:h})}trackSimulated(e,n){let r=jt(e);if(r===void 0)throw new Error("Predict.trackStepped(): instance has no refId \u2014 must run AFTER the decoder delivers the instance (e.g. inside onAdd).");let s=n.fields,o=s.length,i=s.map(h=>Na(e,h)),a=0;for(let h of i)h>a&&(a=h);let c=new Int8Array(a+1).fill(-1);for(let h=0;h<o;h++)i[h]>=0&&(c[i[h]]=h);let u=new Float64Array(o);for(let h=0;h<o;h++)u[h]=e[s[h]]??0;let l=this.presentFn(),d=n.elapsedMs??l??(()=>performance.now()),f={instance:e,fieldIds:i,posOf:c,forwardMs:n.forwardMs,elapsedMs:d,advance:n.advance,smoothMs:n.smoothMs??50,snap:n.snap??0,smoothed:u,out:new Float64Array(o),valueOut:new Float64Array(o),offset:new Float64Array(o),outPrev:new Float64Array(o),frameVel:new Float64Array(o),lastBaseT:NaN,lastApplyTime:-1/0};return this.simByRef.set(r,f),()=>this.untrackSimulated(r)}untrackSimulated(e){this.simByRef.delete(e)}attach(e,n){let r=this.makeGroup("(attach)",n);return this.attachWithPlan(e,this.planFor(r,e))}makeGroup(e,n){return{label:e,config:n,basePlan:this.buildGroupPlan(n,e),planByCtor:new Map}}planFor(e,n){let r=n.constructor,s=e.planByCtor.get(r);return s===void 0&&(s=this.resolveCtorPlan(e,n),e.planByCtor.set(r,s)),s}resolveCtorPlan(e,n){let r=cr(n),s=n.constructor?.name||"?",o=e.config;if(!_0(o)){if(r===void 0)return e.basePlan;let c=Object.keys(o).filter(l=>o[l]!==void 0);if(c.every(l=>typeof r[l]=="number"))return e.basePlan;let u={};for(let l of c)typeof r[l]=="number"&&(u[l]=o[l]);return this.buildGroupPlan(u,`${e.label}:${s}`)}let i=o,a=i.fields;if(r!==void 0){let c=a.filter(u=>typeof r[u]=="number");c.length!==a.length&&(a=c)}return a===i.fields?e.basePlan:this.buildGroupPlan({...i,fields:a},`${e.label}:${s}`)}buildGroupPlan(e,n){let r=[];if(_0(e)){let o=e;if(!Array.isArray(o.fields))throw new Error("Predict.attach(): `fields` must be a numeric-key array.");let i=o.mode??this.defaultMode,a=o.step??this.reckonDefaults.step,c=i==="reckon";if(c&&typeof a!="function")throw new Error("Predict.attach(): reckon mode requires a 'step' function. Either pass `step` in the attach config OR construct the Predict with `Predict.get(room, { mode: 'reckon', step: yourStepFn })` so it can be inherited.");let u=this.groupProfile({mode:i,snap:o.snap,smoothMs:o.smoothMs},n);for(let l of o.fields)r.push({field:l,profileIdx:u,angle:o.angle});return{label:n,isReckon:c,reckonFields:c?o.fields:void 0,reckonStep:c?a:void 0,reckonSmoothMs:o.smoothMs??this.reckonDefaults.smoothMs,reckonSubstep:o.substep??this.reckonDefaults.substep,reckonSnap:o.snap??this.reckonDefaults.snap,reckonSnapshot:o.snapshot,fieldProfiles:r}}let s=e;for(let o of Object.keys(s)){let i=s[o];if(i===void 0)continue;let a=typeof i=="string"?{mode:i}:i;r.push({field:o,profileIdx:this.groupProfile(a,n),angle:a.angle})}return{label:n,isReckon:!1,fieldProfiles:r}}attachToGroup(e,n,r){let s=[];n.isReckon&&s.push(this.trackStepped(e,{fields:n.reckonFields,step:n.reckonStep,smoothMs:n.reckonSmoothMs,substep:n.reckonSubstep,snap:n.reckonSnap,snapshot:n.reckonSnapshot,forwardMs:r}));for(let{field:o,profileIdx:i,angle:a}of n.fieldProfiles)s.push(this.trackWithProfile(e,o,i,!!a));return()=>{for(let o of s)o()}}attachWithPlan(e,n){let r=jt(e);if(r===void 0)throw new Error("Predict.attach(): instance has no refId \u2014 attach must run AFTER the decoder delivers the instance (e.g. inside onAdd).");return this.attachToGroup(e,n),()=>this.detachByRef(r)}detach(e){let n=jt(e);n!==void 0&&this.detachByRef(n)}detachByRef(e){let n=this.slotByRef.get(e);if(n){for(let r of[...n.keys()]){let s=n.get(r);if(s===void 0)continue;let o=this.boundBySlot.get(s);o!==void 0?(this.freeStash(o),this.boundBySlot.delete(s),this.freeSlots.push(s),n.delete(r)):this.untrackSlot(e,r)}n.size===0&&this.slotByRef.delete(e)}this.simByRef.delete(e)}attachAll(...e){let n=typeof e[0]=="string",r=n?void 0:e[0],s=n?e[0]:e[1],o=n?e[1]:e[2],i=this.makeGroup(s,o),a=new Set,c=f=>{this.attachWithPlan(f,this.planFor(i,f)),a.add(f)},u=f=>{a.delete(f),this.detach(f)},l=n?this.callbacks.onAdd(s,c):this.callbacks.onAdd(r,s,c),d=n?this.callbacks.onRemove(s,u):this.callbacks.onRemove(r,s,u);return()=>{l?.(),d?.();for(let f of a)this.detach(f);a.clear()}}tick(e=performance.now()){this.renderTime=e;let n=0,r=this.fixedStepMs;if(r!==void 0&&r>0){let i=this.lastFrameNow<0?0:e-this.lastFrameNow;this.stepAcc+=i,n=Math.floor(this.stepAcc/r),n>vi.MAX_STEPS_PER_FRAME?(this.stepAcc=0,n=vi.MAX_STEPS_PER_FRAME):this.stepAcc-=n*r}this.lastFrameNow=e;let s=this.driven,o=0;for(let i=0;i<s.length;i++){let a=s[i];a.dead||(a.tick?.(e),a.prune?.(),o!==i&&(s[o]=a),o++)}return o!==s.length&&(s.length=o),n}defineEvent(e){let{confirmOn:n,...r}=e,s=new Si(r,this.clock??null);if(n!==void 0){if(n.mine!==void 0&&typeof this.sessionSource.sessionId!="string")throw new Error(`Predict.defineEvent: confirmOn.mine ("${n.mine}") requires a Predict built from a Room (it compares against room.sessionId); confirm manually instead.`);s._addTeardown(w0(this.callbacks,s,n,()=>this.sessionSource.sessionId))}return this.driven.push(s),s}spawns(e,n={}){let r=new no(n,this.clock??null),s=n.fields,o=n.step,i=s!==void 0&&o!==void 0?this.makeGroup(String(e),{mode:"reckon",fields:s,step:o,smoothMs:n.smoothMs??0,substep:n.substep}):void 0,a=i!==void 0?new Map:void 0,c=this.clock;return r.attach((u,l)=>{let d=this.callbacks.onAdd(e,(h,p)=>{if(u(h,p),i===void 0||a.has(h))return;let y=r.entryFor(h)?.leadMs??0,S=c?()=>{let w=c.lastServerTime(),x=w>0?Math.max(0,c.serverNow()-w):0;return Math.max(0,x+y)}:()=>Math.max(0,y);a.set(h,this.attachToGroup(h,this.planFor(i,h),S))}),f=this.callbacks.onRemove(e,(h,p)=>{a?.get(h)?.(),a?.delete(h),l(h,p)});return()=>{if(d?.(),f?.(),a!==void 0){for(let h of a.values())h();a.clear()}}}),i!==void 0&&r.bindReader((u,l)=>this.value(u,l)),this.driven.push(r),r}canonicalDelay(){return this.profileBuf[pr*Gt+oo]}bindInputRenderDelay(e){e instanceof oi&&e.bindRenderDelay(()=>this.canonicalDelay())}reconciler(e,n){let r=new ro(e,{...n,clock:n.clock??this.clock});return this.adoptFixedStep(r.stepMs),this.bindInputRenderDelay(n.input),this.installBoundOverlay(r),this.driven.push(r),r}sim(e){let n=new so({...e,clock:e.clock??this.clock});return this.adoptFixedStep(n.stepMs),this.bindInputRenderDelay(e.input),this.installBoundOverlay(n),this.driven.push(n),n}adoptFixedStep(e){if(this.fixedStepMs===void 0){this.fixedStepMs=e,this.stepAcc=0,this.lastFrameNow=-1;return}Math.abs(this.fixedStepMs-e)>1e-6&&console.warn(`@colyseus/sdk Predict: a reconciler's fixed step (${e}ms) differs from this Predict's (${this.fixedStepMs}ms). tick() paces one rate for the whole room; use a separate Predict per rate.`)}value(e,n){let r=jt(e),s=r===void 0?void 0:this.slotByRef.get(r)?.get(n);if(s===void 0)return e[n];let o=this.slotBuf[s*Ot+Un]|0;return this.profileComputers[o](s)}valueAt(e,n,r){let s=jt(e),o=s===void 0?void 0:this.slotByRef.get(s)?.get(n);if(o===void 0)return e[n];let i=o*Ot,a=this.slotBuf[i+Un]|0;if(this.profileComputers[a]!==this.computeReckon)return this.profileComputers[a](o);let c=this.simByRef.get(this.slotBuf[i+oc]);if(c!==void 0){let u=this.slotBuf[i+ic]|0,l=u<c.posOf.length?c.posOf[u]:-1;if(l>=0){let d=this.clock?.lastServerTime?.()??NaN,f=Number.isNaN(d)?0:Math.max(0,r-d);return c.advance(c.instance,f,c.valueOut,r),c.valueOut[l]}}return this.slotBuf[i+un]}read(e,n,r){let s=r??{},o=jt(e),i=o===void 0?void 0:this.slotByRef.get(o);for(let a=0;a<n.length;a++){let c=n[a],u=i?.get(c);s[c]=u===void 0?e[c]:this.profileComputers[this.slotBuf[u*Ot+Un]|0](u)}return s}readAt(e,n,r,s){let o=s??{},i=jt(e),a=i===void 0?void 0:this.slotByRef.get(i),c,u=!1;for(let l=0;l<n.length;l++){let d=n[l],f=a?.get(d);if(f===void 0){o[d]=e[d];continue}let h=f*Ot,p=this.slotBuf[h+Un]|0;if(this.profileComputers[p]!==this.computeReckon){o[d]=this.profileComputers[p](f);continue}if(!u&&(u=!0,c=this.simByRef.get(this.slotBuf[h+oc]),c!==void 0)){let y=this.clock?.lastServerTime?.()??NaN,S=Number.isNaN(y)?0:Math.max(0,r-y);c.advance(c.instance,S,c.valueOut,r)}if(c!==void 0){let y=this.slotBuf[h+ic]|0,S=y<c.posOf.length?c.posOf[y]:-1;if(S>=0){o[d]=c.valueOut[S];continue}}o[d]=this.slotBuf[h+un]}return o}computeLerpRaw(e){let n=this.slotBuf,r=e*Ot,s=this.profileBuf,o=(n[r+Un]|0)*Gt,i=this.renderTime,a=n[r+_i]|0;if(a===0)return n[r+un];let c=n[r+xi]|0,u=r+ac,l=(c-a+ht)%ht,d=(l+a-1)%ht,f=u+d*2;if(a===1)return n[f+1];let h=s[o+oo],p=this.clock&&this.clock.lastServerTime()>0?this.clock.serverNow()-h-this.clock.smoothedRtt()/2:i-h,y=u+l*2;if(p<=n[y])return n[y+1];if(p>=n[f])return n[f+1];let S=a-2,w=(l+S)%ht;for(;S>0&&!(n[u+w*2]<=p);)S--,w=w===0?ht-1:w-1;let x=u+w*2,R=w+1>=ht?0:w+1,A=u+R*2,E=n[x],k=n[A]-E;if(k<=0)return n[A+1];let M=(p-E)/k,L=n[x+1],K=n[A+1];return L+(K-L)*M}applySimulation(e,n){let r=this.renderTime;if(e.lastApplyTime!==r){let s=e.out,o=e.smoothed,i=e.offset,a=o.length,c=this.clock?.lastServerTime?.()??NaN;if(e.advance(e.instance,e.forwardMs(),s,e.elapsedMs()),e.lastApplyTime===-1/0||e.smoothMs<=0)for(let d=0;d<a;d++)i[d]=0,o[d]=s[d];else if(Number.isNaN(c)){let d=Math.max(0,Math.min(r-e.lastApplyTime,100)),f=1-Math.exp(-d/e.smoothMs);for(let h=0;h<a;h++)o[h]+=(s[h]-o[h])*f}else{let d=Math.max(0,Math.min(r-e.lastApplyTime,100));if(c!==e.lastBaseT&&!Number.isNaN(e.lastBaseT)){let h=e.snap,p=e.frameVel;for(let y=0;y<a;y++){let S=o[y]+p[y]*d-s[y];i[y]=h>0&&Math.abs(S)>h?0:S}}else if(d>0){let h=e.outPrev,p=e.frameVel;for(let y=0;y<a;y++)p[y]=(s[y]-h[y])/d}let f=Math.exp(-d/e.smoothMs);for(let h=0;h<a;h++)i[h]*=f,o[h]=s[h]+i[h]}let l=e.outPrev;for(let d=0;d<a;d++)l[d]=s[d];e.lastBaseT=c,e.lastApplyTime=r}return e.smoothed[n]}};m(vi,"MAX_STEPS_PER_FRAME",5);ao=vi});var q0={};sf(q0,{DEFAULT_GRACE_TICKS:()=>Up,Predict:()=>ao,PredictedEventChannel:()=>Si,PredictedSpawns:()=>no,Reconciler:()=>ro,SimReconciler:()=>so,classifyDrift:()=>bi});var Jp=pt(()=>{"use strict";$p();Ol();vl();Il();Vp();Cl()});var la="genex-native";var uu="genex_native";var lu="genex_protocol",du="genex_attempt",fu="genex_nonce",af="genex_caps";var Uo="genex_";var cf="genex_r";var uf="entryRef",lf="genex_hash",df="genex_referrer",ff="genex_ref";var pu="__genexNative";var uE=/^[0-9a-f]{32}$/,lE=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function Er(t){return typeof t=="string"&&uE.test(t)}function pf(t){return typeof t=="string"&&lE.test(t)}var Vo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",dE=(()=>{let t=new Array(128).fill(-1);for(let e=0;e<Vo.length;e++)t[Vo.charCodeAt(e)]=e;return t})();function Um(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r>=55296&&r<=56319){let s=n+1<t.length?t.charCodeAt(n+1):0;s>=56320&&s<=57343?(r=65536+(r-55296<<10)+(s-56320),n++):r=65533}else r>=56320&&r<=57343&&(r=65533);r<128?e.push(r):r<2048?e.push(192|r>>6,128|r&63):r<65536?e.push(224|r>>12,128|r>>6&63,128|r&63):e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return e}function fE(t){let e="";for(let n=0;n<t.length;){let r=t[n],s,o;if(r<128)s=r,o=1;else if((r&224)===192)s=r&31,o=2;else if((r&240)===224)s=r&15,o=3;else if((r&248)===240)s=r&7,o=4;else return null;if(n+o>t.length)return null;for(let i=1;i<o;i++){let a=t[n+i];if((a&192)!==128)return null;s=s<<6|a&63}if(o===2&&s<128||o===3&&(s<2048||s>=55296&&s<=57343)||o===4&&(s<65536||s>1114111))return null;if(s>65535){let i=s-65536;e+=String.fromCharCode(55296+(i>>10),56320+(i&1023))}else e+=String.fromCharCode(s);n+=o}return e}function hf(t){return Um(t).length}function mf(t){let e=Um(JSON.stringify(t)),n="";for(let r=0;r<e.length;r+=3){let s=e[r],o=e[r+1],i=e[r+2];if(n+=Vo[s>>2],n+=Vo[(s&3)<<4|(o??0)>>4],o===void 0||(n+=Vo[(o&15)<<2|(i??0)>>6],i===void 0))break;n+=Vo[i&63]}return n}function yf(t){if(t.length%4===1)return;let e=[],n=0,r=0;for(let o=0;o<t.length;o++){let i=t.charCodeAt(o),a=i<128?dE[i]:-1;if(a<0)return;n=n<<6|a,r+=6,r>=8&&(r-=8,e.push(n>>r&255))}if(r>0&&(n&(1<<r)-1)!==0)return;let s=fE(e);if(s!==null)try{return JSON.parse(s)}catch{return}}var Vm=2048,Hm=32;var hE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;function mE(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function hu(t,e){if(Object.keys(t).length!==e.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(t,r))return!1;return!0}var mu=["channel","v","type","slug","attemptId","nonce"];function yE(t){return t.channel===la&&t.v===1&&pf(t.slug)&&Er(t.attemptId)&&Er(t.nonce)}function gf(t){if(!(!mE(t)||!yE(t)))switch(t.type){case"ticket":return!hu(t,[...mu,"ticket","expiresAt"])||typeof t.ticket!="string"||t.ticket.length===0||t.ticket.length>Vm||typeof t.expiresAt!="string"||t.expiresAt.length>Hm||!hE.test(t.expiresAt)?void 0:t;case"guest":case"cancel":return hu(t,mu)?t:void 0;case"foreground":return!hu(t,[...mu,"active"])||typeof t.active!="boolean"?void 0:t;case"network":return!hu(t,[...mu,"online"])||typeof t.online!="boolean"?void 0:t;default:return}}function bE(t,e){if(typeof t!="string"||t.length===0)return{ok:!1,reason:"undecodable"};if(hf(t)>4096)return{ok:!1,reason:"too-large"};let n=yf(t);if(n===void 0)return{ok:!1,reason:"undecodable"};let r=e(n);return r===void 0?{ok:!1,reason:"invalid"}:{ok:!0,message:r}}function wf(t){return bE(t,gf)}function Sf(t){let e=mf(t);if(!(e.length>4096))return e}function yu(t,e){let n=t.charAt(0)==="?"?t.slice(1):t;if(n.length===0)return null;for(let r of n.split("&")){let s=r.indexOf("=");if(s!==-1&&r.slice(0,s)===e)return r.slice(s+1)}return null}function gu(t){return yu(t,uu)==="1"}function _f(t){if(!gu(t))return null;let e=yu(t,du),n=yu(t,fu),r=Number(yu(t,lu));return!Er(e)||!Er(n)||r!==1?null:{attemptId:e,nonce:n,protocol:r}}function Gm(t){return t.indexOf("%")===-1?t:t.replace(/%([0-9A-Fa-f]{2})/g,(e,n)=>{let r=parseInt(n,16);return r<128?String.fromCharCode(r):e})}function Ym(t){let e=t.indexOf("="),n=e===-1?t:t.slice(0,e);return Gm(n.indexOf("+")===-1?n:n.split("+").join(" "))}function bu(t){return Km(t,[cf])}var SE=[uu,lu,du,fu,af];function Rf(t){return Km(t,SE)}function Km(t,e){let n=t.charAt(0)==="?"?t.slice(1):t;if(n.length===0)return"";let r=n.split("&"),s=r.filter(i=>!e.includes(Ym(i)));if(s.length===r.length)return`?${n}`;let o=s.join("&");return o.length===0?"":`?${o}`}var xE=/^[!$-&(-;=?-~]+$/;function wu(t,e){if(typeof t!="string")return"";let n=t.charAt(0)==="?"?t.slice(1):t,r=n.indexOf("#");if(r!==-1&&(n=n.slice(0,r)),n.length===0||!xE.test(n))return"";let o=n.split("&").filter(i=>{if(i.length===0)return!1;let a=Ym(i);return!a.startsWith(Uo)&&!e.includes(a)}).join("&");return o.length>1024?"":o}var _E=/^#[!#-;=?-_a-~]+$/;function Su(t){return typeof t!="string"||t.length<2||t.length>4096||!_E.test(t)||Gm(t).includes(Uo)?"":t}var RE=/^[a-z0-9._-]+$/,EE=/^\[[0-9a-f:.]+\]$/;function kE(t){return RE.test(t)&&/[a-z0-9]/.test(t)||EE.test(t)}function xf(t){let e=t.slice(0,8).toLowerCase(),n=e==="https://"?"https":e.slice(0,7)==="http://"?"http":null;if(n===null)return null;let r=n.length+3,s=t.length;for(let u=r;u<t.length;u++){let l=t.charAt(u);if(l==="/"||l==="?"||l==="#"||l==="\\"){s=u;break}}if(s-r>255)return null;let o=t.slice(r,s).toLowerCase();if(o.length===0||o.indexOf("@")!==-1)return null;let i=o,a="",c=o.lastIndexOf(":");if(c!==-1&&o.charAt(o.length-1)!=="]"&&(i=o.slice(0,c),a=o.slice(c+1)),!kE(i))return null;if(a.length>0){if(!/^[0-9]{1,5}$/.test(a))return null;let u=Number(a);if(u>65535)return null;a=u===(n==="https"?443:80)?"":`:${u}`}return`${n}://${i}${a}`}function $o(t,e){if(typeof t!="string"||t.length===0)return null;let n=xf(t);return n===null||n.length>255||typeof e=="string"&&xf(e)===n?null:n}var Xm=["open","save","fullscreen"];var Jm=50*1024*1024,AE=16;function Zm(t){return typeof t=="string"&&Xm.includes(t)}function Ef(t){if(!Array.isArray(t))return[];let e=[],n=Math.min(t.length,AE);for(let r=0;r<n;r++){let s=t[r];Zm(s)&&!e.includes(s)&&e.push(s)}return e}var FE=null;function ey(t){FE=t}var UE=null;function ty(t){UE=t}var VE=null;function ny(t){VE=t}var ha=1,vf="genex:embed:retry",yy="genex:guest:popover-dismissed",gy="genex:embed:local-auth",by="genex:embed:entry-referrer",HE="none",ry="genex:player",$E="0.35.0",Ne=null,ze="pending",rn=null,ss=!1,ns=null,jo=!1,rs,Wo,wy=0,Ht,Sy,Mf,xy,_y=!1,os=null,Ry=[],Go=!1,Vs=!1,fa=!1,nn=0,Yo=1e4,jE=2e3,WE=10*6e4,qE=6e4,sy=500,GE=3e4,YE=3e4,Ye,Tn,qo,oy=!1,iy,xu=null,ay=new Set;var cy=!1,KE=new Map,Ey=[],ma=[],pa=null,_u=null,Us,kf,Af=!1,Ru=new Map;function et(){return globalThis.window}function Cf(){return globalThis.document}function ya(t,e,n){let r;if(n!==void 0)try{let s=globalThis.AbortSignal;s&&typeof s.timeout=="function"&&(r=s.timeout(n))}catch{}return globalThis.fetch(t,r?{...e,signal:r}:e)}function XE(){try{return et()?.sessionStorage?.getItem(vf)==="1"}catch{return!1}}function JE(){try{et()?.sessionStorage?.setItem(vf,"1")}catch{}}function Of(){try{et()?.sessionStorage?.removeItem(vf)}catch{}}function ZE(){try{return et()?.sessionStorage?.getItem(gy)==="1"}catch{return!1}}function QE(){try{et()?.sessionStorage?.setItem(gy,"1")}catch{}}function ek(){try{let t=et()?.sessionStorage?.getItem(by);return t==null?void 0:$o(t)}catch{return}}function tk(t){try{et()?.sessionStorage?.setItem(by,t??HE)}catch{}}function nk(){try{return et()?.sessionStorage?.getItem(yy)==="1"}catch{return!1}}function rk(){try{et()?.sessionStorage?.setItem(yy,"1")}catch{}}function sk(){try{let t=et()?.localStorage;if(!t)return"no-storage";let e=t.getItem(ry);return e||(e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,t.setItem(ry,e)),e}catch{return"no-storage"}}function ku(t){let e=et();if(!e||Go)return;if(Go=!0,qo!==void 0&&(clearTimeout(qo),qo=void 0),Ne={slug:t.slug,apiUrl:t.apiUrl.replace(/\/$/,""),dashboardOrigins:[...t.dashboardOrigins]},ze="pending",Cy(e),ty({apiUrl:Ne.apiUrl,dashboardOrigins:Ne.dashboardOrigins,getToken:()=>Ht,getParentOrigin:()=>os,isEmbedded:$t,isNative:bn,isLocalTest:()=>ss}),ny({apiUrl:Ne.apiUrl,dashboardOrigins:Ne.dashboardOrigins,getToken:()=>Ht,getParentOrigin:()=>os,isEmbedded:$t,isNative:bn,isLocalTest:()=>ss}),Ff(e)){Ck(e);return}Tu("connecting");let n=Oy(e);if(n){wk(e,n);return}$t()?gk(e):_k(e)}function $t(){let t=et();if(!t)return!1;try{return t.self!==t.top}catch{return!0}}function ok(){let t=et();return t?$t()?"page":bn()||Df(t)?"app":Go?ss?"local":"standalone":Ff(t,!1)?"local":"standalone":"standalone"}function Au(){return _y?{embedToken:Ak}:Ht?{embedToken:Ht}:void 0}function ky(){return Sy??[]}function Ay(){return Uy(Mf)??[]}function Py(){return vk(xy)}function If(){return(ze==="authenticated"||ze==="guest")&&rn?Promise.resolve({user:rn,guest:ze==="guest"}):ze==="blocked"?Promise.reject(new Error("genex embed auth: blocked")):(ik("waitForPlayer"),new Promise((t,e)=>{ma.push({resolve:t,reject:e})}))}function ik(t){if(!Go){if(!oy){oy=!0;try{console.error(`[genex] ${t}() called before initEmbed() \u2014 identity can never resolve and the game will sit black. Call initEmbed({ slug, apiUrl, dashboardOrigins }) first (genex-threejs-embed-auth), and draw a frame before you await identity.`)}catch{}}qo===void 0&&(qo=setTimeout(()=>{qo=void 0,Go||kr("no-identity")},Yo))}}var ak=32*1024;async function Ty(){if(!Ne)throw new Error("genex embed: call initEmbed() first");if(ze==="pending"&&await If(),ze==="blocked")throw new Error("genex embed auth: blocked")}function vy(t,e={}){let n={Authorization:`Bearer ${Ht}`};return e.body!==void 0&&(n["Content-Type"]="application/json"),e.ifVersion!==void 0&&(n["If-Match"]=String(e.ifVersion)),ya(`${Ne.apiUrl}/api/projects/${encodeURIComponent(Ne.slug)}${t}`,{method:e.method??"GET",headers:n,body:e.body,keepalive:e.body!==void 0&&e.body.length<=ak?!0:void 0})}async function ck(t){return t.status!==403?!1:(await t.json().catch(()=>null))?.error==="staging_no_save"}async function uk(t){return t.status===409?{saved:!1,conflict:!0,version:(await t.json().catch(()=>({}))).version}:t.ok?{saved:!0,version:(await t.json()).version}:await ck(t)?{saved:!1,staging:!0}:(sn("error",{error:new Error(`genex state save failed (${t.status})`)}),{saved:!1})}async function lk(t,e){return await Ty(),ze==="guest"?(kf=t,Af=!0,{saved:!1,guest:!0,queued:!0}):uk(await vy("/state/me",{method:"PUT",body:JSON.stringify(t),ifVersion:e?.ifVersion}))}async function dk(t,e){let n=e?.board??"main",r=e?.mode??"max";if(await Ty(),ze==="guest"){let i=Ru.get(n);return(!i||(r==="min"?t<i.score:t>i.score))&&Ru.set(n,{score:t,mode:r}),{submitted:!1,guest:!0,queued:!0}}let s=await vy("/scores",{method:"POST",body:JSON.stringify({score:t,board:n,mode:r})});if(!s.ok)return sn("error",{error:new Error(`genex score submit failed (${s.status})`)}),{submitted:!1};let o=await s.json();return{submitted:!0,best:o.best,improved:o.improved}}async function fk(){try{if(Af){let e=kf;kf=void 0,Af=!1,await lk(e)}let t=[...Ru.entries()];Ru.clear();for(let[e,{score:n,mode:r}]of t)await dk(n,{board:e,mode:r})}catch(t){sn("error",{error:t})}}function sn(t,e){let n=KE.get(t);if(n)for(let r of[...n])try{r(e)}catch{}}var pk=["embed"];function My(t,e){let n={ticket:null,guest:!1,entryHash:"",entryReferrer:null};if(!t||t.length<2)return n;try{let r=new URLSearchParams(t.slice(1));return{ticket:r.get("genex_ticket"),guest:r.get("genex_guest")==="1",entryHash:Su(r.get(lf)),entryReferrer:$o(r.get(df),e)}}catch{return n}}function hk(t,e){try{return new URLSearchParams(t).get(e)}catch{return null}}function Cy(t){if(xu)return xu;let e="",n="",r=null;try{e=t.location.search??"",n=Eu??t.location.hash??"",r=t.location.origin??null}catch{}let s=$t(),o=My(n,r),i=!s&&(!!o.ticket||o.guest),a=wu(e,pk);return xu={search:a?`?${a}`:"",hash:i?o.entryHash:n.includes(Uo)?"":n,referrer:mk(e,s,i,o.entryReferrer,r)},xu}function mk(t,e,n,r,s){let o=ek();if(o!==void 0)return o;let i;return e?i=$o(hk(t,ff),s):n?i=r:i=$o(Cf()?.referrer,s),tk(i),i}function yk(){if(!(cy||ay.size===0)){cy=!0;for(let t of[...ay])try{t()}catch{}}}function gk(t){iy=e=>{bk(e)},t.addEventListener("message",iy),t.parent.postMessage({type:"genex:embed:ready",v:ha},"*"),Ye=setTimeout(()=>{Ko()},Yo)}function uy(){return(ze==="pending"||ze==="guest")&&!Vs}async function bk(t){if(!Ne)return;let e=t.data;if(!e||e.v!==ha)return;let n=e.type==="genex:embed:ticket",r=e.type==="genex:embed:guest";if(!(!n&&!r)&&!(n&&(!uy()||typeof e.ticket!="string"||!e.ticket))&&!(r&&(ze!=="pending"||Vs||fa))){if(!Ne.dashboardOrigins.includes(t.origin)){let s=await Pf();if(n&&!uy()||r&&(ze!=="pending"||Vs||fa)||!s.includes(t.origin))return}if(Ye!==void 0&&clearTimeout(Ye),os=t.origin,Ry=Ef(e.caps),r){await Ko();return}await Lf(e.ticket)}}function Df(t){let e=t.ReactNativeWebView;return!e||typeof e!="object"?null:typeof e.postMessage=="function"?e:null}function Oy(t){if($t())return null;let e;try{e=t.location.search??""}catch{return null}return!gu(e)||!Df(t)?null:_f(e)}function bn(){return ns!==null}function Hs(t){let e=et();if(!e||!Ne||!ns)return;let n=Df(e);if(!n)return;let r=Sf({channel:la,v:1,slug:Ne.slug,attemptId:ns.attemptId,nonce:ns.nonce,...t});if(r)try{n.postMessage(r)}catch{}}function Iy(t){bn()&&Hs({type:"error",code:t})}function wk(t,e){ns=e,wy=Date.now(),t[pu]=r=>{Sk(r)},Hs({type:"ready",sdkVersion:$E,capabilities:["native-ticket","native-guest","heartbeat"]}),Ye=setTimeout(()=>{Ko()},Yo)}async function Sk(t){if(!Ne||!ns)return;let e=wf(t);if(!e.ok)return;let n=e.message;if(!(n.slug!==Ne.slug||n.attemptId!==ns.attemptId||n.nonce!==ns.nonce))switch(n.type){case"ticket":Ye!==void 0&&clearTimeout(Ye),await Lf(n.ticket);return;case"guest":Ye!==void 0&&clearTimeout(Ye),await Ko();return;case"cancel":Dy(),yk();return;case"foreground":case"network":return}}function Dy(){Ye!==void 0&&clearTimeout(Ye),Ye=void 0,Tn!==void 0&&clearTimeout(Tn),Tn=void 0,rs!==void 0&&clearTimeout(rs),rs=void 0,Wo!==void 0&&clearInterval(Wo),Wo=void 0}function Ny(){!bn()||Wo!==void 0||(Wo=setInterval(()=>{Hs({type:"heartbeat",uptimeMs:Math.max(0,Date.now()-wy)})},YE),Wo.unref?.())}function xk(){!bn()||jo||(jo=!0,Hs({type:"reauth-required"}),rs=setTimeout(()=>{rs=void 0,jo&&(jo=!1,sn("error",{error:new Error("embed session expired")}),kr("session-expired"))},GE))}function Nf(){jo=!1,rs!==void 0&&clearTimeout(rs),rs=void 0}function Bf(t,e){let n=et();if(!(!n||!$t()))try{n.parent.postMessage(t,e)}catch{}}async function _k(t){let e=By(t);if(e.ticket){ly(),await Lf(e.ticket);return}if(e.guest){ly(),await Ko();return}Tu("redirecting"),await Pu(t,{guestOk:!0})}function ly(){Ye!==void 0&&clearTimeout(Ye),Ye=setTimeout(()=>{Ye=void 0,ze==="pending"&&kr("no-identity")},Yo+jE)}var Eu=null;function Rk(t){return t.location.pathname+bu(t.location.search)}function By(t){let e=Eu??t.location.hash;Eu=null;let{ticket:n,guest:r,entryHash:s}=My(e);if(n||r)try{t.history.replaceState(t.history.state??null,"",Rk(t)+s)}catch{}return{ticket:n,guest:r}}async function Pu(t,e){if(!Ne||ss||bn())return;let n=e?.guestOk?Ne.dashboardOrigins[0]??(await Pf())[0]:(await Pf())[0]??Ne.dashboardOrigins[0];if(!n){kr();return}let r=t.location.origin+t.location.pathname,s=Rf(bu(t.location.search));s.length-1<=1024&&r.length+s.length<=2048&&s.indexOf("#")===-1&&(r+=s);let o=e?.guestOk?"&guest=ok":"",i=`${n}/play/authorize?returnTo=${encodeURIComponent(r)}&slug=${encodeURIComponent(Ne.slug)}${o}`,a=Cy(t).referrer;a&&(i+=`&${uf}=${encodeURIComponent(a)}`),i+=Su(t.location.hash),t.location.replace(i)}async function Pf(){if(!Ne)return[];try{let t=await ya(`${Ne.apiUrl}/api/embed/dashboard-origins`);if(!t.ok)return Ne.dashboardOrigins;let e=await t.json();if(Array.isArray(e.origins)&&e.origins.every(n=>typeof n=="string"))return e.origins}catch{}return Ne.dashboardOrigins}async function Lf(t){if(!Ne||ss||Vs||ze!=="pending"&&ze!=="guest"&&!(jo&&ze==="authenticated"))return;let n=ze==="guest",r=++nn;Vs=!0;try{let s=await ya(`${Ne.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ticket:t})},Yo);if(r!==nn)return;if(!s.ok){sn("error",{error:new Error(`ticket redemption failed (${s.status})`)}),n||await dy();return}let o=await s.json();if(r!==nn)return;Ht=o.embedToken,rn=o.user,zy(o.colyseus),ze="authenticated",Ye!==void 0&&clearTimeout(Ye),Ye=void 0,Of(),vu(),Uf(),zf(),$t()&&os&&Bf({type:"genex:embed:authenticated",v:ha},os),bn()&&(Nf(),Hs({type:"authenticated",guest:!1}),Ny()),n&&await fk();let i={user:rn};for(let a of Ey.splice(0))a.resolve(i);for(let a of ma.splice(0))a.resolve({user:rn,guest:!1});sn("authenticated",i)}catch(s){if(r!==nn)return;sn("error",{error:s}),n||await dy()}finally{Vs=!1}}async function Ko(){if(!Ne||ss||fa||Vs||ze!=="pending"&&ze!=="guest")return;let t=++nn;fa=!0;try{let e=await ya(`${Ne.apiUrl}/api/embed/guest-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:Ne.slug,playerId:sk()})},Yo);if(t!==nn)return;if(!e.ok){sn("error",{error:new Error(`guest session failed (${e.status})`)}),Iy("guest-failed"),kr(e.status===404?"not-available":"no-identity");return}let n=await e.json();if(t!==nn)return;Ht=n.embedToken,rn=n.user,zy(n.colyseus),Ek()}catch(e){if(t!==nn)return;sn("error",{error:e}),kr()}finally{fa=!1}}function Ek(){let t=ze!=="guest";if(ze="guest",Ye!==void 0&&clearTimeout(Ye),vu(),zf(),$t()?Bf({type:"genex:embed:authenticated",v:ha,guest:!0},os??"*"):bn()?(Hs({type:"authenticated",guest:!0}),Ny()):t&&!nk()&&Fk(),rn){let e={user:rn};for(let n of ma.splice(0))n.resolve({user:rn,guest:!0});sn("guest",e)}}function Ly(t){try{let e=new URL(t.location.origin);return e.protocol==="http:"&&Fy.has(e.hostname)}catch{return!1}}var Fy=new Set(["localhost","127.0.0.1","[::1]"]),kk="genex_authority_url",Ak="local:test",Pk=64;function Tk(t){if(!t||t.length>Pk)return null;let e;try{e=new URL(t)}catch{return null}let n=!e.username&&!e.password&&e.pathname==="/"&&!e.search&&!e.hash;return e.protocol!=="ws:"||!Fy.has(e.hostname)||!n?null:`ws://${e.host}`}function zy(t){Sy=t?.urls,Mf=t?.authorityUrls,xy=t?.authorityRegions}function Uy(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string"&&e.length>0)}function vk(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(n===null||typeof n!="object")continue;let{region:r,urls:s}=n,o=Uy(s)??[];typeof r=="string"&&r.length>0&&o.length>0&&e.push({region:r,urls:o})}return e}function Ff(t,e=!0){if($t()||Oy(t)||!Ly(t))return!1;let n=null;try{n=new URLSearchParams(t.location.search)}catch{}return n?.get("genex_local_test")==="1"?!0:n?.get("genex_auth")==="1"?(e&&QE(),!1):ZE()?!1:!Mk(t)}function Mk(t){let e=Eu??t.location.hash;return!!e&&e.includes("genex_")}function Ck(t){ss=!0,By(t),Ok(t);let e={id:"local:test",name:"Local Tester"};rn=e,ze="guest",vu();try{console.info("[genex] local test mode \u2014 local visuals and controls only. Auth, saves, leaderboards, and multiplayer are NOT validated here; no Genex credential exists.")}catch{}for(let n of ma.splice(0))n.resolve({user:e,guest:!0});sn("guest",{user:e})}function Ok(t){if(!Ly(t))return;let e=null;try{e=new URLSearchParams(t.location.search).get(kk)}catch{return}let n=Tk(e);n&&(Mf=[n],_y=!0)}async function dy(){let t=et();if(Ye!==void 0&&clearTimeout(Ye),Ye=void 0,bn()){Nf(),Iy("ticket-rejected"),kr();return}if(t&&!$t()&&!XE()){JE(),Tu("redirecting"),await Pu(t,{guestOk:!0});return}kr()}function zf(){Tn!==void 0&&clearTimeout(Tn),Tn=setTimeout(()=>{Vy()},WE)}async function Vy(){if(!Ne||ze!=="authenticated"&&ze!=="guest"||!Ht)return;let t=nn,e=Ht,n;try{let r=await ya(`${Ne.apiUrl}/api/embed/session/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`},keepalive:!0});if(n=r.status,t!==nn||Ht!==e)return;if(r.ok){let s=await r.json();if(t!==nn||Ht!==e)return;Ht=s.embedToken,zf();return}}catch{n=void 0}if(!(t!==nn||Ht!==e)){if(n===401){if(ze==="guest"){Ko();return}if(bn()){xk();return}sn("error",{error:new Error("embed session expired")}),kr("session-expired");return}Tn!==void 0&&clearTimeout(Tn),Tn=setTimeout(()=>{Vy()},qE)}}function kr(t="no-identity"){if(ze==="blocked")return;nn++,ze="blocked",rn=null,Ht=void 0,Ye!==void 0&&clearTimeout(Ye),Tn!==void 0&&clearTimeout(Tn),Uf(),bn()?(Dy(),Nf(),vu(),Hs({type:"blocked",reason:t})):Tu($t()?"blocked-embedded":"blocked-standalone"),$t()&&Bf({type:"genex:embed:blocked",v:ha},os??"*");let e=new Error("genex embed auth: blocked");for(let n of Ey.splice(0))n.reject(e);for(let n of ma.splice(0))n.reject(e);sn("blocked")}var Ik={connecting:{title:"GENEX",wordmark:!0},redirecting:{title:"GENEX",wordmark:!0},"blocked-standalone":{title:"Sign in to play",button:"Sign in",instant:!0},"blocked-embedded":{title:"Sign in on the Genex dashboard to continue",instant:!0}},Dk="https://cdn.genex.technology/fonts/GeistMono-variable.woff2",Hy="'Geist Mono',ui-monospace,SFMono-Regular,Menlo,monospace",fy=!1,py="!<>-_/[]{}=+*^?#$%&@",$y=50,hy=10,my=[{name:"churn",ticks:5},{name:"settle",ticks:10},{name:"hold",ticks:12},{name:"dissolve",ticks:8}];function Tf(t){let e="";for(let n=0;n<t;n++)e+=py[Math.floor(Math.random()*py.length)];return e}function jy(){try{let t=et();return!t||typeof t.matchMedia!="function"?!0:t.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!0}}function Nk(t,e){if(jy())return t.textContent=e,()=>{};let n=0;t.textContent=Tf(e.length);let r=setInterval(()=>{if(n++,n>=hy){t.textContent=e,clearInterval(r);return}let s=Math.floor(n/hy*e.length);t.textContent=e.slice(0,s)+Tf(e.length-s)},$y);return()=>clearInterval(r)}function Bk(t,e){if(jy())return t.textContent=e,()=>{};let n=0,r=0,s=()=>{let i=my[n],a;i.name==="churn"?a=0:i.name==="settle"?a=Math.floor(r/i.ticks*e.length):i.name==="hold"?a=e.length:a=e.length-Math.floor(r/i.ticks*e.length),t.textContent=e.slice(0,a)+Tf(e.length-a),r++,r>=i.ticks&&(r=0,n=(n+1)%my.length)};s();let o=setInterval(s,$y);return()=>clearInterval(o)}function Wy(t){if(!fy){fy=!0;try{let e=et()?.FontFace,n=t.fonts;if(!e||!n?.add)return;new e("Geist Mono",`url(${Dk}) format('woff2')`,{weight:"100 900",display:"swap"}).load().then(s=>n.add(s)).catch(()=>{})}catch{}}}function Tu(t){let e=Cf();if(e?.createElement)try{pa||(pa=Lk(e)),pa.setContent(t)}catch{}}function vu(t=!1){try{let e=pa;if(pa=null,!e)return;e.stopText();let n=e.root;if(t||!n.style){n.remove?.();return}n.style.pointerEvents="none",n.style.transition="opacity 180ms ease",n.style.opacity="0",setTimeout(()=>{try{n.remove?.()}catch{}},220)}catch{}}function Lk(t){Wy(t);let e=t.createElement("div");e.setAttribute("data-genex-embed-overlay",""),e.style.cssText=`position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:14px;background:#000;color:#fff;font-family:${Hy};text-align:center;pointer-events:auto;user-select:none`;let n=t.createElement("div");n.style.cssText="font-size:13px;font-weight:400;line-height:1.3;padding:0 24px;opacity:0;min-height:1.3em;font-variant-ligatures:none",e.appendChild(n);let r=t.createElement("button");r.style.cssText="font-family:inherit;font-size:13px;font-weight:500;line-height:1.3;padding:8px 22px;border-radius:9px;border:none;cursor:pointer;background:#4b60bf;color:#fff;display:none",r.addEventListener("mouseenter",()=>{r.style.background="#3f51a8"}),r.addEventListener("mouseleave",()=>{r.style.background="#4b60bf"}),r.addEventListener("click",()=>{let c=et();c&&(r.disabled=!0,Of(),Pu(c))}),e.appendChild(r);let s=()=>{t.body&&!e.isConnected&&t.body.appendChild(e)};t.body?s():t.addEventListener?.("DOMContentLoaded",s);let o,i,a=()=>{o!==void 0&&(clearTimeout(o),o=void 0),i&&(i(),i=void 0)};return{root:e,stopText:a,setContent(c){let u=Ik[c];a(),n.textContent=u.title,n.style.letterSpacing=u.wordmark?"0.22em":"",n.style.marginRight=u.wordmark?"-0.22em":"";let l=()=>{n.style.opacity="1",i=u.wordmark?Bk(n,u.title):Nk(n,u.title)};u.instant||sy<=0?l():(n.style.opacity="0",o=setTimeout(()=>{o=void 0,l()},sy)),r.style.display=u.button?"inline-block":"none",u.button&&(r.textContent=u.button),s()}}}function Fk(){let t=Cf();if(!(!t?.createElement||_u))try{_u=zk(t)}catch{}}function Uf(){Us!==void 0&&(clearTimeout(Us),Us=void 0);try{_u?.root?.remove?.()}catch{}_u=null}function zk(t){Wy(t);let e=!1;try{let c=et(),u=c?.navigator;if(c&&u){let l=c.matchMedia?.("(pointer: coarse)").matches??!1,d=(u.maxTouchPoints??0)>1,f=u.userAgentData?u.userAgentData.mobile:/Mobi|Android/i.test(u.userAgent??"");e=d&&l||f}}catch{}let n=t.createElement("div");n.setAttribute("data-genex-guest-popover",""),n.style.cssText="position:fixed;top:calc(12px + env(safe-area-inset-top));right:calc(12px + env(safe-area-inset-right));z-index:2147483646;display:flex;justify-content:flex-end;pointer-events:none";let r=t.createElement("div");r.style.cssText=`display:flex;align-items:center;border-radius:12px;background:rgba(0,0,0,0.85);color:#fff;font-family:${Hy};box-shadow:0 4px 24px rgba(0,0,0,0.4);pointer-events:auto;user-select:none;`+(e?"gap:8px;padding:8px 8px 8px 12px;font-size:12px;max-width:calc(100vw - 88px)":"gap:12px;padding:10px 12px 10px 16px;font-size:13px"),n.appendChild(r);let s=t.createElement("span");s.textContent=!e&&rn?.name?`Playing as ${rn.name} \u2014 sign in to save progress`:"Sign in to save progress",e&&(s.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap"),r.appendChild(s);let o=t.createElement("button");o.textContent="Sign in",o.style.cssText="font-family:inherit;font-weight:500;border-radius:9px;border:none;cursor:pointer;background:#4b60bf;color:#fff;"+(e?"font-size:12px;padding:5px 12px":"font-size:13px;padding:6px 16px"),o.addEventListener("mouseenter",()=>{o.style.background="#3f51a8"}),o.addEventListener("mouseleave",()=>{o.style.background="#4b60bf"}),o.addEventListener("click",()=>{let c=et();c&&(o.disabled=!0,Of(),Pu(c))}),r.appendChild(o);let i=t.createElement("button");if(i.textContent="\xD7",i.setAttribute("aria-label","Dismiss"),i.style.cssText="font-size:16px;line-height:1;padding:6px 8px;border:none;cursor:pointer;background:transparent;color:rgba(255,255,255,0.6)",i.addEventListener("click",()=>{rk(),Uf()}),r.appendChild(i),e){let c=t.createElement("button");c.setAttribute("aria-label","Sign in to save progress"),c.style.cssText="display:none;width:44px;height:44px;border-radius:50%;border:none;cursor:pointer;background:rgba(0,0,0,0.55);color:#fff;align-items:center;justify-content:center;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);pointer-events:auto",c.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>',n.appendChild(c);let u=l=>{r.style.display=l?"none":"flex",c.style.display=l?"flex":"none"};Us=setTimeout(()=>u(!0),5e3),r.addEventListener("pointerdown",()=>{Us!==void 0&&clearTimeout(Us),Us=void 0}),c.addEventListener("click",()=>u(!1))}let a=()=>{t.body&&!n.isConnected&&t.body.appendChild(n)};return t.body?a():t.addEventListener?.("DOMContentLoaded",a),{root:n}}ey({getShell:ok,isLocalTest:()=>{let t=et();return!t||$t()?!1:Go?ss:Ff(t,!1)},getConfig:()=>Ne,getParentOrigin:()=>os,getShellCaps:()=>Ry});var nh={};sf(nh,{chatSend:()=>hv,claim:()=>mv,claimAsHost:()=>yv,connect:()=>rv,destroy:()=>bv,dispose:()=>sv,drainEventsJson:()=>Tv,leave:()=>cw,listen:()=>dv,objectsJson:()=>Av,open:()=>nv,playersJson:()=>kv,release:()=>gv,reportEliminated:()=>wv,reportFinish:()=>xv,reportScore:()=>Sv,send:()=>lv,sendInput:()=>fv,serverNow:()=>_v,sessionJson:()=>Ev,setIdentity:()=>ZT,setMe:()=>ov,setObject:()=>cv,setRoomOpen:()=>pv,setShared:()=>av,sharedJson:()=>Pv,snapMe:()=>iv,snapObject:()=>uv,timeUntil:()=>Rv,version:()=>JT});var ga={ready(t){let e=globalThis.__GENEX__;return t&&e&&typeof e.apiUrl=="string"&&Array.isArray(e.dashboardOrigins)&&ku({slug:t,apiUrl:e.apiUrl,dashboardOrigins:e.dashboardOrigins.filter(n=>typeof n=="string")}),If()},auth:()=>Au(),urls:()=>ky()},Uk=4096;function me(t,e){t.q.length>=Uk&&(t.overflowed?t.q.splice(1,1):(t.overflowed=!0,t.q.splice(0,2,{type:"warning",message:"genex bridge: event queue full; drain it every frame (oldest events dropped)"}))),t.q.push(e)}var Xo=t=>({type:"warning",message:`genex bridge: ${t}`});function Vk(t){try{return JSON.stringify(t)}catch(e){let n=typeof t.kind=="string"?t.kind:t.type;return JSON.stringify(Xo(`event ${JSON.stringify(n)} dropped: JSON cannot carry it (${Qn(e)})`))}}function Mu(t){return t.overflowed=!1,`[${t.q.splice(0).map(Vk).join(",")}]`}var vn=t=>!!t&&typeof t=="object"&&!Array.isArray(t),Jo=t=>{let e=vn(t)||t instanceof Error?t.code:void 0;return typeof e=="number"&&Number.isFinite(e)?e:0},Qn=t=>t instanceof Error?t.message:typeof t=="string"?t:"join failed";function ba(t,e){if(typeof t!="string")throw new TypeError(`genex bridge: ${e} must be a JSON string`);return JSON.parse(t)}function er(t,e){let n=ba(t,e);if(!vn(n))throw new TypeError(`genex bridge: ${e} must be a JSON object`);return n}ArrayBuffer.isView||(ArrayBuffer.isView=t=>t!==null&&typeof t=="object"&&t.buffer instanceof ArrayBuffer);typeof globalThis>"u"&&typeof window<"u"&&(window.globalThis=window);typeof FormData>"u"&&(globalThis.FormData=class{});Ar();var tr=class extends Error{constructor(n,r,s){super(r);m(this,"code");m(this,"headers");m(this,"status");m(this,"response");m(this,"data");this.name="ServerError",this.code=n,s&&(this.headers=s.headers,this.status=s.status,this.response=s.response,this.data=s.data)}};var wa=class t extends Error{constructor(n,r){super(n);m(this,"code");this.code=r,this.name="MatchMakeError",Object.setPrototypeOf(this,t.prototype)}};Ar();At();At();At();At();At();At();At();At();var bb=256,dp=5,Js=class Js{constructor(e,n={}){m(this,"instance");m(this,"mode");m(this,"historySize");m(this,"_desc");m(this,"_numFields");m(this,"_slots");m(this,"_slotLens");m(this,"_slotHead",0);m(this,"_slotCount",0);m(this,"_outBuffer");m(this,"_seq",0);m(this,"_encoder");this.instance=e,this.mode=n.mode??"reliable",this.historySize=this.mode==="unreliable"?Math.max(1,n.historySize??3):1,this._desc=rp(e);let r=this._desc.metadata?.[kt];if(r===void 0)throw new Error(`InputEncoder: '${e.constructor.name}' has no fields`);this._numFields=r;for(let s=0;s<=r;s++)if(this._desc.names[s]!==void 0&&this._desc.encoders[s]===void 0)throw new Error(`InputEncoder: non-primitive field '${this._desc.names[s]}' on '${e.constructor.name}' is not supported. Use Encoder for state containing refs/collections.`);if(this.mode==="unreliable"){this._slots=new Array(this.historySize),this._slotLens=new Array(this.historySize).fill(0);for(let s=0;s<this.historySize;s++)this._slots[s]=new Uint8Array(bb);this._outBuffer=new Uint8Array((bb+dp)*this.historySize)}this._encoder=new Ta(e)}get seq(){return this._seq}encode(){let e=this._produceDelta();return this.mode==="reliable"?e:this._pushAndEmitRing(e)}reset(){this._slotHead=0,this._slotCount=0,this._encoder.discardChanges();let e=this.instance[I],n=this.instance[vt];for(let r=0;r<=this._numFields;r++)n[r]===void 0||n[r]===null||e.markDirty(r)}copyInto(e){let n=this.instance[vt],r=e[vt];for(let s=0;s<=this._numFields;s++)r[s]=n[s]}_produceDelta(){let e=this._encoder.encode();return this._encoder.discardChanges(),e}_pushAndEmitRing(e){this._seq++;let n=this._slots[this._slotHead];return e.length>n.byteLength&&(n=this._slots[this._slotHead]=Js._grow(n,e.length,"unreliable ring slot")),n.set(e),this._slotLens[this._slotHead]=e.length,this._slotHead=(this._slotHead+1)%this.historySize,this._slotCount<this.historySize&&this._slotCount++,this._emitRing()}_emitRing(){let e=this._seq-this._slotCount+1,n=dp;for(let i=0;i<this._slotCount;i++)n+=this._slotLens[i]+dp;let r=this._outBuffer;n>r.byteLength&&(r=this._outBuffer=Js._grow(r,n,"unreliable output packet"));let s={offset:0};Se.number(r,e,s);let o=(this._slotHead-this._slotCount+this.historySize)%this.historySize;for(let i=0;i<this._slotCount;i++){let a=(o+i)%this.historySize,c=this._slotLens[a];Se.number(r,c,s),r.set(this._slots[a].subarray(0,c),s.offset),s.offset+=c}return r.subarray(0,s.offset)}static _grow(e,n,r){let s=Math.max(n,e.byteLength*2);return Js._warned||(Js._warned=!0,console.warn(`@colyseus/schema/input: InputEncoder buffer overflow in ${r}. Growing to ${s} bytes.`)),new Uint8Array(s)}};m(Js,"_warned",!1);var sl=Js;Ar();pp();ul();var Zs,zn,ai,Fa,za,Ua,Va,Ha,$a,ci,ja,ll,_b,ui=class{constructor(e){Ve(this,ll);Ve(this,Zs);Ve(this,zn);Ve(this,ai);Ve(this,Fa);Ve(this,za,!1);Ve(this,Ua);Ve(this,Va,!1);Ve(this,Ha,!1);Ve(this,$a);Ve(this,ci);Ve(this,ja);He(this,Zs,e)}get patchRate(){return le(this,ci)}applyReflection(e,n,r){let s=Fn.decode(e.subarray(0,r),n);Fn.makeEncodable(s.state.constructor),He(this,Ua,s.state.constructor),le(this,Zs).clock===ii&&(le(this,Zs).clock=new cl)}applyOptions(e,n){let r=e[n.offset++];He(this,Va,(r&$s.RENDER_TIME)!==0),He(this,Ha,(r&$s.RECKON_TIME)!==0),r&$s.FIXED_TIMESTEP&&He(this,$a,Ae.number(e,n)),r&$s.PATCH_RATE&&He(this,ci,Ae.number(e,n)),r&$s.SUB_STEPS&&He(this,ja,Ae.number(e,n))}ackInput(e){return le(this,zn)?le(this,zn).ackInput(e):-1}reset(){le(this,zn)?.reset()}handle(e){if(le(this,zn))return e!==void 0&&zs(this,ll,_b).call(this,e),le(this,zn);let n=e?.type??le(this,Ua);if(!n)throw new Error("room.input(): no input schema available. The server room must call `defineInput(YourInput)`, or you can pass `{ type: YourInput }` explicitly.");let r=new n,s=new sl(r,e);return He(this,zn,new oi(le(this,Zs),r,s,{stampRender:le(this,Va),stampReckon:le(this,Ha),renderDelay:e?.renderDelay,allowRewind:e?.allowRewind,tickRate:le(this,$a),patchRate:le(this,ci),subSteps:le(this,ja)})),He(this,ai,e),He(this,Fa,s),le(this,zn)}};Zs=new WeakMap,zn=new WeakMap,ai=new WeakMap,Fa=new WeakMap,za=new WeakMap,Ua=new WeakMap,Va=new WeakMap,Ha=new WeakMap,$a=new WeakMap,ci=new WeakMap,ja=new WeakMap,ll=new WeakSet,_b=function(e){if(le(this,za))return;let n=le(this,zn),r=[];e.type!==void 0&&e.type!==n.data?.constructor&&r.push("type"),e.mode!==void 0&&e.mode!==n.mode&&r.push("mode"),e.historySize!==void 0&&n.mode==="unreliable"&&e.historySize!==le(this,Fa).historySize&&r.push("historySize"),e.renderDelay!==void 0&&e.renderDelay!==le(this,ai)?.renderDelay&&r.push("renderDelay"),e.allowRewind!==void 0!=(le(this,ai)?.allowRewind!==void 0)&&r.push("allowRewind"),r.length!==0&&(He(this,za,!0),console.warn(`@colyseus/sdk: room.input() options ignored \u2014 the input handle was already created by an earlier call (first call wins). Differing: ${r.join(", ")}.`))};var mp;try{mp=new TextDecoder}catch{}var Q,Sn,O=0;var Ib=[],yp=Ib,gp=0,Be={},Me,ps,wn=0,ur=0,xt,Ir,qt=[],Te,Rb={useRecords:!1,mapsAsObjects:!0},Wa=class{},wp=new Wa;wp.name="MessagePack 0xC1";var hs=!1,Eb=2;var ms=class t{constructor(e){e&&(e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.sequential&&e.trusted!==!1&&(e.trusted=!0,!e.structures&&e.useRecords!=!1&&(e.structures=[],e.maxSharedStructures||(e.maxSharedStructures=0))),e.structures?e.structures.sharedLength=e.structures.length:e.getStructures&&((e.structures=[]).uninitialized=!0,e.structures.sharedLength=0),e.int64AsNumber&&(e.int64AsType="number")),Object.assign(this,e)}unpack(e,n){if(Q)return Fb(()=>(fl(),this?this.unpack(e,n):t.prototype.unpack.call(Rb,e,n)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof n=="object"?(Sn=n.end||e.length,O=n.start||0):(O=0,Sn=n>-1?n:e.length),gp=0,ur=0,ps=null,yp=Ib,xt=null,Q=e;try{Te=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw Q=null,e instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof t){if(Be=this,this.structures)return Me=this.structures,dl(n);(!Me||Me.length>0)&&(Me=[])}else Be=Rb,(!Me||Me.length>0)&&(Me=[]);return dl(n)}unpackMultiple(e,n){let r,s=0;try{hs=!0;let o=e.length,i=this?this.unpack(e,o):hl.unpack(e,o);if(n){if(n(i,s,O)===!1)return;for(;O<o;)if(s=O,n(dl(),s,O)===!1)return}else{for(r=[i];O<o;)s=O,r.push(dl());return r}}catch(o){throw o.lastPosition=s,o.values=r,o}finally{hs=!1,fl()}}_mergeStructures(e,n){this._onLoadedStructures&&(e=this._onLoadedStructures(e)),e=e||[],Object.isFrozen(e)&&(e=e.map(r=>r.slice(0)));for(let r=0,s=e.length;r<s;r++){let o=e[r];o&&(o.isShared=!0,r>=32&&(o.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in n||[])if(r>=0){let s=e[r],o=n[r];o&&(s&&((e.restoreStructures||(e.restoreStructures=[]))[r]=s),e[r]=o)}return this.structures=e}decode(e,n){return this.unpack(e,n)}};function dl(t){try{if(!Be.trusted&&!hs){let n=Me.sharedLength||0;n<Me.length&&(Me.length=n)}let e;if(Be._readStruct&&Q[O]<64&&Q[O]>=32?(e=Be._readStruct(Q,O,Sn),Q=null,!(t&&t.lazy)&&e&&(e=e.toJSON()),O=Sn):e=ot(),xt&&(O=xt.postBundlePosition,xt=null),hs&&(Me.restoreStructures=null),O==Sn)Me&&Me.restoreStructures&&kb(),Me=null,Q=null,Ir&&(Ir=null);else{if(O>Sn)throw new Error("Unexpected end of MessagePack data");if(!hs){let n;try{n=JSON.stringify(e,(r,s)=>typeof s=="bigint"?`${s}n`:s).slice(0,100)}catch(r){n="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+n)}}return e}catch(e){throw Me&&Me.restoreStructures&&kb(),fl(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||O>Sn)&&(e.incomplete=!0),e}}function kb(){for(let t in Me.restoreStructures)Me[t]=Me.restoreStructures[t];Me.restoreStructures=null}function ot(){let t=Q[O++];if(t<160)if(t<128){if(t<64)return t;{let e=Me[t&63]||Be.getStructures&&Db()[t&63];return e?(e.read||(e.read=Sp(e,t&63)),e.read()):t}}else if(t<144)if(t-=128,Be.mapsAsObjects){let e={};for(let n=0;n<t;n++){let r=Bb();r==="__proto__"&&(r="__proto_"),e[r]=ot()}return e}else{let e=new Map;for(let n=0;n<t;n++)e.set(ot(),ot());return e}else{t-=144;let e=new Array(t);for(let n=0;n<t;n++)e[n]=ot();return Be.freezeData?Object.freeze(e):e}else if(t<192){let e=t-160;if(ur>=O)return ps.slice(O-wn,(O+=e)-wn);if(ur==0&&Sn<140){let n=e<16?xp(e):Nb(e);if(n!=null)return n}return bp(e)}else{let e;switch(t){case 192:return null;case 193:return xt?(e=ot(),e>0?xt[1].slice(xt.position1,xt.position1+=e):xt[0].slice(xt.position0,xt.position0-=e)):wp;case 194:return!1;case 195:return!0;case 196:if(e=Q[O++],e===void 0)throw new Error("Unexpected end of buffer");return hp(e);case 197:return e=Te.getUint16(O),O+=2,hp(e);case 198:return e=Te.getUint32(O),O+=4,hp(e);case 199:return Qs(Q[O++]);case 200:return e=Te.getUint16(O),O+=2,Qs(e);case 201:return e=Te.getUint32(O),O+=4,Qs(e);case 202:if(e=Te.getFloat32(O),Be.useFloat32>2){let n=pl[(Q[O]&127)<<1|Q[O+1]>>7];return O+=4,(n*e+(e>0?.5:-.5)>>0)/n}return O+=4,e;case 203:return e=Te.getFloat64(O),O+=8,e;case 204:return Q[O++];case 205:return e=Te.getUint16(O),O+=2,e;case 206:return e=Te.getUint32(O),O+=4,e;case 207:return Be.int64AsType==="number"?(e=Te.getUint32(O)*4294967296,e+=Te.getUint32(O+4)):Be.int64AsType==="string"?e=Te.getBigUint64(O).toString():Be.int64AsType==="auto"?(e=Te.getBigUint64(O),e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=Te.getBigUint64(O),O+=8,e;case 208:return Te.getInt8(O++);case 209:return e=Te.getInt16(O),O+=2,e;case 210:return e=Te.getInt32(O),O+=4,e;case 211:return Be.int64AsType==="number"?(e=Te.getInt32(O)*4294967296,e+=Te.getUint32(O+4)):Be.int64AsType==="string"?e=Te.getBigInt64(O).toString():Be.int64AsType==="auto"?(e=Te.getBigInt64(O),e>=BigInt(-2)<<BigInt(52)&&e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=Te.getBigInt64(O),O+=8,e;case 212:if(e=Q[O++],e==114)return Cb(Q[O++]&63);{let n=qt[e];if(n)return n.read?(O++,n.read(ot())):n.noBuffer?(O++,n()):n(Q.subarray(O,++O));throw new Error("Unknown extension "+e)}case 213:return e=Q[O],e==114?(O++,Cb(Q[O++]&63,Q[O++])):Qs(2);case 214:return Qs(4);case 215:return Qs(8);case 216:return Qs(16);case 217:return e=Q[O++],ur>=O?ps.slice(O-wn,(O+=e)-wn):CP(e);case 218:return e=Te.getUint16(O),O+=2,ur>=O?ps.slice(O-wn,(O+=e)-wn):OP(e);case 219:return e=Te.getUint32(O),O+=4,ur>=O?ps.slice(O-wn,(O+=e)-wn):IP(e);case 220:return e=Te.getUint16(O),O+=2,Pb(e);case 221:return e=Te.getUint32(O),O+=4,Pb(e);case 222:return e=Te.getUint16(O),O+=2,Tb(e);case 223:return e=Te.getUint32(O),O+=4,Tb(e);default:if(t>=224)return t-256;if(t===void 0){let n=new Error("Unexpected end of MessagePack data");throw n.incomplete=!0,n}throw new Error("Unknown MessagePack token "+t)}}}var MP=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Sp(t,e){function n(){if(n.count++>Eb){let s;try{s=t.read=new Function("r","return function(){return "+(Be.freezeData?"Object.freeze":"")+"({"+t.map(o=>o==="__proto__"?"__proto_:r()":MP.test(o)?o+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"})}")(ot)}catch{return Eb=1/0,n()}return t.read0=s,t.highByte===0&&(t.read=Ab(e,t.read)),s()}let r={};for(let s=0,o=t.length;s<o;s++){let i=t[s];i==="__proto__"&&(i="__proto_"),r[i]=ot()}return Be.freezeData?Object.freeze(r):r}return n.count=0,t.read0=n,t.highByte===0?Ab(e,n):n}var Ab=(t,e)=>function(){let n=Q[O++];if(n===0)return e();let r=t<32?-(t+(n<<5)):t+(n<<5),s=Me[r]||Db()[r];if(!s)throw new Error("Record id is not defined for "+r);return s.read||(s.read=Sp(s,t)),s.read()};function Db(){let t=Fb(()=>(Q=null,Be.getStructures()));return Me=Be._mergeStructures(t,Me)}var bp=qa,CP=qa,OP=qa,IP=qa;function qa(t){let e;if(t<16&&(e=xp(t)))return e;if(t>64&&mp)return mp.decode(Q.subarray(O,O+=t));let n=O+t,r=[];for(e="";O<n;){let s=Q[O++];if((s&128)===0)r.push(s);else if((s&224)===192){let o=Q[O++]&63,i=(s&31)<<6|o;i<128?r.push(65533):r.push(i)}else if((s&240)===224){let o=Q[O++]&63,i=Q[O++]&63,a=(s&31)<<12|o<<6|i;a<2048||a>=55296&&a<=57343?r.push(65533):r.push(a)}else if((s&248)===240){let o=Q[O++]&63,i=Q[O++]&63,a=Q[O++]&63,c=(s&7)<<18|o<<12|i<<6|a;c<65536||c>1114111?r.push(65533):(c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c))}else r.push(65533);r.length>=4096&&(e+=St.apply(String,r),r.length=0)}return r.length>0&&(e+=St.apply(String,r)),e}function Pb(t){let e=new Array(t);for(let n=0;n<t;n++)e[n]=ot();return Be.freezeData?Object.freeze(e):e}function Tb(t){if(Be.mapsAsObjects){let e={};for(let n=0;n<t;n++){let r=Bb();r==="__proto__"&&(r="__proto_"),e[r]=ot()}return e}else{let e=new Map;for(let n=0;n<t;n++)e.set(ot(),ot());return e}}var St=String.fromCharCode;function Nb(t){let e=O,n=new Array(t);for(let r=0;r<t;r++){let s=Q[O++];if((s&128)>0){O=e;return}n[r]=s}return St.apply(String,n)}function xp(t){if(t<4)if(t<2){if(t===0)return"";{let e=Q[O++];if((e&128)>1){O-=1;return}return St(e)}}else{let e=Q[O++],n=Q[O++];if((e&128)>0||(n&128)>0){O-=2;return}if(t<3)return St(e,n);let r=Q[O++];if((r&128)>0){O-=3;return}return St(e,n,r)}else{let e=Q[O++],n=Q[O++],r=Q[O++],s=Q[O++];if((e&128)>0||(n&128)>0||(r&128)>0||(s&128)>0){O-=4;return}if(t<6){if(t===4)return St(e,n,r,s);{let o=Q[O++];if((o&128)>0){O-=5;return}return St(e,n,r,s,o)}}else if(t<8){let o=Q[O++],i=Q[O++];if((o&128)>0||(i&128)>0){O-=6;return}if(t<7)return St(e,n,r,s,o,i);let a=Q[O++];if((a&128)>0){O-=7;return}return St(e,n,r,s,o,i,a)}else{let o=Q[O++],i=Q[O++],a=Q[O++],c=Q[O++];if((o&128)>0||(i&128)>0||(a&128)>0||(c&128)>0){O-=8;return}if(t<10){if(t===8)return St(e,n,r,s,o,i,a,c);{let u=Q[O++];if((u&128)>0){O-=9;return}return St(e,n,r,s,o,i,a,c,u)}}else if(t<12){let u=Q[O++],l=Q[O++];if((u&128)>0||(l&128)>0){O-=10;return}if(t<11)return St(e,n,r,s,o,i,a,c,u,l);let d=Q[O++];if((d&128)>0){O-=11;return}return St(e,n,r,s,o,i,a,c,u,l,d)}else{let u=Q[O++],l=Q[O++],d=Q[O++],f=Q[O++];if((u&128)>0||(l&128)>0||(d&128)>0||(f&128)>0){O-=12;return}if(t<14){if(t===12)return St(e,n,r,s,o,i,a,c,u,l,d,f);{let h=Q[O++];if((h&128)>0){O-=13;return}return St(e,n,r,s,o,i,a,c,u,l,d,f,h)}}else{let h=Q[O++],p=Q[O++];if((h&128)>0||(p&128)>0){O-=14;return}if(t<15)return St(e,n,r,s,o,i,a,c,u,l,d,f,h,p);let y=Q[O++];if((y&128)>0){O-=15;return}return St(e,n,r,s,o,i,a,c,u,l,d,f,h,p,y)}}}}}function vb(){let t=Q[O++],e;if(t<192)e=t-160;else switch(t){case 217:e=Q[O++];break;case 218:e=Te.getUint16(O),O+=2;break;case 219:e=Te.getUint32(O),O+=4;break;default:throw new Error("Expected string")}return qa(e)}function hp(t){return Be.copyBuffers?Uint8Array.prototype.slice.call(Q,O,O+=t):Q.subarray(O,O+=t)}function Qs(t){let e=Q[O++];if(qt[e]){let n;return qt[e](Q.subarray(O,n=O+=t),r=>{O=r;try{return ot()}finally{O=n}})}else throw new Error("Unknown extension type "+e)}var Mb=new Array(4096);function Bb(){let t=Q[O++];if(t>=160&&t<192){if(t=t-160,ur>=O)return ps.slice(O-wn,(O+=t)-wn);if(!(ur==0&&Sn<180))return bp(t)}else return O--,Lb(ot());let e=(t<<5^(t>1?Te.getUint16(O):t>0?Q[O]:0))&4095,n=Mb[e],r=O,s=O+t-3,o,i=0;if(n&&n.bytes==t){for(;r<s;){if(o=Te.getUint32(r),o!=n[i++]){r=1879048192;break}r+=4}for(s+=3;r<s;)if(o=Q[r++],o!=n[i++]){r=1879048192;break}if(r===s)return O=r,n.string;s-=3,r=O}for(n=[],Mb[e]=n,n.bytes=t;r<s;)o=Te.getUint32(r),n.push(o),r+=4;for(s+=3;r<s;)o=Q[r++],n.push(o);let a=t<16?xp(t):Nb(t);return a!=null?n.string=a:n.string=bp(t)}function Lb(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(t==null)return t+"";if(Be.allowArraysInMapKeys&&Array.isArray(t)&&t.flat().every(e=>["string","number","boolean","bigint"].includes(typeof e)))return t.flat().toString();throw new Error(`Invalid property type for record: ${typeof t}`)}var Cb=(t,e)=>{let n=ot().map(Lb),r=t;e!==void 0&&(t=t<32?-((e<<5)+t):(e<<5)+t,n.highByte=e);let s=Me[t];return s&&(s.isShared||hs)&&((Me.restoreStructures||(Me.restoreStructures=[]))[t]=s),Me[t]=n,n.read=Sp(n,r),(n.read0||n.read)()};qt[0]=()=>{};qt[0].noBuffer=!0;qt[66]=t=>{let e=t.byteLength%8||8,n=BigInt(t[0]&128?t[0]-256:t[0]);for(let r=1;r<e;r++)n<<=BigInt(8),n+=BigInt(t[r]);if(t.byteLength!==e){let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=(o,i)=>{let a=i-o;if(a<=40){let d=r.getBigUint64(o);for(let f=o+8;f<i;f+=8)d<<=BigInt(64),d|=r.getBigUint64(f);return d}let c=o+(a>>4<<3),u=s(o,c),l=s(c,i);return u<<BigInt((i-c)*8)|l};n=n<<BigInt((r.byteLength-e)*8)|s(e,r.byteLength)}return n};var Ob={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError=="function"?AggregateError:null};qt[101]=()=>{let t=ot();if(!Ob[t[0]]){let e=Error(t[1],{cause:t[2]});return e.name=t[0],e}return Ob[t[0]](t[1],{cause:t[2]})};qt[105]=t=>{if(Be.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=Te.getUint32(O-4);Ir||(Ir=new Map);let n=Q[O],r;n>=144&&n<160||n==220||n==221?r=[]:n>=128&&n<144||n==222||n==223?r=new Map:(n>=199&&n<=201||n>=212&&n<=216)&&Q[O+1]===115?r=new Set:r={};let s={target:r};Ir.set(e,s);let o=ot();if(s.used)Object.assign(r,o);else return s.target=o;if(r instanceof Map)for(let[i,a]of o.entries())r.set(i,a);if(r instanceof Set)for(let i of Array.from(o))r.add(i);return r};qt[112]=t=>{if(Be.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=Te.getUint32(O-4),n=Ir.get(e);return n.used=!0,n.target};qt[115]=()=>new Set(ot());var _p=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(t=>t+"Array"),DP=typeof globalThis=="object"?globalThis:window;qt[116]=t=>{let e=t[0],n=Uint8Array.prototype.slice.call(t,1).buffer,r=_p[e];if(!r){if(e===16)return n;if(e===17)return new DataView(n);throw new Error("Could not find typed array for code "+e)}return new DP[r](n)};qt[120]=()=>{let t=ot();return new RegExp(t[0],t[1])};var NP=[];qt[98]=t=>{let e=(t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3],n=O;return O+=e-t.length,xt=NP,xt=[vb(),vb()],xt.position0=0,xt.position1=0,xt.postBundlePosition=O,O=n,ot()};qt[255]=t=>t.length==4?new Date((t[0]*16777216+(t[1]<<16)+(t[2]<<8)+t[3])*1e3):t.length==8?new Date(((t[0]<<22)+(t[1]<<14)+(t[2]<<6)+(t[3]>>2))/1e6+((t[3]&3)*4294967296+t[4]*16777216+(t[5]<<16)+(t[6]<<8)+t[7])*1e3):t.length==12?new Date(((t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3])/1e6+((t[4]&128?-281474976710656:0)+t[6]*1099511627776+t[7]*4294967296+t[8]*16777216+(t[9]<<16)+(t[10]<<8)+t[11])*1e3):new Date("invalid");function Fb(t){Be&&Be._onSaveState&&Be._onSaveState();let e=Sn,n=O,r=gp,s=wn,o=ur,i=ps,a=yp,c=Ir,u=xt,l=new Uint8Array(Q.slice(0,Sn)),d=Me,f=Me.slice(0,Me.length),h=Be,p=hs,y=t();return Sn=e,O=n,gp=r,wn=s,ur=o,ps=i,yp=a,Ir=c,xt=u,Q=l,hs=p,Me=d,Me.splice(0,Me.length,...f),Be=h,Te=new DataView(Q.buffer,Q.byteOffset,Q.byteLength),y}function fl(){Q=null,Ir=null,Me=null}var pl=new Array(147);for(let t=0;t<256;t++)pl[t]=+("1e"+Math.floor(45.15-t*.30103));var hl=new ms({useRecords:!1}),ml=hl.unpack,BP=hl.unpackMultiple,LP=hl.unpack,yl={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},FP=new Float32Array(1),gL=new Uint8Array(FP.buffer,0,4);ms.SUPPORTS_STRUCT_HOOKS=!0;var bl;try{bl=new TextEncoder}catch{}var kp,Ap,di=typeof Buffer<"u",gl=di?function(t){return Buffer.allocUnsafeSlow(t)}:Uint8Array,Hb=di?Buffer:Uint8Array,zb=di?4294967296:2144337920,F,Ga,$e,D=0,Ct,Ze=null,zP=21760,UP=/[\u0080-\uFFFF]/,li=Symbol("record-id"),ys=class extends ms{constructor(e){super(e),this.offset=0;let n,r,s,o,i,a=Hb.prototype.utf8Write?function(v,$){return F.utf8Write(v,$,F.byteLength-$)}:bl&&bl.encodeInto?function(v,$){return bl.encodeInto(v,F.subarray($)).written}:!1,c=this;e||(e={});let u=e&&e.sequential,l=e.structures||e.saveStructures,d=e.maxSharedStructures;if(d==null&&(d=l?32:0),d>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let f=e.maxOwnStructures;f==null&&(f=l?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let h=d>32||f+d>64,p=d+64,y=d+f+64;if(y>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let S=[],w=0,x=0;this.pack=this.encode=function(v,$){if(F||(F=new gl(8192),$e=F.dataView||(F.dataView=new DataView(F.buffer,0,8192)),D=0),Ct=F.length-10,Ct-D<2048?(F=new gl(F.length),$e=F.dataView||(F.dataView=new DataView(F.buffer,0,F.length)),Ct=F.length-10,D=0):D=D+7&2147483640,r=D,$&fi&&(D+=$&255),i=c.structuredClone?new Map:null,c.bundleStrings&&typeof v!="string"?(Ze=[],Ze.size=1/0):Ze=null,o=c.structures,o){o.uninitialized&&(o=c._mergeStructures(c.getStructures()));let j=o.sharedLength||0;if(j>d)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+o.sharedLength);if(!o.transitions){o.transitions=Object.create(null);for(let q=0;q<j;q++){let oe=o[q];if(!oe)continue;let ce,ne=o.transitions;for(let Re=0,G=oe.length;Re<G;Re++){let ae=oe[Re];ce=ne[ae],ce||(ce=ne[ae]=Object.create(null)),ne=ce}ne[li]=q+64}this.lastNamedStructuresLength=j}u||(o.nextId=j+64)}s&&(s=!1);let Y;try{c._writeStruct&&v&&typeof v=="object"?v.constructor===Object?K(v):v.constructor!==Map&&!Array.isArray(v)&&!Ap.some(q=>v instanceof q)?K(v.toJSON?v.toJSON():v):E(v):E(v);let j=Ze;if(Ze&&Vb(r,E,0),i&&i.idsToInsert){let q=i.idsToInsert.sort((Re,G)=>Re.offset>G.offset?1:-1),oe=q.length,ce=-1;for(;j&&oe>0;){let Re=q[--oe].offset+r;Re<j.stringsPosition+r&&ce===-1&&(ce=0),Re>j.position+r?ce>=0&&(ce+=6):(ce>=0&&($e.setUint32(j.position+r,$e.getUint32(j.position+r)+ce),ce=-1),j=j.previous,oe++)}ce>=0&&j&&$e.setUint32(j.position+r,$e.getUint32(j.position+r)+ce),D+=q.length*6,D>Ct&&W(D),c.offset=D;let ne=VP(F.subarray(r,D),q);return i=null,ne}return c.offset=D,$&jb?(F.start=r,F.end=D,F):F.subarray(r,D)}catch(j){throw Y=j,j}finally{if(o&&(R(),s&&c.saveStructures)){let j=o.sharedLength||0,q=F.subarray(r,D),oe=(c._prepareStructures||HP)(o,c);if(!Y)return c.saveStructures(oe,oe.isCompatible)===!1?(o.uninitialized=!0,c.pack(v,$)):(c.lastNamedStructuresLength=j,F.length>1073741824&&(F=null),q)}F.length>1073741824&&(F=null),$&Wb&&(D=r)}};let R=()=>{x<10&&x++;let v=o.sharedLength||0;if(o.length>v&&!u&&(o.length=v),w>1e4)o.transitions=null,x=0,w=0,S.length>0&&(S=[]);else if(S.length>0&&!u){for(let $=0,Y=S.length;$<Y;$++)S[$][li]=0;S=[]}},A=v=>{var $=v.length;$<16?F[D++]=144|$:$<65536?(F[D++]=220,F[D++]=$>>8,F[D++]=$&255):(F[D++]=221,$e.setUint32(D,$),D+=4);for(let Y=0;Y<$;Y++)E(v[Y])},E=v=>{D>Ct&&(F=W(D));var $=typeof v,Y;if($==="string"){let j=v.length;if(Ze&&j>=4&&j<4096){if((Ze.size+=j)>zP){let ne,Re=(Ze[0]?Ze[0].length*3+Ze[1].length:0)+10;D+Re>Ct&&(F=W(D+Re));let G;Ze.position?(G=Ze,F[D]=200,D+=3,F[D++]=98,ne=D-r,D+=4,Vb(r,E,0),$e.setUint16(ne+r-3,D-r-ne)):(F[D++]=214,F[D++]=98,ne=D-r,D+=4),Ze=["",""],Ze.previous=G,Ze.size=0,Ze.position=ne}let ce=UP.test(v);Ze[ce?0:1]+=v,F[D++]=193,E(ce?-j:j);return}let q;j<32?q=1:j<256?q=2:j<65536?q=3:q=5;let oe=j*3;if(D+oe>Ct&&(F=W(D+oe)),j<64||!a){let ce,ne,Re,G=D+q;for(ce=0;ce<j;ce++)ne=v.charCodeAt(ce),ne<128?F[G++]=ne:ne<2048?(F[G++]=ne>>6|192,F[G++]=ne&63|128):(ne&64512)===55296&&((Re=v.charCodeAt(ce+1))&64512)===56320?(ne=65536+((ne&1023)<<10)+(Re&1023),ce++,F[G++]=ne>>18|240,F[G++]=ne>>12&63|128,F[G++]=ne>>6&63|128,F[G++]=ne&63|128):(F[G++]=ne>>12|224,F[G++]=ne>>6&63|128,F[G++]=ne&63|128);Y=G-D-q}else Y=a(v,D+q);Y<32?F[D++]=160|Y:Y<256?(q<2&&F.copyWithin(D+2,D+1,D+1+Y),F[D++]=217,F[D++]=Y):Y<65536?(q<3&&F.copyWithin(D+3,D+2,D+2+Y),F[D++]=218,F[D++]=Y>>8,F[D++]=Y&255):(q<5&&F.copyWithin(D+5,D+3,D+3+Y),F[D++]=219,$e.setUint32(D,Y),D+=4),D+=Y}else if($==="number")if(v>>>0===v)v<32||v<128&&this.useRecords===!1||v<64&&!this._writeStruct?F[D++]=v:v<256?(F[D++]=204,F[D++]=v):v<65536?(F[D++]=205,F[D++]=v>>8,F[D++]=v&255):(F[D++]=206,$e.setUint32(D,v),D+=4);else if(v>>0===v)v>=-32?F[D++]=256+v:v>=-128?(F[D++]=208,F[D++]=v+256):v>=-32768?(F[D++]=209,$e.setInt16(D,v),D+=2):(F[D++]=210,$e.setInt32(D,v),D+=4);else{let j;if((j=this.useFloat32)>0&&v<4294967296&&v>=-2147483648){F[D++]=202,$e.setFloat32(D,v);let q;if(j<4||(q=v*pl[(F[D]&127)<<1|F[D+1]>>7])>>0===q){D+=4;return}else D--}F[D++]=203,$e.setFloat64(D,v),D+=8}else if($==="object"||$==="function")if(!v)F[D++]=192;else{if(i){let q=i.get(v);if(q){if(!q.id){let oe=i.idsToInsert||(i.idsToInsert=[]);q.id=oe.push(q)}F[D++]=214,F[D++]=112,$e.setUint32(D,q.id),D+=4;return}else i.set(v,{offset:D-r})}let j=v.constructor;if(j===Object)L(v);else if(j===Array)A(v);else if(j===Map)if(this.mapAsEmptyObject)F[D++]=128;else{Y=v.size,Y<16?F[D++]=128|Y:Y<65536?(F[D++]=222,F[D++]=Y>>8,F[D++]=Y&255):(F[D++]=223,$e.setUint32(D,Y),D+=4);for(let[q,oe]of v)E(q),E(oe)}else{for(let q=0,oe=kp.length;q<oe;q++){let ce=Ap[q];if(v instanceof ce){let ne=kp[q];if(ne.write){ne.type&&(F[D++]=212,F[D++]=ne.type,F[D++]=0);let Ge=ne.write.call(this,v);Ge===v?Array.isArray(v)?A(v):L(v):E(Ge);return}let Re=F,G=$e,ae=D;F=null;let be;try{be=ne.pack.call(this,v,Ge=>(F=Re,Re=null,D+=Ge,D>Ct&&W(D),{target:F,targetView:$e,position:D-Ge}),E)}finally{Re&&(F=Re,$e=G,D=ae,Ct=F.length-10)}be&&(be.length+D>Ct&&W(be.length+D),D=Ub(be,F,D,ne.type));return}}if(Array.isArray(v))A(v);else{if(v.toJSON){let q=v.toJSON();if(q!==v)return E(q)}if($==="function")return E(this.writeFunction&&this.writeFunction(v));L(v)}}}else if($==="boolean")F[D++]=v?195:194;else if($==="bigint"){if(v<9223372036854776e3&&v>=-9223372036854776e3)F[D++]=211,$e.setBigInt64(D,v);else if(v<18446744073709552e3&&v>0)F[D++]=207,$e.setBigUint64(D,v);else if(this.largeBigIntToFloat)F[D++]=203,$e.setFloat64(D,Number(v));else{if(this.largeBigIntToString)return E(v.toString());if(this.useBigIntExtension||this.moreTypes){let j=v<0?BigInt(-1):BigInt(0),q;if(v>>BigInt(65536)===j){let oe=BigInt(18446744073709552e3)-BigInt(1),ce=[];for(;ce.push(v&oe),v>>BigInt(63)!==j;)v>>=BigInt(64);q=new Uint8Array(new BigUint64Array(ce).buffer),q.reverse()}else{let oe=v<0,ce=(oe?~v:v).toString(16);if(ce.length%2?ce="0"+ce:parseInt(ce.charAt(0),16)>=8&&(ce="00"+ce),di)q=Buffer.from(ce,"hex");else{q=new Uint8Array(ce.length/2);for(let ne=0;ne<q.length;ne++)q[ne]=parseInt(ce.slice(ne*2,ne*2+2),16)}if(oe)for(let ne=0;ne<q.length;ne++)q[ne]=~q[ne]}q.length+D>Ct&&W(q.length+D),D=Ub(q,F,D,66);return}else throw new RangeError(v+" 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")this.encodeUndefinedAsNil?F[D++]=192:(F[D++]=212,F[D++]=0,F[D++]=0);else throw new Error("Unknown type: "+$)},P=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?v=>{let $;if(this.skipValues){$=[];for(let q in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(q))&&!this.skipValues.includes(v[q])&&$.push(q)}else $=Object.keys(v);let Y=$.length;Y<16?F[D++]=128|Y:Y<65536?(F[D++]=222,F[D++]=Y>>8,F[D++]=Y&255):(F[D++]=223,$e.setUint32(D,Y),D+=4);let j;if(this.coercibleKeyAsNumber)for(let q=0;q<Y;q++){j=$[q];let oe=Number(j);E(isNaN(oe)?j:oe),E(v[j])}else for(let q=0;q<Y;q++)E(j=$[q]),E(v[j])}:v=>{F[D++]=222;let $=D-r;D+=2;let Y=0;for(let j in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(j))&&(E(j),E(v[j]),Y++);if(Y>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');F[$+++r]=Y>>8,F[$+r]=Y&255},k=this.useRecords===!1?P:e.progressiveRecords&&!h?v=>{let $,Y=o.transitions||(o.transitions=Object.create(null)),j=D++-r,q;for(let oe in v)if(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(oe)){if($=Y[oe],$)Y=$;else{let ce=Object.keys(v),ne=Y;Y=o.transitions;let Re=0;for(let G=0,ae=ce.length;G<ae;G++){let be=ce[G];$=Y[be],$||($=Y[be]=Object.create(null),Re++),Y=$}j+r+1==D?(D--,B(Y,ce,Re)):se(Y,ce,j,Re),q=!0,Y=ne[oe]}E(v[oe])}if(!q){let oe=Y[li];oe?F[j+r]=oe:se(Y,Object.keys(v),j,0)}}:v=>{let $,Y=o.transitions||(o.transitions=Object.create(null)),j=0;for(let oe in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(oe))&&($=Y[oe],$||($=Y[oe]=Object.create(null),j++),Y=$);let q=Y[li];q?q>=96&&h?(F[D++]=((q-=96)&31)+96,F[D++]=q>>5):F[D++]=q:B(Y,Y.__keys__||Object.keys(v),j);for(let oe in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(oe))&&E(v[oe])},M=typeof this.useRecords=="function"&&this.useRecords,L=M?v=>{M(v)?k(v):P(v)}:k,K=v=>{let $=c._writeStruct(v,F,r,D,o,W,(Y,j,q)=>{if(q)return s=!0;D=j;let oe=F;return E(Y),R(),oe!==F?{position:D,targetView:$e,target:F}:D});if($===0)return L(v);D=$},W=v=>{let $;if(v>16777216){if(v-r>zb)throw new Error("Packed buffer would be larger than maximum buffer size");$=Math.min(zb,Math.round(Math.max((v-r)*(v>67108864?1.25:2),4194304)/4096)*4096)}else $=(Math.max(v-r<<2,F.length-1)>>12)+1<<12;let Y=new gl($);return $e=Y.dataView||(Y.dataView=new DataView(Y.buffer,0,$)),v=Math.min(v,F.length),F.copy?F.copy(Y,0,r,v):Y.set(F.slice(r,v)),D-=r,r=0,Ct=Y.length-10,F=Y},B=(v,$,Y)=>{let j=o.nextId;j||(j=64),j<p&&this.shouldShareStructure&&!this.shouldShareStructure($)?(j=o.nextOwnId,j<y||(j=p),o.nextOwnId=j+1):(j>=y&&(j=p),o.nextId=j+1);let q=$.highByte=j>=96&&h?j-96>>5:-1;v[li]=j,v.__keys__=$,o[j-64]=$,j<p?($.isShared=!0,o.sharedLength=j-63,s=!0,q>=0?(F[D++]=(j&31)+96,F[D++]=q):F[D++]=j):(q>=0?(F[D++]=213,F[D++]=114,F[D++]=(j&31)+96,F[D++]=q):(F[D++]=212,F[D++]=114,F[D++]=j),Y&&(w+=x*Y),S.length>=f&&(S.shift()[li]=0),S.push(v),E($))},se=(v,$,Y,j)=>{let q=F,oe=D,ce=Ct,ne=r;F=Ga,D=0,r=0,F||(Ga=F=new gl(8192)),Ct=F.length-10,B(v,$,j),Ga=F;let Re=D;if(F=q,D=oe,Ct=ce,r=ne,Re>1){let G=D+Re-1;G>Ct&&W(G);let ae=Y+r;F.copyWithin(ae+Re,ae+1,D),F.set(Ga.slice(0,Re),ae),D=G}else F[Y+r]=Ga[0]}}useBuffer(e){F=e,F.dataView||(F.dataView=new DataView(F.buffer,F.byteOffset,F.byteLength)),$e=F.dataView,D=0}set position(e){D=e}get position(){return D}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}};Ap=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Wa];kp=[{pack(t,e,n){let r=t.getTime()/1e3;if((this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:s,targetView:o,position:i}=e(6);s[i++]=214,s[i++]=255,o.setUint32(i,r)}else if(r>0&&r<4294967296){let{target:s,targetView:o,position:i}=e(10);s[i++]=215,s[i++]=255,o.setUint32(i,t.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),o.setUint32(i+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),n(this.onInvalidDate());let{target:s,targetView:o,position:i}=e(3);s[i++]=212,s[i++]=255,s[i++]=255}else{let{target:s,targetView:o,position:i}=e(15);s[i++]=199,s[i++]=12,s[i++]=255,o.setUint32(i,t.getMilliseconds()*1e6),o.setBigInt64(i+4,BigInt(Math.floor(r)))}}},{pack(t,e,n){if(this.setAsEmptyObject)return e(0),n({});let r=Array.from(t),{target:s,position:o}=e(this.moreTypes?3:0);this.moreTypes&&(s[o++]=212,s[o++]=115,s[o++]=0),n(r)}},{pack(t,e,n){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=101,r[s++]=0),n([t.name,t.message,t.cause])}},{pack(t,e,n){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=120,r[s++]=0),n([t.source,t.flags])}},{pack(t,e){this.moreTypes?Rp(t,16,e):Ep(di?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let n=t.constructor;n!==Hb&&this.moreTypes?Rp(t,_p.indexOf(n.name),e):Ep(t,e)}},{pack(t,e){this.moreTypes?Rp(t,17,e):Ep(di?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let{target:n,position:r}=e(1);n[r]=193}}];function Rp(t,e,n,r){let s=t.byteLength;if(s+1<256){var{target:o,position:i}=n(4+s);o[i++]=199,o[i++]=s+1}else if(s+1<65536){var{target:o,position:i}=n(5+s);o[i++]=200,o[i++]=s+1>>8,o[i++]=s+1&255}else{var{target:o,position:i,targetView:a}=n(7+s);o[i++]=201,a.setUint32(i,s+1),i+=4}o[i++]=116,o[i++]=e,t.buffer||(t=new Uint8Array(t)),o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i)}function Ep(t,e){let n=t.byteLength;var r,s;if(n<256){var{target:r,position:s}=e(n+2);r[s++]=196,r[s++]=n}else if(n<65536){var{target:r,position:s}=e(n+3);r[s++]=197,r[s++]=n>>8,r[s++]=n&255}else{var{target:r,position:s,targetView:o}=e(n+5);r[s++]=198,o.setUint32(s,n),s+=4}r.set(t,s)}function Ub(t,e,n,r){let s=t.length;switch(s){case 1:e[n++]=212;break;case 2:e[n++]=213;break;case 4:e[n++]=214;break;case 8:e[n++]=215;break;case 16:e[n++]=216;break;default:s<256?(e[n++]=199,e[n++]=s):s<65536?(e[n++]=200,e[n++]=s>>8,e[n++]=s&255):(e[n++]=201,e[n++]=s>>24,e[n++]=s>>16&255,e[n++]=s>>8&255,e[n++]=s&255)}return e[n++]=r,e.set(t,n),n+=s,n}function VP(t,e){let n,r=e.length*6,s=t.length-r;for(;n=e.pop();){let o=n.offset,i=n.id;t.copyWithin(o+r,o,s),r-=6;let a=o+r;t[a++]=214,t[a++]=105,t[a++]=i>>24,t[a++]=i>>16&255,t[a++]=i>>8&255,t[a++]=i&255,s=o}return t}function Vb(t,e,n){if(Ze.length>0){$e.setUint32(Ze.position+t,D+n-Ze.position-t),Ze.stringsPosition=D-t;let r=Ze;Ze=null,e(r[0]),e(r[1])}}function HP(t,e){return t.isCompatible=n=>{let r=!n||(e.lastNamedStructuresLength||0)===n.length;return r||e._mergeStructures(n),r},t}ys.SUPPORTS_STRUCT_HOOKS=!0;var $b=new ys({useRecords:!1}),$P=$b.pack,jP=$b.pack;var{NEVER:WP,ALWAYS:qP,DECIMAL_ROUND:GP,DECIMAL_FIT:YP}=yl,jb=512,Wb=1024,fi=2048;At();Ar();var KP=9,wl=class{constructor(){m(this,"pending",new Uint8Array(0))}push(e){if(!e||e.byteLength===0)return[];let n=this.pending.byteLength===0?e:XP(this.pending,e),r=[],s=0;for(;s<n.byteLength;){let o={offset:s},i;try{i=Ae.number(n,o)}catch(c){if(n.byteLength-s<=KP)break;throw c}let a=o.offset+i;if(a>n.byteLength)break;r.push(n.subarray(o.offset,a)),s=a}return this.pending=s<n.byteLength?n.slice(s):new Uint8Array(0),r}};function XP(t,e){let n=new Uint8Array(t.byteLength+e.byteLength);return n.set(t,0),n.set(e,t.byteLength),n}var Ya=class{constructor(e){m(this,"wt");m(this,"url");m(this,"isOpen",!1);m(this,"events");m(this,"reader");m(this,"writer");m(this,"unreliableReader");m(this,"unreliableWriter");m(this,"lengthPrefixBuffer",new Uint8Array(9));m(this,"reliableReassembler",new wl);m(this,"unreliableReassembler",new wl);this.events=e}connect(e,n={}){this.url=e;let r=n.fingerprint&&{serverCertificateHashes:[{algorithm:"sha-256",value:new Uint8Array(n.fingerprint)}]}||void 0;this.wt=new WebTransport(e,r),this.wt.ready.then(s=>{console.log("WebTransport ready!",s),this.isOpen=!0,this.unreliableReader=this.wt.datagrams.readable.getReader();let o=this.wt.datagrams;this.unreliableWriter=(o.createWritable?o.createWritable():o.writable).getWriter(),this.wt.incomingBidirectionalStreams.getReader().read().then(a=>{this.reader=a.value.readable.getReader(),this.writer=a.value.writable.getWriter(),this.sendSeatReservation(n.roomId,n.sessionId,n.reconnectionToken,n.skipHandshake),this.readIncomingData(),this.readIncomingUnreliableData()}).catch(a=>{console.error("failed to read incoming stream",a),console.error("TODO: close the connection")})}).catch(s=>{console.log("WebTransport not ready!",s),this._close()}),this.wt.closed.then(s=>{console.log("WebTransport closed w/ success",s),this.events.onclose({code:s.closeCode,reason:s.reason})}).catch(s=>{console.log("WebTransport closed w/ error",s),this.events.onerror(s),this.events.onclose({code:s.closeCode,reason:s.reason})}).finally(()=>{this._close()})}send(e){this.writer.write(this.frame(e))}sendUnreliable(e){this.unreliableWriter.write(this.frame(e))}frame(e){let n=e instanceof Uint8Array?e:new Uint8Array(e),r=Se.number(this.lengthPrefixBuffer,n.length,{offset:0}),s=new Uint8Array(r+n.length);return s.set(this.lengthPrefixBuffer.subarray(0,r),0),s.set(n,r),s}close(e,n){this.isOpen=!1;try{let r=this.wt?.close({closeCode:e,reason:n});r&&typeof r.catch=="function"&&r.catch(()=>{})}catch{}}readIncomingData(){return this.readLoop(this.reader,this.reliableReassembler,"reliable")}readIncomingUnreliableData(){return this.readLoop(this.unreliableReader,this.unreliableReassembler,"unreliable")}async readLoop(e,n,r){for(;this.isOpen;){let s;try{s=await e.read()}catch(o){await this.onChannelFailure(r,o);return}if(s.done||!s.value)return;for(let o of n.push(s.value))this.events.onmessage({data:o})}}async onChannelFailure(e,n){await new Promise(r=>setTimeout(r,0)),this.isOpen&&(console.error(`H3Transport: stopped reading the ${e} channel while the session was open`,n),this.close(wt.ABNORMAL_CLOSURE,`h3 ${e} channel failed`))}sendSeatReservation(e,n,r,s){let o={offset:0},i=[];Se.string(i,e,o),Se.string(i,n,o),r&&Se.string(i,r,o),s&&Se.boolean(i,1,o),this.writer.write(new Uint8Array(i).buffer)}_close(){this.isOpen=!1}};var Kb=cE(Gb(),1);Ar();var Pp=globalThis.WebSocket||Kb.default,Yb=!1,Sl=class{constructor(e){m(this,"ws");m(this,"protocols");m(this,"events");this.events=e}send(e){this.ws.send(e)}sendUnreliable(e){Yb||(Yb=!0,console.warn('@colyseus/sdk: the WebSocket transport has no unreliable channel \u2014 sending `mode:"unreliable"` traffic reliably instead. Use @colyseus/h3-transport (WebTransport) for datagram delivery.')),this.send(e)}connect(e,n){try{this.ws=new Pp(e,{headers:n,protocols:this.protocols})}catch{this.ws=new Pp(e,this.protocols)}this.ws.binaryType="arraybuffer",this.ws.onopen=r=>this.events.onopen?.(r),this.ws.onmessage=r=>this.events.onmessage?.(r),this.ws.onclose=r=>this.events.onclose?.(r),this.ws.onerror=r=>this.events.onerror?.(r)}close(e,n){e===wt.MAY_TRY_RECONNECT&&this.events.onclose&&(this.ws.onclose=null,this.events.onclose({code:e,reason:n})),this.ws.close(e,n)}get isOpen(){return this.ws.readyState===Pp.OPEN}};Ar();var Ka=[],Tp=typeof addEventListener=="function"&&typeof removeEventListener=="function";Tp&&addEventListener("offline",()=>{console.warn(`@colyseus/sdk: \u{1F6D1} Network offline. Closing ${Ka.length} connection(s)`),Ka.forEach(t=>t())},!1);var Xa,pi=class{constructor(e){m(this,"transport");m(this,"events",{});m(this,"url");m(this,"options");Ve(this,Xa,Tp?()=>this.close(wt.MAY_TRY_RECONNECT):null);e==="h3"?this.transport=new Ya(this.events):this.transport=new Sl(this.events)}connect(e,n){if(Tp){let r=this.events.onopen;this.events.onopen=o=>{Ka.push(le(this,Xa)),r?.(o)};let s=this.events.onclose;this.events.onclose=o=>{Ka.splice(Ka.indexOf(le(this,Xa)),1),s?.(o)}}this.url=e,this.options=n,this.transport.connect(e,n)}send(e){this.transport.send(e)}sendUnreliable(e){this.transport.sendUnreliable(e)}reconnect(e){if(this.transport instanceof Ya){this.transport.connect(this.url,{...this.options,...e});return}let n=new URL(this.url);for(let r in e)n.searchParams.set(r,e[r]);this.transport.connect(n.toString(),this.options)}close(e,n){this.transport.close(e,n)}get isOpen(){return this.transport.isOpen}};Xa=new WeakMap;var Xb={};function vp(t,e){Xb[t]=e}function Mp(t){let e=Xb[t];if(!e)throw new Error("missing serializer: "+t);return e}var xl=()=>({emit(t,...e){let n=this.events[t]||[];for(let r=0,s=n.length;r<s;r++)n[r](...e)},events:{},on(t,e){return this.events[t]?.push(e)||(this.events[t]=[e]),()=>{this.events[t]=this.events[t]?.filter(n=>e!==n)}}});var Jb=new WeakMap,Cp=class{constructor(){m(this,"handlers",[])}register(e,n=!1){return this.handlers.push(e),this}invoke(...e){let n=this.handlers;for(let r=0,s=n.length;r<s;r++)n[r].apply(this,e)}invokeAsync(...e){return Promise.all(this.handlers.map(n=>n.apply(this,e)))}remove(e){let n=this.handlers.indexOf(e);n===-1&&(n=this.handlers.findIndex(r=>Jb.get(r)===e)),n!==-1&&(this.handlers=this.handlers.filter((r,s)=>s!==n))}clear(){this.handlers=[]}};function eo(){let t=new Cp;function e(n){return t.register(n,this===null)}return e.once=n=>{let r=function(...s){t.remove(r),n.apply(this,s)};Jb.set(r,n),t.register(r)},e.remove=n=>t.remove(n),e.invoke=(...n)=>t.invoke(...n),e.invokeAsync=(...n)=>t.invokeAsync(...n),e.clear=()=>t.clear(),e}At();function Ja(t){try{return Gu(t.serializer.decoder)}catch{return}}var hi=class{constructor(){m(this,"state");m(this,"decoder")}setState(e,n){this.decoder.root.refs.size>1&&typeof this.decoder.decodeResync=="function"?this.decoder.decodeResync(e,n):this.decoder.decode(e,n)}getState(){return this.state}patch(e,n){return this.decoder.decode(e,n)}teardown(){this.decoder.root.clearRefs()}handshake(e,n){this.state?(Fn.decode(e,n),this.decoder=new Ln(this.state)):(this.decoder=Fn.decode(e,n),this.state=this.decoder.state)}};ul();function Zb(){return{enabled:!0,retryCount:0,maxRetries:15,delay:100,minDelay:100,maxDelay:5e3,minUptime:5e3,backoff:JP,maxEnqueuedMessages:10,enqueuedMessages:[],isReconnecting:!1}}var JP=(t,e)=>Math.floor(Math.pow(2,t)*e);function _l(t,e){t.reconnection.enqueuedMessages.push({data:e}),t.reconnection.enqueuedMessages.length>t.reconnection.maxEnqueuedMessages&&t.reconnection.enqueuedMessages.shift()}function Qb(t,e){if(!e){let r=new Error("request rejected");return r.name="rejected",r.reason=t,r}let n=new Error(t?.message??"request failed");return t?.name&&(n.name=t.name),t?.code!==void 0&&(n.code=t.code),n}Ia();var Qa,mi,yi,lr,dr,gi,fr,e0,t0,n0,r0,Rl=class Rl{constructor(e,n){Ve(this,fr);m(this,"roomId");m(this,"sessionId");m(this,"reconnectionToken");m(this,"name");m(this,"connection");m(this,"onStateChange",eo());m(this,"onError",eo());m(this,"onLeave",eo());m(this,"onReconnect",eo());m(this,"onDrop",eo());m(this,"onJoin",eo());m(this,"serializerId");m(this,"serializer");m(this,"reconnection",Zb());m(this,"joinedAtTime",0);m(this,"clock",ii);m(this,"onMessageHandlers",xl());m(this,"packr");m(this,"sharedBuffer");Ve(this,Qa,0);Ve(this,mi);Ve(this,yi,0);Ve(this,lr,new Map);Ve(this,dr);Ve(this,gi,0);if(this.name=e,this.packr=new ys,this.sharedBuffer=new Uint8Array(8192),n){let r=new(Mp("schema"));this.serializer=r;let s=new n;r.state=s,r.decoder=new Ln(s)}this.onLeave(()=>{this.removeAllListeners(),this.destroy()})}connect(e,n,r){this.connection=new pi(n.protocol),this.connection.events.onmessage=this.onMessageCallback.bind(this),this.connection.events.onclose=o=>{if(zs(this,fr,n0).call(this,"connection closed before a response was received."),this.joinedAtTime===0){console.warn?.(`Room connection was closed unexpectedly (${o.code}): ${o.reason}`),this.onError.invoke(o.code,o.reason);return}o.code===wt.NO_STATUS_RECEIVED||o.code===wt.ABNORMAL_CLOSURE||o.code===wt.GOING_AWAY||o.code===wt.MAY_TRY_RECONNECT?(this.onDrop.invoke(o.code,o.reason),this.handleReconnection(o.code,o.reason)):this.onLeave.invoke(o.code,o.reason)},this.connection.events.onerror=o=>{this.onError.invoke(o.code,o.reason)};let s=this.serializer?.getState()!==void 0;if(n.protocol==="h3"){let o=new URL(e);this.connection.connect(o.origin,{...n,skipHandshake:s})}else this.connection.connect(`${e}${s?"&skipHandshake=1":""}`,r)}leave(e=!0){return new Promise(n=>{this.onLeave(r=>n(r)),this.connection?e?(this.sharedBuffer[0]=Ke.LEAVE_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1))):this.connection.close():this.onLeave.invoke(wt.CONSENTED)})}onMessage(e,n){return this.onMessageHandlers.on(this.getMessageHandlerKey(e),n)}ping(e){this.connection?.isOpen&&(He(this,Qa,Mt()),He(this,mi,e),this.sharedBuffer[0]=Ke.PING,this.connection.send(this.sharedBuffer.subarray(0,1)))}send(e,n,r){if(r!==void 0){this.request(e,n).then(a=>r(a,void 0),a=>r(void 0,a));return}let s={offset:1};this.sharedBuffer[0]=Ke.ROOM_DATA,typeof e=="string"?Se.string(this.sharedBuffer,e,s):Se.number(this.sharedBuffer,e,s);let o=s.offset,i;n!==void 0?(i=this.packr.pack(n,fi|o),i.set(this.sharedBuffer.subarray(0,o),0)):i=this.sharedBuffer.subarray(0,o),this.connection.isOpen?this.connection.send(i):_l(this,new Uint8Array(i))}request(e,n,r){if(!this.connection.isOpen)return Promise.reject(new Error(`cannot send request "${e}": connection is not open.`));let s=r?.timeout??Rl.defaultRequestTimeout;return new Promise((o,i)=>{let a,c=this.sendRequest(e,n,{mode:r?.mode},(u,l,d)=>{clearTimeout(a),u?o(l):i(Qb(l,d))},u=>{clearTimeout(a),i(new Error(u))});a=setTimeout(()=>{this.cancelRequest(c),i(new Error(`request "${e}" timed out after ${s}ms.`))},s)})}sendRequest(e,n,r,s,o){let i=zs(this,fr,e0).call(this),a=zs(this,fr,t0).call(this,i,e,n);if(r.mode==="unreliable"){if(!this.connection.isOpen)return-1;this.connection.sendUnreliable(a)}else this.connection.isOpen?this.connection.send(a):_l(this,new Uint8Array(a));return le(this,lr).set(i,{onReply:s,onClose:o}),i}cancelRequest(e){le(this,lr).delete(e)}sendUnreliable(e,n){if(!this.connection.isOpen)return;let r={offset:1};this.sharedBuffer[0]=Ke.ROOM_DATA,typeof e=="string"?Se.string(this.sharedBuffer,e,r):Se.number(this.sharedBuffer,e,r);let s=r.offset,o;n!==void 0?(o=this.packr.pack(n,fi|s),o.set(this.sharedBuffer.subarray(0,s),0)):o=this.sharedBuffer.subarray(0,s),this.connection.sendUnreliable(o)}sendBytes(e,n){let r={offset:1};this.sharedBuffer[0]=Ke.ROOM_DATA_BYTES,typeof e=="string"?Se.string(this.sharedBuffer,e,r):Se.number(this.sharedBuffer,e,r);let s=r.offset;if(s+n.byteLength>this.sharedBuffer.byteLength){let o=new Uint8Array(s+n.byteLength);o.set(this.sharedBuffer.subarray(0,s)),this.sharedBuffer=o}this.sharedBuffer.set(n,s),this.connection.isOpen?this.connection.send(this.sharedBuffer.subarray(0,s+n.byteLength)):_l(this,this.sharedBuffer.subarray(0,s+n.byteLength))}input(e){return(le(this,dr)??He(this,dr,new ui(this))).handle(e)}get state(){return this.serializer.getState()}removeAllListeners(){this.onJoin.clear(),this.onStateChange.clear(),this.onError.clear(),this.onLeave.clear(),this.onReconnect.clear(),this.onDrop.clear(),this.onMessageHandlers.events={},this.serializer instanceof hi&&(this.serializer.decoder.root.callbacks={})}onMessageCallback(e){zs(this,fr,r0).call(this,new Uint8Array(e.data))}dispatchMessage(e,n){let r=this.getMessageHandlerKey(e);this.onMessageHandlers.events[r]?this.onMessageHandlers.emit(r,n):this.onMessageHandlers.events["*"]?this.onMessageHandlers.emit("*",e,n):r.startsWith("__")||console.warn?.(`@colyseus/sdk: onMessage() not registered for type '${e}'.`)}destroy(){this.serializer&&this.serializer.teardown()}getMessageHandlerKey(e){switch(typeof e){case"string":return e;case"number":return`i${e}`;default:throw new Error("invalid message type.")}}handleReconnection(e,n){if(!this.reconnection.enabled){this.onLeave.invoke(e,n);return}if(Date.now()-this.joinedAtTime<this.reconnection.minUptime){console.info(`[Colyseus reconnection]: ${String.fromCodePoint(10060)} Room has not been up for long enough for automatic reconnection. (min uptime: ${this.reconnection.minUptime}ms)`),this.onLeave.invoke(wt.ABNORMAL_CLOSURE,"Room uptime too short for reconnection.");return}this.reconnection.isReconnecting||(this.reconnection.retryCount=0,this.reconnection.isReconnecting=!0,le(this,dr)?.reset()),this.retryReconnection()}retryReconnection(){if(this.reconnection.retryCount>=this.reconnection.maxRetries){console.info(`[Colyseus reconnection]: ${String.fromCodePoint(10060)} \u274C Reconnection failed after ${this.reconnection.maxRetries} attempts.`),this.reconnection.isReconnecting=!1,this.onLeave.invoke(wt.FAILED_TO_RECONNECT,"No more retries. Reconnection failed.");return}this.reconnection.retryCount++;let e=Math.min(this.reconnection.maxDelay,Math.max(this.reconnection.minDelay,this.reconnection.backoff(this.reconnection.retryCount,this.reconnection.delay)));console.info(`[Colyseus reconnection]: ${String.fromCodePoint(9203)} will retry in ${(e/1e3).toFixed(1)} seconds...`),setTimeout(()=>{try{console.info(`[Colyseus reconnection]: ${String.fromCodePoint(128260)} Re-establishing sessionId '${this.sessionId}' with roomId '${this.roomId}'... (attempt ${this.reconnection.retryCount} of ${this.reconnection.maxRetries})`),this.connection.reconnect({reconnectionToken:this.reconnectionToken.split(":")[1],skipHandshake:!0})}catch{this.retryReconnection()}},e)}};Qa=new WeakMap,mi=new WeakMap,yi=new WeakMap,lr=new WeakMap,dr=new WeakMap,gi=new WeakMap,fr=new WeakSet,e0=function(){let e=le(this,yi);return He(this,yi,le(this,yi)+1>>>0),e},t0=function(e,n,r){let s={offset:1};this.sharedBuffer[0]=Ke.ROOM_REQUEST,Se.number(this.sharedBuffer,e,s),typeof n=="string"?Se.string(this.sharedBuffer,n,s):Se.number(this.sharedBuffer,n,s);let o=s.offset;if(r!==void 0){let i=this.packr.pack(r,fi|o);return i.set(this.sharedBuffer.subarray(0,o),0),i}return this.sharedBuffer.subarray(0,o)},n0=function(e){if(le(this,lr).size!==0){for(let n of le(this,lr).values())n.onClose?.(e);le(this,lr).clear()}},r0=function(e){var o;let n={offset:1},r=e[0],s=r&Vf;if(r&Zo.TIMED){let i=Ae.uint32(e,n),a=Ae.uint32(e,n),c=le(this,dr)?le(this,dr).ackInput(a):-1;this.clock.sample(i,c)}if(s===Ke.JOIN_ROOM){let i=Ae.utf8Read(e,n,e[n.offset++]);if(this.serializerId=Ae.utf8Read(e,n,e[n.offset++]),!this.serializer){let u=Mp(this.serializerId);this.serializer=new u}let a=Ae.number(e,n);if(a>0&&this.serializer.handshake){let u=n.offset+a;this.serializer.handshake(e.subarray(0,u),n),n.offset=u}for(;n.offset<e.byteLength;){let u=e[n.offset++],l=Ae.number(e,n),d=n.offset+l;u===Ou.INPUT_REFLECTION?(le(this,dr)??He(this,dr,new ui(this))).applyReflection(e,n,d):u===Ou.INPUT_OPTIONS&&(le(this,dr)??He(this,dr,new ui(this))).applyOptions(e,n),n.offset=d}let c=le(this,dr)?.patchRate;if(c!==void 0&&this.clock.setPatchInterval?.(c),this.joinedAtTime===0?(this.joinedAtTime=Date.now(),this.onJoin.invoke()):(console.info(`[Colyseus reconnection]: ${String.fromCodePoint(9989)} reconnection successful!`),this.reconnection.isReconnecting=!1,this.onReconnect.invoke()),this.reconnectionToken=`${this.roomId}:${i}`,this.sharedBuffer[0]=Ke.JOIN_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1)),this.reconnection.enqueuedMessages.length>0){for(let u of this.reconnection.enqueuedMessages)this.connection.send(u.data);this.reconnection.enqueuedMessages=[]}}else if(s===Ke.ERROR){let i=Ae.number(e,n),a=Ae.string(e,n);this.onError.invoke(i,a)}else if(s===Ke.LEAVE_ROOM)this.leave();else if(s===Ke.ROOM_STATE)He(this,gi,0),this.serializer.setState(e,n),this.onStateChange.invoke(this.serializer.getState());else if(s===Ke.ROOM_STATE_PATCH){if(r&Zo.UNRELIABLE){let i=Ae.uint16(e,n);if(i-le(this,gi)<<16>>16<=0)return;He(this,gi,i)}this.serializer.patch(e,n),this.onStateChange.invoke(this.serializer.getState())}else if(s===Ke.ROOM_DATA){let i=Ae.stringCheck(e,n)?Ae.string(e,n):Ae.number(e,n),a=e.byteLength>n.offset?ml(e,{start:n.offset}):void 0;this.dispatchMessage(i,a)}else if(s===Ke.ROOM_DATA_BYTES){let i=Ae.stringCheck(e,n)?Ae.string(e,n):Ae.number(e,n);this.dispatchMessage(i,e.subarray(n.offset))}else if(s===Ke.ROOM_RESPONSE){let i=Ae.number(e,n),a=e[n.offset++],c=e.byteLength>n.offset?ml(e,{start:n.offset}):void 0,u=le(this,lr).get(i);u!==void 0&&(le(this,lr).delete(i),u.onReply(a===Cu.OK,c,a===Cu.ERROR))}else s===Ke.PING&&((o=le(this,mi))==null||o.call(this,Math.round(Mt()-le(this,Qa))),He(this,mi,void 0))},m(Rl,"defaultRequestTimeout",1e4);var Za=Rl;function s0(t,e){return new Promise((n,r)=>{let s=new XMLHttpRequest,o=e?.method||"GET";s.open(o,t.toString()),s.withCredentials=e?.credentials==="include",e?.headers&&(e.headers instanceof Headers?e.headers:new Headers(e.headers)).forEach((a,c)=>{s.setRequestHeader(c,a)}),s.onload=()=>{let i=new Headers,a=s.getAllResponseHeaders().trim();if(a)for(let u of a.split(/[\r\n]+/)){let l=u.indexOf(": ");l>0&&i.append(u.substring(0,l),u.substring(l+2))}let c=s.response??s.responseText;n(new Op(c,{status:s.status,statusText:s.statusText,headers:i}))},s.onerror=()=>r(new TypeError("Network request failed")),s.ontimeout=()=>r(new TypeError("Network request timed out")),s.send(e?.body??null)})}var Op=class{constructor(e,n){m(this,"status");m(this,"statusText");m(this,"headers");m(this,"ok");m(this,"body");this.body=e,this.status=n.status,this.statusText=n.statusText,this.headers=n.headers,this.ok=n.status>=200&&n.status<300}async json(){return typeof this.body=="string"?JSON.parse(this.body):this.body}async text(){return typeof this.body=="string"?this.body:JSON.stringify(this.body)}async blob(){return new Blob([this.body])}};function ZP(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function QP(t,e){let{params:n,query:r}=e||{},[s,o]=t.split("?"),i=s;if(n)if(Array.isArray(n)){let u=i.split("/").filter(l=>l.startsWith(":"));for(let[l,d]of u.entries()){let f=n[l];i=i.replace(d,f)}}else for(let[u,l]of Object.entries(n))i=i.replace(`:${u}`,String(l));let a=new URLSearchParams(o);if(r)for(let[u,l]of Object.entries(r))l!=null&&a.set(u,String(l));let c=a.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",`${i}${c}`}var El=class{constructor(e,n,r){m(this,"authToken");m(this,"options");m(this,"sdk");m(this,"_fetchFn");m(this,"del",this.delete);this.sdk=e,this.options=n,this._fetchFn=r}get fetchFn(){return this._fetchFn||(this._fetchFn=typeof globalThis.fetch<"u"?globalThis.fetch.bind(globalThis):s0),this._fetchFn}async request(e,n,r){return this.executeRequest(e,n,r)}get(e,n){return this.request("GET",e,n)}post(e,n){return this.request("POST",e,n)}delete(e,n){return this.request("DELETE",e,n)}patch(e,n){return this.request("PATCH",e,n)}put(e,n){return this.request("PUT",e,n)}async executeRequest(e,n,r){let s=this.options.body?{...this.options.body,...r?.body||{}}:r?.body,o=this.options.query?{...this.options.query,...r?.query||{}}:r?.query,i=this.options.params?{...this.options.params,...r?.params||{}}:r?.params,a=new Headers(this.options.headers?{...this.options.headers,...r?.headers||{}}:r?.headers);if(this.authToken&&!a.has("authorization")&&a.set("authorization",`Bearer ${this.authToken}`),ZP(s)&&typeof s=="object"&&s!==null){a.has("content-type")||a.set("content-type","application/json");for(let[h,p]of Object.entries(s))p instanceof Date&&(s[h]=p.toISOString());s=JSON.stringify(s)}let c={credentials:r?.credentials||"include",...this.options,...r,query:o,params:i,headers:a,body:s,method:e},u=QP(this.sdk.getHttpEndpoint(n.toString()),c),l;try{l=await this.fetchFn(u,c)}catch(h){if(h.name==="AbortError")throw h;let p=new tr(h.cause?.code||h.code,h.message);throw p.response=l,p.cause=h.cause,p}let d=l.headers.get("content-type"),f;if(d?.includes("json")?f=await l.json():d?.includes("text")?f=await l.text():f=await l.blob(),!l.ok)throw new tr(l.status,f.message??f.error??l.statusText,{headers:l.headers,status:l.status,response:l,data:f});return{raw:l,data:f,headers:l.headers,status:l.status,statusText:l.statusText}}};var to;function Dp(){if(!to)try{to=typeof cc<"u"&&cc.sys&&cc.sys.localStorage?cc.sys.localStorage:window.localStorage}catch{}return!to&&typeof globalThis.indexedDB<"u"&&(to=new Ip),to||(to={cache:{},setItem:function(t,e){this.cache[t]=e},getItem:function(t){return this.cache[t]},removeItem:function(t){delete this.cache[t]}}),to}function o0(t,e){Dp().setItem(t,e)}function i0(t){Dp().removeItem(t)}function a0(t,e){let n=Dp().getItem(t);typeof Promise>"u"||!(n instanceof Promise)?e(n):n.then(r=>e(r))}var Ip=class{constructor(){m(this,"dbPromise",new Promise(e=>{let n=indexedDB.open("_colyseus_storage",1);n.onupgradeneeded=()=>n.result.createObjectStore("store"),n.onsuccess=()=>e(n.result)}))}async tx(e,n){let s=(await this.dbPromise).transaction("store",e).objectStore("store");return n(s)}setItem(e,n){return this.tx("readwrite",r=>r.put(n,e)).then()}async getItem(e){let n=await this.tx("readonly",r=>r.get(e));return new Promise(r=>{n.onsuccess=()=>r(n.result)})}removeItem(e){return this.tx("readwrite",n=>n.delete(e)).then()}};var tc,Dr,nc,ec=class{constructor(e){m(this,"settings",{path:"/auth",key:"colyseus-auth-token"});Ve(this,tc,!1);Ve(this,Dr,null);Ve(this,nc,xl());m(this,"http");this.http=e,a0(this.settings.key,n=>this.token=n)}set token(e){this.http.authToken=e}get token(){return this.http.authToken}onChange(e){let n=le(this,nc).on("change",e);return le(this,tc)||this.getUserData().then(r=>{this.emitChange({...r,token:this.token})}).catch(r=>{this.emitChange({user:null,token:void 0})}),He(this,tc,!0),n}async getUserData(){if(this.token)return(await this.http.get(`${this.settings.path}/userdata`)).data;throw new Error("missing auth.token")}async registerWithEmailAndPassword(e,n,r){let s=(await this.http.post(`${this.settings.path}/register`,{body:{email:e,password:n,options:r}})).data;return this.emitChange(s),s}async signInWithEmailAndPassword(e,n){let r=(await this.http.post(`${this.settings.path}/login`,{body:{email:e,password:n}})).data;return this.emitChange(r),r}async signInAnonymously(e){let n=(await this.http.post(`${this.settings.path}/anonymous`,{body:{options:e}})).data;return this.emitChange(n),n}async sendPasswordResetEmail(e){return(await this.http.post(`${this.settings.path}/forgot-password`,{body:{email:e}})).data}async signInWithProvider(e,n={}){return new Promise((r,s)=>{let o=n.width||480,i=n.height||768,a=this.token?`?token=${this.token}`:"",c=`Login with ${e[0].toUpperCase()+e.substring(1)}`,u=this.http.sdk.getHttpEndpoint(`${n.prefix||`${this.settings.path}/provider`}/${e}${a}`),l=screen.width/2-o/2,d=screen.height/2-i/2;He(this,Dr,window.open(u,c,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+o+", height="+i+", top="+d+", left="+l));let f=p=>{if(!(p.data.user===void 0&&p.data.token===void 0))if(clearInterval(h),le(this,Dr)?.close(),He(this,Dr,null),window.removeEventListener("message",f),p.data.error!==void 0){let y=new Error(String(p.data.error));y.code=p.data.error,p.data.reason!==void 0&&(y.reason=p.data.reason),p.data.until!==void 0&&(y.until=p.data.until),s(y)}else r(p.data),this.emitChange(p.data)},h=setInterval(()=>{(!le(this,Dr)||le(this,Dr).closed)&&(He(this,Dr,null),s("cancelled"),window.removeEventListener("message",f))},200);window.addEventListener("message",f)})}async signOut(){this.emitChange({user:null,token:null})}emitChange(e){e.token!==void 0&&(this.token=e.token,e.token===null?i0(this.settings.key):o0(this.settings.key,e.token)),le(this,nc).emit("change",e)}};tc=new WeakMap,Dr=new WeakMap,nc=new WeakMap;function c0(t){let e=window?.location?.hostname||"localhost",n=t.hostname.split("."),r=!t.hostname.includes("trycloudflare.com")&&!t.hostname.includes("discordsays.com")&&n.length>2?`/${n[0]}`:"";return t.pathname.startsWith("/.proxy")?`${t.protocol}//${e}${r}${t.pathname}${t.search}`:`${t.protocol}//${e}/.proxy/colyseus${r}${t.pathname}${t.search}`}Da();var u0=typeof window<"u"&&typeof window?.location?.hostname<"u"?`${window.location.protocol.replace("http","ws")}//${window.location.hostname}${window.location.port&&`:${window.location.port}`}`:"ws://127.0.0.1:2567",Al=class Al{constructor(e=u0,n){m(this,"http");m(this,"auth");m(this,"settings");m(this,"urlBuilder");if(typeof e=="string"){let r=e.startsWith("/")?new URL(e,u0):new URL(e),s=r.protocol==="https:"||r.protocol==="wss:",o=Number(r.port||(s?443:80));this.settings={hostname:r.hostname,pathname:r.pathname,port:o,secure:s,searchParams:r.searchParams.toString()||void 0}}else e.port===void 0&&(e.port=e.secure?443:80),e.pathname===void 0&&(e.pathname=""),this.settings=e;this.settings.pathname.endsWith("/")&&(this.settings.pathname=this.settings.pathname.slice(0,-1)),n?.protocol&&(this.settings.protocol=n.protocol),this.http=new El(this,{headers:n?.headers||{}},n?.fetchFn),this.auth=new ec(this.http),this.urlBuilder=n?.urlBuilder,!this.urlBuilder&&typeof window<"u"&&window?.location?.hostname?.includes("discordsays.com")&&(this.urlBuilder=c0,console.log("Colyseus SDK: Discord Embedded SDK detected. Using custom URL builder."))}static async selectByLatency(e,n,r={}){let s=e.map(i=>new Al(i,n)),o=(await Promise.allSettled(s.map((i,a)=>i.getLatency(r).then(c=>{let u=s[a].settings;return console.log(`\u{1F6DC} Endpoint Latency: ${c}ms - ${u.hostname}:${u.port}${u.pathname}`),[a,c]})))).filter(i=>i.status==="fulfilled").map(i=>i.value);if(o.length===0)throw new Error("All endpoints failed to respond");return s[o.sort((i,a)=>i[1]-a[1])[0][0]]}async joinOrCreate(e,n={},r){return await this.createMatchMakeRequest("joinOrCreate",e,n,r)}async create(e,n={},r){return await this.createMatchMakeRequest("create",e,n,r)}async join(e,n={},r){return await this.createMatchMakeRequest("join",e,n,r)}async joinById(e,n={},r){return await this.createMatchMakeRequest("joinById",e,n,r)}async reconnect(e,n){if(typeof e=="string"&&typeof n=="string")throw new Error("DEPRECATED: .reconnect() now only accepts 'reconnectionToken' as argument.\nYou can get this token from previously connected `room.reconnectionToken`");let[r,s]=e.split(":");if(!r||!s)throw new Error(`Invalid reconnection token format.
|
|
13
|
-
The format should be roomId:reconnectionToken`);return await this.createMatchMakeRequest("reconnect",r,{reconnectionToken:s},n)}async consumeSeatReservation(e,n){let r=this.createRoom(e.name,n);r.roomId=e.roomId,r.sessionId=e.sessionId;let s={sessionId:r.sessionId};return e.reconnectionToken&&(s.reconnectionToken=e.reconnectionToken),r.connect(this.buildEndpoint(e,s),{...e,protocol:this.settings.protocol},this.http.options.headers),new Promise((o,i)=>{let a=(c,u)=>i(new tr(c,u));r.onError.once(a),r.onJoin.once(()=>{r.onError.remove(a),ol("room",r),o(r)})})}getLatency(e={}){let n=e.protocol??"ws",r=e.pingCount??1,s=e.timeout??1500;return new Promise((o,i)=>{let a=new pi(n),c=[],u=0,l=!1,d,f=p=>{if(!l){l=!0,clearTimeout(d);try{a.close()}catch{}p()}},h=p=>f(()=>i(new tr(wt.ABNORMAL_CLOSURE,`Failed to get latency: ${p}`)));d=setTimeout(()=>h(`timed out after ${s}ms`),s),a.events.onopen=()=>{u=Date.now(),a.send(new Uint8Array([Ke.PING]))},a.events.onmessage=p=>{if(c.push(Date.now()-u),c.length<r)u=Date.now(),a.send(new Uint8Array([Ke.PING]));else{let y=c.reduce((S,w)=>S+w,0)/c.length;f(()=>o(y))}},a.events.onclose=p=>h(`connection closed${p?.code?` (${p.code})`:""}${p?.reason?`: ${p.reason}`:""}`),a.events.onerror=p=>h(p.message);try{a.connect(this.getHttpEndpoint())}catch(p){h(p?.message??"failed to connect")}})}async createMatchMakeRequest(e,n,r={},s){try{if(!n)throw new Error("Must provide a room name");let i=(await this.http.post(`/matchmake/${e}/${n}`,{headers:{Accept:"application/json","Content-Type":"application/json"},body:r})).data;return e==="reconnect"&&(i.reconnectionToken=r.reconnectionToken),await this.consumeSeatReservation(i,s)}catch(o){throw o instanceof tr?new wa(o.message,o.code):o}}createRoom(e,n){return new Za(e,n)}buildEndpoint(e,n={}){let r=this.settings.protocol||"ws",s=this.settings.searchParams||"";this.http.authToken&&(n._authToken=this.http.authToken);for(let a in n)n.hasOwnProperty(a)&&(s+=(s?"&":"")+`${a}=${n[a]}`);r==="h3"&&(r="http");let o=this.settings.secure?`${r}s://`:`${r}://`;e.publicAddress?o+=`${e.publicAddress}`:o+=`${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}`;let i=`${o}/${e.processId}/${e.roomId}?${s}`;return this.urlBuilder?this.urlBuilder(new URL(i)):i}getHttpEndpoint(e=""){let n=e.startsWith("/")?e:`/${e}`,r=`${this.settings.secure?"https":"http"}://${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}${n}`;return this.settings.searchParams&&(r+=`?${this.settings.searchParams}`),this.urlBuilder?this.urlBuilder(new URL(r)):r}getEndpointPort(){return this.settings.port!==80&&this.settings.port!==443?`:${this.settings.port}`:""}};m(Al,"VERSION","0.18");var kl=Al,Nr=kl;Ar();var Pl=class{setState(e){}getState(){return null}patch(e){}teardown(){}handshake(e){}};At();$p();Ol();Il();Cl();vp("schema",hi);vp("none",Pl);var Y2=Object.freeze({min:3,max:3}),K2=Object.freeze({min:4,max:4});var co={PLAY:"play",QUEUE:"queue",MATCH:"match",AUTHORITY:"authority"};var jp={CAPS:"caps",SDK:"sdk",MATCH_KEY:"matchKey",PRIVATE:"private",SUCCESSOR_OF:"successorOf",SUCCESSOR_CLOSED:"successorClosed"},E0="ts/0.17.8",ln={PHYSICS:"physics@1",PHYSICS_PREDICT:"physics@2",INPUT_REPEAT:"repeat@1",LIFTS:"lifts@1",INPUT_TICK:"tick@1",FAST:"fast@1",FAST_RETURN:"fast-return@1",MAX_CAPS:16,MAX_CAP_CHARS:32};var cT=["clients","preset","winCondition","config","matchmade"],X2=[...cT,"moduleSha","tickHz","maxPlayers","lagComp","seed","units","leaseId","region","createdBy"],_n={BAD_OPTION:400,AUTH_REQUIRED:401,FORBIDDEN:403,WRONG_REGION:421,PROTOCOL_UNSUPPORTED:426,NOT_ENTITLED:402,ROOM_QUOTA:429,MODULE_UNAVAILABLE:424,AUTHORITY_CAPACITY:503};var pe={STATE:"state",STATE_SNAP:"__state:snap",SHARED:"shared",CLAIM:"claim",RELEASE:"release",DESTROY:"destroy",OBJECT:"obj",OBJECT_SNAP:"__object:snap",INPUT:"__input",ROOM_OPEN:"__room:open",CHAT:"__chat",CHAT_HISTORY_REQUEST:"__chat:history:request",VOICE_ICE_REQUEST:"__voice:ice:request",VOICE_JOIN:"__voice:join",VOICE_LEAVE:"__voice:leave",VOICE_SIGNAL:"__voice:signal",MATCH_ELIMINATED:"match:eliminated",MATCH_SCORE:"match:score",MATCH_FINISH:"match:finish",POSE:"__pose",POSE_SNAP:"__pose:snap"},xe={OBJECT_RESULT:"__object:result",INPUT:"__input",ROOM_OPEN:"__room:open",CHAT:"__chat",CHAT_HISTORY:"__chat:history",VOICE_ICE:"__voice:ice",VOICE_SIGNAL:"__voice:signal",VOICE_REJECTED:"__voice:rejected",RATE_DROP:"rate:drop",SERVER_RESTART:"server:restart",MATCH_START:"match:start",MATCH_ENDED:"match:ended",MATCH_REQUEUE:"match:requeue",QUEUE:"queue",SEAT:"seat"},uT=["__","match:","server:","rate:"],lT=["state","shared","claim","release","destroy","obj","queue","seat"];function bs(t){return lT.includes(t)||uT.some(e=>t.startsWith(e))}var zl="__",hr="__t";var J2=4*1024;var Z2={[pe.STATE]:"state",[pe.STATE_SNAP]:"state",[pe.SHARED]:"bulk",[pe.CLAIM]:"control",[pe.RELEASE]:"control",[pe.DESTROY]:"control",[pe.OBJECT]:"bulk",[pe.OBJECT_SNAP]:"bulk",[pe.INPUT]:"input",[pe.ROOM_OPEN]:"control",[pe.CHAT]:"chat",[pe.CHAT_HISTORY_REQUEST]:"control",[pe.VOICE_ICE_REQUEST]:"voice",[pe.VOICE_JOIN]:"voice",[pe.VOICE_LEAVE]:"voice",[pe.VOICE_SIGNAL]:"voice",[pe.MATCH_ELIMINATED]:"bulk",[pe.MATCH_SCORE]:"bulk",[pe.MATCH_FINISH]:"bulk",[pe.POSE]:"pose",[pe.POSE_SNAP]:"pose"},dn={GOING_AWAY:1001,NO_STATUS:1005,ABNORMAL:1006,MAY_TRY_RECONNECT:4010,NORMAL:1e3,CONSENTED:4e3,MATCH_BOOT:4e3,SERVER_SHUTDOWN:4001,WITH_ERROR:4002,FAILED_TO_RECONNECT:4003,REVOKED:4401,SUPERSEDED:4409,IDLE:4408,MODULE_HALTED:4500,MODULE_FAULT:4501},dT={ModuleTimeout:"module_timeout",ModuleMemory:"module_memory",ModuleError:"module_error",ModuleOutputInvalid:"module_output_invalid",ModuleBudget:"module_budget",Halted:"halted",HostStall:"host_stall",PhysicsBudget:"physics_budget",RoomAge:"room_age",ModuleBandwidth:"module_bandwidth",PhysicsInternal:"physics_internal"};function k0(t){return Object.values(dT).includes(t)?t:null}var Yt={ROOM_MAX_CLIENTS:64,MAX_NAME_CHARS:64,MAX_AVATAR_URL_CHARS:512,MAX_UID_CHARS:64,MAX_STATE_BYTES:16*1024,MAX_SHARED_KEY_CHARS:256,MAX_SHARED_VALUE_BYTES:64*1024,MAX_SHARED_KEYS:256,MAX_OBJECT_ID_CHARS:128,MAX_OBJECT_STATE_BYTES:64*1024,MAX_OBJECTS:128,MAX_REQUEST_ID_CHARS:96,MAX_EVENT_BYTES:16*1024,MAX_EVENT_TYPE_CHARS:128,MAX_JSON_DEPTH:32,MAX_JSON_NODES:4096,MAX_CHAT_CHARS:500,CHAT_HISTORY_MAX:50,CHAT_HISTORY_MAX_BYTES:8*1024,MAX_VOICE_PARTICIPANTS:6,MAX_VOICE_SIGNAL_BYTES:8*1024,MAX_SCORE_DELTA:1e3,CONTROL_RESULTS_PER_SESSION:128,CONTROL_RESULT_TTL_MS:6e4,MAX_TEAMS:8,MAX_ANIM_CHARS:64,MAX_POSE_ABS:1e9},Q2={PATCH_INTERVAL_MS:1e3/30,RECONNECT_GRACE_S:30,GOING_AWAY_GRACE_S:5,HOST_FAILOVER_GRACE_MS:1500,MIN_OWNERSHIP_HOLD_MS:300,SHUTDOWN_DRAIN_MS:3e3,REQUEUE_GRACE_MS:5e3,SEAT_RESERVATION_S:15,QUEUE_TICK_MS:1e3,REVOCATION_SWEEP_MS:3e4},ws={TICK_HZ:30,RENDER_DELAY_MS:100,MAX_REWIND_MS:500,INPUT_BUFFER:32,PATCH_INTERVAL_MS:50,INPUT_REPEAT_MAX_MS:100,INPUT_REPEAT_RUN_MS:33},fn={enabled:!0,minUptime:0,delay:125,minDelay:100,maxDelay:4e3,maxRetries:9,maxEnqueuedMessages:0,firstStateTimeoutMs:2e3},A0=["x","y","z","yaw","vx","vy","vz","anim"],qe={RATIO:1.5,JITTER_SAFETY:1.25,MIN_MS:90,MAX_MS:300,DEFAULT_MS:100,EASE:.1,CLOCK_WINDOW:80,CLOCK_WINDOW_MS:5e3,CLOCK_WINDOW_MAX:4096,INTERVAL_WINDOW:30,MIN_GAP_MS:5,MAX_GAP_MS:2e3,HISTORY_MS:1500,MAX_EXTRAP_MS:250,ROT_EXTRAP_MS:150,SMOOTH_TAU_POS_MS:30,SMOOTH_TAU_ROT_MS:70,POISON_GUARD_MS:2e3,REBASE_AFTER_GAP_MS:1e3,MAX_HOST_TICK_DT_MS:250},Lr={HEARTBEAT_HZ:10,MIN_HEARTBEAT_HZ:5,MAX_HEARTBEAT_HZ:20,HEARTBEAT_DITHER:.15,RELAY_BUFFER:4,WARMUP_ACKS:30};var uo={SAMPLES:3,TIMEOUT_MS:4e3,GRACE_MS:1e3};async function P0(t,e={}){let n=t[0];if(n===void 0)throw new Error("genex multiplayer: `urls` must contain at least one relay URL");if(t.length===1)return n;let r=e.probe??Wp,s=Math.max(1,e.samples??uo.SAMPLES),o=e.timeoutMs??uo.TIMEOUT_MS,i=e.graceMs??uo.GRACE_MS,a=t.map(()=>{});await new Promise(u=>{let l=t.length*s,d,f=setTimeout(h,o);function h(){clearTimeout(f),clearTimeout(d),u()}let p=()=>{--l===0&&h()};t.forEach((y,S)=>{for(let w=0;w<s;w++){let x;try{x=r(y,o)}catch(R){x=Promise.reject(R)}x.then(R=>{Number.isFinite(R)&&R>=0&&(a[S]=Math.min(a[S]??1/0,R),d??(d=setTimeout(h,i))),p()},p)}})});let c=-1;return a.forEach((u,l)=>{u!==void 0&&(c<0||u<a[c])&&(c=l)}),c<0?(console.warn(`genex multiplayer: no relay answered the latency probe \u2014 connecting to ${n}`),n):t[c]}var Wp=(t,e)=>new Nr(t).getLatency({pingCount:1,timeout:e});var fT=t=>typeof t=="function"?t():t;async function lc(t){return t.url?new Nr(t.url):new Nr(await P0(t.urls))}function dc(t,e,n){return{gameId:t,name:e,embedToken:fT(n)?.embedToken,protocol:3}}var fc=t=>!!t&&typeof t=="object"&&t.code===_n.PROTOCOL_UNSUPPORTED,qp=()=>console.error(`[multiplayer] the relay refused protocol ${3} (code 426) \u2014 this game was built with a @genex-ai/multiplayer that this relay no longer serves. Update the package and republish.`),T0=t=>{throw fc(t)&&qp(),t};function v0(t,e){let n=null,r=null;return{request(){return n||(n=new Promise(s=>{let o,i=a=>{r&&(r=null,n=null,o&&clearTimeout(o),s(a))};r=i,o=setTimeout(()=>i(null),e),t()}),n)},deliver(s){r?.(s)},get pending(){return n!==null}}}var M0=["x","y","z","yaw","vx","vy","vz"],C0=[["x","vx"],["y","vy"],["z","vz"]],Gp=Math.PI*2,pT=t=>A0.includes(t);function Yp(t){if(!Number.isFinite(t))return 0;let e=t%Gp;return e<=-Math.PI?e+=Gp:e>Math.PI&&(e-=Gp),e}var O0=t=>typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=Yt.MAX_POSE_ABS;function I0(t){let e={},n={},r=[];for(let s of Object.keys(t)){let o=t[s];if(!pT(s)){n[s]=o;continue}o!==void 0&&(s==="anim"?typeof o=="string"&&o.length<=Yt.MAX_ANIM_CHARS?e.anim=o:r.push(s):O0(o)?e[s]=o:r.push(s))}return{pose:e,data:n,invalid:r}}function D0(t){for(let e in t)if(t[e]!==void 0)return!0;return!1}function N0(t,e,n){let r={...t},s={t:e},o=n?e-n.t:0,i=n!==void 0&&o>qe.MIN_GAP_MS&&o<qe.MAX_GAP_MS;for(let[a,c]of C0){let u=t[a];if(u===void 0||(s[a]=u,t[c]!==void 0))continue;let l=n?.[a],d=i&&l!==void 0?(u-l)/o*1e3:0;r[c]=O0(d)?d:0}return{pose:r,memory:s}}function $l(t){let e=n=>typeof n=="number"&&Number.isFinite(n)?n:0;return{x:e(t.x),y:e(t.y),z:e(t.z),yaw:e(t.yaw),vx:e(t.vx),vy:e(t.vy),vz:e(t.vz),anim:typeof t.anim=="string"?t.anim:""}}var Mi=(t,e)=>{let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0};function B0(t,e){let n=t.length;if(n===0)return;let r=0;for(;r<n&&t[r].t<=e;)r++;if(r===0)return t[0].state;if(r>=n){let u=t[n-1],l={...u.state},d=Math.min(Math.max(0,e-u.t),qe.MAX_EXTRAP_MS)/1e3;for(let[f,h]of C0)l[f]=Mi(u.state,f)+Mi(u.state,h)*d;if(n>=2){let f=t[n-2],h=u.t-f.t;if(h>0){let p=Math.min(Math.max(0,e-u.t),qe.ROT_EXTRAP_MS)/h,y=Mi(u.state,"yaw");l.yaw=y+Yp(y-Mi(f.state,"yaw"))*p}}return l}let s=t[r-1],o=t[r],i=o.t-s.t,a=i>0?(e-s.t)/i:1,c={...s.state};for(let u of M0){let l=Mi(s.state,u),d=Mi(o.state,u);c[u]=u==="yaw"?l+Yp(d-l)*a:l+(d-l)*a}return c}function L0(t,e,n,r){let s={...e};for(let o of M0){let i=t[o],a=e[o];typeof i!="number"||typeof a!="number"||!Number.isFinite(i)||!Number.isFinite(a)||(s[o]=o==="yaw"?i+Yp(a-i)*r:i+(a-i)*n)}return s}var Hl=class Hl{constructor(){m(this,"pending",[]);m(this,"current")}push(e,n){for(this.pending.push({t:e,state:n});this.pending.length>Hl.MAX_PENDING;)this.current=this.pending.shift()?.state}at(e){for(;this.pending.length>0;){let n=this.pending[0];if(this.current!==void 0&&e!==void 0&&n.t!==void 0&&n.t>e)break;this.current=n.state,this.pending.shift()}return this.current}flush(){this.at(void 0)}};m(Hl,"MAX_PENDING",64);var Vl=Hl;function F0(t){try{let e=t.input();return e&&typeof e.send=="function"?e:null}catch{return null}}function z0(t,e,n=Lr.HEARTBEAT_HZ,r=Math.random){let o=1e3/Math.min(Lr.MAX_HEARTBEAT_HZ,Math.max(Lr.MIN_HEARTBEAT_HZ,n)),i=1e3/Lr.MAX_HEARTBEAT_HZ,a=1e3/Lr.MIN_HEARTBEAT_HZ,c=!1,u=!1,l,d=()=>{if(u)return;if(e()){try{t.send()}catch{}!c&&t.lastProcessed>=Lr.WARMUP_ACKS&&(c=!0)}let f=o*(1+(r()*2-1)*Lr.HEARTBEAT_DITHER);l=setTimeout(d,Math.min(a,Math.max(i,f)))};return d(),{get synced(){return!c&&t.lastProcessed>=Lr.WARMUP_ACKS&&(c=!0),c},stop(){u=!0,l&&clearTimeout(l)}}}function U0(t,e){return e.synced&&e.clockOrigin>0&&e.serverNow!==void 0&&Number.isFinite(e.serverNow)?t-e.clockOrigin-e.serverNow:t-e.wallNow}function Ss(t){let e=t.reconnection;return e.enabled=fn.enabled,e.minUptime=fn.minUptime,e.delay=fn.delay,e.minDelay=fn.minDelay,e.maxDelay=fn.maxDelay,e.maxRetries=fn.maxRetries,e.maxEnqueuedMessages=fn.maxEnqueuedMessages,e.enqueuedMessages.length=0,t}function V0(t){return t.reconnection.enabled=!1,t}function pc(t,e){return new Promise(n=>{let r=()=>{clearTimeout(s),n(!0)},s=setTimeout(()=>{t.onStateChange.remove(r),n(!1)},e);t.onStateChange.once(r)})}function H0(t,e,n){return t!==e&&n!=null}var hT="The microphone was refused by the page that frames this game, not by the player: the frame was not given it, so the browser never asked. On its Genex page a build is given the microphone only when it declares it. An up-to-date genex CLI declares it at `genex preview` and `genex publish` when the game's own source calls voice.join(); to declare it by hand, add \"microphone\" to genex.capabilities in the game's package.json. Then preview or publish again.",Kp=class extends Error{constructor(e){super(hT,{cause:e}),this.name="VoiceNotDelegatedError"}},$0=[{urls:"stun:stun.l.google.com:19302"}],mT=120,j0=.02,yT=.6,jl=class{constructor(e){m(this,"transport");m(this,"peers",new Map);m(this,"listeners",new Set);m(this,"roster",[]);m(this,"local",null);m(this,"audio",null);m(this,"localAnalyser",null);m(this,"levelTimer",null);m(this,"iceServers",$0);m(this,"spatial",!1);m(this,"threshold",j0);m(this,"micOn",!0);m(this,"selfSpeaking",!1);m(this,"running",!1);m(this,"peeringHeld",!1);this.transport=e}get active(){return this.running}get micEnabled(){return this.micOn}get speaking(){return this.selfSpeaking}get participants(){return[...this.peers.values()].map(e=>({id:e.id,name:this.transport.nameOf(e.id),stream:e.stream,speaking:e.speaking,muted:e.muted,volume:e.volume,connection:e.connection}))}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async start(e={},n=!1){if(!this.running){this.peeringHeld=n,this.iceServers=e.iceServers?.length?e.iceServers:$0,this.spatial=e.spatial===!0,this.threshold=e.speakingThreshold??j0,this.micOn=e.startMuted!==!0;try{this.local=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1})}catch(r){throw bT(r)}for(let r of this.local.getAudioTracks())r.enabled=this.micOn;this.audio=new AudioContext,this.localAnalyser=this.makeAnalyser(this.local),this.running=!0,this.levelTimer=setInterval(()=>this.pollLevels(),mT)}}stop(){this.running=!1,this.peeringHeld=!1,this.levelTimer&&(clearInterval(this.levelTimer),this.levelTimer=null);for(let e of[...this.peers.keys()])this.destroyPeer(e);for(let e of this.local?.getTracks()??[])e.stop();this.local=null,this.localAnalyser=null,this.audio?.close().catch(()=>{}),this.audio=null,this.roster=[],this.selfSpeaking=!1,this.emit()}setIceServers(e){if(e.length){this.iceServers=e;for(let n of this.peers.values())try{n.pc.setConfiguration({iceServers:e})}catch{}}}releasePeering(){this.peeringHeld&&(this.peeringHeld=!1,this.setRoster(this.roster))}setRoster(e){if(this.roster=e,!this.running||this.peeringHeld)return;let n=this.transport.selfId(),r=new Set(e.filter(s=>s!==n));for(let s of r)this.peers.has(s)||this.createPeer(s);for(let s of[...this.peers.keys()])r.has(s)||this.destroyPeer(s);this.emit()}setMicEnabled(e){this.micOn=e;for(let n of this.local?.getAudioTracks()??[])n.enabled=e;!e&&this.selfSpeaking&&(this.selfSpeaking=!1,this.emit())}mute(e){this.setMuted(e,!0)}unmute(e){this.setMuted(e,!1)}setVolume(e,n){let r=this.peers.get(e);r&&(r.volume=Math.max(0,Math.min(1,n)),r.el&&(r.el.volume=r.volume),this.emit())}async handleSignal(e,n){if(!this.running)return;let r=n;if(!r||typeof r!="object"||typeof r.t!="string")return;let s=this.peers.get(e)??(this.roster.includes(e)?this.createPeer(e):void 0);if(s)try{if(r.t==="offer"){await s.pc.setRemoteDescription(r.sdp),await this.flushIce(s);let o=await s.pc.createAnswer();await s.pc.setLocalDescription(o),this.transport.sendSignal(e,{t:"answer",sdp:o})}else if(r.t==="answer"){if(s.pc.signalingState!=="have-local-offer")return;await s.pc.setRemoteDescription(r.sdp),await this.flushIce(s)}else r.t==="ice"&&(s.pc.remoteDescription?await s.pc.addIceCandidate(r.c):s.pendingIce.push(r.c))}catch(o){console.warn(`[multiplayer] voice signaling failed with ${e}`,o)}}setMuted(e,n){let r=this.peers.get(e);!r||r.muted===n||(r.muted=n,r.el&&(r.el.muted=n||this.spatial),n&&r.speaking&&(r.speaking=!1),this.emit())}createPeer(e){let n=new RTCPeerConnection({iceServers:this.iceServers}),r={id:e,pc:n,el:null,stream:null,analyser:null,pendingIce:[],speaking:!1,muted:!1,volume:1,connection:"connecting"};this.peers.set(e,r);for(let s of this.local?.getAudioTracks()??[])this.local&&n.addTrack(s,this.local);return n.onicecandidate=s=>{s.candidate&&this.transport.sendSignal(e,{t:"ice",c:s.candidate.toJSON()})},n.ontrack=s=>{let o=s.streams[0]??new MediaStream([s.track]);r.stream=o,r.el=this.attachSink(o,r),r.analyser=this.makeAnalyser(o),this.emit()},n.onconnectionstatechange=()=>{let s=n.connectionState,o=s==="connected"?"connected":s==="failed"||s==="closed"?"failed":"connecting";if(o!==r.connection){if(r.connection=o,o==="failed"){let i=this.iceServers.some(a=>wT(a));console.warn(`[multiplayer] voice connection to ${e} failed`+(i?"":" \u2014 no TURN in the ICE list (relay offered none?)"))}this.emit()}},this.transport.selfId()<e&&this.offer(r),r}async offer(e){try{let n=await e.pc.createOffer();await e.pc.setLocalDescription(n),this.transport.sendSignal(e.id,{t:"offer",sdp:n})}catch(n){console.warn(`[multiplayer] voice offer to ${e.id} failed`,n)}}async flushIce(e){let n=e.pendingIce.splice(0);for(let r of n)try{await e.pc.addIceCandidate(r)}catch{}}destroyPeer(e){let n=this.peers.get(e);if(n){this.peers.delete(e),n.pc.onicecandidate=null,n.pc.ontrack=null,n.pc.onconnectionstatechange=null;try{n.pc.close()}catch{}n.el&&(n.el.srcObject=null,n.el.remove())}}attachSink(e,n){let r=document.createElement("audio");return r.autoplay=!0,r.srcObject=e,r.muted=this.spatial||n.muted,r.volume=n.volume,r.style.display="none",document.body.appendChild(r),r.play().catch(s=>{console.warn("[multiplayer] voice playback was blocked \u2014 join voice from a click/tap",s)}),r}makeAnalyser(e){if(!this.audio)return null;try{let n=this.audio.createMediaStreamSource(e),r=this.audio.createAnalyser();return r.fftSize=512,n.connect(r),r}catch{return null}}pollLevels(){let e=!1,n=this.micOn?W0(this.localAnalyser):0,r=this.crossed(n,this.selfSpeaking);r!==this.selfSpeaking&&(this.selfSpeaking=r,e=!0);for(let s of this.peers.values()){let o=s.muted?!1:this.crossed(W0(s.analyser),s.speaking);o!==s.speaking&&(s.speaking=o,e=!0)}e&&this.emit()}crossed(e,n){return e>=(n?this.threshold*yT:this.threshold)}emit(){for(let e of[...this.listeners])try{e()}catch(n){console.error("[multiplayer] a voice listener threw",n)}}};function gT(){try{return window.self!==window.top}catch{return!0}}function bT(t){if(t?.name!=="NotAllowedError")return t;try{if(!gT()||document.featurePolicy?.allowsFeature?.("microphone")!==!1)return t}catch{return t}return new Kp(t)}function wT(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some(n=>typeof n=="string"&&n.startsWith("turn"))}function W0(t){if(!t)return 0;let e=new Uint8Array(t.fftSize);t.getByteTimeDomainData(e);let n=0;for(let r=0;r<e.length;r++){let s=((e[r]??128)-128)/128;n+=s*s}return Math.sqrt(n/e.length)}var Xp=Symbol("genex.roomRef"),Fr=t=>t[Xp]();var ST=qe.RATIO,xT=qe.MIN_MS,_T=qe.MAX_MS,Wl=qe.DEFAULT_MS,RT=qe.JITTER_SAFETY,ET=qe.POISON_GUARD_MS,kT=qe.EASE,AT=qe.MAX_EXTRAP_MS,PT=qe.ROT_EXTRAP_MS,G0=qe.CLOCK_WINDOW,TT=qe.CLOCK_WINDOW_MS,vT=qe.CLOCK_WINDOW_MAX,MT=qe.INTERVAL_WINDOW,CT=qe.MIN_GAP_MS,OT=qe.MAX_GAP_MS,IT=qe.HISTORY_MS,DT=qe.SMOOTH_TAU_POS_MS,NT=qe.SMOOTH_TAU_ROT_MS,Y0=qe.MAX_HOST_TICK_DT_MS,BT=qe.REBASE_AFTER_GAP_MS,mr="obj:",LT=3e3,FT=5e3,zT=6e4,UT=2e3;function J0(t){if(t==="predict")return{mode:"lerp"};if(t&&typeof t=="object"&&t.engine==="predict")return{mode:t.mode==="damped"?"damped":"lerp",delay:t.delay,smoothMs:t.smoothMs}}var Yl=async t=>J0(t)?Promise.resolve().then(()=>(Jp(),q0)):void 0;function K0(t){if(!t)return{state:{}};try{let e=JSON.parse(t);if(!e||typeof e!="object")return{state:{}};let n=e,r=n[hr];if(typeof r=="number"&&Number.isFinite(r)){let s={...n};return delete s[hr],{state:s,sendTime:r}}return{state:n}}catch{return{state:{}}}}function ql(t){if(t!=null)try{return JSON.parse(t)}catch{return}}var VT=(t,e)=>typeof e=="number"?Number.isFinite(e)?e:0:typeof e=="bigint"?Number(e):e;function Ci(t){return JSON.parse(JSON.stringify(t,VT))}var lo=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function Z0(t,e,n){let[r,s,o,i]=e,[a,c,u,l]=t,d=a*r+c*s+u*o+l*i;if(d<0&&(r=-r,s=-s,o=-o,i=-i,d=-d),d>.9995){let S=a+(r-a)*n,w=c+(s-c)*n,x=u+(o-u)*n,R=l+(i-l)*n,A=Math.hypot(S,w,x,R)||1;return[S/A,w/A,x/A,R/A]}let f=Math.acos(d),h=Math.sin(f),p=Math.sin(f-f*n)/h,y=Math.sin(f*n)/h;return[a*p+r*y,c*p+s*y,u*p+o*y,l*p+i*y]}function Gl(t){return Array.isArray(t)&&t.length===4&&t.every(e=>typeof e=="number"&&Number.isFinite(e))}function X0(t,e,n,r){let s={},o=n<1;for(let i in e){let a=t[i],c=e[i];typeof a=="number"&&typeof c=="number"&&Number.isFinite(a)&&Number.isFinite(c)?s[i]=a+(c-a)*n:Gl(a)&&Gl(c)?s[i]=Z0(a,c,r):s[i]=o&&i in t?a:c}return s}function HT(t,e,n,r){let s={};for(let o in e){let i=e[o],a=t[o];typeof a=="number"&&typeof i=="number"&&Number.isFinite(a)&&Number.isFinite(i)?s[o]=a+(i-a)*n:Gl(a)&&Gl(i)?s[o]=Z0(a,i,r):s[o]=i}return s}function $T(t,e){let n=t.length;if(n===0)return;if(n===1)return t[0].state;let r=0;for(;r<n&&t[r].t<=e;)r++;if(r===0)return t[0].state;if(r>=n){let c=t[n-2],u=t[n-1],l=u.t-c.t;if(l<=0)return u.state;let d=(Math.min(e,u.t+AT)-c.t)/l,f=(Math.min(e,u.t+PT)-c.t)/l;return X0(c.state,u.state,d,f)}let s=t[r-1],o=t[r],i=o.t-s.t,a=i>0?(e-s.t)/i:1;return X0(s.state,o.state,a,a)}function jT(t){if(t.length===0)return 66;let e=[...t].sort((n,r)=>n-r);return e[e.length>>1]}function WT(t,e){if(t.length===0)return 0;let n=[...t].sort((s,o)=>s-o),r=Math.min(n.length-1,Math.max(0,Math.round(e*(n.length-1))));return n[r]}async function Q0(t){let e=await lc(t),n=await Yl(t.smoothing),r=Ss(await e.joinOrCreate(co.PLAY,{...dc(t.room,t.name,t.auth),...t.options,protocol:3}).catch(T0));return Zp(r,{pose:t.pose,smoothing:t.smoothing,predict:n})}var qT=t=>typeof t=="string"&&t.length>0&&t.length<=Yt.MAX_EVENT_TYPE_CHARS&&!bs(t),GT=new Set(["join","leave","change","shared","object","host","reconnecting","reconnected","disconnect","room:open","voice","voice:rejected"]),YT=new Set([xe.OBJECT_RESULT,xe.INPUT,xe.ROOM_OPEN,xe.CHAT,xe.CHAT_HISTORY,xe.VOICE_ICE,xe.VOICE_SIGNAL,xe.VOICE_REJECTED,xe.RATE_DROP,...Object.values(pe)]),KT=[500,1e3,2e3,4e3,8e3];function Zp(t,e={}){let n=new Map,r=new Map,s=new Map,o=new Map,i=new Map,a=new Map,c=new Set,u=new Map,l=new Map,d=new Map,f=new Map,h,p=new Map,y=new Map,S=new Map,w=new Map,x=new Map,R=new Map,A=new Map,E=new Map,P=new Set,k=new Map,M,L=0,K=new Map,W=b=>{for(let C of K.values())if(C.id===b)return!0;return!1},B=typeof globalThis<"u"&&globalThis.__GENEX_MP_TEST_SKEW__||0,se=B?()=>lo()+B:lo,v=(b,C)=>{if(p.get(C)===t.sessionId)return!1;let V=`${b}:${C}`;return P.has(V)||(P.add(V),console.warn(`[multiplayer] objects.${b}('${C}') ignored because this session does not own the object \u2014 await objects.claimConfirmed('${C}') and check accepted before publishing`)),!0},$=(b,C,V,J)=>{let we=se(),fe=V,ve=we-V,ie=o.get(J);ie||o.set(J,ie={samples:[],mins:[],n:0});let De=++ie.n;for(ie.samples.push({at:we,n:De});ie.mins.length>0&&ie.mins[ie.mins.length-1].v>=ve;)ie.mins.pop();for(ie.mins.push({v:ve,n:De});ie.samples.length>vT||ie.samples.length>G0&&ie.samples[0].at<we-TT;)ie.samples.shift();let Fe=ie.samples[0].n;for(;ie.mins[0].n<Fe;)ie.mins.shift();s.set(J,ie.mins[0].v);let nt=i.get(b);nt||i.set(b,nt=[]),nt.push(ve),nt.length>G0&&nt.shift(),a.set(b,J);let ut=r.get(b);if(r.set(b,fe),ut!=null){let rt=fe-ut;if(rt>CT&&rt<OT){let Rr=d.get(b);Rr||d.set(b,Rr=[]),Rr.push(rt),Rr.length>MT&&Rr.shift();let Gd=nt.length>=8?Math.max(0,WT(nt,.9)-ie.mins[0].v):0,tu=Math.min(_T,Math.max(xT,ST*jT(Rr),RT*Gd)),Jn=f.get(b)??Wl;f.set(b,Jn+(tu-Jn)*kT)}}let Qe=n.get(b);Qe||n.set(b,Qe=[]);let Kn=k.get(b);if(Kn&&Qe.length===0){let rt=f.get(b)??Wl;Qe.push({t:fe-Math.max(1,rt),state:Kn})}k.delete(b),Qe.push({t:fe,state:C});let Xn=fe-IT;for(;Qe.length>2&&Qe[0].t<Xn;)Qe.shift();for(;Qe.length>1&&Qe[0].t>Qe[Qe.length-1].t+ET;)Qe.shift()},Y=(b,C)=>{let V=a.get(b),J=V===void 0?void 0:s.get(V);if(J!==void 0)return C-J-(f.get(b)??Wl)},j=(b,C)=>{let V=n.get(b),J=Y(b,C)??C-Wl,we=c.has(b),fe=V&&(we?B0(V,J):$T(V,J));if(!fe)return u.get(b);let ve=u.get(b),ie;if(ve){let De=Math.min(Y0,Math.max(0,C-(l.get(b)??C))),Fe=1-Math.exp(-De/DT),nt=1-Math.exp(-De/NT);ie=we?L0(ve,fe,Fe,nt):HT(ve,fe,Fe,nt)}else ie=fe;return u.set(b,ie),l.set(b,C),ie},q=b=>{n.delete(b),r.delete(b),a.delete(b),u.delete(b),l.delete(b),d.delete(b),f.delete(b),i.delete(b),k.delete(b)},oe=b=>{n.delete(b),r.delete(b),a.delete(b),d.delete(b),f.delete(b),i.delete(b)},ce=b=>{s.delete(b),o.delete(b)},ne=new Map,Re=new Set,G=(b,...C)=>ne.get(b)?.forEach(V=>{try{V(...C)}catch(J){console.error(`[multiplayer] a '${b}' listener threw:`,J)}}),ae=new Map,be=(b,C)=>{ae.get(C)!==b&&(ae.set(C,b),G("shared",C,ql(b)))},Ge=b=>{let C=b||void 0;C!==M&&(M=C,G("host",M))},Zt="",Sr=()=>{let b=t.state?.voice?[...t.state.voice.keys()].sort():[],C=b.join(`
|
|
14
|
-
`);C!==Zt&&(Zt=C,Ue.setRoster(b),G("voice",Ue.participants))},xr=(b,C)=>{let V=mr+b,J=t.sessionId,we=w.has(b),fe=C.owner||void 0,ve=Number.isFinite(C.seq)?C.seq:0,ie=Number.isFinite(C.epoch)?C.epoch:0,De=Number.isFinite(C.t)?C.t:0,Fe=typeof C.d=="string"?C.d:"",ut=fe!==y.get(b)||we&&ve!==w.get(b),Qe=S.has(b)&&ie!==S.get(b),Kn=De!==x.get(b);if(w.set(b,ve),S.set(b,ie),x.set(b,De),Fe!==R.get(b)){R.set(b,Fe);let rt=Fe?ql(Fe):void 0;rt&&typeof rt=="object"&&!Array.isArray(rt)&&A.set(b,rt)}fe?y.set(b,fe):y.delete(b),(ut||p.get(b)!==fe&&!W(b))&&(fe?p.set(b,fe):p.delete(b)),Qe&&q(V),ut&&fe!==J&&(E.delete(b),Qe||oe(V));let Xn=A.get(b);if(Xn&&fe!==J){let rt=De!==0&&Kn&&fe!==void 0;Qe?(u.set(V,Xn),l.set(V,se()),rt&&$(V,Xn,De,fe)):(ut&&k.set(V,u.get(V)??Xn),rt&&$(V,Xn,De,fe))}(!we||ut)&&G("object",b)},vs=b=>{let C=w.has(b)||p.has(b)||A.has(b)||E.has(b);q(mr+b),A.delete(b),p.delete(b),y.delete(b),S.delete(b),w.delete(b),x.delete(b),R.delete(b),E.delete(b),C&&G("object",b)},Co=new Map,Ms=new Map,na=new Map,Wd=(b,C)=>{if(!C)return{};let V=Co.get(b);if(V&&V.raw===C)return V.state;let{state:J}=K0(C);return Co.set(b,{raw:C,state:J}),J},kn=new Map,yn=new Map,qn=e.predict?J0(e.smoothing):void 0,ct,Gn=new Map,qd=(b,C)=>{if(!qn||!e.predict)return;ct??(ct=e.predict.Predict.get(t));let V={mode:qn.mode,delay:qn.delay,smoothMs:qn.smoothMs};ct.attach(C,{x:V,y:V,z:V,vx:V,vy:V,vz:V}),ct.attach(C,{yaw:{...V,angle:!0}}),Gn.set(b,C)},Wc=b=>{let C=Gn.get(b);C&&ct&&ct.detach(C),Gn.delete(b)},qc=b=>{let C=ct;return{x:C.value(b,"x"),y:C.value(b,"y"),z:C.value(b,"z"),yaw:C.value(b,"yaw"),vx:C.value(b,"vx"),vy:C.value(b,"vy"),vz:C.value(b,"vz"),anim:b.anim??""}},Qt=!1,An=!1,gt=!0,Kr=!1,ra=0,Xr=0,sa=0,oa=new Set,Cs=()=>oa.forEach(b=>b()),Os=(b,C)=>{if(K.delete(b.requestId),b.timeout&&clearTimeout(b.timeout),b.abort?.(),b.operation==="claim"&&b.optimistic&&!C.accepted){let V=C.owner??y.get(b.id);V?p.set(b.id,V):p.delete(b.id),V!==t.sessionId&&E.delete(b.id)}b.operation==="claim"&&C.accepted&&(p.set(b.id,t.sessionId),oe(mr+b.id)),b.operation==="release"&&C.accepted&&(E.delete(b.id),p.get(b.id)===t.sessionId&&p.delete(b.id),oe(mr+b.id)),b.operation==="remove"&&C.accepted&&(E.delete(b.id),A.delete(b.id),p.delete(b.id),q(mr+b.id)),b.resolve(C)},Is=(b,C)=>{let V=t.state?.objects?.get(b.id);return{requestId:b.requestId,operation:b.operation,id:b.id,accepted:!1,owner:V?.owner||void 0,sequence:V&&Number.isFinite(V.seq)?V.seq:0,reason:C}},Oo=b=>{for(let C of[...K.values()])Os(C,Is(C,b))},ia=(b,C=!1)=>{if(!C&&!gt)return;let V=b.operation==="claim"?pe.CLAIM:b.operation==="release"?pe.RELEASE:pe.DESTROY;tt(V,b.payload)},Jr=(b,C,V={})=>{let J=String(C),we=`${t.sessionId.slice(0,12)}:${Date.now().toString(36)}:${(++L).toString(36)}`,fe=Math.max(250,Math.min(V.timeoutMs??FT,zT));return new Promise(ve=>{let ie={operation:b,id:J,requestId:we,payload:{id:J,requestId:we,...V.authority==="host"?{authority:"host"}:{}},optimistic:b==="claim"&&V.optimistic===!0,resolve:ve,timeout:null,abort:void 0};if(Qt||An){ve(Is(ie,Qt?"aborted":"disconnected"));return}if(ie.optimistic&&p.set(J,t.sessionId),ie.timeout=setTimeout(()=>Os(ie,Is(ie,"timeout")),fe),V.signal){let De=()=>Os(ie,Is(ie,"aborted"));V.signal.addEventListener("abort",De,{once:!0}),ie.abort=()=>V.signal?.removeEventListener("abort",De)}if(K.set(we,ie),V.signal?.aborted){Os(ie,Is(ie,"aborted"));return}ia(ie)})},Zr=0,tt=(b,C,V=!1)=>{if(t.connection?.isOpen)try{return t.send(b,C),!0}catch{}return V&&Zr++,!1},Io,Gc=0,Yc,Kc=new Set,Xc=(b,C)=>{let{pose:V,data:J,invalid:we}=I0(b);for(let Fe of we)Kc.has(Fe)||(Kc.add(Fe),console.warn(`[multiplayer] me.set: '${Fe}' is a typed pose key (pose: true) and its value is not a `+(Fe==="anim"?`string of \u2264${Yt.MAX_ANIM_CHARS} chars`:"finite number")+" \u2014 it is not sent."));if(!D0(V))return!1;let fe=se(),ve=N0(V,fe,C?void 0:Yc);Yc=ve.memory;let ie=JSON.stringify(J),De=C||ie!==Io||fe-Gc>=UT;return De&&tt(pe.STATE,JSON.stringify({...J,[hr]:fe}))?(Io=ie,Gc=fe):De&&(Io=void 0),tt(C?pe.POSE_SNAP:pe.POSE,{...ve.pose,t:fe})||(Io=void 0),!0},Ue=new jl({selfId:()=>t.sessionId,nameOf:b=>t.state?.players?.get(b)?.name??"",sendSignal:(b,C)=>tt(pe.VOICE_SIGNAL,{to:b,data:C},!0)});Ue.onChange(()=>G("voice",Ue.participants));let Qr=null,Ds=v0(()=>tt(pe.VOICE_ICE_REQUEST,{},!0),LT),Do=()=>{Qr&&clearTimeout(Qr),Qr=null},Yn=b=>{Do(),!(typeof b!="number"||!Number.isFinite(b)||b<=0)&&(Qr=setTimeout(()=>{Ue.active&&Ds.request().then(C=>{!Ue.active||!C?.iceServers?.length||(Ue.setIceServers(C.iceServers),Yn(C.ttl))})},Math.max(6e4,Math.floor(b*800))))},_r=[],No=new Set,Ns=new Set,Bs=new Set,Nt=b=>!!b&&typeof b=="object"&&typeof b.id=="number"&&typeof b.from=="string"&&typeof b.name=="string"&&typeof b.text=="string",Jc=b=>{if(!Nt(b)||No.has(b.id)||Bs.has(b.from))return;No.add(b.id);let C=_r[_r.length-1];if(!C||b.id>C.id)_r.push(b);else{let V=_r.length;for(;V>0&&(_r[V-1]?.id??0)>b.id;)V--;_r.splice(V,0,b)}for(let V of[...Ns])try{V(b)}catch(J){console.error("[multiplayer] a chat listener threw",J)}},Rt=Ja(t);if(!Rt)throw new Error("genex multiplayer: the relay room has no schema state");let Bo=(b,C,V)=>{let J=b===t.sessionId,{state:we,sendTime:fe}=K0(C.data),ve=Number.isFinite(C.epoch)?C.epoch:0,ie=Ms.has(b)&&ve!==Ms.get(b);Ms.set(b,ve);let De=V||C.data!==na.get(b);na.set(b,C.data);let Fe=Number.isFinite(C.poseT)?C.poseT:0,nt=Fe!==(yn.get(b)??0);yn.set(b,Fe);let ut=C.posed===!0;if(!J&&ut&&!c.has(b)&&(q(b),c.add(b),kn.set(b,new Vl)),!J&&ie&&(q(b),Gn.has(b)&&Wc(b)),G(V?"join":"change",b,ut?{...we,...$l(C)}:we),!J){if(ut){let Qe=kn.get(b);(De||ie)&&(Qe.push(fe,we),(ie||qn)&&Qe.flush()),qn?Gn.has(b)||qd(b,C):Fe!==0&&(nt||ie)&&$(b,$l(C),Fe,b);return}(De||ie)&&H0(b,t.sessionId,fe)&&$(b,we,fe,b)}};Rt(t.state).players.onAdd((b,C)=>{Bo(C,b,!0),Rt(b).onChange(()=>Bo(C,b,!1))});let Lo=b=>{G("leave",b),q(b),ce(b),Wc(b),Co.delete(b),Ms.delete(b),na.delete(b),yn.delete(b),c.delete(b),kn.delete(b)};Rt(t.state).players.onRemove((b,C)=>Lo(C)),Rt(t.state).shared.onAdd(be),Rt(t.state).shared.onChange(be),Rt(t.state).objects.onAdd((b,C)=>{xr(C,b),Rt(b).onChange(()=>xr(C,b))}),Rt(t.state).objects.onRemove((b,C)=>vs(C)),Rt(t.state).listen("host",b=>Ge(b)),Rt(t.state).voice.onAdd(Sr),Rt(t.state).voice.onRemove(Sr);let Zc=()=>{let b=t.state;if(b){for(let C of new Set([...p.keys(),...A.keys(),...w.keys()]))b.objects?.has(C)||vs(C);for(let C of[...Ms.keys()])b.players?.has(C)||Lo(C);Ge(b.host),Sr()}};t.onMessage(xe.VOICE_SIGNAL,b=>{b&&typeof b.from=="string"&&Ue.handleSignal(b.from,b.data)}),t.onMessage(xe.VOICE_REJECTED,b=>{Do(),Ue.stop(),G("voice:rejected",b??{reason:"full"})}),t.onMessage(xe.VOICE_ICE,b=>{Ds.deliver(b??null)}),t.onMessage(xe.CHAT,b=>Jc(b)),t.onMessage(xe.CHAT_HISTORY,b=>{if(Array.isArray(b?.messages))for(let C of b.messages)Jc(C)}),t.onMessage(xe.OBJECT_RESULT,b=>{if(!b||typeof b.requestId!="string")return;let C=K.get(b.requestId);!C||b.operation!==C.operation||b.id!==C.id||Os(C,b)}),t.onMessage(xe.INPUT,b=>{b&&typeof b.from=="string"&&G(xe.INPUT,b.from,b.d)}),t.onMessage(xe.ROOM_OPEN,b=>{typeof b?.open=="boolean"&&G("room:open",{open:b.open})}),t.onMessage(xe.RATE_DROP,b=>{console.warn(`[multiplayer] the relay dropped ${b?.dropped??"some"} of your messages in the last second \u2014 you are publishing over budget. Publish idle/unchanged objects at \u22642Hz keepalive, not every tick (see the multiplayer skill's "message budget" section).`)}),t.onMessage(xe.SERVER_RESTART,()=>{}),tt(pe.CHAT_HISTORY_REQUEST,{});let Qc=F0(t),es=Qc?z0(Qc,()=>!An&&!Qt):void 0,ts=()=>es?t.clock.serverNow():void 0,aa=b=>U0(b,{synced:es?.synced===!0,clockOrigin:Number.isFinite(t.state?.clockOrigin)?t.state?.clockOrigin:0,serverNow:ts(),wallNow:Date.now()}),eu=()=>{es?.stop(),ct?.dispose(),ct=void 0,Gn.clear()};t.onDrop(b=>{if(Qt||An)return;sa++,Kr||(Kr=!0,ra=0,Xr=lo()),gt=!1,Cs();let{isReconnecting:C,retryCount:V,maxRetries:J}=t.reconnection;C&&V>=J||G("reconnecting",{attempt:++ra,code:b})}),t.onReconnect(()=>{if(An)return;if(Qt){t.leave().catch(()=>{});return}let b=sa;if((Xr?lo()-Xr:0)>BT){for(let V of[...n.keys()])q(V);for(let V of[...o.keys()])ce(V)}(async()=>{if(await pc(t,fn.firstStateTimeoutMs),!(b!==sa||An||Qt)){Zc();for(let V of[...K.values()])ia(V,!0);tt(pe.CHAT_HISTORY_REQUEST,{}),Kr=!1,Xr=0,gt=!0,Cs(),G("reconnected"),Zr>0&&(console.warn(`[multiplayer] ${Zr} fire-and-forget event(s)/input(s) were dropped while reconnecting \u2014 they are not buffered; player/object state re-synced automatically.`),Zr=0)}})()}),t.onLeave(b=>{An||(An=!0,gt=!1,Kr=!1,eu(),Cs(),!Qt&&(Oo("disconnected"),G("disconnect",b??1006)))}),t.onError(()=>{});let Fo=((b,C)=>{let V=ne.get(b);return V||ne.set(b,V=new Set),V.add(C),!GT.has(b)&&!YT.has(b)&&!Re.has(b)&&(Re.add(b),t.onMessage(b,J=>G(b,J))),()=>{V?.delete(C)}}),Ls={id:t.sessionId,get players(){let b=new Map,C=se();return ct&&Gn.size>0&&ct.tick(lo()),t.state?.players?.forEach((V,J)=>{let we=Wd(J,V.data),fe=we,ve=we,ie=kn.get(J);if(J!==t.sessionId&&ie){let De=$l(V);if(ve={...we,...De},Gn.has(J))fe={...ie.at(void 0)??we,...qc(V)};else{let Fe=j(J,C)??De;fe={...ie.at(Y(J,C))??we,...Fe}}}else J===t.sessionId?h&&(fe=h,ve=h):fe=j(J,C)??we;b.set(J,{id:J,name:V.name??"",avatarUrl:V.avatarUrl??"",connected:V.connected!==!1,uid:V.uid??"",team:Number.isFinite(V.team)?V.team:-1,state:fe,stateRaw:ve})}),b},get activePlayers(){return new Map([...Ls.players].filter(([,b])=>b.connected))},me:{set(b){hr in b&&console.warn(`[multiplayer] '${hr}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let C=Ci(b);h=C,!(e.pose&&Xc(C,!1))&&tt(pe.STATE,JSON.stringify({...C,[hr]:se()}))},snap(b){hr in b&&console.warn(`[multiplayer] '${hr}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let C=Ci(b);h=C,!(e.pose&&Xc(C,!0))&&tt(pe.STATE_SNAP,JSON.stringify({...C,[hr]:se()}))}},shared:{get(b){return ql(t.state?.shared?.get(b))},set(b,C){b.startsWith(zl)||tt(pe.SHARED,{key:b,value:JSON.stringify(Ci(C))})},keys(){return t.state?.shared?Array.from(t.state.shared.keys()):[]}},objects:{claim(b){Jr("claim",b,{optimistic:!0})},claimConfirmed(b,C){return Jr("claim",b,C)},release(b){let C=String(b);E.delete(C),p.get(C)===t.sessionId&&p.delete(C),oe(mr+C),Jr("release",C)},releaseConfirmed(b,C){return Jr("release",b,C)},remove(b){let C=String(b);p.get(C)===t.sessionId&&(E.delete(C),A.delete(C),p.delete(C),q(mr+C)),Jr("remove",C)},removeConfirmed(b,C){return Jr("remove",b,C)},set(b,C){let V=String(b);if(v("set",V))return;let J=Ci(C);p.get(V)===t.sessionId&&E.set(V,J),tt(pe.OBJECT,{id:V,d:J,t:se()})},snap(b,C){let V=String(b);if(v("snap",V))return;let J=Ci(C);p.get(V)===t.sessionId&&E.set(V,J),tt(pe.OBJECT_SNAP,{id:V,d:J,t:se()})},get(b){let C=String(b),V=p.get(C),J=E.get(C);if(V===void 0&&!A.has(C)&&!J)return;let we=V!==void 0&&V===t.sessionId,fe,ve;return we&&J?(fe=J,ve=J,u.set(mr+C,J),l.set(mr+C,se())):(ve=A.get(C)??{},fe=j(mr+C,se())??ve),{id:C,epoch:S.get(C)??0,owner:V,isMine:we,state:fe,stateRaw:ve}},ids(){return[...new Set([...p.keys(),...A.keys(),...E.keys()])]}},get isHost(){return gt&&!Qt&&!An&&M!==void 0&&M===t.sessionId},get host(){return M},inputs:{send(b){tt(pe.INPUT,Ci(b),!0)},on(b){let C=ne.get(xe.INPUT);C||ne.set(xe.INPUT,C=new Set);let V=(J,we)=>b(J,we);return C.add(V),()=>{C?.delete(V)}}},onHostTick(b,C){let V=null,J=0,we=Number.isFinite(b)&&b>0?Math.min(b,100):20,fe=Math.max(10,Math.round(1e3/we)),ve=()=>{let De=gt&&!Qt&&!An&&M!==void 0&&M===t.sessionId;De&&!V?(J=lo(),V=setInterval(()=>{let Fe=lo();C(Math.min(Fe-J,Y0)),J=Fe},fe)):!De&&V&&(clearInterval(V),V=null)},ie=Fo("host",ve);return oa.add(ve),ve(),()=>{ie(),oa.delete(ve),V&&clearInterval(V),V=null}},on:Fo,send(b,C){if(!qT(b)){console.warn(`[multiplayer] send('${b}') collides with a relay-internal channel \u2014 use a different event name`);return}tt(b,C,!0)},chat:{send(b){typeof b=="string"&&b.trim()&&tt(pe.CHAT,{text:b},!0)},on(b){return Ns.add(b),()=>Ns.delete(b)},get history(){return[..._r]},mute(b){typeof b=="string"&&b&&Bs.add(b)},unmute(b){Bs.delete(b)},get muted(){return[...Bs]}},voice:{async join(b){if(await Ue.start(b,!0),!b?.iceServers?.length){let C=await Ds.request();Ue.active&&C?.iceServers?.length&&(Ue.setIceServers(C.iceServers),Yn(C.ttl))}Ue.active&&(tt(pe.VOICE_JOIN,{},!0),Ue.releasePeering())},leave(){Do(),tt(pe.VOICE_LEAVE,{},!0),Ue.stop()},get active(){return Ue.active},get participants(){return Ue.participants},setMicEnabled(b){Ue.setMicEnabled(b===!0)},get micEnabled(){return Ue.micEnabled},get speaking(){return Ue.speaking},mute(b){Ue.mute(b)},unmute(b){Ue.unmute(b)},setVolume(b,C){Ue.setVolume(b,C)},get muted(){return Ue.participants.filter(b=>b.muted).map(b=>b.id)}},setRoomOpen(b){tt(pe.ROOM_OPEN,{open:b===!0})},leave(){Qt=!0,eu(),Ue.stop(),Do(),gt=!1,Cs(),Oo("aborted"),t.reconnection.enabled=!1,t.leave().catch(()=>{})},serverNow:ts,get rtt(){if(!es)return;let b=t.clock.smoothedRtt();return b>0?b:void 0},get clockSynced(){return es?.synced===!0},timeUntil:aa};return Object.defineProperty(Ls,Xp,{value:()=>t,enumerable:!1}),Object.defineProperty(Ls,Symbol.for("genex.multiplayer.internals"),{enumerable:!1,value:{senderOf:b=>a.get(b),offsetOf:b=>{let C=a.get(b);return C===void 0?void 0:s.get(C)},offsetSamples:b=>o.get(b)?.samples.length??0,bufferLength:b=>n.get(b)?.length??0}}),Ls}var XT=[1e3,2e3,4e3],Qp=t=>dc(t.room,t.name,t.auth);function ew(t,e,n=r=>r-Date.now()){let r=t?.state?.match,s=r?ql(r):null,o=s&&typeof s=="object"?s:null;if(!o)return{status:t?"waiting":"searching",role:"player",queue:e,players:[],connectedPlayers:[],opponents:[],teams:{},myTeam:null,scores:{},config:{},winCondition:"lastStanding",championId:null,challengerId:null,roundId:0,winnerId:null,message:t?"Waiting for players\u2026":"Finding a match\u2026",startsAt:null,endsBy:null,startsInMs:null,endsInMs:null};let i=t?.sessionId,a=o.championId??null,c=o.challengerId??null,u=o.teams??{},l=Array.isArray(o.players)?o.players:[],d=o.connectedPlayers??l,f=i!=null&&l.includes(i),h=f?o.phase:"spectating",p=l.filter(P=>P!==i),y=i?Object.keys(u).find(P=>u[P]?.includes(i))??null:null,{winCondition:S,...w}=o.cfg??{},x=P=>typeof P=="number"&&Number.isFinite(P)&&P>0?P:null,R=x(o.startsAt),A=x(o.endsBy),E=P=>P===null?null:Math.max(0,n(P));return{status:h,role:f?"player":"spectator",queue:{position:0,size:0},players:l,connectedPlayers:d,opponents:p,teams:u,myTeam:y,scores:o.scores??{},config:w,winCondition:S?.type??"lastStanding",championId:a,challengerId:c,roundId:o.roundId??0,winnerId:o.winnerId??null,message:o.message??"",startsAt:R,endsBy:A,startsInMs:E(R),endsInMs:E(A)}}function Oi(t,e,n){if(t?.connection?.isOpen)try{t.send(e,n)}catch{}}async function tw(t){let e=await lc(t),n=await Yl(t.smoothing),r=new Map,s=(P,...k)=>r.get(P)?.forEach(M=>M(...k)),o=((P,k)=>{let M=r.get(P);return M||r.set(P,M=new Set),M.add(k),()=>{M?.delete(k)}}),i=null,a=null,c=null,u={position:0,size:0},l=!1,d=!1,f=0,h=!1,p=!1,y=async()=>{if(l||d)return;d=!0;let P=++f;try{i=null,a=null;for(let k=0;;k++){c&&(c.leave(),c=null),u={position:0,size:0};let M;try{M=V0(await e.joinOrCreate(co.QUEUE,Qp(t)))}catch(L){if(l)return;let K=fc(L);K&&qp();let W=K?void 0:XT[k];if(W==null){if(k===0&&await new Promise(B=>setTimeout(B,0)),l)return;s("error",L);return}if(await new Promise(B=>setTimeout(B,W)),l)return;continue}if(l||P!==f){M.leave();return}c=M,M.onMessage(xe.QUEUE,L=>{u={position:L.position,size:L.size},s("queue",L)}),M.onMessage(xe.SEAT,L=>{l||P!==f||c!==M||h||(h=!0,c=null,M.leave(),S(L.reservation,L.role,P))}),M.onLeave(()=>{l||c!==M||(c=null,(async()=>{for(let L of KT)if(await new Promise(K=>setTimeout(K,L)),l||c||i||(await y(),c||i))return})())}),s("searching");return}}finally{d=!1}},S=async(P,k,M)=>{try{let L=Ss(await e.consumeSeatReservation(P));if(l||M!==f){L.leave();return}a=L;let K=Zp(L,{pose:t.pose,smoothing:t.smoothing,predict:n});i=K,K.on(xe.MATCH_START,W=>s("matchStart",W)),K.on(xe.MATCH_ENDED,W=>s("matchEnded",W)),K.on(xe.MATCH_REQUEUE,()=>{i===K&&w()}),K.on("disconnect",W=>{if(!(l||i!==K)){if(W===dn.SUPERSEDED||W===dn.REVOKED){f++,h=!1,a=null,i=null,s("disconnect",W);return}w()}}),c&&(c.leave(),c=null),s("matched"),k==="spectator"&&s("spectate")}catch{!l&&M===f&&(h=!1,y())}finally{M===f&&(h=!1)}},w=async()=>{if(!(l||p)){p=!0;try{f++,h=!1,i?.leave(),a=null,i=null,await y()}finally{p=!1}}};y();let x=()=>i?Fr(i):null,R=null,A=null,E=()=>{i!==R&&(R=i,A=null);let P=x(),k=!!P?.state?.match;if(!k&&i&&A)return A;let M=ew(P,u,i?i.timeUntil:void 0);return k&&(A=M),M};return{get session(){return i},get matchmaking(){return E()},on:o,eliminated(){Oi(x(),pe.MATCH_ELIMINATED,{})},score(P=1){Oi(x(),pe.MATCH_SCORE,{delta:P})},finish(){Oi(x(),pe.MATCH_FINISH,{})},retry(){l||d||c||a||y()},cancel(){l=!0,f++,h=!1,i?.leave(),!i&&a&&a.leave(),c&&c.leave(),a=null,c=null,i=null}}}function nw(t,e){let n=new Map,r=(c,...u)=>n.get(c)?.forEach(l=>l(...u)),s=((c,u)=>{let l=n.get(c);return l||n.set(c,l=new Set),l.add(u),()=>{l?.delete(u)}}),o=!0,i=Zp(t,e);i.on(xe.MATCH_START,c=>r("matchStart",c)),i.on(xe.MATCH_ENDED,c=>r("matchEnded",c)),i.on(xe.MATCH_REQUEUE,()=>{o=!1}),i.on("disconnect",()=>{o=!1});let a=()=>o?Fr(i):null;return{get session(){return o?i:null},get matchmaking(){return ew(a(),{position:0,size:0},i.timeUntil)},on:s,eliminated(){Oi(a(),pe.MATCH_ELIMINATED,{})},score(c=1){Oi(a(),pe.MATCH_SCORE,{delta:c})},finish(){Oi(a(),pe.MATCH_FINISH,{})},retry(){},cancel(){i.leave(),o=!1}}}async function rw(t){let e=await lc(t),n=await Yl(t.smoothing),r=Ss(await e.create(co.MATCH,Qp(t))),s=nw(r,{pose:t.pose,smoothing:t.smoothing,predict:n});return Object.defineProperty(s,"code",{value:r.roomId,enumerable:!0}),s}async function sw(t,e){let n=await lc(e),r=await Yl(e.smoothing),s=Ss(await n.joinById(t,Qp(e)));return nw(s,{pose:e.pose,smoothing:e.smoothing,predict:r})}var JT=2,Kl=ga;function ZT(t){Kl=t??ga}function QT(t){let e=JSON.parse(t);if(!vn(e))throw new TypeError("genex bridge: options must be a JSON object");let n=typeof e.gameId=="string"?e.gameId:"";if(!n)throw new TypeError("genex bridge: `gameId` (the game slug) is required");let r=Array.isArray(e.urls)?e.urls.filter(a=>typeof a=="string"&&a!==""):[],s="play";if(e.room==="queue"||e.room==="private")s=e.room;else if(vn(e.room)&&typeof e.room.joinById=="string"&&e.room.joinById)s={joinById:e.room.joinById};else if(e.room!==void 0&&e.room!==null&&e.room!=="play")throw new TypeError('genex bridge: `room` must be "play", "queue", "private" or {"joinById": code}');let o=typeof e.controlTimeoutMs=="number"&&Number.isFinite(e.controlTimeoutMs)?e.controlTimeoutMs:void 0,i=e.smoothing==="genex"||e.smoothing==="predict"||vn(e.smoothing)?e.smoothing:void 0;return{gameId:n,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:r,room:s,pose:e.pose===!0,smoothing:i,controlTimeoutMs:o,options:vn(e.options)?e.options:void 0}}var eh=new Map,ev=1,th=t=>t.closed?null:t.mm?t.mm.session:t.session;function hc(t){t.closed=!0,t.connected=!1;for(let e of t.unwire.splice(0))e();t.wired=null,t.session=null,t.mm=null}function iw(t,e){if(t.wired===e)return;for(let i of t.unwire.splice(0))i();t.wired=e,t.connected=!0,t.lastConnected.clear(),t.lastMatch="";let n=Fr(e);t.sessionId=e.id,t.roomId=n.roomId;let r=t.unwire,s=i=>n.state?.players?.get(i)?.connected!==!1,o=i=>{let a=s(i),c=t.lastConnected.get(i);t.lastConnected.set(i,a),c!==void 0&&c!==a&&me(t,{type:"playerConnection",id:i,connected:a})};me(t,{type:"joined",sessionId:e.id}),n.state?.players?.forEach((i,a)=>{t.lastConnected.set(a,s(a)),me(t,{type:"playerJoined",id:a})});for(let i of e.objects.ids())me(t,{type:"objectChanged",id:i,owner:e.objects.get(i)?.owner??null});e.host!==void 0&&me(t,{type:"hostChanged",host:e.host}),r.push(e.on("join",i=>{t.lastConnected.set(i,s(i)),me(t,{type:"playerJoined",id:i})}),e.on("change",i=>{o(i),t.changed.has(i)||(t.changed.add(i),me(t,{type:"playerChanged",id:i}))}),e.on("leave",i=>{t.lastConnected.delete(i),me(t,{type:"playerLeft",id:i})}),e.on("host",i=>me(t,{type:"hostChanged",host:i??null})),e.on("shared",(i,a)=>me(t,{type:"sharedChanged",key:i,value:a??null})),e.on("object",i=>{let a=e.objects.get(i);me(t,a?{type:"objectChanged",id:i,owner:a.owner??null}:{type:"objectRemoved",id:i})}),e.on("room:open",({open:i})=>me(t,{type:"roomOpen",open:i})),e.on("reconnecting",({attempt:i,code:a})=>{t.connected=!1,me(t,{type:"reconnecting",code:a,attempt:i})}),e.on("reconnected",()=>{t.connected=!0,me(t,{type:"reconnected"})}),e.on("disconnect",i=>{t.connected=!1,t.opts.room!=="queue"&&(hc(t),me(t,{type:"disconnected",code:i,reason:""}))}),e.on(xe.SERVER_RESTART,()=>me(t,{type:"serverRestart"})),e.on(xe.MATCH_START,i=>me(t,{type:"matchStart",roundId:vn(i)&&typeof i.roundId=="number"?i.roundId:0})),e.on(xe.MATCH_ENDED,i=>me(t,{type:"matchEnded",data:i??null})),e.on(xe.MATCH_REQUEUE,i=>me(t,{type:"matchRequeue",reason:vn(i)&&typeof i.reason=="string"?i.reason:null})),e.inputs.on((i,a)=>me(t,{type:"input",from:i,data:a??null})),e.chat.on(i=>me(t,{type:"chat",id:i.id,from:i.from,name:i.name,text:i.text,at:i.at})),n.onMessage(xe.RATE_DROP,i=>me(t,{type:"rateDrop",dropped:vn(i)&&typeof i.dropped=="number"?i.dropped:0})),n.onMessage("*",(i,a)=>{typeof i=="string"&&!bs(i)&&me(t,{type:"message",kind:i,data:a??null})}))}function Xl(t){let e=th(t);e&&e!==t.wired&&iw(t,e)}async function tv(t){let e=t.opts;if(await Kl.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:Kl.urls();if(!n.length)throw Object.assign(new Error("genex bridge: no relay URL (pass urls, or run on a Genex page)"),{code:0});let r=()=>Kl.auth(),s={urls:n,room:e.gameId,name:e.name,auth:r,pose:e.pose,smoothing:e.smoothing};if(e.room==="play"){let a=await Q0({...s,options:e.options});if(t.closed)return void a.leave();t.session=a,iw(t,a);return}let o=s,i=e.room==="queue"?await tw(o):e.room==="private"?await rw(o):await sw(e.room.joinById,o);if(t.closed)return void i.cancel();t.mm=i,i.on("queue",a=>{vn(a)&&me(t,{type:"queue",position:Number(a.position)||0,size:Number(a.size)||0})}),i.on("matched",()=>{me(t,{type:"seated"}),Xl(t)}),i.on("searching",()=>{if(t.wired){for(let a of t.unwire.splice(0))a();t.wired=null,t.connected=!1}}),i.on("error",a=>{let c=t.mm;hc(t),c?.cancel(),me(t,{type:"joinFailed",code:Jo(a),message:Qn(a)})}),i.on("disconnect",a=>{hc(t),me(t,{type:"disconnected",code:typeof a=="number"?a:0,reason:""})}),Xl(t)}function aw(t){let e=QT(t),n=ev++,r={opts:e,q:[],overflowed:!1,session:null,mm:null,wired:null,unwire:[],changed:new Set,lastConnected:new Map,lastMatch:"",sessionId:"",roomId:"",connected:!1,closed:!1};eh.set(n,r);let s=tv(r).catch(o=>{throw hc(r),me(r,{type:"joinFailed",code:Jo(o),message:Qn(o)}),o});return{handle:n,done:s}}function nv(t){let{handle:e,done:n}=aw(t);return n.catch(()=>{}),e}async function rv(t){let{handle:e,done:n}=aw(t);try{await n}catch(r){let s=new Error(Qn(r));throw s.code=Jo(r),s}return e}var xs=t=>eh.get(t),It=t=>{let e=xs(t);return e?(Xl(e),th(e)):null};function cw(t){let e=xs(t);if(!e||e.closed)return;let{mm:n,session:r}=e;hc(e),n?n.cancel():r?.leave(),me(e,{type:"disconnected",code:4e3,reason:"left"})}function sv(t){cw(t),typeof t=="number"&&eh.delete(t)}function ov(t,e){let n=er(e,"state"),r=It(t);return r?(r.me.set(n),!0):!1}function iv(t,e){let n=er(e,"state"),r=It(t);return r?(r.me.snap(n),!0):!1}function av(t,e,n){let r=ba(n,"value");if(typeof e!="string"||!e||e.startsWith(zl))return!1;let s=It(t);return s?(s.shared.set(e,r),!0):!1}function cv(t,e,n){let r=er(n,"object state"),s=It(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.set(e,r),!0)}function uv(t,e,n){let r=er(n,"object state"),s=It(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.snap(e,r),!0)}function lv(t,e,n){let r=ba(n,"event data");if(typeof e!="string"||!e||e.length>Yt.MAX_EVENT_TYPE_CHARS||bs(e))return!1;let s=It(t);return s?(s.send(e,r),!0):!1}function dv(t,e){}function fv(t,e){let n=ba(e,"input"),r=It(t);return r?(r.inputs.send(n),!0):!1}function pv(t,e){let n=It(t);return n?(n.setRoomOpen(e===!0),!0):!1}function hv(t,e){let n=It(t);return!n||typeof e!="string"?!1:(n.chat.send(e),!0)}function Jl(t,e,n,r,s=!1){if(typeof n!="string"||!n)throw new TypeError("genex bridge: object id must be a non-empty string");let o=xs(t),i=It(t),a=l=>{if(!o)return;let d={type:"controlResult",requestId:String(r),operation:e,id:n,accepted:l.accepted,owner:l.owner??null,sequence:l.sequence,reason:l.reason};typeof l.retryAfterMs=="number"&&(d.retryAfterMs=l.retryAfterMs),me(o,d)};if(!i){a({accepted:!1,sequence:0,reason:"disconnected"});return}let c={timeoutMs:o?.opts.controlTimeoutMs,...s?{authority:"host"}:{}};(e==="claim"?i.objects.claimConfirmed(n,c):e==="release"?i.objects.releaseConfirmed(n,c):i.objects.removeConfirmed(n,c)).then(a,()=>a({accepted:!1,sequence:0,reason:"disconnected"}))}function mv(t,e,n){Jl(t,"claim",e,n)}function yv(t,e,n){Jl(t,"claim",e,n,!0)}function gv(t,e,n){Jl(t,"release",e,n)}function bv(t,e,n){Jl(t,"remove",e,n)}function wv(t){let e=xs(t);return!e?.mm||e.closed?!1:(e.mm.eliminated(),!0)}function Sv(t,e=1){let n=xs(t);return!n?.mm||n.closed||typeof e!="number"||!Number.isFinite(e)?!1:(n.mm.score(e),!0)}function xv(t){let e=xs(t);return!e?.mm||e.closed?!1:(e.mm.finish(),!0)}function _v(t){return It(t)?.serverNow()??null}function Rv(t,e){let n=It(t);return n?n.timeUntil(e):e-Date.now()}var ow=t=>typeof t=="number"&&Number.isFinite(t)?t:null;function Ev(t){let e=xs(t),n=It(t),r=n?Fr(n):null,s=r?.state?.match,o=null;if(s)try{o=JSON.parse(s)}catch{o=null}return JSON.stringify({sessionId:n?.id??e?.sessionId??"",roomId:r?.roomId??e?.roomId??"",hostId:n?.host??null,isHost:n?.isHost??!1,connected:!!n&&!!e?.connected,closed:!e||e.closed,serverNow:ow(n?.serverNow()),rtt:ow(n?.rtt),clockSynced:n?.clockSynced??!1,clockOrigin:r?.state?.clockOrigin??0,matchState:o})}function kv(t){let e=It(t);if(!e)return"[]";let n=Fr(e).state?.players,r=[];for(let[s,o]of e.players){let i=n?.get(s);r.push({id:s,name:o.name,uid:o.uid,team:o.team,connected:o.connected,avatarUrl:o.avatarUrl,state:o.state??{},stateRaw:o.stateRaw??{},epoch:i?.epoch??0,isMe:s===e.id,posed:i?.posed===!0})}return JSON.stringify(r)}function Av(t){let e=It(t);if(!e)return"[]";let n=Fr(e).state?.objects,r=[];for(let s of e.objects.ids()){let o=e.objects.get(s);o&&r.push({id:s,owner:o.owner??null,isMine:o.isMine,seq:n?.get(s)?.seq??0,epoch:o.epoch,state:o.state??null,stateRaw:o.stateRaw??null})}return JSON.stringify(r)}function Pv(t){let e=It(t),n={};if(e)for(let r of e.shared.keys())n[r]=e.shared.get(r)??null;return JSON.stringify(n)}function Tv(t){let e=xs(t);if(!e)return"[]";try{Xl(e);let n=th(e);if(n){let r=Fr(n).state?.match??"";if(r!==e.lastMatch){e.lastMatch=r;let s=null;try{s=r?JSON.parse(r):null}catch{s=null}me(e,{type:"matchState",state:s})}}e.changed.clear()}catch(n){me(e,Xo(Qn(n)))}return Mu(e)}var km={};sf(km,{BODY_F32_STRIDE:()=>xm,BodyF32Flag:()=>_m,authorityJson:()=>wD,bodiesF32:()=>gD,bodyKeysJson:()=>bD,closeAuthority:()=>zR,disposeAuthority:()=>_D,drainAuthorityEventsJson:()=>xD,frame:()=>mD,openAuthority:()=>lD,predictProjectile:()=>fD,setAuthorityIdentity:()=>Z1,setAuthorityPhysicsCore:()=>Q1,setInput:()=>dD,setWorld:()=>pD,version:()=>J1});var uw=2*Math.PI,lw=Math.fround(Math.PI),Ce=t=>t===0?0:t;function Vn(t){if(typeof t!="number"||!Number.isFinite(t))return 0;let e=t<-1?-1:t>1?1:t;return Ce(Math.fround(e))}function _s(t){if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>1e9)return null;let e=Math.fround(t-uw*Math.floor((t+Math.PI)/uw));return e===lw?-lw:Ce(e)}function fo(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<16777216?t:0}function Zl(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:t>e?e:t}var pn=(t,e,n)=>t<e?e:t>n?n:t,dw=5734161139222659/2**53,fw=1686629713/2**30,pw=2242054355/2**65,hw=5376105825661043/2**121,mw=-6004799503160649/2**55,yw=0x8888888887c53/2**58,gw=-7320136532976085/2**65,bw=6506786730409597/2**71,ww=-7571127717829867/2**78,Sw=0x5764e96b3f55f/2**83,xw=0x5555555555553/2**55,_w=-6405119470031223/2**62,Rw=457508533350745/2**64,Ew=-5205429506036397/2**74,kw=0x47ba7af6d2c71/2**79,Aw=-0x63eba6fa20e35/2**87,Fz=Object.freeze({invpio2:dw,pio2_1:fw,pio2_2:pw,pio2_2t:hw,S1:mw,S2:yw,S3:gw,S4:bw,S5:ww,S6:Sw,C1:xw,C2:_w,C3:Rw,C4:Ew,C5:kw,C6:Aw});function Ft(t){if(!Number.isFinite(t)||Math.abs(t)>1e9)return[0,1];let e=Math.floor(t*dw+.5),n=e-4*Math.floor(e/4),r=t-e*fw-e*pw-e*hw,s=r*r,o=r+s*r*(mw+s*(yw+s*(gw+s*(bw+s*(ww+s*Sw))))),i=.5*s,a=1-i,c=a+(1-a-i+s*(s*(xw+s*(_w+s*(Rw+s*(Ew+s*(kw+s*Aw)))))));return n===0?[Ce(o),Ce(c)]:n===1?[Ce(c),Ce(-o)]:n===2?[Ce(-o),Ce(-c)]:[Ce(-c),Ce(o)]}var Pw=t=>Ft(t)[0],Tw=t=>Ft(t)[1];var gr={TOPDOWN:"topdown",FIRSTPERSON:"firstperson",VEHICLE:"vehicle"},ah=.25,vv=Object.freeze({speed:6,arena:20}),Mv={speed:{min:0,max:1e3,positive:!1},arena:{min:0,max:1e6,positive:!0}};var ch=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.getPrototypeOf(t)===Object.prototype;function Dw(t,e){if(e===void 0)return!0;let n=bc(t)?.ranges;return n===void 0||!ch(e)?!1:Object.keys(e).every(r=>{if(!Object.hasOwn(n,r))return!1;let s=n[r],o=e[r];return typeof o!="number"||!Number.isFinite(o)||o<s.min||o>s.max||s.integer===!0&&!Number.isInteger(o)?!1:!s.positive||o>0&&Math.fround(o)>0})}function Di(t,e){let n=bc(t);if(n===void 0)return{};let r={...n.defaults};if(!ch(e))return r;for(let s of Object.keys(n.ranges))Dw(t,{[s]:e[s]})&&(r[s]=e[s]);return r}var rh=t=>Number.isFinite(t)?t:0;function Cv(t,e,n,r){let s=Vn(e.moveX),o=Vn(e.moveY),i=Zl(n,ah),a=Math.sqrt(s*s+o*o),c=a>1?1/a:1,u=rh(t.x)+s*c*r.speed*i,l=rh(t.y)+o*c*r.speed*i;return{x:Ce(Math.fround(pn(u,-r.arena,r.arena))),y:Ce(Math.fround(pn(l,-r.arena,r.arena))),yaw:_s(e.yaw)??Ce(Math.fround(rh(t.yaw)))}}var Nw=2615243109,Ov=Object.freeze({maxSpeed:250,walkSpeed:.52,crouchSpeed:.34,accelerate:5.5,airAccelerate:12,airMaxWishSpeed:30,friction:5.2,stopSpeed:80,gravity:800,jumpImpulse:301.993,maxVelocity:3500,radius:16,standHeight:72,crouchHeight:54,duckTime:.4,airDuck:1,stepHeight:18,standable:.7,groundTrace:2.5,groundSnap:1,skin:.03,pitchLimit:1.5533430576324463,jumpBit:1,duckBit:2,walkBit:4,substeps:2,capZeroJump:1,runBit:0,jogSpeed:1,world:Nw}),Ee=(t,e)=>({min:t,max:e,positive:!1}),ho=t=>({min:0,max:t,positive:!0}),Kt=(t,e)=>({min:t,max:e,positive:!1,integer:!0}),Iv={maxSpeed:Ee(0,1e4),walkSpeed:Ee(0,1),crouchSpeed:Ee(0,1),accelerate:Ee(0,1e3),airAccelerate:Ee(0,1e3),airMaxWishSpeed:Ee(0,1e4),friction:Ee(0,1e3),stopSpeed:Ee(0,1e4),gravity:Ee(0,1e5),jumpImpulse:Ee(0,1e5),maxVelocity:Ee(0,1e5),radius:ho(1e4),standHeight:ho(1e4),crouchHeight:ho(1e4),duckTime:ho(100),airDuck:Kt(0,1),stepHeight:Ee(0,1e4),standable:Ee(0,1),groundTrace:Ee(0,1e4),groundSnap:Ee(0,1e4),skin:Ee(0,100),pitchLimit:Ee(0,1.5707963705062866),jumpBit:Kt(0,16777215),duckBit:Kt(0,16777215),walkBit:Kt(0,16777215),substeps:Kt(1,8),capZeroJump:Kt(0,1),runBit:Kt(0,16777215),jogSpeed:Ee(0,1),world:Kt(0,2**32-1)};var zt={ON_GROUND:1,DUCKING:2,JUMP_HELD:4},Dv=zt.ON_GROUND|zt.DUCKING|zt.JUMP_HELD,Nv={MAX_BOXES:32768,MAX_RAMPS:4096,MAX_ABS:1e9},hn=class extends RangeError{constructor(n,r){super(`firstperson world: ${n} ${r}`);m(this,"path");this.name="WorldError",this.path=n}},mc=new WeakMap,Bv=(t,e)=>{if(typeof t!="number"||!Number.isFinite(t))throw new hn(e,"is not a finite number");if(Math.fround(t)!==t)throw new hn(e,"is not a float32");if(Math.abs(t)>1e9)throw new hn(e,`is past \xB1${1e9}`);return Ce(t)};function vw(t,e,n){if(!Array.isArray(t)||t.length!==e)throw new hn(n,`is not an array of ${e} numbers`);let r=[];for(let s=0;s<e;s++)r.push(Bv(t[s],`${n}[${s}]`));if(!(r[0]<r[3]&&r[1]<r[4]&&r[2]<r[5]))throw new hn(n,"needs min < max on every axis");return r}function Mw(t,e,n){if(t===void 0)return[];if(!Array.isArray(t))throw new hn(e,"is not an array");if(t.length>n)throw new hn(e,`holds more than ${n}`);return t}function Lv(t,e){let n=new DataView(new ArrayBuffer(8+4*(6*t.length+9*e.length)));n.setUint32(0,t.length,!0),n.setUint32(4,e.length,!0);let r=8;for(let o of[...t,...e])for(let i of o)n.setFloat32(r,i,!0),r+=4;let s=2166136261;for(let o=0;o<n.byteLength;o++)s=Math.imul(s^n.getUint8(o),16777619)>>>0;return s}function mo(t,e={}){let n=mc.has(t)?t:void 0;if(n!==void 0&&(e.broadphase===void 0||e.broadphase===n.broadphase))return n;if(t!==void 0&&!ch(t))throw new hn("$","is not an object");let r=t??{},s=e.caps??Nv,o=Mw(r.boxes,"boxes",s.MAX_BOXES).map((c,u)=>Object.freeze(vw(c,6,`boxes[${u}]`))),i=Mw(r.ramps,"ramps",s.MAX_RAMPS).map((c,u)=>{let l=`ramps[${u}]`,d=vw(c,9,l);if(d[6]!==0&&d[6]!==1)throw new hn(`${l}[6]`,"is not an axis (0 or 1)");let[f,h,p,y]=[d[2],d[5],d[7],d[8]];if(!(f<=p&&f<=y))throw new hn(l,"needs minZ \u2264 lo and minZ \u2264 hi");if(h!==Math.max(p,y))throw new hn(l,"needs maxZ = max(lo, hi)");return Object.freeze(d)}),a=Object.freeze({boxes:Object.freeze(o),ramps:Object.freeze(i),hash:Lv(o,i),broadphase:e.broadphase!==!1});return mc.set(a,Fv(a)),a}var yc=mo(void 0),Vr={Box:0,OBox:1,Disc:2},oh=96,uh=new Int32Array(oh);function gc(t){let e=t.length;if(e>oh)throw new RangeError(`posed solids: at most ${oh} a tick`);let n=()=>new Float64Array(e),r={count:e,kind:new Uint8Array(e),minX:n(),minY:n(),minZ:n(),maxX:n(),maxY:n(),maxZ:n(),cx:n(),cy:n(),hx:n(),hy:n(),sin:n(),cos:n(),radius:n()};return t.forEach((s,o)=>{if(s.kind==="box"){r.kind[o]=Vr.Box,[r.minX[o],r.minY[o],r.minZ[o]]=s.min,[r.maxX[o],r.maxY[o],r.maxZ[o]]=s.max;return}if(r.cx[o]=s.c[0],r.cy[o]=s.c[1],r.minZ[o]=s.c[2]-(s.kind==="disc"?s.half:s.half[2]),r.maxZ[o]=s.c[2]+(s.kind==="disc"?s.half:s.half[2]),s.kind==="disc"){r.kind[o]=Vr.Disc,r.radius[o]=s.radius,r.minX[o]=s.c[0]-s.radius,r.maxX[o]=s.c[0]+s.radius,r.minY[o]=s.c[1]-s.radius,r.maxY[o]=s.c[1]+s.radius;return}r.kind[o]=Vr.OBox,r.hx[o]=s.half[0],r.hy[o]=s.half[1],r.sin[o]=s.sin,r.cos[o]=s.cos;let i=Math.abs(s.cos),a=Math.abs(s.sin),c=s.half[0]*i+s.half[1]*a,u=s.half[0]*a+s.half[1]*i;r.minX[o]=s.c[0]-c,r.maxX[o]=s.c[0]+c,r.minY[o]=s.c[1]-u,r.maxY[o]=s.c[1]+u}),r}var Bw=gc([]);function lh(t){let e=mc.get(t);if(e!==void 0)return e;let n=mo(t,{broadphase:t.broadphase!==!1}),r=mc.get(n);return mc.set(t,r),r}var Ii=8,Cw=2**23;function Fv(t){let e=[...t.boxes,...t.ramps],n=e.length,r=()=>new Float64Array(n),s={boxCount:t.boxes.length,count:n,minX:r(),minY:r(),minZ:r(),maxX:r(),maxY:r(),maxZ:r(),axis:new Uint8Array(n),lo:r(),hi:r(),m0:r(),span:r(),slope:r(),topZ:r()};return e.forEach((o,i)=>{if(s.minX[i]=o[0],s.minY[i]=o[1],s.minZ[i]=o[2],s.maxX[i]=o[3],s.maxY[i]=o[4],s.maxZ[i]=o[5],i<s.boxCount)return;let a=o[6],c=a===0?o[0]:o[1],l=(a===0?o[3]:o[4])-c,d=(o[8]-o[7])/l;s.axis[i]=a,s.lo[i]=o[7],s.hi[i]=o[8],s.m0[i]=c,s.span[i]=l,s.slope[i]=d,s.topZ[i]=1/Math.sqrt(1+d*d)}),{...s,tree:t.broadphase&&n>0?Uv(s):null}}function sh(t){let e=t&1023;return e=(e|e<<16)&50331903,e=(e|e<<8)&50393103,e=(e|e<<4)&51130563,e=(e|e<<2)&153391689,e}function zv(t,e){let n=1/0,r=1/0,s=1/0,o=-1/0,i=-1/0,a=-1/0;for(let d=0;d<t;d++)n=Math.min(n,e.minX[d]),r=Math.min(r,e.minY[d]),s=Math.min(s,e.minZ[d]),o=Math.max(o,e.maxX[d]),i=Math.max(i,e.maxY[d]),a=Math.max(a,e.maxZ[d]);let c=(d,f,h)=>h>f?Math.min(1023,Math.floor((d-f)/(h-f)*1024)):0,u=new Float64Array(t);for(let d=0;d<t;d++){let f=c((e.minX[d]+e.maxX[d])/2,n,o),h=c((e.minY[d]+e.maxY[d])/2,r,i),p=c((e.minZ[d]+e.maxZ[d])/2,s,a);u[d]=(sh(f)|sh(h)<<1|sh(p)<<2)*Cw+d}u.sort();let l=new Int32Array(t);for(let d=0;d<t;d++)l[d]=u[d]%Cw;return l}function Uv(t){let e=t.count,n=zv(e,t),r=[e];for(;r[r.length-1]>1;)r.push(Math.ceil(r[r.length-1]/Ii));let s=r.reduce((l,d)=>l+d,0),o=new Float64Array(s*6),i=new Int32Array(s),a=new Int32Array(r.length);for(let l=0;l<e;l++){let d=n[l],f=l*6;o[f]=t.minX[d],o[f+1]=t.minY[d],o[f+2]=t.minZ[d],o[f+3]=t.maxX[d],o[f+4]=t.maxY[d],o[f+5]=t.maxZ[d],i[l]=d}a[0]=e;let c=0,u=e;for(let l=1;l<r.length;l++){let d=a[l-1];for(let f=c;f<d;f+=Ii){let h=Math.min(f+Ii,d),p=1/0,y=1/0,S=1/0,w=-1/0,x=-1/0,R=-1/0;for(let E=f;E<h;E++){let P=E*6;p=Math.min(p,o[P]),y=Math.min(y,o[P+1]),S=Math.min(S,o[P+2]),w=Math.max(w,o[P+3]),x=Math.max(x,o[P+4]),R=Math.max(R,o[P+5])}let A=u*6;o[A]=p,o[A+1]=y,o[A+2]=S,o[A+3]=w,o[A+4]=x,o[A+5]=R,i[u]=f,u++}c=d,a[l]=u}return{boxes:o,ref:i,levelEnd:a,root:s-1}}var Lw=16,Fw=50,Vv=.5,dh=(t,e)=>t/e<Vv?t/e:1,fh=(t,e,n,r,s,o)=>.001+1e-7*(Math.abs(t)+Math.abs(e)+Math.abs(n)+Math.abs(r)+Math.abs(s)+Math.abs(o)),yr=null;function ph(t,e,n,r,s,o,i){Hv(t,e,n,r,s,o,i);let a=t.w.tree;if(a===null){t.nCand=-1;return}let c=fh(e,n,r,s,o,i),u=t.r+c,l=e-u,d=s+u,f=n-u,h=o+u,p=r-c,y=i+c,{boxes:S,ref:w,levelEnd:x}=a,R=x[0],A=t.cand,E=t.stack,P=0,k=0,M=0;for(E[k++]=a.root;k>0;){let L=E[--k];M+=1;let K=L*6;if(S[K+3]<l||S[K]>d||S[K+4]<f||S[K+1]>h||S[K+5]<p||S[K+2]>y)continue;if(L<R){A[P++]=w[L];continue}let W=w[L],B=W+Ii;for(let se=0;se<x.length;se++)if(W<x[se]){B=Math.min(B,x[se]);break}for(let se=W;se<B;se++)E[k++]=se}t.nCand=P,yr!==null&&(yr.nodes+=M,yr.tests+=P)}function Hv(t,e,n,r,s,o,i){let a=t.p,c=0;if(a.count>0){let u=fh(e,n,r,s,o,i),l=t.r+u,d=e-l,f=s+l,h=n-l,p=o+l,y=r-u,S=i+u;for(let w=0;w<a.count;w++)a.maxX[w]<d||a.minX[w]>f||a.maxY[w]<h||a.minY[w]>p||a.maxZ[w]<y||a.minZ[w]>S||(t.pc[c++]=w)}t.nPosed=c}var hh=t=>(t.nCand<0?t.w.count:t.nCand)+t.nPosed,mh=(t,e)=>{let n=t.nCand<0?t.w.count:t.nCand;return e>=n?t.w.count+t.pc[e-n]:t.nCand<0?e:t.cand[e]},zr=(t,e)=>t.standHeight+(t.crouchHeight-t.standHeight)*e;function $v(t,e,n,r){let s=t.w,o=s.slope[e],i=s.axis[e]===0?n:r,a=o>0?i+t.r:o<0?i-t.r:i;return s.lo[e]+o*pn(a-s.m0[e],0,s.span[e])}function zw(t,e,n,r){let s=t.w;return e<s.boxCount?s.maxZ[e]:e<s.count?$v(t,e,n,r):t.p.maxZ[e-s.count]}var jv=(t,e)=>e<t.w.count?t.w.minZ[e]:t.p.minZ[e-t.w.count];function Uw(t,e,n,r){let s=t.w,o=t.r;return e>=s.count?Ww(t,e-s.count,n,r):n+o>s.minX[e]&&n-o<s.maxX[e]&&r+o>s.minY[e]&&r-o<s.maxY[e]}function Vw(t,e,n,r,s){let o=t.w;ph(t,e,n,r,e,n,r+s);let i=hh(t);for(let a=0;a<i;a++){let c=mh(t,a);if(!Uw(t,c,e,n)||!(r+s>jv(t,c)))continue;let u=zw(t,c,e,n);if(r<u-1e-4)return!1}return!0}function sd(t,e,n,r,s,o){let i=t.w;ph(t,e,n,r-s,e,n,r+o);let a=hh(t),c=Number.NaN,u=Number.NaN;for(let l=0;l<a;l++){let d=mh(t,l);if(!Uw(t,d,e,n))continue;let f=zw(t,d,e,n);f<=r+o&&f>=r-s&&(d<i.boxCount||d>=i.count||i.topZ[d]>=t.standable?(c!==c||f>c)&&(c=f):(u!==u||f>u)&&(u=f))}return u>c?Number.NaN:c}function td(t){if(t.vz>.1*t.unit){t.onGround=!1;return}let e=sd(t,t.x,t.y,t.z,t.groundTrace,t.groundSnap);e===e?(t.z=e,t.onGround=!0):t.onGround=!1}function ed(t,e,n,r,s,o){if(Math.abs(n)<1e-9)return e>r&&e<s;let i=(r-e)/n,a=(s-e)/n,c=-1;if(i>a){let u=i;i=a,a=u,c=1}return i>=t.tMin&&(t.tMin=i,t.ax=o,t.sg=c),a<t.tMax&&(t.tMax=a),!(t.tMin>t.tMax)}var Je=new Float64Array(4);function Wv(t,e,n,r){let s=t.w,o=t.r,i=0,a=0,c=0,u;switch(n){case 0:i=1,u=s.maxX[e]+o;break;case 1:i=-1,u=-s.minX[e]+o;break;case 2:a=1,u=s.maxY[e]+o;break;case 3:a=-1,u=-s.minY[e]+o;break;case 4:c=-1,u=-s.minZ[e]+r;break;case 5:{let l=s.slope[e];s.axis[e]===0?i=-l:a=-l,c=1,u=s.lo[e]-l*s.m0[e]+o*Math.abs(l);break}default:c=1,u=s.maxZ[e]}Je[0]=i,Je[1]=a,Je[2]=c,Je[3]=u}function nd(t,e,n,r,s,o){let i=t.w,a=t.r,c=t.skin;if(s>=i.count)return Xv(t,e,n,r,s-i.count,o);if(s<i.boxCount)return e-(i.minX[s]-a)>c&&i.maxX[s]+a-e>c&&n-(i.minY[s]-a)>c&&i.maxY[s]+a-n>c&&r-(i.minZ[s]-o)>c&&i.maxZ[s]-r>c;for(let u=0;u<7;u++){Wv(t,s,u,o);let l=Je[0],d=Je[1],f=Je[2];if(!(-(l*e+d*n+f*r-Je[3])*(1/Math.sqrt(l*l+d*d+f*f))>c))return!1}return!0}function yh(t,e,n,r,s,o,i,a,c){let u=t.w.count,l=t.w.tree,d=0,f=0,h=y=>(f+=1,y!==a&&nd(t,e,n,r,y,c)&&!nd(t,s,o,i,y,c)),p=!1;if(l===null)for(let y=0;y<u&&!p;y++)p=h(y);else{let y=fh(e,n,r,e,n,r+c),S=t.r+y,w=e-S,x=e+S,R=n-S,A=n+S,E=r-y,P=r+c+y,{boxes:k,ref:M,levelEnd:L}=l,K=L[0],W=t.stack,B=0;for(W[B++]=l.root;B>0&&!p;){let se=W[--B];d+=1;let v=se*6;if(k[v+3]<w||k[v]>x||k[v+4]<R||k[v+1]>A||k[v+5]<E||k[v+2]>P)continue;if(se<K){p=h(M[se]);continue}let $=M[se],Y=$+Ii;for(let j=0;j<L.length;j++)if($<L[j]){Y=Math.min(Y,L[j]);break}for(let j=$;j<Y;j++)W[B++]=j}}for(let y=u;!p&&y<u+t.p.count;y++)p=h(y);return yr!==null&&(yr.nodes+=d,yr.tests+=f),p}function Hw(t,e,n,r,s,o,i,a,c,u){return yh(t,e+s*a,n+o*a,r+i*a,e,n,r,c,u)}function qv(t,e,n,r,s,o,i,a){let c=t.r,u=t.skin,l=e-(s.minX[o]-c),d=s.maxX[o]+c-e,f=n-(s.minY[o]-c),h=s.maxY[o]+c-n,p=r-(s.minZ[o]-i),y=s.maxZ[o]-r;if(!(l>u&&d>u&&f>u&&h>u&&p>u&&y>u))return!1;let S=l,w=-1,x=0,R=0;return d<S&&([S,w,x,R]=[d,1,0,0]),f<S&&([S,w,x,R]=[f,0,-1,0]),h<S&&([S,w,x,R]=[h,0,1,0]),y<S&&!yh(t,e,n,r+y,e,n,r,a,i)&&([S,w,x,R]=[y,0,0,1]),t.tMin=0,t.nx=w,t.ny=x,t.nz=R,t.depth=S,!0}function gh(t,e,n,r,s,o,i,a,c,u=t.w,l=a){let d=t.r;return t.depth=0,qv(t,e,n,r,u,a,c,l)?!0:(t.tMin=0,t.tMax=1,t.ax=-1,t.sg=0,!ed(t,e,s,u.minX[a]-d,u.maxX[a]+d,0)||!ed(t,n,o,u.minY[a]-d,u.maxY[a]+d,1)||!ed(t,r,i,u.minZ[a]-c,u.maxZ[a],2)||t.tMin>=1||t.ax<0?!1:(t.nx=t.ax===0?t.sg:0,t.ny=t.ax===1?t.sg:0,t.nz=t.ax===2?t.sg:0,!0))}function Gv(t,e,n,r,s,o,i,a,c){let u=t.w,l=t.r,d=u.slope[a],f=u.axis[a]===0,h=0,p=1,y=!1,S=!0,w=Number.POSITIVE_INFINITY,x=0,R=0,A=0;t.depth=0;for(let E=0;E<7;E++){let P=0,k=0,M=0,L;switch(E){case 0:P=1,L=u.maxX[a]+l;break;case 1:P=-1,L=-u.minX[a]+l;break;case 2:k=1,L=u.maxY[a]+l;break;case 3:k=-1,L=-u.minY[a]+l;break;case 4:M=-1,L=-u.minZ[a]+c;break;case 5:f?P=-d:k=-d,M=1,L=u.lo[a]-d*u.m0[a]+l*Math.abs(d);break;default:M=1,L=u.maxZ[a]}let K=P*e+k*n+M*r-L,W=P*s+k*o+M*i,B=1/Math.sqrt(P*P+k*k+M*M),se=-K*B;if(se>t.skin?E!==4&&se<w&&!(S&&E>=5&&Hw(t,e,n,r,P*B,k*B,M*B,se,a,c))&&(w=se,x=P*B,R=k*B,A=M*B):S=!1,Math.abs(W)<1e-9){if(K>0)return!1;continue}let v=W<0&&K<=0&&K>-t.skin?0:-K/W;if(W<0?v>=h&&(h=v,t.nx=P*B,t.ny=k*B,t.nz=M*B,y=!0):p=Math.min(p,v),h>p)return!1}return S?(t.tMin=0,t.nx=x,t.ny=R,t.nz=A,t.depth=w,!0):!y||!(h<1)||!(p>=0)?!1:(t.tMin=h,!0)}function $w(t,e,n,r){let s=t.p,o=s.cos[e],i=s.sin[e],a=s.cx[e],c=s.cy[e],u=s.hx[e],l=s.hy[e],d=t.r,f=d*(Math.abs(o)+Math.abs(i)),h=0,p=0,y=0,S;switch(n){case 0:h=o,p=i,S=o*a+i*c+u+f;break;case 1:h=-o,p=-i,S=-(o*a+i*c)+u+f;break;case 2:h=-i,p=o,S=-i*a+o*c+l+f;break;case 3:h=i,p=-o,S=i*a-o*c+l+f;break;case 4:h=1,S=a+d+u*Math.abs(o)+l*Math.abs(i);break;case 5:h=-1,S=-a+d+u*Math.abs(o)+l*Math.abs(i);break;case 6:p=1,S=c+d+u*Math.abs(i)+l*Math.abs(o);break;case 7:p=-1,S=-c+d+u*Math.abs(i)+l*Math.abs(o);break;case 8:y=-1,S=-s.minZ[e]+r;break;default:y=1,S=s.maxZ[e]}Je[0]=h,Je[1]=p,Je[2]=y,Je[3]=S}var Yv=10,jw=8,Kv=9;function Ww(t,e,n,r){let s=t.p,o=t.r;if(!(n+o>s.minX[e]&&n-o<s.maxX[e]&&r+o>s.minY[e]&&r-o<s.maxY[e]))return!1;let i=s.kind[e];if(i===Vr.Box)return!0;let a=n-s.cx[e],c=r-s.cy[e];if(i===Vr.Disc){let f=Math.max(Math.abs(a)-o,0),h=Math.max(Math.abs(c)-o,0);return f*f+h*h<s.radius[e]*s.radius[e]}let u=s.cos[e],l=s.sin[e],d=o*(Math.abs(u)+Math.abs(l));return Math.abs(u*a+l*c)<s.hx[e]+d&&Math.abs(-l*a+u*c)<s.hy[e]+d}function qw(t,e,n,r){let s=t.p,o=t.r,i=n-s.cx[e],a=r-s.cy[e],c=Math.abs(i),u=Math.abs(a),l=s.radius[e];if(c<=o&&u<=o){let p=c>=u;return Je[0]=p?i<0?-1:1:0,Je[1]=p?0:a<0?-1:1,l+o-(p?c:u)}let d=c>o?i<0?-(c-o):c-o:0,f=u>o?a<0?-(u-o):u-o:0,h=Math.sqrt(d*d+f*f);return Je[0]=d/h,Je[1]=f/h,l-h}function Xv(t,e,n,r,s,o){let i=t.p,a=t.skin,c=i.kind[s];if(c===Vr.Box){let u=t.r;return e-(i.minX[s]-u)>a&&i.maxX[s]+u-e>a&&n-(i.minY[s]-u)>a&&i.maxY[s]+u-n>a&&r-(i.minZ[s]-o)>a&&i.maxZ[s]-r>a}if(!(r-(i.minZ[s]-o)>a&&i.maxZ[s]-r>a))return!1;if(c===Vr.Disc)return qw(t,s,e,n)>a;for(let u=0;u<jw;u++){$w(t,s,u,o);let l=Je[0],d=Je[1];if(!(-(l*e+d*n-Je[3])*(1/Math.sqrt(l*l+d*d))>a))return!1}return!0}function Jv(t,e,n,r,s,o,i,a,c,u){let l=0,d=1,f=!1,h=!0,p=Number.POSITIVE_INFINITY,y=0,S=0,w=0;t.depth=0;for(let x=0;x<Yv;x++){$w(t,a,x,u);let R=Je[0],A=Je[1],E=Je[2],P=R*e+A*n+E*r-Je[3],k=R*s+A*o+E*i,M=1/Math.sqrt(R*R+A*A+E*E),L=-P*M;if(L>t.skin?x!==jw&&L<p&&!(h&&x===Kv&&Hw(t,e,n,r,R*M,A*M,E*M,L,c,u))&&(p=L,y=R*M,S=A*M,w=E*M):h=!1,Math.abs(k)<1e-9){if(P>0)return!1;continue}let K=k<0&&P<=0&&P>-t.skin?0:-P/k;if(k<0?K>=l&&(l=K,t.nx=R*M,t.ny=A*M,t.nz=E*M,f=!0):d=Math.min(d,K),l>d)return!1}return h?(t.tMin=0,t.nx=y,t.ny=S,t.nz=w,t.depth=p,!0):!f||!(l<1)||!(d>=0)?!1:(t.tMin=l,!0)}function Zv(t,e,n,r,s,o,i,a,c,u,l,d){t.tMin=0,t.tMax=1,t.ax=-1,t.sg=0;let f=e-a,h=n-c,p=s*s+o*o,y=f*f+h*h-u*u;if(p<1e-18){if(!(y<0))return!1}else{let S=f*s+h*o,w=S*S-p*y;if(w<0)return!1;let x=Math.sqrt(w),R=(-S-x)/p,A=(-S+x)/p;if(R>=t.tMin&&(t.tMin=R,t.ax=3),A<t.tMax&&(t.tMax=A),t.tMin>t.tMax)return!1}if(!ed(t,r,i,l,d,2)||t.tMin>=1||t.ax<0)return!1;if(t.ax===3){let S=f+s*t.tMin,w=h+o*t.tMin,x=Math.sqrt(S*S+w*w);t.nx=S/x,t.ny=w/x,t.nz=0}else t.nx=0,t.ny=0,t.nz=t.sg;return!0}var Hn={minX:new Float64Array(2),minY:new Float64Array(2),minZ:new Float64Array(2),maxX:new Float64Array(2),maxY:new Float64Array(2),maxZ:new Float64Array(2)};function Qv(t,e,n,r,s,o,i,a,c,u){let l=t.p,d=t.r,f=l.radius[a],h=l.cx[a],p=l.cy[a],y=l.minZ[a]-u,S=l.maxZ[a];t.depth=0;let w=qw(t,a,e,n),x=r-y,R=S-r;if(w>t.skin&&x>t.skin&&R>t.skin)return t.tMin=0,R<w&&!yh(t,e,n,r+R,e,n,r,c,u)?[t.nx,t.ny,t.nz,t.depth]=[0,0,1,R]:[t.nx,t.ny,t.nz,t.depth]=[Je[0],Je[1],0,w],!0;let A=!1,E=0,P=0,k=0,M=0;Hn.minX[0]=h-f,Hn.maxX[0]=h+f,Hn.minY[0]=p,Hn.maxY[0]=p,Hn.minX[1]=h,Hn.maxX[1]=h,Hn.minY[1]=p-f,Hn.maxY[1]=p+f;for(let L=0;L<2;L++)Hn.minZ[L]=l.minZ[a],Hn.maxZ[L]=S,gh(t,e,n,r,s,o,i,L,u,Hn,c)&&(!A||t.tMin<E)&&(A=!0,E=t.tMin,P=t.nx,k=t.ny,M=t.nz);for(let L=0;L<4;L++){let K=L%2===0?h-d:h+d,W=L<2?p-d:p+d;Zv(t,e,n,r,s,o,i,K,W,f,y,S)&&(!A||t.tMin<E)&&(A=!0,E=t.tMin,P=t.nx,k=t.ny,M=t.nz)}return A?(t.tMin=E,t.nx=P,t.ny=k,t.nz=M,t.depth=0,!0):!1}function eM(t,e,n,r,s,o,i,a,c){let u=a-t.w.count,l=t.p.kind[u];return l===Vr.Box?gh(t,e,n,r,s,o,i,u,c,t.p,a):l===Vr.OBox?Jv(t,e,n,r,s,o,i,u,a,c):Qv(t,e,n,r,s,o,i,u,a,c)}function bh(t,e,n,r,s,o,i){let a=t.w,c=zr(t,t.duck),u=e+s,l=n+o,d=r+i;ph(t,e<u?e:u,n<l?n:l,r<d?r:d,e<u?u:e,n<l?l:n,(r<d?d:r)+c);let f=hh(t),h=!1,p=0,y=0,S=0,w=0,x=0,R=0;yr!==null&&(yr.sweeps+=f);for(let A=0;A<f;A++){let E=mh(t,A);yr!==null&&E>=a.boxCount&&E<a.count&&(yr.wedges+=1),(E<a.boxCount?gh(t,e,n,r,s,o,i,E,c):E<a.count?Gv(t,e,n,r,s,o,i,E,c):eM(t,e,n,r,s,o,i,E,c))&&(!h||t.tMin<p||t.tMin===p&&E<y)&&(h=!0,p=t.tMin,y=E,S=t.nx,w=t.ny,x=t.nz,R=t.depth)}t.hit=h,h?(t.tMin=Math.max(0,p-1e-4),t.nx=S,t.ny=w,t.nz=x,t.depth=R):(t.tMin=1,t.depth=0)}function rd(t,e,n=!1){let r=e,s=!1,o=0,i=0,a=0;for(let c=0;c<4&&r>1e-6;c++){if(t.vx*t.vx+t.vy*t.vy+t.vz*t.vz<1e-8)return;bh(t,t.x,t.y,t.z,t.vx*r,t.vy*r,t.vz*r);let u=t.tMin;if(u>0){let y=u*r;t.x=t.x+t.vx*y,t.y=t.y+t.vy*y,t.z=t.z+t.vz*y,r=r-y}if(!t.hit)return;t.depth>0&&(t.x=t.x+t.nx*t.depth,t.y=t.y+t.ny*t.depth,t.z=t.z+t.nz*t.depth);let l=t.nx,d=t.ny,f=t.nz,h=!1;if(n&&f>0)if(f>=t.standable)h=!0;else{let y=1/Math.sqrt(l*l+d*d);l=l*y,d=d*y,f=0}t.x=t.x+l*t.skin,t.y=t.y+d*t.skin,t.z=t.z+f*t.skin;let p=t.vx*l+t.vy*d+t.vz*f;if(p<0&&(h?t.vz=t.vz-p/f:(t.vx=t.vx+l*-p,t.vy=t.vy+d*-p,t.vz=t.vz+f*-p)),s){let y=i*f-a*d,S=a*l-o*f,w=o*d-i*l,x=y*y+S*S+w*w;if(x>1e-6){let R=1/Math.sqrt(x);y=y*R,S=S*R,w=w*R;let A=t.vx*y+t.vy*S+t.vz*w;t.vx=y*A,t.vy=S*A,t.vz=w*A}}if(s=!0,o=l,i=d,a=f,t.vx*t.vx+t.vy*t.vy+t.vz*t.vz<1e-8)return}}function Gw(t,e=!1){let n=t.x,r=t.y,s=t.z,o=t.vx,i=t.vy,a=t.vz;rd(t,t.h,e);let c=t.x,u=t.y,l=t.z,d=t.vx,f=t.vy,h=t.vz,p=c-n,y=u-r,S=p*p+y*y;t.x=n,t.y=r,t.z=s,t.vx=o,t.vy=i,t.vz=a;let w=t.stepHeight+t.skin;bh(t,n,r,s,0,0,w);let x=t.tMin,R=s+w*x;if(x>0&&Vw(t,n,r,R,zr(t,t.duck))){t.z=R,rd(t,t.h,e);let A=sd(t,t.x,t.y,t.z,t.stepHeight*2,.001);A===A&&(t.z=A);let E=t.x-n,P=t.y-r,k=E*E+P*P;if(A===A&&k>S+.001*t.unit*t.unit){t.vz=0;return}}t.x=c,t.y=u,t.z=l,t.vx=d,t.vy=f,t.vz=h}function Yw(t){let e=sd(t,t.x,t.y,t.z,t.stepHeight,t.groundSnap);e===e&&(t.z=e,t.vz=0)}function tM(t){let e=Math.sqrt(t.vx*t.vx+t.vy*t.vy);if(e<.1*t.unit){t.vx=0,t.vy=0;return}let r=(e<t.stopSpeed?t.stopSpeed:e)*t.friction*t.h,s=Math.max(0,e-r)/e;t.vx=t.vx*s,t.vy=t.vy*s}function nM(t){let e=t.wishSpeed-(t.vx*t.dirX+t.vy*t.dirY);if(e<=0)return;let n=t.accelerate*t.h*Math.max(t.wishSpeed,t.maxSpeed);n>e&&(n=e),t.vx=t.vx+n*t.dirX,t.vy=t.vy+n*t.dirY}function Ow(t){let e=Math.min(t.wishSpeed,t.airMaxWishSpeed)-(t.vx*t.dirX+t.vy*t.dirY);if(e<=0)return;let n=t.airAccelerate*t.wishSpeed*t.h;n>e&&(n=e),t.vx=t.vx+n*t.dirX,t.vy=t.vy+n*t.dirY}var Rn=t=>Ce(Math.fround(pn(t,-1e9,1e9)));function rM(t,e,n){let r=t.h/t.duckTime;if(!(e&&!t.onGround&&!t.airDuck)){if(e){let a=Math.min(1,t.duck+r);t.onGround||(t.z=t.z+(zr(t,t.duck)-zr(t,a))),t.duck=a,t.ducking=!0}else if(t.duck>0){let a=Math.max(0,t.duck-r),c=t.onGround?t.z:t.z-(zr(t,a)-zr(t,t.duck));Vw(t,t.x,t.y,c,zr(t,a))&&(t.duck=a,t.z=c,t.duck===0&&(t.ducking=!1))}}let s=t.onGround;td(t),t.onGround&&!s&&(t.vz=0),t.base=t.maxSpeed*t.cap;let o=t.ducking?t.base*t.crouchSpeed:n?t.base*t.walkSpeed:t.jogging?t.base*t.jogSpeed:t.base;t.wishSpeed=t.amount*o,t.onGround?t.pressed?(t.vz=t.jumpImpulse,t.onGround=!1,t.pressed=!1,Ow(t)):(tM(t),nM(t),t.vz=0):Ow(t);let i=!t.onGround;i&&(t.vz=t.vz-t.gravity*t.h*.5),t.vx=pn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=pn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=pn(t.vz,-t.maxVelocity,t.maxVelocity),t.onGround?(Gw(t),Yw(t)):rd(t,t.h),td(t),i&&!t.onGround?t.vz=t.vz-t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=Rn(t.x),t.y=Rn(t.y),t.z=Rn(t.z),t.vx=Rn(t.vx),t.vy=Rn(t.vy),t.vz=Rn(t.vz),t.duck=Ce(Math.fround(t.duck))}var Pt=(t,e,n,r)=>Ce(Math.fround(pn(typeof t=="number"&&Number.isFinite(t)?t:e,n,r))),ih=t=>Ce(Math.fround(typeof t=="number"&&Number.isFinite(t)?t:0)),Ql={cand:new Int32Array(0),stack:new Int32Array(Ii*16)};function wh(t){return Ql.cand.length<t.count&&(Ql={cand:new Int32Array(t.count),stack:Ql.stack}),Ql}function Kw(t,e,n=yc){let r=lh(n),s=Math.fround,o=a=>s(t==="vehicle"?e.height:e[a]),i=(a,c)=>{let u=wh(r);return{w:r,p:gc(c),r:s(e.radius),unit:dh(s(e.radius),t==="vehicle"?Fw:Lw),standHeight:o("standHeight"),crouchHeight:o("crouchHeight"),stepHeight:s(e.stepHeight),standable:s(e.standable),groundTrace:s(e.groundTrace),groundSnap:s(e.groundSnap),skin:s(e.skin),x:a.x,y:a.y,z:a.z,vx:0,vy:0,vz:a.vz??0,duck:t==="vehicle"?0:a.duck??0,onGround:!1,h:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:u.cand,nCand:-1,pc:uh,nPosed:0,stack:u.stack}};return{support(a,c){let u=i(a,c);if(u.vz>.1*u.unit)return-1;let l=sd(u,u.x,u.y,u.z,u.groundTrace,u.groundSnap);if(l!==l)return-1;for(let d=0;d<u.p.count;d++)if(u.p.maxZ[d]===l&&Ww(u,d,u.x,u.y))return d;return-1},inside(a,c,u){let l=i(a,c);return nd(l,l.x,l.y,l.z,r.count+u,zr(l,l.duck))},pushOut(a,c){let u=i(a,c);for(let f=0;f<4&&(bh(u,u.x,u.y,u.z,0,0,0),!!u.hit);f++)u.x=u.x+u.nx*u.depth,u.y=u.y+u.ny*u.depth,u.z=u.z+u.nz*u.depth,u.x=u.x+u.nx*u.skin,u.y=u.y+u.ny*u.skin,u.z=u.z+u.nz*u.skin;let l=zr(u,u.duck),d=!1;for(let f=0;f<r.count+u.p.count&&!d;f++)d=nd(u,u.x,u.y,u.z,f,l);return{x:u.x,y:u.y,z:u.z,inside:d}}}}function sM(t,e,n,r,s=yc,o=Bw){let i=lh(s),a=wh(i),c=Math.fround,u=fo(t.mstate)&Dv,l={w:i,p:o,maxSpeed:c(r.maxSpeed),walkSpeed:c(r.walkSpeed),jogSpeed:c(r.jogSpeed),jogging:!1,crouchSpeed:c(r.crouchSpeed),accelerate:c(r.accelerate),airAccelerate:c(r.airAccelerate),airMaxWishSpeed:c(r.airMaxWishSpeed),friction:c(r.friction),stopSpeed:c(r.stopSpeed),gravity:c(r.gravity),jumpImpulse:c(r.jumpImpulse),maxVelocity:c(r.maxVelocity),r:c(r.radius),unit:dh(c(r.radius),Lw),standHeight:c(r.standHeight),crouchHeight:c(r.crouchHeight),duckTime:c(r.duckTime),airDuck:r.airDuck!==0,stepHeight:c(r.stepHeight),standable:c(r.standable),groundTrace:c(r.groundTrace),groundSnap:c(r.groundSnap),skin:c(r.skin),x:Pt(t.x,0,-1e9,1e9),y:Pt(t.y,0,-1e9,1e9),z:Pt(t.z,0,-1e9,1e9),vx:Pt(t.vx,0,-1e9,1e9),vy:Pt(t.vy,0,-1e9,1e9),vz:Pt(t.vz,0,-1e9,1e9),duck:Pt(t.duck,0,0,1),cap:Pt(t.cap,1,0,4),onGround:(u&zt.ON_GROUND)!==0,ducking:(u&zt.DUCKING)!==0,jumpHeld:(u&zt.JUMP_HELD)!==0,pressed:!1,h:0,dirX:0,dirY:0,amount:0,base:0,wishSpeed:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:a.cand,nCand:-1,pc:uh,nPosed:0,stack:a.stack},d=Vn(e.moveX),f=Vn(e.moveY),h=Math.sqrt(d*d+f*f);h>1e-4&&(l.dirX=d/h,l.dirY=f/h,l.amount=Math.min(h,1));let p=fo(e.buttons),y=(p&r.jumpBit)!==0,S=(p&r.duckBit)!==0,w=(p&r.walkBit)!==0;l.jogging=r.runBit!==0&&(p&r.runBit)===0;let x=Zl(n,ah);l.h=x/r.substeps;let R=_s(e.yaw)??ih(t.yaw),A=c(r.pitchLimit),E=Ce(pn(_s(e.pitch)??ih(t.pitch),-A,A));if(x>0){l.pressed=y&&!l.jumpHeld&&(r.capZeroJump!==0||l.cap!==0),l.jumpHeld=y;for(let P=0;P<r.substeps;P++)rM(l,S,w)}return{x:l.x,y:l.y,z:l.z,vx:l.vx,vy:l.vy,vz:l.vz,yaw:R,pitch:E,duck:l.duck,mstate:(l.onGround?zt.ON_GROUND:0)+(l.ducking?zt.DUCKING:0)+(l.jumpHeld?zt.JUMP_HELD:0)}}var oM=Object.freeze({maxSpeed:1410,accel:1e3,brake:3500,coast:525,boostAccel:1e3,boostMaxSpeed:2300,boostBurn:.3333333432674408,grip:6e3,driftGrip:1500,turnRate:2.2,turnSpeed:400,spinAccel:30,airTurnRate:5.5,airSpinAccel:9,gravity:650,jumpImpulse:450,maxVelocity:6e3,radius:50,height:36,stepHeight:8,standable:.7,groundTrace:4,groundSnap:2,skin:.03,jumpBit:1,boostBit:2,driftBit:4,substeps:2,capZeroJump:1,world:Nw}),iM={maxSpeed:Ee(0,1e5),accel:Ee(0,1e5),brake:Ee(0,1e5),coast:Ee(0,1e5),boostAccel:Ee(0,1e5),boostMaxSpeed:Ee(0,1e5),boostBurn:Ee(0,1e3),grip:Ee(0,1e5),driftGrip:Ee(0,1e5),turnRate:Ee(0,100),turnSpeed:ho(1e5),spinAccel:Ee(0,1e4),airTurnRate:Ee(0,100),airSpinAccel:Ee(0,1e4),gravity:Ee(0,1e5),jumpImpulse:Ee(0,1e5),maxVelocity:Ee(0,1e5),radius:ho(1e4),height:ho(1e4),stepHeight:Ee(0,1e4),standable:Ee(0,1),groundTrace:Ee(0,1e4),groundSnap:Ee(0,1e4),skin:Ee(0,100),jumpBit:Kt(0,16777215),boostBit:Kt(0,16777215),driftBit:Kt(0,16777215),substeps:Kt(1,8),capZeroJump:Kt(0,1),world:Kt(0,2**32-1)};var aM=zt.ON_GROUND|zt.JUMP_HELD,po=(t,e,n)=>t<e?Math.min(e,t+n):t>e?Math.max(e,t-n):t,Xw=t=>_s(t)??0;function cM(t){let e=t.maxSpeed*t.cap,n=t.boosting?1:t.throttle,r=n*e,s=t.f;if(n===0?s=po(s,0,t.coast*t.h):n>0&&s<0||n<0&&s>0?s=po(s,0,t.brake*t.h):Math.abs(s)<Math.abs(r)?s=po(s,r,t.accel*t.h):t.boosting||(s=po(s,r,t.coast*t.h)),t.boosting){let a=t.boostMaxSpeed*t.cap;s<a&&(s=Math.min(a,s+t.boostAccel*t.h))}let o=po(t.l,0,(t.drift?t.driftGrip:t.grip)*t.h),i=t.steer*t.turnRate*Math.min(1,Math.abs(s)/t.turnSpeed);s<0&&(i=-i),t.spin=po(t.spin,i,t.spinAccel*t.h),t.vx=s*t.c-o*t.s,t.vy=s*t.s+o*t.c,t.vz=0,t.f=s,t.l=o}function uM(t){if(t.spin=po(t.spin,t.steer*t.airTurnRate,t.airSpinAccel*t.h),t.boosting){let e=t.boostMaxSpeed*t.cap;if(t.f<e){let n=Math.min(t.boostAccel*t.h,e-t.f);t.vx=t.vx+n*t.c,t.vy=t.vy+n*t.s}}}function lM(t){let e=t.onGround;td(t),t.onGround&&!e&&(t.vz=0),t.c=Tw(t.yaw),t.s=Pw(t.yaw),t.f=t.vx*t.c+t.vy*t.s,t.l=t.vy*t.c-t.vx*t.s,t.boosting=t.boost&&t.fuel>0,t.boosting&&(t.fuel=Math.max(0,t.fuel-t.boostBurn*t.h)),t.onGround&&t.pressed&&(t.vz=t.jumpImpulse,t.onGround=!1,t.pressed=!1),t.onGround?cM(t):uM(t);let n=!t.onGround;n&&(t.vz-=t.gravity*t.h*.5),t.vx=pn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=pn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=pn(t.vz,-t.maxVelocity,t.maxVelocity),t.yaw=Xw(t.yaw+t.spin*t.h),t.onGround?(Gw(t,!0),Yw(t)):rd(t,t.h),td(t),n&&!t.onGround?t.vz-=t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=Rn(t.x),t.y=Rn(t.y),t.z=Rn(t.z),t.vx=Rn(t.vx),t.vy=Rn(t.vy),t.vz=Rn(t.vz),t.spin=Ce(Math.fround(t.spin)),t.fuel=Ce(Math.fround(t.fuel))}function dM(t,e,n,r,s=yc,o=Bw){let i=lh(s),a=wh(i),c=Math.fround,u=fo(t.mstate)&aM,l=c(r.height),d=Ce(-Vn(e.moveX)),f=Vn(e.moveY),h=fo(e.buttons),p=(h&r.jumpBit)!==0,y=Zl(n,ah),S=ih(t.yaw),w={w:i,p:o,r:c(r.radius),unit:dh(c(r.radius),Fw),standHeight:l,crouchHeight:l,stepHeight:c(r.stepHeight),standable:c(r.standable),groundTrace:c(r.groundTrace),groundSnap:c(r.groundSnap),skin:c(r.skin),maxSpeed:c(r.maxSpeed),accel:c(r.accel),brake:c(r.brake),coast:c(r.coast),boostAccel:c(r.boostAccel),boostMaxSpeed:c(r.boostMaxSpeed),boostBurn:c(r.boostBurn),grip:c(r.grip),driftGrip:c(r.driftGrip),turnRate:c(r.turnRate),turnSpeed:c(r.turnSpeed),spinAccel:c(r.spinAccel),airTurnRate:c(r.airTurnRate),airSpinAccel:c(r.airSpinAccel),gravity:c(r.gravity),jumpImpulse:c(r.jumpImpulse),maxVelocity:c(r.maxVelocity),x:Pt(t.x,0,-1e9,1e9),y:Pt(t.y,0,-1e9,1e9),z:Pt(t.z,0,-1e9,1e9),vx:Pt(t.vx,0,-1e9,1e9),vy:Pt(t.vy,0,-1e9,1e9),vz:Pt(t.vz,0,-1e9,1e9),yaw:Math.abs(S)<=1e9?Xw(S):0,spin:Pt(t.spin,0,-1e3,1e3),fuel:Pt(t.fuel,0,0,1),cap:Pt(t.cap,1,0,4),duck:0,onGround:(u&zt.ON_GROUND)!==0,jumpHeld:(u&zt.JUMP_HELD)!==0,pressed:!1,boosting:!1,steer:d,throttle:f,boost:(h&r.boostBit)!==0,drift:(h&r.driftBit)!==0,h:y/r.substeps,c:1,s:0,f:0,l:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:a.cand,nCand:-1,pc:uh,nPosed:0,stack:a.stack};if(y>0){w.pressed=p&&!w.jumpHeld&&(r.capZeroJump!==0||w.cap!==0),w.jumpHeld=p;for(let x=0;x<r.substeps;x++)lM(w)}return{x:w.x,y:w.y,z:w.z,vx:w.vx,vy:w.vy,vz:w.vz,yaw:w.yaw,spin:w.spin,fuel:w.fuel,mstate:(w.onGround?zt.ON_GROUND:0)+(w.jumpHeld?zt.JUMP_HELD:0)}}var fM={defaults:vv,ranges:Mv,fields:["x","y","yaw"],reads:[],world:!1,step:(t,e,n,r)=>Cv(t,e,n,r)},pM={defaults:Ov,ranges:Iv,fields:["x","y","z","vx","vy","vz","yaw","pitch","duck","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>sM(t,e,n,r,s,o)},hM={defaults:oM,ranges:iM,fields:["x","y","z","vx","vy","vz","yaw","spin","fuel","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>dM(t,e,n,r,s,o)},Iw=Object.freeze({[gr.TOPDOWN]:Object.freeze(fM),[gr.FIRSTPERSON]:Object.freeze(pM),[gr.VEHICLE]:Object.freeze(hM)});function bc(t){return typeof t=="string"&&Object.hasOwn(Iw,t)?Iw[t]:void 0}Jp();var mM=2,Jw=t=>typeof t=="string"&&t.length>0;function Qw(t,e){let n=[],r=new Set;for(let s of Array.isArray(t)?t:[]){if(s===null||typeof s!="object")continue;let{region:o,urls:i}=s;if(typeof o!="string"||o.length===0||r.has(o))continue;let a=Array.isArray(i)?i.filter(Jw):[];a.length!==0&&(r.add(o),n.push({region:o,urls:a}))}return n.length>0?n:(Array.isArray(e)?e.filter(Jw):[]).map(s=>({region:s,urls:[s]}))}function yM(t,e){return Array.from({length:e},(n,r)=>t[r%t.length])}var eS=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0;function Zw(t,e){let n=[],r=[];return t.forEach((s,o)=>{let i=null,a=s.urls[0];s.urls.forEach((c,u)=>{let l=e[o]?.[u];!eS(l)||i!==null&&l>=i||(i=l,a=c)}),(i===null?r:n).push({index:o,ms:i,pick:{region:s.region,url:a}})}),n.sort((s,o)=>s.ms-o.ms||s.index-o.index),[...n,...r].map(s=>s.pick)}var Ni={Capacity:"capacity",NextRegion:"next_region",Final:"final"},gM=new Set([503,4213]),bM=new Set([502,504,520,521,522,523,524,525,526,530]);function tS(t){return typeof t!="number"||t<=0||bM.has(t)?Ni.NextRegion:gM.has(t)?Ni.Capacity:Ni.Final}function nS(t,e,n){let r=t.refused+1;if(r>=mM&&t.region+1<e){let o=t.region+1;return{attempt:{region:o,waitMs:0},state:{region:o,refused:0,step:t.step}}}let s=n[t.step];return s===void 0?null:{attempt:{region:t.region,waitMs:s},state:{region:t.region,refused:r,step:t.step+1}}}async function rS(t,e={}){if(t.length===0)return[];if(t.length===1)return Zw(t,[]);let n=Math.max(1,e.samples??uo.SAMPLES),r=t.map(i=>yM(i.urls,n)),s=await wM(r,e),o=t.map((i,a)=>i.urls.map(c=>{let u;return r[a]?.forEach((l,d)=>{let f=s[a]?.[d];l===c&&eS(f)&&(u=Math.min(u??Number.POSITIVE_INFINITY,f))}),u}));return Zw(t,o)}async function wM(t,e={}){let n=e.probe??Wp,r=e.timeoutMs??uo.TIMEOUT_MS,s=e.graceMs??uo.GRACE_MS,o=t.map(a=>a.map(()=>{})),i=t.reduce((a,c)=>a+c.length,0);return i===0||await new Promise(a=>{let c,u=!1,l=setTimeout(d,r);function d(){u=!0,clearTimeout(l),clearTimeout(c),a()}let f=()=>{--i===0&&d()};t.forEach((h,p)=>{h.forEach((y,S)=>{let w;try{w=n(y,r)}catch(x){w=Promise.reject(x)}w.then(x=>{!u&&Number.isFinite(x)&&x>=0&&(o[p][S]=x,c??(c=setTimeout(d,s))),f()},f)})})}),o}var _h={MAX_MATCH_KEY_CHARS:32,MAX_CODE_CHARS:32,MAX_WORLDS:16},SM=522,xh=(t,e,n)=>t>=e.charCodeAt(0)&&t<=n.charCodeAt(0),sS=t=>xh(t,"a","z")||xh(t,"0","9"),xM="._:-",_M="_-";function oS(t){if(typeof t!="string"||t.length===0||t.length>_h.MAX_MATCH_KEY_CHARS)return!1;for(let e=0;e<t.length;e++)if(!sS(t.charCodeAt(e))&&(e===0||!xM.includes(t.charAt(e))))return!1;return!0}function iS(t){if(typeof t!="string"||t.length===0||t.length>_h.MAX_CODE_CHARS)return!1;for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(!sS(n)&&!xh(n,"A","Z")&&!_M.includes(t.charAt(e)))return!1}return!0}function RM(t){return t===void 0||t===""?"":oS(t)?t:null}var br={JoinOrCreate:"joinOrCreate",Create:"create",JoinById:"joinById"},Sh={BadMatchKey:"bad_match_key",BadCode:"bad_code",Conflict:"conflict"};function aS(t){let e=t.matchKey??"";if(t.code!==void 0)return t.createPrivate===!0||e!==""?{refused:Sh.Conflict}:iS(t.code)?{method:br.JoinById,roomId:t.code,options:{}}:{refused:Sh.BadCode};let n=RM(e);if(n===null)return{refused:Sh.BadMatchKey};let r=n===""?{}:{matchKey:n};return t.createPrivate===!0?{method:br.Create,options:{...r,private:!0}}:{method:br.JoinOrCreate,options:r}}function cS(t,e,n){return(t===_n.WRONG_REGION||t===SM)&&e+1<n?e+1:null}var Bi={scheduleMs:[0,250,500,1e3,2e3,4e3],jitterMs:250,budgetMs:18e4,regionStayMs:6e4,successorMs:9e4};var Li={Room:"room",Successor:"successor",Pool:"pool"},uS={Final:"final",Budget:"budget"},EM=new Set([dn.GOING_AWAY,dn.NO_STATUS,dn.ABNORMAL,1011,1012,1013,dn.SERVER_SHUTDOWN,dn.FAILED_TO_RECONNECT,dn.MAY_TRY_RECONNECT]),kM=new Set([_n.BAD_OPTION,_n.NOT_ENTITLED,_n.FORBIDDEN,_n.MODULE_UNAVAILABLE,_n.PROTOCOL_UNSUPPORTED]);function lS(t){return EM.has(t)}function dS(t){let{attempt:e,elapsedMs:n,refusal:r,lostCode:s,closed:o,regions:i,jitter:a}=t;if(r!==null&&kM.has(r))return{stop:uS.Final};if(n>=Bi.budgetMs)return{stop:uS.Budget};let c=Bi.scheduleMs.length-1,l=Bi.scheduleMs[Math.min(e,c)]+Math.floor(a*Bi.jitterMs);if(e===0&&s!==dn.SERVER_SHUTDOWN)return{waitMs:l,region:0,way:Li.Room};let d=i<1?0:Math.floor(n/Bi.regionStayMs)%i,f=o||n<Bi.successorMs?Li.Successor:Li.Pool;return{waitMs:l,region:d,way:f}}function fS(t){return{...t.matchKey===""?{}:{matchKey:t.matchKey},successorOf:t.lostRoomId,...t.closed?{successorClosed:!0}:{}}}var Rs={Draining:"draining",Rejoining:"rejoining",Rejoined:"rejoined"},od="disconnect",AM=-1,PM=t=>new Promise(e=>setTimeout(e,t)),TM=t=>{let e=t!==null&&typeof t=="object"?t.code:void 0;return typeof e=="number"?e:null};function pS(t,e){let n=e.now??Date.now,r=e.random??Math.random,s=e.sleep??PM,o={...t.input},i=new Map,a=t,c=!1,u=null,l=null,d=(w,...x)=>{for(let R of i.get(w)??[])R(...x)},f=(w,x)=>{x===od||x===Rs.Draining||x===Rs.Rejoining||x===Rs.Rejoined||w.on(x,(...R)=>{w===a&&d(x,...R)})},h=async(w,x)=>{let R=n(),A={roomId:a.code,matchKey:a.matchKey,closed:e.closed},E=e.targets.length,P=0,k=null;for(;!c;){let M=dS({attempt:P,elapsedMs:n()-R,refusal:k,lostCode:w,closed:e.closed,regions:E,jitter:r()});if("stop"in M){d(od,w,x);return}if(P+=1,d(Rs.Rejoining,{attempt:P,code:w,waitMs:M.waitMs}),await s(M.waitMs),c)return;try{let L=await e.join(e.targets[M.region],M.way,A);if(c){await L.leave().catch(()=>{});return}p(L),d(Rs.Rejoined,{code:L.code,url:L.url});return}catch(L){k=TM(L)}}},p=w=>{a=w,u!==null&&w.setPhysics(u),l!==null&&w.setWorld(l);for(let x of i.keys())f(w,x);y(w)},y=w=>{w.on(xe.SERVER_RESTART,x=>{if(w!==a)return;let R=x?.drainMs;d(Rs.Draining,{closesInMs:typeof R=="number"?R:AM})}),w.on(od,(x,R)=>{w!==a||c||(lS(x)?h(x,R):d(od,x,R))})};y(t);let S={input:o,frame(w){return Object.assign(a.input,o),a.frame(w)},setWorld(w){let x=a.setWorld(w);return l=w,x},setPhysics(w){return u=w,a.setPhysics(w)},on(w,x){let R=i.get(w);R===void 0&&(R=new Set,i.set(w,R),f(a,w));let A=x;return R.add(A),()=>{R.delete(A)}},async leave(){c=!0,await a.leave()}};return new Proxy(t,{get(w,x){if(Object.hasOwn(S,x))return S[x];let R=a[x];return typeof R=="function"?R.bind(a):R}})}var Xt={EXTRAPOLATE:"extrapolate",HOLD:"hold",INPUT_DECAY:"inputDecay"};var MM=Object.freeze({bodies:512,collidersPerBody:8,hullVertices:64,triangles:65536,joints:64,ccdBodies:16,queriesPerStep:64,eventsPerStep:64,heightfieldSamples:1048576,staticPieces:4608,memoryBytes:64*1024*1024,worldExtent:1e5,maxSpeed:1e3,maxAngularSpeed:1e3}),rU=Object.freeze(Object.keys(MM)),sU=Object.freeze(["worldExtent","maxSpeed"]),oU=Object.freeze(["worldExtent","maxSpeed","maxAngularSpeed"]);var hS=Object.freeze({[gr.FIRSTPERSON]:39.37,[gr.VEHICLE]:100}),iU=Object.freeze([10,15,20,30,60]);var wr={DEFAULT_REMOTE_PREDICT:Xt.EXTRAPOLATE,DEFAULT_REMOTE_DECAY_MS:50,MAX_REMOTE_DECAY_MS:1e3,DEFAULT_LEAD_MS:250,MIN_LEAD_MS:50,MAX_LEAD_MS:1e3},aU=Object.values(Xt);var mS=64,yS=64;var cU=Object.freeze({20:3,30:2,60:1,120:1});var CM=Object.freeze(["qx","qy","qz","qw","lvx","lvy","lvz","avx","avy","avz","sleep"]),OM=Object.freeze(["x","y","z",...CM]),id={BITS:16,SPAN:65534,ORIENTATION:Object.freeze({min:-1,max:1}),VELOCITY:Object.freeze({min:-64,max:64})};function Jt(t,e){if(Number.isNaN(t))return 0;let n=t<e.min?e.min:t>e.max?e.max:t;return Math.floor((n-e.min)/(e.max-e.min)*id.SPAN+.5)}var gS=250,bS=1,wS=100,SS=1;var kh=[0,0,0,1];function $n(t,e){return[t[3]*e[0]+t[0]*e[3]+t[1]*e[2]-t[2]*e[1],t[3]*e[1]-t[0]*e[2]+t[1]*e[3]+t[2]*e[0],t[3]*e[2]+t[0]*e[1]-t[1]*e[0]+t[2]*e[3],t[3]*e[3]-t[0]*e[0]-t[1]*e[1]-t[2]*e[2]]}function Hr(t){let e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]);return e===0?kh:[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function xS(t,e,n,r){let s=Math.sin(r/2);return[t*s,e*s,n*s,Math.cos(r/2)]}function Fi(t,e){let n=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(n===0)return kh;let r=2*Math.atan2(n,t[3]);return xS(t[0]/n,t[1]/n,t[2]/n,e*r)}function _S(t,e){return{tick:e+1,p:[t.x,t.y,t.z],q:Hr([t.qx,t.qy,t.qz,t.qw]),lv:[t.lvx,t.lvy,t.lvz],av:[t.avx,t.avy,t.avz],sleep:t.sleep,epoch:t.epoch}}function IM(t,e,n){if(t.sleep||!(n.tickHz>0))return 0;let s=((e-n.tickOrigin)*n.tickHz/1e3-t.tick)/n.tickHz,o=-bS/n.tickHz,i=gS/1e3;return s<o?o:s>i?i:s}function RS(t,e,n){let r=IM(t,e,n),s=n.lengthUnit,o=[t.p[0]+t.lv[0]*s*r,t.p[1]+t.lv[1]*s*r,t.p[2]+t.lv[2]*s*r],[i,a,c]=t.av,u=Math.sqrt(i*i+a*a+c*c);return u===0||r===0?{p:o,q:t.q}:{p:o,q:Hr($n(xS(i/u,a/u,c/u,u*r),t.q))}}var Rh={SPAWNED:"spawned",EPOCH:"epoch",DISTANCE:"distance"},Eh=(t,e)=>({state:t,arrivedAt:e,dp:[0,0,0],dq:kh});function Ah(t,e,n){let r=RS(t.state,e,n),s=e-t.arrivedAt,o=Math.exp(-(s<0?0:s)/wS),{dp:i}=t;return{p:[r.p[0]+i[0]*o,r.p[1]+i[1]*o,r.p[2]+i[2]*o],q:$n(Fi(t.dq,o),r.q)}}function ES(t,e,n,r){if(t===null)return{drawing:Eh(e,n),snap:Rh.SPAWNED};if(e.epoch!==t.state.epoch)return{drawing:Eh(e,n),snap:Rh.EPOCH};let s=Ah(t,n,r),o=RS(e,n,r),i=[s.p[0]-o.p[0],s.p[1]-o.p[1],s.p[2]-o.p[2]];if(Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2])>SS*r.lengthUnit)return{drawing:Eh(e,n),snap:Rh.DISTANCE};let a=$n(s.q,[-o.q[0],-o.q[1],-o.q[2],o.q[3]]),c=a[3]<0?[-a[0],-a[1],-a[2],-a[3]]:a;return{drawing:{state:e,arrivedAt:n,dp:i,dq:c},snap:null}}function kS(t,e){let n=(r,s)=>r.every((o,i)=>Object.is(o,s[i]));return t.sleep===e.sleep&&t.epoch===e.epoch&&n(t.p,e.p)&&n(t.q,e.q)&&n(t.lv,e.lv)&&n(t.av,e.av)}var AS=2**32-1,wc=1e3,$r=t=>typeof t.t0=="number"&&t.t0>0;function Ph(t,e,n){let r=(e-t.t0)/n,s=Number.isFinite(r)&&r>=0?r:0;return{x:Ce(Math.fround(t.x+t.vx*s)),y:Ce(Math.fround(t.y+t.vy*s)),z:Ce(Math.fround(t.z+t.vz*s-.5*t.g*s*s)),vx:Ce(t.vx),vy:Ce(t.vy),vz:Ce(Math.fround(t.vz-t.g*s))}}function Th(t,e,n){return(t-e)*n/1e3}function ad(t,e,n){return e+t*1e3/n}var mn={Predicted:"predicted",Separate:"separate",Timeline:"timeline"},yo={Shared:"shared",Mover:"mover"},jn={Shooter:"shooter",Platformer:"platformer",VehicleArena:"vehicle-arena",PhysicsSandbox:"physics-sandbox",Party:"party"},it={Stand:"stand",Slide:"slide",Bounce:"bounce",Ghost:"ghost"},Wn={Box:"box",Hull:"hull"},go={Slide:"slide",Carry:"carry"};var vh=(t,e,n)=>({speed:t,step:e,share:n}),Sc=t=>({policy:it.Slide,...t}),xc=(t,e,n)=>({policy:it.Stand,ride:t,center:e,slide:n}),zi=vh(300,150,1),jr=vh(950,480,1),DM=vh(600,null,.5),NM=.25,mU=Object.freeze({speed:300,step:150}),yU={policy:it.Bounce,stompMin:150,bounceSpeed:450,jumpBoost:150,slide:zi},PS={[jn.Shooter]:{character:xc(!1,NM,zi),vehicle:Sc(jr),restitution:0,passes:16,vehicleOffWall:jr,stopSpin:!1,drawing:mn.Separate,push:yo.Mover,headFriction:go.Slide},[jn.Platformer]:{character:xc(!0,null,zi),vehicle:Sc(jr),restitution:0,passes:16,vehicleOffWall:jr,stopSpin:!1,drawing:mn.Separate,push:yo.Mover,headFriction:go.Slide},[jn.VehicleArena]:{character:Sc(zi),vehicle:Sc(jr),restitution:.6,passes:32,vehicleOffWall:DM,stopSpin:!0,drawing:mn.Predicted,push:yo.Shared,headFriction:go.Carry},[jn.PhysicsSandbox]:{character:xc(!0,null,zi),vehicle:xc(!0,null,jr),restitution:.2,passes:16,vehicleOffWall:jr,stopSpin:!1,drawing:mn.Separate,push:yo.Shared,headFriction:go.Carry},[jn.Party]:{character:xc(!0,null,zi),vehicle:Sc(jr),restitution:.3,passes:16,vehicleOffWall:jr,stopSpin:!1,drawing:mn.Separate,push:yo.Shared,headFriction:go.Slide}},gU=Object.freeze({supportCos:.7,entrySpeed:1,entryWindow:1/60,slop:.1,roofSkin:.01});var bU={[it.Stand]:new Set(["policy","ride","center","slide"]),[it.Slide]:new Set(["policy","speed","step","share"]),[it.Bounce]:new Set(["policy","stompMin","bounceSpeed","jumpBoost"]),[it.Ghost]:new Set(["policy"])};var BM=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0],[0,0,1],[0,0,-1]],LM=[0,3,1,4,5,2];function FM(t,e,n,r,s){let[o,i,a,c,u,l,d,f,h]=n,p=d===0?o:i,y=(h-f)/((d===0?c:u)-p),S=1/Math.sqrt(y*y+1),w=(f-y*p+r*Math.abs(y))*S,x=[1,0,0,c+r,-1,0,0,-o+r,0,1,0,u+r,0,-1,0,-i+r,d===0?-y*S:0,d===0?0:-y*S,S,w,0,0,1,l,0,0,-1,-a+s];t.set(x,e)}function CS(t,e,n,r){let s=t?.boxes??[],o=t?.ramps??[],i=s.length+o.length,a=new Float64Array(i*6),c=new Float64Array(o.length*28);for(let d=0;d<i;d++){let f=d<s.length?s[d]:o[d-s.length],h=d*6;a[h]=f[0]-e,a[h+1]=f[1]-e,a[h+2]=f[2]-n,a[h+3]=f[3]+e,a[h+4]=f[4]+e,a[h+5]=f[5],d>=s.length&&FM(c,(d-s.length)*28,f,e,n)}let u={count:i,boxCount:s.length,bounds:a,rampPlanes:c,skin:r},l=zM(u);return l===null?u:{...u,grid:l}}function TS(t,e){let n=e*6;return Number.isFinite(t[n])&&Number.isFinite(t[n+3])&&Number.isFinite(t[n+1])&&Number.isFinite(t[n+4])}function Es(t,e,n,r){let s=Math.floor((t-e)/n);return s<0?0:s>r-1?r-1:s}function zM(t){let{count:e,bounds:n}=t,r=0,s=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let x=0;x<e;x++){if(!TS(n,x))continue;r+=1;let R=x*6;s=Math.min(s,n[R]-1),o=Math.min(o,n[R+1]-1),i=Math.max(i,n[R+3]+1),a=Math.max(a,n[R+4]+1)}if(r<32)return null;let c=Math.max(64,(i-s)/32,(a-o)/32);if(!Number.isFinite(c))return null;let u=Math.min(32,Math.floor((i-s)/c)+1),l=Math.min(32,Math.floor((a-o)/c)+1),d=(x,R)=>{for(let A=0;A<e;A++){if(!TS(n,A)){x(A);continue}let E=A*6,P=Es(n[E]-1,s,c,u),k=Es(n[E+3]+1,s,c,u),M=Es(n[E+1]-1,o,c,l),L=Es(n[E+4]+1,o,c,l);if((k-P+1)*(L-M+1)>64){x(A);continue}for(let K=M;K<=L;K++)for(let W=P;W<=k;W++)R(W+K*u,A)}},f=new Int32Array(u*l+1),h=0;d(()=>{h+=1},x=>{f[x+1]+=1});for(let x=0;x<u*l;x++)f[x+1]=f[x+1]+f[x];let p=new Int32Array(f[u*l]),y=new Int32Array(h),S=f.slice(),w=0;return d(x=>{y[w]=x,w+=1},(x,R)=>{p[S[x]]=R,S[x]=S[x]+1}),{x0:s,y0:o,size:c,nx:u,ny:l,cellStart:f,cellSolids:p,wide:y,merged:new Array(w<=64?u*l:0)}}function vS(t,e,n,r){if(r===n)return t;let s=[],o=0,i=n;for(;o<t.length||i<r;){let a=i>=r||o<t.length&&t[o]<=e[i],c=a?t[o]:e[i];a?o+=1:i+=1,s[s.length-1]!==c&&s.push(c)}return s}function OS(t,e,n,r,s){let o=t.grid;if(o===void 0||!(Number.isFinite(e)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(s)))return null;let i=Es(e,o.x0,o.size,o.nx),a=n===e?i:Es(n,o.x0,o.size,o.nx),c=Es(r,o.y0,o.size,o.ny),u=s===r?c:Es(s,o.y0,o.size,o.ny);if((a-i+1)*(u-c+1)>16)return null;if(i===a&&c===u&&o.merged.length>0){let d=i+c*o.nx,f=o.merged[d];if(f!==void 0)return f;let h=vS(o.wide,o.cellSolids,o.cellStart[d],o.cellStart[d+1]);return o.merged[d]=h,h}let l=o.wide;for(let d=c;d<=u;d++)for(let f=i;f<=a;f++){let h=f+d*o.nx;l=vS(l,o.cellSolids,o.cellStart[h],o.cellStart[h+1])}return l}var mt={nx:0,ny:0,nz:0,e:0};function _c(t,e,n){if(e<t.boxCount){let o=BM[n],i=LM[n],a=t.bounds[e*6+i];mt.nx=o[0],mt.ny=o[1],mt.nz=o[2],mt.e=i<3?-a:a;return}let r=(e-t.boxCount)*28+n*4,s=t.rampPlanes;mt.nx=s[r],mt.ny=s[r+1],mt.nz=s[r+2],mt.e=s[r+3]}var cd=(t,e)=>e<t.boxCount?6:7;function Rc(t,e,n,r,s,o){let i=cd(t,e);for(let a=0;a<i;a++)if(_c(t,e,a),!(mt.e-(mt.nx*r+mt.ny*s+mt.nz*o)>n))return!1;return!0}var IS=(t,e,n)=>OS(t,e,e,n,n);function UM(t,e,n,r,s){let o=e*6;for(let i=0;i<3;i++){let a=n[i],c=a+r[i]*s,u=a<c?a:c;if((a<c?c:a)<t.bounds[o+i]-1||u>t.bounds[o+3+i]+1)return!1}return!0}function VM(t,e,n,r,s,o){let i=cd(t,e);for(let a=0;a<i;a++){_c(t,e,a);let{nx:c,ny:u,nz:l,e:d}=mt;if(d-(c*r[0]+u*r[1]+l*r[2])<=n&&c*s[0]+u*s[1]+l*s[2]<0){let h=[c,u,l,d];if(!o?.(h))return{t:0,face:h}}}return null}var DS=(t,e)=>n=>n[2]>=e&&n[0]*t[0]+n[1]*t[1]+n[2]*t[2]>=e;function HM(t,e,n,r,s,o,i){if(Rc(t,e,n,r[0],r[1],r[2]))return null;if(Rc(t,e,-n,r[0],r[1],r[2]))return VM(t,e,n,r,s,i);let a=0,c=o,u=Number.NEGATIVE_INFINITY,l=-1,d=cd(t,e);for(let h=0;h<d;h++){_c(t,e,h);let{nx:p,ny:y,nz:S,e:w}=mt,x=w+n-(p*r[0]+y*r[1]+S*r[2]),R=p*s[0]+y*s[1]+S*s[2];if(R===0){if(!(x>0))return null;continue}let A=x/R;R>0&&A<c&&(c=A),R<0&&A>u&&(u=A,l=h)}if(u>a&&(a=u),l<0||!(a<c))return null;_c(t,e,l);let f=[mt.nx,mt.ny,mt.nz,mt.e];return i?.(f)?null:{t:a,face:f}}function Ec(t,e,n,r,s){let o={t:r,face:null};if(!(r>0))return{t:0,face:null};let i=f=>{if(!UM(t,f,e,n,o.t))return;let h=HM(t,f,t.skin,e,n,o.t,s);h!==null&&h.t<o.t&&(o=h)},[a,c]=[e[0],e[1]],[u,l]=[a+n[0]*r,c+n[1]*r],d=OS(t,Math.min(a,u),Math.max(a,u),Math.min(c,l),Math.max(c,l));if(d===null)for(let f=0;f<t.count;f++)i(f);else for(let f=0;f<d.length;f++)i(d[f]);return o}function ud(t,e,n,r,s){if(t===null)return r;let o=Ec(t,e,n,r,s).t;return o<0?0:o}var MS=[0,0,1],$M=[0,0,-1];function Mh(t,e,n,r,s){if(t===null)return MS;let o=Ec(t,[e,n,r],$M,s);return o.face===null||!(o.face[2]>0)?MS:[o.face[0],o.face[1],o.face[2]]}function jM(t,e,n,r,s,o){let{count:i,skin:a}=t,c=IS(t,o[0],o[1]),u=c===null?i:c.length;for(let l=0;l<u;l++){let d=c===null?l:c[l];if(d!==e&&Rc(t,d,a,o[0],o[1],o[2])&&!Rc(t,d,a,n,r,s))return!0}return!1}function WM(t,e,n,r,s){let o=null,i=cd(t,e);for(let a=0;a<i-1;a++){_c(t,e,a);let{nx:c,ny:u,nz:l,e:d}=mt,f=d-(c*n+u*r+l*s);o!==null&&!(f<o[3])||l>0&&jM(t,e,n,r,s,[n+c*f,r+u*f,s+l*f])||(o=[c,u,l,f])}return o}function qM(t,e,n,r){let{count:s,skin:o}=t,i=IS(t,e,n),a=i===null?s:i.length;for(let c=0;c<a;c++){let u=i===null?c:i[c];if(Rc(t,u,o,e,n,r))return WM(t,u,e,n,r)}return null}function NS(t,e,n){let{x:r,y:s,z:o}=e,i=0;for(let a=0;a<4;a++){let c=qM(t,r,s,o);if(c===null)break;n?.(c);let[u,l,d,f]=c;i=Math.max(i,f),r+=u*(f+t.skin),s+=l*(f+t.skin),o+=d*(f+t.skin)}return i>0&&(e.x=r,e.y=s,e.z=o),i}var wo={Side:"side",Top:"top"},fd={Free:"free",LowerYields:"lower-yields",Pinned:"pinned"},GM={Stomp:"stomp"},Ch={j:0,way:null,w:null},kc=[0,0,1],Le=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2],So=(t,e)=>[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]],ft=t=>[-t[0],-t[1],-t[2]];function YM(t,e,n){if(n.supportUp!==void 0)return n.supportUp(t.x,t.y,t.z);let r=n.supports;if(r===void 0)return Mh(n.world,t.x,t.y,t.z,e.groundTrace);let s=r.get(t);if(s!==void 0&&s.x===t.x&&s.y===t.y&&s.z===t.z)return s.up;let o=Mh(n.world,t.x,t.y,t.z,e.groundTrace);return r.set(t,{x:t.x,y:t.y,z:t.z,up:o}),o}function Wr(t,e,n){let r=e.shape,s=YM(t,e,n);if(r.kind===Wn.Hull)return{b:t,up:kc,support:s,hl:r.radius,hw:r.radius,top:r.height,s:0,c:1};let[o,i]=Ft(t.yaw);return{b:t,up:s,support:s,hl:r.length/2,hw:r.width/2,top:r.top,s:o,c:i}}var pd=t=>Math.sqrt(t.hl*t.hl+t.hw*t.hw),ld=(t,e,n)=>t.hl*Math.abs(t.c*e+t.s*n)+t.hw*Math.abs(t.c*n-t.s*e);function KM(t,e){let n=e.b.z-t.b.z+(e.top-t.top)/2,r=(t.top+e.top)/2;if(Math.abs(n)>=r)return null;let s=e.b.x-t.b.x,o=e.b.y-t.b.y,i=pd(t)+pd(e);if(Math.abs(s)>=i||Math.abs(o)>=i)return null;let a=[t.c,t.s,-t.s,t.c,e.c,e.s,-e.s,e.c],c=null,u=[];for(let d=0;d<8;d+=2){let f=a[d],h=a[d+1],p=s*f+o*h,y=ld(t,f,h)+ld(e,f,h)-Math.abs(p);if(y<=0)return null;let S=p<0?{depth:y,n:[-f,-h,0]}:{depth:y,n:[f,h,0]};u.push(S),(c===null||y<c.depth)&&(c=S)}let l=n<0?[0,0,-1]:kc;return{plane:kc,level:!0,side:c,axes:u,across:{depth:r-Math.abs(n),n:l},d:[s,o,0],half:d=>ld(t,d[0],d[1])+ld(e,d[0],d[1])}}function Ih(t,e,n){let r=t*n[0]+e*n[1],s=t-r*n[0],o=e-r*n[1],i=-r*n[2],a=Math.sqrt(s*s+o*o+i*i);return a<1e-9&&(s=-n[2]*n[0],o=-n[2]*n[1],i=1-n[2]*n[2],a=Math.sqrt(s*s+o*o+i*i)),[s/a,o/a,i/a]}function XM(t,e){let n=[t.up[0]+e.up[0],t.up[1]+e.up[1],t.up[2]+e.up[2]],r=Math.sqrt(Le(n,n));if(r<1e-9)return null;let s=[n[0]/r,n[1]/r,n[2]/r],o=t.top/2,i=e.top/2,a=[e.b.x+e.up[0]*i-t.b.x-t.up[0]*o,e.b.y+e.up[1]*i-t.b.y-t.up[1]*o,e.b.z+e.up[2]*i-t.b.z-t.up[2]*o],c=Le(a,s),u=o+i;if(Math.abs(c)>=u)return null;let l=Ih(t.c,t.s,s),d=Ih(e.c,e.s,s),f=So(s,l),h=So(s,d),p=w=>t.hl*Math.abs(Le(l,w))+t.hw*Math.abs(Le(f,w))+(e.hl*Math.abs(Le(d,w))+e.hw*Math.abs(Le(h,w))),y=null,S=[];for(let w of[l,f,d,h]){let x=Le(a,w),R=t.hl*Math.abs(Le(l,w))+t.hw*Math.abs(Le(f,w))+(e.hl*Math.abs(Le(d,w))+e.hw*Math.abs(Le(h,w)))-Math.abs(x);if(R<=0)return null;let A={depth:R,n:x<0?ft(w):w};S.push(A),(y===null||R<y.depth)&&(y=A)}return{plane:s,level:!1,side:y,axes:S,across:{depth:u-Math.abs(c),n:c<0?ft(s):s},d:a,half:p}}var JM=1e-6;function BS(t){let e=Ih(t.c,t.s,t.up),n=t.top/2;return{c:[t.b.x+t.up[0]*n,t.b.y+t.up[1]*n,t.b.z+t.up[2]*n],axes:[e,So(t.up,e),t.up],half:[t.hl,t.hw,n]}}function ZM(t,e,n){let r=BS(t),s=BS(e),o=[s.c[0]-r.c[0],s.c[1]-r.c[1],s.c[2]-r.c[2]],i=(f,h)=>f.half[0]*Math.abs(Le(f.axes[0],h))+f.half[1]*Math.abs(Le(f.axes[1],h))+f.half[2]*Math.abs(Le(f.axes[2],h)),a=f=>i(r,f)+i(s,f),c=[...r.axes,...s.axes];for(let f of r.axes)for(let h of s.axes){let p=So(f,h),y=Math.sqrt(Le(p,p));y>JM&&c.push([p[0]/y,p[1]/y,p[2]/y])}let u=[];for(let f of c){let h=Le(o,f),p=a(f)-Math.abs(h);if(p<=0)return null;u.push({depth:p,n:h<0?ft(f):f})}let l=u.reduce((f,h)=>h.depth<f.depth?h:f),d=Le(o,n);return{plane:n,level:!1,side:l,axes:u,across:{depth:a(n)-Math.abs(d),n:d<0?ft(n):n},d:o,half:a}}function Dh(t,e){let n=pd(t)+pd(e),r=(t.top+e.top)/2,s=Math.sqrt(n*n+r*r)+r;if(Math.abs(e.b.x-t.b.x)>=s||Math.abs(e.b.y-t.b.y)>=s||Math.abs(e.b.z-t.b.z)>=s)return null;if(t.up[2]===1&&e.up[2]===1)return KM(t,e);if(t.up[0]===e.up[0]&&t.up[1]===e.up[1]&&t.up[2]===e.up[2])return XM(t,e);let o=[t.up[0]+e.up[0],t.up[1]+e.up[1],t.up[2]+e.up[2]],i=Math.sqrt(Le(o,o));return i<1e-9?null:ZM(t,e,[o[0]/i,o[1]/i,o[2]/i])}var hd=(t,e,n)=>-((e.vx-t.vx)*n[0]+(e.vy-t.vy)*n[1]+((e.vz??0)-(t.vz??0))*n[2]);function QM(t,e,n,r){let s=t.across.depth/Math.max(hd(e.b,n.b,t.across.n),r.entrySpeed),i=s<=r.entryWindow&&t.across.depth<=(e.top+n.top)/4||!t.level&&t.across.depth<=r.groundTrace;if(!i)return{across:!1,landed:i};let a=t.side.depth/Math.max(hd(e.b,n.b,t.side.n),r.entrySpeed);return{across:s<a||s===a&&t.across.depth<t.side.depth,landed:i}}function LS(t){let e=[...t.tags??[]],n=t.flags??0;for(let r=0;r<24;r++)Math.floor(n/2**r)%2===1&&e.push(`flag:${r}`);return e}function xo(t,e,n){if(t.pairs.length===0)return t.top;let r=LS(e),s=LS(n),o=i=>r.includes(i.a)&&s.includes(i.b)||r.includes(i.b)&&s.includes(i.a);return t.pairs.find(o)?.top??t.top}function md(t,e,n){let r=Dh(t,e);if(r===null)return eC(t,e,n);let s=QM(r,t,e,n);if(!s.across){let l=Le(r.d,r.plane)>=0;return{contact:{kind:wo.Side,n:r.side.n,depth:r.side.depth,upperIsB:l},g:r}}let o=r.across.n,i=o===r.plane||Le(o,r.plane)>0,a=i?t:e,c=i?o:ft(o);return{contact:{kind:s.landed&&Le(c,a.support)>=n.supportCos?wo.Top:wo.Side,n:o,depth:r.across.depth,upperIsB:i},g:r}}function eC(t,e,n){let r=e.b.z>=t.b.z,s=l=>({...l,b:{...l.b,z:l.b.z-n.groundTrace}}),o=r?Dh(t,s(e)):Dh(s(t),e);if(o===null||!(o.across.depth<o.side.depth))return null;let i=r?o.across.n:ft(o.across.n);if(!(Le(i,o.plane)>0))return null;let a=r?t:e;if(a.support[2]<n.supportCos||Le(i,a.support)<n.supportCos)return null;let[c,u]=r?[e.b,t.b]:[t.b,e.b];return-hd(u,c,i)>n.entrySpeed?null:{contact:{kind:wo.Top,n:o.across.n,depth:o.across.depth-n.groundTrace,upperIsB:r},g:o}}function tC(t,e,n,r){return yd(t,e,n)?null:md(Wr(t,n,r),Wr(e,n,r),n)?.contact??null}function nC(t){let e=t.shape;return e.kind===Wn.Hull?Math.sqrt(2*e.radius*e.radius+e.height*e.height):Math.sqrt(e.length*e.length/4+e.width*e.width/4+e.top*e.top)}function yd(t,e,n){let r=2*nC(n)+n.groundTrace+1,s=e.x-t.x,o=e.y-t.y,i=e.z-t.z;return s*s+o*o+i*i>r*r}var jS=t=>e=>{let n=t.maxVelocity;return n===null?e:e<-n?-n:e>n?n:e},qr=t=>[t.x,t.y,t.z],rC=.7,sC=.5,FS=.5;function Ui(t,e,n,r,s,o){let i=Ec(t,e,n,r,Le(n,o)<-sC?void 0:s),a=i.t,c=i.face;if(c===null||!(a<r))return{d:n,straight:a,slide:null,cos:1,sep:a};let u=[c[0],c[1],c[2]],l=oC(u,n,o);if(l===null)return{d:n,straight:a,slide:null,cos:1,sep:a};let d=Le(l,n),f=[e[0]+n[0]*a,e[1]+n[1]*a,e[2]+n[2]*a],h=Ec(t,f,l,(r-a)/d,s).t;return{d:n,straight:a,slide:l,cos:d,sep:a+h*d}}function oC(t,e,n){if(Le(t,n)>=rC){let a=Le(e,t),c=[e[0]-a*t[0],e[1]-a*t[1],e[2]-a*t[2]],u=Math.hypot(c[0],c[1],c[2]);return u>=FS?[c[0]/u,c[1]/u,c[2]/u]:null}let r=So(t,n),s=Math.hypot(r[0],r[1],r[2]),o=s>0?Le(r,e)/s:0;if(!(Math.abs(o)>=FS))return null;let i=o>0?1/s:-1/s;return[r[0]*i,r[1]*i,r[2]*i]}function zS(t,e){let n=t.d;if(t.slide===null||!(e>t.straight))return[n[0]*e,n[1]*e,n[2]*e];let r=(e-t.straight)/t.cos,s=t.slide;return[n[0]*t.straight+s[0]*r,n[1]*t.straight+s[1]*r,n[2]*t.straight+s[2]*r]}function iC(t,e,n=.5){let r=Math.min(e,1-Math.min(t,n));return[Math.min(t,1-r),r]}function aC(t,e,n,r,s,o,i,a=kc,c=kc,u=.5){if(s===null)return[u,1-u];let l=Ui(s,qr(t),ft(n),r,o,a),d=Ui(s,qr(e),n,r,i,c);return iC(l.sep/r,d.sep/r,u)}function WS(t,e,n,r){if(r.push!==yo.Mover)return .5;let s=t.vx*n[0]+t.vy*n[1],o=e.vx*n[0]+e.vy*n[1];n[2]!==0&&(s+=(t.vz??0)*n[2],o+=(e.vz??0)*n[2]);let i=s>0?s:0,a=o<0?-o:0;return i+a>0?i/(i+a):.5}function Nh(t,e,n,r,s,o){let[i,a]=aC(t.b,e.b,n,r,o.world,bo(t,s),bo(e,s),t.support,e.support,WS(t.b,e.b,n,s));return o.fixed===void 0?[i,a]:t.b.id===o.fixed?[0,o.world===null?1:Ui(o.world,qr(e.b),n,r,bo(e,s),e.support).sep/r]:e.b.id===o.fixed?[o.world===null?1:Ui(o.world,qr(t.b),ft(n),r,bo(t,s),t.support).sep/r,0]:[i,a]}var bo=(t,e)=>DS(t.support,e.supportCos);function cC(t,e,n,r,s,o){let i=r.axes.filter(l=>l.n!==n.n).sort((l,d)=>l.depth-d.depth);for(let l of i){let[d,f]=Nh(t,e,l.n,l.depth,s,o);if(!(d+f<1))return{n:l.n,depth:l.depth,sa:d,sb:f}}let[a,c]=Nh(t,e,n.n,n.depth,s,o),u=1-a-c;return t.b.id===o.fixed?{n:n.n,depth:n.depth,sa:a,sb:c+u}:e.b.id===o.fixed?{n:n.n,depth:n.depth,sa:a+u,sb:c}:{n:n.n,depth:n.depth,sa:a+u/2,sb:c+u/2}}function US(t,e){t.x+=e[0],t.y+=e[1],e[2]!==0&&(t.z+=e[2])}function uC(t,e,n,r,s,o,i,a){let[c,u]=[t.b,e.b],l=a.world,d=ft(n),f=l===null?{d,straight:r,slide:null,cos:1,sep:r}:Ui(l,qr(c),d,r,bo(t,i),t.support),h=l===null?{d:n,straight:r,slide:null,cos:1,sep:r}:Ui(l,qr(u),n,r,bo(e,i),e.support);US(c,zS(f,r*s)),US(u,zS(h,r*o))}function lC(t,e,n,r,s,o,i){let a=jS(s),[c,u]=[t.b,e.b],[l,d]=Nh(t,e,n.n,n.depth,s,o),f=l+d<1?cC(t,e,n,r,s,o):null,{depth:h,n:p,sa:y,sb:S}=f??{depth:n.depth,n:n.n,sa:l,sb:d},[w,x,R]=p,A=(u.vx-c.vx)*w+(u.vy-c.vy)*x;R!==0&&(A+=((u.vz??0)-(c.vz??0))*R);let E=A<0&&!i?-(1+s.restitution)*A/2:0,P=WS(c,u,p,s),k=2*E*P,M=2*E*(1-P);return uC(t,e,p,h,y,S,s,o),c.vx=a(c.vx-k*w),c.vy=a(c.vy-k*x),s.stopSpin&&(c.spin=0),u.vx=a(u.vx+M*w),u.vy=a(u.vy+M*x),s.stopSpin&&(u.spin=0),R!==0&&(c.vz=a((c.vz??0)-k*R),u.vz=a((u.vz??0)+M*R)),{j:E,n:p,depth:h}}function qS(t,e){let n=e?t.side.n:ft(t.side.n),r=e?t.d:ft(t.d),s=So(t.plane,n);return[n,ft(n),s,ft(s)].map(i=>({w:i,move:t.half(i)-Le(r,i)})).map((i,a)=>({way:i,k:a})).sort((i,a)=>i.way.move-a.way.move||i.k-a.k).map(i=>i.way)}var VS=(t,e,n)=>t.half(n)-Le(e?t.d:ft(t.d),n);function dC(t,e,n,r,s){let o=[];for(let i of n){if(i===t.b||i===e||yd(t.b,i,r)||xo(r,t.b,i).policy===it.Ghost)continue;let a=md(t,Wr(i,r,s),r);a!==null&&a.contact.kind===wo.Top&&!a.contact.upperIsB&&o.push(a.g)}return o}function fC(t,e,n){if(n.length===0)return qS(t,e);let r=e?t.side.n:ft(t.side.n),s=So(t.plane,r);return[r,ft(r),s,ft(s)].map(i=>({w:i,move:n.reduce((a,c)=>Math.max(a,VS(c,!1,i)),VS(t,e,i))})).map((i,a)=>({way:i,k:a})).sort((i,a)=>i.way.move-a.way.move||i.k-a.k).map(i=>i.way)}var HS=(t,e,n,r)=>n.move<=0||ud(t,qr(e.b),n.w,n.move,bo(e,r))>=n.move;function Oh(t,e,n,r){t.vx=r(t.vx+n*e[0]),t.vy=r(t.vy+n*e[1]),e[2]!==0&&(t.vz=r((t.vz??0)+n*e[2]))}function $S(t,e){if(!(e<t.speed))return 0;let n=t.speed-e;return t.step===null?n:Math.min(n,t.step)}function dd(t,e,n,r,s,o,i,a){let[c,u]=[t.b,e.b],l=jS(o),d=qS(n,r),f=fC(n,r,dC(t,u,a,o,i)).find(S=>HS(i.world,t,S,o));if(f!==void 0){let S=(c.vx-u.vx)*f.w[0]+(c.vy-u.vy)*f.w[1]+((c.vz??0)-(u.vz??0))*f.w[2],w=$S(s,S);return Oh(c,f.w,w*s.share,l),s.share!==1&&Oh(u,f.w,-w*(1-s.share),l),{j:w,way:fd.Free,w:f.w}}let h=d.map(S=>({w:ft(S.w),move:S.move})).find(S=>HS(i.world,e,S,o));if(h===void 0)return{j:0,way:fd.Pinned,w:null};let p=(u.vx-c.vx)*h.w[0]+(u.vy-c.vy)*h.w[1]+((u.vz??0)-(c.vz??0))*h.w[2],y=$S(s,p);return Oh(u,h.w,y,l),{j:y,way:fd.LowerYields,w:h.w}}function pC(t,e,n,r,s,o,i,a){let c=r+i.roofSkin;if(!(c>0))return;let u=t.id===a.fixed?0:ud(a.world,qr(t),n,c);if(u>=c&&s.level){t.z=e.z+o+i.roofSkin;return}if(t.x+=n[0]*u,t.y+=n[1]*u,t.z+=n[2]*u,u>=c)return;let l=e.id===a.fixed?0:ud(a.world,qr(e),ft(n),c-u);e.x-=n[0]*l,e.y-=n[1]*l,e.z-=n[2]*l}function hC(t,e,n){let r=t.vx*n[0]+t.vy*n[1]+(t.vz??0)*n[2],s=e.vx*n[0]+e.vy*n[1]+(e.vz??0)*n[2];if(r<s){if(n[0]===0&&n[1]===0){t.vz=e.vz??0;return}t.vx+=n[0]*(s-r),t.vy+=n[1]*(s-r),t.vz=(t.vz??0)+n[2]*(s-r)}}function mC(t,e,n){let r=t.vx*e[0]+t.vy*e[1]+(t.vz??0)*e[2];t.vx+=e[0]*(n-r),t.vy+=e[1]*(n-r),t.vz=(t.vz??0)+e[2]*(n-r)}function Bh(t,e,n){let r=t.x-e.x,s=t.y-e.y,o=n.shape;if(o.kind===Wn.Hull)return Math.max(Math.abs(r),Math.abs(s))/o.radius;let[i,a]=Ft(e.yaw);return Math.max(Math.abs(r*a+s*i)/(o.length/2),Math.abs(s*a-r*i)/(o.width/2))}function yC(t,e,n){if(n)return 0;let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s);return o>0?-(e.vx*r+e.vy*s)/o:0}var gC=100,ks={Stand:"stand",Release:"release",Slide:"slide"};function GS(t,e,n,r){if(n.center===null)return ks.Stand;let s=Bh(t,e,r);return s<=n.center?ks.Stand:(e.vz??0)-(t.vz??0)>gC?ks.Slide:yC(t,e,n.ride)>=(n.slide.step??n.slide.speed)/2?ks.Release:s>1?ks.Slide:ks.Stand}var YS=(t,e,n,r)=>n.policy===it.Stand&&GS(t,e,n,r)===ks.Stand;function bC(t,e,n,r,s,o,i,a){let[c,u]=n.upperIsB?[e,t]:[t,e],l=c.b,d=u.b,f=n.upperIsB?n.n:ft(n.n),h=hd(d,l,f),p=s.policy===it.Stand&&GS(l,d,s,o)===ks.Slide;return pC(l,d,f,n.depth,r,u.top,o,i),hC(l,d,f),u.support[2]<o.supportCos?dd(c,u,r,n.upperIsB,o.offWall,o,i,a):s.policy===it.Stand?p?dd(c,u,r,n.upperIsB,s.slide,o,i,a):Ch:s.policy===it.Slide?dd(c,u,r,n.upperIsB,s,o,i,a):s.policy===it.Bounce&&h>=s.stompMin?(mC(l,f,s.bounceSpeed+(l.jump?s.jumpBoost:0)),i.onContact?.(l,d,GM.Stomp),Ch):s.policy===it.Bounce?dd(c,u,r,n.upperIsB,s.slide,o,i,a):Ch}function KS(t,e,n,r,s=!1,o=[]){let i=xo(n,t,e);if(i.policy===it.Ghost||yd(t,e,n))return null;let a=Wr(t,n,r),c=Wr(e,n,r),u=md(a,c,n);return u===null?null:XS(a,c,u,i,n,r,s,o)}function XS(t,e,n,r,s,o,i,a){let{contact:c,g:u}=n;return c.kind===wo.Side?{...c,...lC(t,e,c,u,s,o,i),way:null,w:null}:{...c,...bC(t,e,c,u,r,s,o,a)}}function wC(t,e,n,r,s,o,i){let a=o.cooling?o.cooling(t,e):!1,c=n===0?o.first?.(t,e,a):void 0;return c===void 0?KS(t,e,r,s,a,i):c}var JS=(t,e)=>t!==null&&(t.depth>e.slop||t.kind===wo.Top&&t.depth>0),SC=t=>({moves:new Int32Array(t),still:new Int32Array(t*t).fill(-1)});function xC(t,e,n,r,s){if(yd(t,e,n))return null;let o=xo(n,t,e);if(o.policy===it.Ghost)return null;let i=Wr(t,n,r),a=Wr(e,n,r),c=md(i,a,n);return c===null||!JS(c.contact,n)?null:XS(i,a,c,o,n,r,!1,s)}function _C(t,e,n,r,s,o,i){let a=!1,c=t.length;for(let u=0;u<c;u++)for(let l=u+1;l<c;l++){let d=t[u],f=t[l],h=u*c+l;if(i!==null&&e>0&&i.still[h]===i.moves[u]+i.moves[l])continue;let p;if(i!==null&&e>0)p=xC(d,f,n,r,t);else{if(e>0&&!JS(tC(d,f,n,r),n))continue;p=wC(d,f,e,n,r,s,t)}if(p===null){i!==null&&(i.still[h]=i.moves[u]+i.moves[l]);continue}i!==null&&(i.moves[u]=i.moves[u]+1,i.moves[l]=i.moves[l]+1),a=!0,p.way===fd.Pinned&&(o.pinned+=1),s.onPair?.(d,f,p)}return a}function RC(t,e,n,r={}){let s={passes:0,pushed:new Map,walls:new Map,pinned:0};n={...n,supports:new Map};let o=r.first===void 0&&r.onPair===void 0&&r.cooling===void 0?SC(t.length):null;for(let i=0;i<e.passes&&_C(t,i,e,n,r,s,o);i++)s.passes+=1,n.world!==null&&t.forEach((a,c)=>{let u=d=>{d[2]<e.supportCos&&d[3]>(s.walls.get(a.id)??0)&&s.walls.set(a.id,d[3])},l=NS(n.world,a,u);l>(s.pushed.get(a.id)??0)&&s.pushed.set(a.id,l),o!==null&&l>0&&(o.moves[c]=o.moves[c]+1)});return s}var Lh=(t,e)=>(n,r)=>{KS(n,r,t,e)},ZS=(t,e)=>n=>{RC(n,t,e)};function QS(t){return t.top.policy===it.Stand||t.pairs.some(e=>e.top.policy===it.Stand)}function EC(t,e,n){let r=t.x+t.vx*n,s=t.y+t.vy*n,o=t.z+(t.vz??0)*n,i=e.shape,a=e.groundTrace;if(i.kind===Wn.Hull){let l=i.radius;return{kind:"box",min:[r-l,s-l,o+i.height-a],max:[r+l,s+l,o+i.height]}}let[c,u]=Ft(t.yaw);return{kind:"obox",c:[r,s,o+i.top-a/2],half:[i.length/2,i.width/2,a/2],sin:c,cos:u}}var ex=t=>t.shape.kind===Wn.Hull?t.shape.height:t.shape.top,tx=2;function kC(t,e,n,r){let s=xo(n,t,e);if(s.policy!==it.Stand)return!1;let o=ex(n);return t.z<e.z+o-n.groundTrace||t.z>e.z+2*o||!(Bh(t,e,n)<tx)||Wr(e,n,r).support[2]<n.supportCos?!1:YS(t,e,s,n)}var AC=t=>tx*(t.shape.kind===Wn.Hull?t.shape.radius:Math.hypot(t.shape.length,t.shape.width)/2);function PC(t,e,n=0){let r=ex(e),s=AC(e);for(let o of t)for(let i of t){if(i===o)continue;let a=i.z+(i.vz??0)*n;if(o.z<a+r-e.groundTrace||o.z>a+2*r)continue;let c=(Math.abs(i.vx)+Math.abs(i.vy))*n;if(Math.abs(o.x-i.x)<s+c&&Math.abs(o.y-i.y)<s+c)return!0}return!1}function Ac(t,e,n,r){return PC(t,e)?t.map(s=>{let o=[],i=[];for(let a of t)a===s||!kC(s,a,e,n)||(o.push(EC(a,e,r)),i.push(a.id));return{solids:o,lowers:i}}):t.map(()=>({solids:[],lowers:[]}))}function Fh(t,e,n){let[r,s,o]=[e[0],e[1],e[2]],[i,a,c]=[n[0],n[1],n[2]];return t.find(u=>Math.abs(i-u.x)<=r&&Math.abs(a-u.y)<=s&&c>u.z+2*o&&c<=u.z+4*o)}function nx(t,e,n,r){let s=[];for(let o of n){let[i,a]=[o.p[0],o.p[1]],c=Fh(t,e,o.p);if(c===void 0)continue;let u=i-c.x,l=a-c.y,d=Math.hypot(u,l),[f,h]=d>0?[u/d,l/d]:[1,0],[p,y,S]=[o.v[0],o.v[1],o.v[2]],w=(p-c.vx)*f+(y-c.vy)*h;if(!(w<r.speed))continue;let x=Math.min(r.step,r.speed-w);s.push({key:o.key,v:[p+f*x,y+h*x,S]})}return s}var _o={Box:"box",Disc:"disc"},rx={PingPong:"pingpong",Loop:"loop"},sx={Linear:"linear",Smooth:"smooth"},ox={All:"all",None:"none"},ix=Object.freeze({platforms:Object.freeze([]),bodies:!1});var MU=2**24;var CU=2*Math.PI;var ux=2*Math.PI,Dt=Math.fround,lx=(t,e)=>(t%e+e)%e;function TC(t,e,n,r,s){if(s===sx.Linear)return[Dt(t[0]+(e[0]-t[0])*n/r),Dt(t[1]+(e[1]-t[1])*n/r),Dt(t[2]+(e[2]-t[2])*n/r)];let o=n/r,i=o*o*(3-2*o);return[Dt(t[0]+(e[0]-t[0])*i),Dt(t[1]+(e[1]-t[1])*i),Dt(t[2]+(e[2]-t[2])*i)]}function vC(t,e){let n=t.legs.length,r=t.mode===rx.Loop,s=r?n:2*n,o=e;for(let i=0;i<s;i++){let a=i,c=i,u=i+1;r?u=(i+1)%n:i>=n&&(a=2*n-1-i,c=a+1,u=a);let l=t.legs[a],d=t.points[u];if(o<l)return TC(t.points[c],d,o,l,t.ease);o-=l;let f=t.waits[u];if(o<f)return d;o-=f}return t.points[0]}function MC(t,e,n,r){return t.called?r===void 0||n<r||n-r>=e.period?0:n-r:lx(n+e.phase,e.period)}function As(t,e,n){let r=t.path===null?t.at:vC(t.path,MC(t,t.path,e,n)),s=t.spin;return s===null?{c:r,yaw:0}:{c:r,yaw:Dt(s.dir*(ux*lx(e+s.phase,s.period)/s.period))}}function ax(t,e,n){return t.platforms.map(r=>As(r,e,n?.get(r.id)))}var zh=t=>t.spin===null?0:t.spin.dir*ux/t.spin.period;function bd(t,e,n,r,s){let o=As(t,n,s),i=As(t,n+1,s),a=zh(t),c,u;if(a===0)c=e.x+(i.c[0]-o.c[0]),u=e.y+(i.c[1]-o.c[1]);else{let[d,f]=Ft(a),h=e.x-o.c[0],p=e.y-o.c[1];c=i.c[0]+(f*h-d*p),u=i.c[1]+(d*h+f*p)}let l=e.z+(i.c[2]-o.c[2]);if(t.surface!==null){let[d,f]=t.surface;if(i.yaw===0)c+=d/r,u+=f/r;else{let[h,p]=Ft(i.yaw);c+=(p*d-h*f)/r,u+=(h*d+p*f)/r}}return{x:c,y:u,z:l,yaw:e.yaw+a,v:[(c-e.x)*r,(u-e.y)*r,(l-e.z)*r]}}function gd(t,e){return t.platforms.map((n,r)=>{let{c:s,yaw:o}=e[r],i=n.shape;if(i.kind===_o.Disc)return{kind:"disc",c:s,radius:i.radius,half:i.half};let a=i.half;if(n.spin===null)return{kind:"box",min:[s[0]-a[0],s[1]-a[1],s[2]-a[2]],max:[s[0]+a[0],s[1]+a[1],s[2]+a[2]]};let[c,u]=Ft(o);return{kind:"obox",c:s,half:a,sin:c,cos:u}})}var dx=4;function wd(t,e,n){return{now:gd(t,ax(t,e,n)),next:gd(t,ax(t,e+1,n))}}var fx=(t,e)=>t?.get(e.id);function cx(t,e){t.x=Dt(e.x),t.y=Dt(e.y),t.z=Dt(e.z)}function CC(t,e,n,r,s){let o=[],i=[],a=s===void 0?null:Ac(e,s.policy,s.env,0);return e.forEach((c,u)=>{let l=a?.[u];if(n.length===0&&(l===void 0||l.solids.length===0)){o.push(-1),i.push(null);return}let d=l===void 0||l.solids.length===0?r.support(c,n):r.support(c,[...n,...l.solids]),f=d>=t.platforms.length&&l!==void 0?e.find(p=>p.id===l.lowers[d-t.platforms.length])??null:null,h=s!==void 0&&f!==null?xo(s.policy,c,f):null;o.push(d<t.platforms.length?d:-1),i.push(f!==null&&h?.policy==="stand"&&h.ride?f.id:null)}),{bases:o,on:i}}function OC(t,e,n,r,s,o,i){let a=e.map((l,d)=>{let f=n[d];if(f<0)return null;let h=t.platforms[f];return bd(h,l,s,o,fx(i,h))}),c=new Map(e.map((l,d)=>[l.id,d])),u=(l,d)=>{let f=a[l];if(f!=null)return[f.x-e[l].x,f.y-e[l].y,f.z-e[l].z];let h=r[l]===null||r[l]===void 0?void 0:c.get(r[l]);return h===void 0||d>=dx?[0,0,0]:u(h,d+1)};return e.map((l,d)=>{if(a[d]!==null)return a[d];if(r[d]===null)return null;let f=u(d,0);return{x:l.x+f[0],y:l.y+f[1],z:l.z+f[2],yaw:l.yaw,v:[f[0]*o,f[1]*o,f[2]*o]}})}function px(t,e,n,r,s,o,i,a=wd(t,n,s),c){let{now:u,next:l}=a,d=e.map(w=>({...w})),{bases:f,on:h}=CC(t,d,u,o,c),p=OC(t,d,f,h,n,r,s),y=[],S=[];return e.forEach((w,x)=>{let R=f[x],A=p[x]??null;A!==null&&(cx(w,A),i&&R>=0&&(w.yaw=Dt(A.yaw))),y.push(A===null?null:A.v),t.platforms.forEach((E,P)=>{if(P===R||!o.inside(w,l,P))return;let k=bd(E,w,n,r,fx(s,E)),M=o.pushOut({...w,x:k.x,y:k.y,z:k.z},l);cx(w,M),M.inside&&S.push({seat:w.id,lift:E.id})})}),{bases:f,on:h,v:y,crushed:S,from:e.map(w=>[w.x,w.y,w.z])}}function hx(t,e,n){if(e.on.every(c=>c===null))return e;let r=new Map(t.map((c,u)=>[c.id,u])),s=t.map((c,u)=>{let l=e.from[u];return[c.x-l[0],c.y-l[1]]}),o=(c,u)=>{let l=e.on[c],d=l==null?void 0:r.get(l);if(d===void 0||u>=dx)return[0,0];let f=s[d],h=o(d,u+1);return[f[0]+h[0],f[1]+h[1]]},i=t.map((c,u)=>o(u,0)),a=e.v.map((c,u)=>{let l=i[u];return c===null||e.on[u]===null?c:[c[0]+l[0]*n,c[1]+l[1]*n,c[2]]});return t.forEach((c,u)=>{let l=i[u];e.on[u]!==null&&(c.x=Dt(c.x+l[0]),c.y=Dt(c.y+l[1]))}),{...e,v:a}}function IC(t,e,n,r,s,o){let i=Ac(t,o.policy,o.env,0)[e];if(i===void 0||i.solids.length===0)return!1;let a=s.support(t[e],[...r,...i.solids]);return a>=r.length&&i.lowers[a-r.length]===n}function mx(t,e,n,r,s,o,i=wd(t,r,s).next,a){if(n.v.every(u=>u===null))return;let c=e.map(u=>({...u}));e.forEach((u,l)=>{let d=n.bases[l]??-1,f=n.v[l],h=n.on[l]??null;if(f!=null){if(h!==null&&a!==void 0){if(IC(c,l,h,i,o,a))return}else if(d<0||t.platforms[d].impart!==ox.All||o.support(u,i)===d)return;u.vx=Dt(u.vx+f[0]),u.vy=Dt(u.vy+f[1]),u.vz=Dt(u.vz+f[2])}})}var Pc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function DC(t){return!Pc(t)||!Array.isArray(t.platforms)||typeof t.bodies!="boolean"?!1:t.platforms.every(e=>Pc(e)&&typeof e.id=="string"&&Pc(e.shape)&&Array.isArray(e.at)&&typeof e.called=="boolean")}function wx(t,e,n,r){if(!t)return null;let s;try{s=JSON.parse(t)}catch{return null}if(!Pc(s)||s.name!==gr.FIRSTPERSON&&s.name!==gr.VEHICLE)return null;let o=DC(s.lifts)?s.lifts:null;if(o===null&&n===void 0)return null;let i=Di(s.name,s.params);return{policy:o??ix,ops:Kw(s.name,i,e),vehicle:s.name===gr.VEHICLE,heads:n,tickHz:r}}function Sx(t){if(!t)return;let e;try{e=JSON.parse(t)}catch{return}if(!Pc(e))return;let n=new Map;for(let[r,s]of Object.entries(e))typeof s=="number"&&Number.isInteger(s)&&n.set(r,s);return n}var NC=128,Vi=class{constructor(){m(this,"kept",new Map);m(this,"startsText","")}at(e,n,r){let s=r===void 0?"":JSON.stringify([...r]);s!==this.startsText&&(this.kept.clear(),this.startsText=s);let o=this.kept.get(n);if(o!==void 0)return o;let i=wd(e,n,r),a={solids:i,next:gc(i.next)};return this.kept.size>=NC&&this.kept.delete(this.kept.keys().next().value),this.kept.set(n,a),a}};function vc(t,e,n,r,s,o){let{solids:i,next:a}=o.at(t.policy,n,r),c=px(t.policy,e,n,t.tickHz,r,t.ops,t.vehicle,i,t.heads),u=new Map;return t.heads!==void 0&&Ac(e,t.heads.policy,t.heads.env,s).forEach((d,f)=>{d.solids.length>0&&u.set(e[f].id,gc([...i.next,...d.solids]))}),{tick:n,solids:i,report:c,seats:e,posed:u,next:a}}function xx(t,e){e.report=hx(e.seats,e.report,t.tickHz)}function _x(t,e,n,r){let s=e.report.v;e.report={...e.report,v:s.map((o,i)=>i!==n||o===null?o:[o[0]+r[0]*t.tickHz,o[1]+r[1]*t.tickHz,o[2]])}}var Mc=(t,e)=>t.posed.get(e)??t.next;function Cc(t,e,n){mx(t.policy,e.seats,e.report,e.tick,n,t.ops,e.solids.next,t.heads)}function BC(t,e,n){return t.platforms.map((r,s)=>Tc(t,s,e,n))}function Tc(t,e,n,r){let s=t.platforms[e];if(s===void 0)return{c:[0,0,0],yaw:0};let o=Math.floor(n),i=As(s,o,r?.get(s.id)),a=As(s,o+1,r?.get(s.id)),c=s.spin===null?0:s.spin.dir*2*Math.PI/s.spin.period,u=n-o;return{c:[i.c[0]+(a.c[0]-i.c[0])*u,i.c[1]+(a.c[1]-i.c[1])*u,i.c[2]+(a.c[2]-i.c[2])*u],yaw:i.yaw+c*u}}function Oc(t,e,n,r){return t.policy.platforms.length===0?-1:t.ops.support({x:e.x,y:e.y,z:e.z,vz:0,duck:e.duck??0},gd(t.policy,BC(t.policy,n,r)))}function Uh(t,e,n,r,s,o){let i=Tc(t,e,r,o),a=Tc(t,e,s,o),c=a.yaw-i.yaw,[u,l]=[Math.sin(c),Math.cos(c)],d=n.x-i.c[0],f=n.y-i.c[1];return{x:a.c[0]+l*d-u*f,y:a.c[1]+u*d+l*f,z:n.z+a.c[2]-i.c[2],yaw:n.yaw+c}}function Rx(t,e,n,r){let s=t.platforms.findIndex(i=>i.id===e);if(s<0)return;let o=Tc(t,s,n,r);return{x:o.c[0],y:o.c[1],z:o.c[2],yaw:o.yaw}}function Vh(t,e,n,r){let s=t.platforms[e];if(s===void 0)return 0;let o=s.shape.kind===_o.Box?s.shape.half[2]:s.shape.half;return Tc(t,e,n,r).c[2]+o}var yx=["x","y","z"],gx=["vx","vy","vz"];function Ex(t,e,n,r,s,o,i){let a={...t,heads:void 0},c={id:"",x:s.x??0,y:s.y??0,z:s.z??0,vx:s.vx??0,vy:s.vy??0,vz:s.vz??0,yaw:s.yaw??0,duck:s.duck??0,flags:0},u=vc(a,[c],o,e,i,n);for(let l of yx)s[l]=c[l];t.vehicle&&(s.yaw=c.yaw),r(s,Mc(u,c.id));for(let l of[...yx,...gx])c[l]=s[l]??0;Cc(a,u,e);for(let l of gx)s[l]=c[l]}var Ic=t=>`lift.${t}`,bx=16;function LC(t){let e=t.surface===null?{}:{friction:0};if(t.shape.kind===_o.Box)return{key:"lift",shape:{kind:"box",half:[t.shape.half[0],t.shape.half[1],t.shape.half[2]]},...e};let{radius:n,half:r}=t.shape,s=[];for(let o=0;o<bx;o++){let[i,a]=Ft(2*Math.PI*o/bx);s.push([Math.fround(n*a),Math.fround(n*i),-r],[Math.fround(n*a),Math.fround(n*i),r])}return{key:"lift",shape:{kind:"hull",points:s},...e}}function Sd(t,e,n){let r=As(t,e,n?.get(t.id)),[s,o]=Ft(r.yaw/2);return{p:[r.c[0],r.c[1],r.c[2]],q:[0,0,Math.fround(s),Math.fround(o)]}}function kx(t,e,n){return{key:Ic(t.id),type:"kinematic",pose:Sd(t,e,n),colliders:[LC(t)]}}var FC=20;function zC(t,e,n,r){let s=n-e.c[0],o=r-e.c[1],[i,a]=e.yaw===0?[0,1]:Ft(e.yaw),c=a*s+i*o,u=a*o-i*s;return t.shape.kind===_o.Disc?c*c+u*u<=t.shape.radius*t.shape.radius:Math.abs(c)<=t.shape.half[0]&&Math.abs(u)<=t.shape.half[1]}var UC=(t,e)=>e+(t.shape.kind===_o.Disc?t.shape.half:t.shape.half[2]);function Hh(t,e,n,r){let s=t.platforms.filter(i=>i.surface!==null),o=s.map(i=>As(i,e,n?.get(i.id)));return i=>{let[a,c,u]=[i[0],i[1],i[2]];return s.find((l,d)=>{let f=o[d],h=u-UC(l,f.c[2]);return h>0&&h<=r&&zC(l,f,a,c)})}}function Ax(t,e,n,r,s,o){let i=Hh(t,e,n,o),a=Math.min(1,FC/r),c=[];for(let u of s){let[l,d,f]=[u.p[0],u.p[1],u.p[2]],h=i(u.p);if(h===void 0)continue;let p=bd(h,{x:l,y:d,z:f,yaw:0},e,r,n?.get(h.id)),[y,S,w]=[u.v[0],u.v[1],u.v[2]],x=p.v[0]-y,R=p.v[1]-S;x===0&&R===0||c.push({key:u.key,v:[y+x*a,S+R*a,w]})}return c}var Ro=15,VC=65535;var HC=Object.values(Xt),Px=(t,e,n)=>typeof t=="number"&&Number.isFinite(t)&&t>=e&&t<=n,Gr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Tx=t=>typeof t=="number"&&Number.isFinite(t)&&t>0;function Nc(t){if(t===void 0||t==="")return null;let e;try{e=JSON.parse(t)}catch{return null}if(!Gr(e)||!Gr(e.world))return null;let{keyframeTicks:n,maxLinear:r,maxAngular:s}=e;if(!(typeof n=="number"&&Number.isInteger(n)&&n>=1)||!Tx(r)||!Tx(s))return null;let i=e.presetBody,a=Gr(i)&&Array.isArray(i.half)&&i.half.length===3?{half:i.half,events:i.events===!0}:null,c=HC.includes(e.remotePredict)?e.remotePredict:wr.DEFAULT_REMOTE_PREDICT,u=e.remoteDecayMs,l=Px(u,0,wr.MAX_REMOTE_DECAY_MS)?u:wr.DEFAULT_REMOTE_DECAY_MS,d=e.leadMs,f=Px(d,wr.MIN_LEAD_MS,wr.MAX_LEAD_MS)?d:wr.DEFAULT_LEAD_MS;return{world:e.world,keyframeTicks:n,maxLinear:r,maxAngular:s,presetBody:a,remotePredict:c,remoteDecayMs:l,leadMs:f}}function $h(t){return Math.fround(Math.fround(t.dt)/t.substeps)}function $C(t,e){let n=Math.floor(t/e+.5);return Number.isNaN(n)||n<0?0:Math.min(n,VC)}var Dc=id.ORIENTATION,Ps=id.VELOCITY,Hi=t=>t===0?0:t;function Cx(t,e,n){e[n]=Hi(t.x),e[n+1]=Hi(t.y),e[n+2]=Hi(t.z),e[n+3]=Jt(t.qx,Dc),e[n+4]=Jt(t.qy,Dc),e[n+5]=Jt(t.qz,Dc),e[n+6]=Jt(t.qw,Dc),e[n+7]=Jt(t.lvx,Ps),e[n+8]=Jt(t.lvy,Ps),e[n+9]=Jt(t.lvz,Ps),e[n+10]=Jt(t.avx,Ps),e[n+11]=Jt(t.avy,Ps),e[n+12]=Jt(t.avz,Ps),e[n+13]=t.sleep?1:0,e[n+14]=t.rest}function jh(t,e,n,r,s,o){s[o]=Hi(t[e]),s[o+1]=Hi(t[e+1]),s[o+2]=Hi(t[e+2]);for(let i=3;i<7;i++)s[o+i]=Jt(t[e+i],Dc);for(let i=7;i<10;i++)s[o+i]=Jt(t[e+i]/n,Ps);for(let i=10;i<13;i++)s[o+i]=Jt(t[e+i],Ps);s[o+13]=t[e+13]===1?1:0,s[o+14]=$C(t[e+14],r)}function Ox(t,e,n){let r=[...Array.from(t.p),...Array.from(t.q),...Array.from(t.v),...Array.from(t.w),t.sleeping?1:0,t.rest??0],s=[];return jh(r,0,e,n,s,0),s}function vx(t,e){let n=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(!(n>e))return null;let r=e/n;return[t[0]*r,t[1]*r,t[2]*r]}function Ix(t,e,n,r=mS,s=yS){let o=vx(t,r*n),i=vx(e,s);return o===null&&i===null?null:{linvel:o??[t[0],t[1],t[2]],angvel:i??[e[0],e[1],e[2]]}}var XU=16*1024;function Dx(t,e){let n;try{n=JSON.parse(t)}catch{return null}if(!Gr(n)||!Array.isArray(n.colliders))return null;for(let r of n.colliders){if(!Gr(r)||!Gr(r.shape))return null;let s=r.shape.ref;if(s===void 0)continue;let o=typeof s=="string"?e(s):void 0;if(o===void 0)return null;try{r.shape=JSON.parse(o)}catch{return null}}return n}var Nx=.5,xd=t=>{if(!Array.isArray(t)||t.length!==3)return 0;let[e,n,r]=t;return Math.sqrt(e*e+n*n+r*r)},Mx=t=>Array.isArray(t)?t.reduce((e,n)=>Math.max(e,xd(n)),0):0;function jC(t){switch(t.kind){case"box":return xd(t.half);case"sphere":return typeof t.radius=="number"?t.radius:0;case"capsule":return(typeof t.halfHeight=="number"?t.halfHeight:0)+(typeof t.radius=="number"?t.radius:0);case"hull":return Mx(t.points);case"trimesh":return Mx(t.vertices);case"heightfield":return xd(t.size);default:return 0}}function Bc(t){let e=Array.isArray(t.colliders)?t.colliders:[],n=0;for(let r of e){if(!Gr(r)||!Gr(r.shape))continue;let s=Gr(r.offset)?xd(r.offset.p):0;n=Math.max(n,s+jC(r.shape))}return n}function Bx(t,e,n){let r=new Map,s=u=>{let l=u;for(;r.get(l)!==l;)l=r.get(l);let d=u;for(;d!==l;){let f=r.get(d);r.set(d,l),d=f}return l},o=(u,l)=>{let d=s(u),f=s(l);d!==f&&(d<f?r.set(f,d):r.set(d,f))};for(let u of t)r.set(u.key,u.key);let i=[...t].sort((u,l)=>u.x-l.x||(u.key<l.key?-1:1)),a=i.reduce((u,l)=>Math.max(u,l.radius),0);for(let u=0;u<i.length;u++){let l=i[u];for(let d=u+1;d<i.length;d++){let f=i[d];if(f.x-l.x>l.radius+a+n)break;let h=f.x-l.x,p=f.y-l.y,y=f.z-l.z,S=l.radius+f.radius+n;h*h+p*p+y*y<=S*S&&o(l.key,f.key)}}for(let[u,l]of e)r.has(u)&&r.has(l)&&o(u,l);let c=new Map;for(let u of t)c.set(u.key,s(u.key));return c}function WC(t,e,n){if(n<=0)return t<=1?1:0;let r=1-(t-1)*(1e3/e)/n;return r<=0?0:r>=1?1:r}function Rd(t,e,n,r){let s=WC(e,n,r);return{...t,moveX:t.moveX*s,moveY:t.moveY*s,moveZ:t.moveZ*s}}var _t={TAU_SMALL_MS:300,TAU_LARGE_MS:100,SMALL_METRES:.25,LARGE_METRES:1,SNAP_PLAYER_METRES:2,SNAP_OTHER_METRES:6,PLAYER_KINDS:Object.freeze(["player","vehicle"]),SEAT_TAU_MS:70,SEAT_CONTACT_TAU_MS:100,SEAT_SNAP_METRES:6,SEAT_HOLD_MS:120,SEAT_MOVING_UNITS_PER_MS:.2,SEAT_CLOCK_TAU_MS:100,SEAT_CLOCK_SNAP_INPUTS:1.5};function qC(t,e){let n=Math.max(t,0)/e;return(1+n)*Math.exp(-n)}function Ed(t,e,n,r){let s=Math.max(n,0),o=r/2,i=Math.exp(-s/o),a=e+t/o;return[(t+a*s)*i,(e-a*s/o)*i]}function $i(t){let{TAU_SMALL_MS:e,TAU_LARGE_MS:n,SMALL_METRES:r,LARGE_METRES:s}=_t;return t<=r?e:t>=s?n:e+(t-r)/(s-r)*(n-e)}var _d=class{constructor(){m(this,"last",null);m(this,"offset",null)}draw(e,n,r,s,o,i){let a=this.last;a===null||a.epoch!==r?this.offset=null:a.predicted!==n&&this.startFrom(a,e,s,o,i);let c=this.apply(e,s);return this.last={p:c.p,q:c.q,predicted:n,epoch:r},c}startFrom(e,n,r,s,o){let i=[e.p[0]-n.p[0],e.p[1]-n.p[1],e.p[2]-n.p[2]],a=Math.hypot(i[0],i[1],i[2])/o;if(a>s){this.offset=null;return}let c=$n(e.q,[-n.q[0],-n.q[1],-n.q[2],n.q[3]]),u=c[3]<0?[-c[0],-c[1],-c[2],-c[3]]:c;this.offset={dp:i,dq:u,since:r,tau:$i(a)}}apply(e,n){let r=this.offset;if(r===null)return{p:[e.p[0],e.p[1],e.p[2]],q:[e.q[0],e.q[1],e.q[2],e.q[3]]};let s=qC(n-r.since,r.tau);return{p:[e.p[0]+r.dp[0]*s,e.p[1]+r.dp[1]*s,e.p[2]+r.dp[2]*s],q:$n(Fi(r.dq,s),e.q)}}};function kd(t){return typeof t=="string"&&_t.PLAYER_KINDS.includes(t)?_t.SNAP_PLAYER_METRES:_t.SNAP_OTHER_METRES}function Vx(t,e,n,r){let s=(n-r.tickOrigin)*r.tickHz/1e3,o=Math.floor(s),i=t(e,o),a=t(e,o+1);if(i===null||a===null)return null;let c=s-o;return{p:[i.p[0]+(a.p[0]-i.p[0])*c,i.p[1]+(a.p[1]-i.p[1])*c,i.p[2]+(a.p[2]-i.p[2])*c],q:Hr([...i.q])}}var GC=.1,YC=30,Pd={desktop:4,mobile:5};function Hx(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:e}var Kh=Object.freeze([128,64,32]),Wh=60,KC=20,XC=2,Lx=.5,JC=500,ZC=4;function QC(t,e){for(let n=t+1;n<Kh.length;n++)if(Kh[n]<e)return n;return null}function Fx(t,e){if(t.length===0)return 0;let n=[...t].sort((r,s)=>r-s);return n[Math.min(n.length-1,Math.floor(e*n.length))]}var zx=500,eO=.02,tO=200,je={ON:"on",OFF:"off",LOADING:"loading",UNAVAILABLE:"unavailable",MISMATCH:"mismatch",SELF_TEST:"self_test",DIVERGED:"diverged",CPU:"cpu"},nO=600;function Ux(t,e){return[Ed(t.dp[0],t.dv[0],e,t.tau),Ed(t.dp[1],t.dv[1],e,t.tau),Ed(t.dp[2],t.dv[2],e,t.tau)]}var Lc=[0,0,0,1],rO=[32767,32767,32767,65534,32767,32767,32767,32767,32767,32767,0,0],sO=[32767,32767,32767,32767,32767,32767,0,0],oO=t=>Math.floor((t+1)/2*65534+.5),ji=[0,0,0],Wi=(t,e)=>t<e?-1:t>e?1:0,iO=(t,e)=>{for(let n=0;n<Ro;n++)if(!Object.is(t[n],e[n]))return!1;return!0},Ad=class{constructor(e,n){m(this,"status",je.LOADING);m(this,"core");m(this,"desc");m(this,"tickHz");m(this,"innerDt");m(this,"lengthUnit");m(this,"leadMax");m(this,"budgetMs");m(this,"clock");m(this,"remoteStep");m(this,"hashesKept");m(this,"world",null);m(this,"base",null);m(this,"seq",0);m(this,"simulated",new Map);m(this,"seats",new Map);m(this,"kinematic",new Map);m(this,"joints",new Map);m(this,"ring",new Map);m(this,"pure",new Set);m(this,"drawn",new Map);m(this,"kinds",new Map);m(this,"ruledClock",null);m(this,"ownPose",()=>{});m(this,"ownVelocity",()=>{});m(this,"bodyRule");m(this,"headSlide");m(this,"propStates",null);m(this,"propStale",!1);m(this,"kinematicRule");m(this,"lifts");m(this,"liftBodies",null);m(this,"seatRule");m(this,"seatPose");m(this,"contactPass");m(this,"posedBySeats",!1);m(this,"remoteBodies",new Map);m(this,"setSize",0);m(this,"costs",[]);m(this,"probedAt",Number.NEGATIVE_INFINITY);m(this,"calmProbes",0);m(this,"chosenCount",0);m(this,"fallbacks",0);m(this,"recoveries",0);m(this,"steppedAt",0);m(this,"canary",[]);m(this,"epochs",new Map);m(this,"hashes",[]);m(this,"chosenKeys",new Set);this.core=e,this.desc=n.desc,this.tickHz=n.tickHz,this.innerDt=$h(n.desc.world),this.lengthUnit=Math.fround(n.desc.world.lengthUnit);let r=n.leadMs??n.desc.leadMs;this.leadMax=Math.ceil(r*n.tickHz/1e3)+n.desc.keyframeTicks-1;let s=n.desc.remotePredict===Xt.INPUT_DECAY||n.desc.remotePredict===Xt.HOLD;this.remoteStep=s?n.remoteStep:void 0,this.seatPose=n.seatPose,this.contactPass=n.contactPass,this.budgetMs=n.budgetMs??Pd.desktop,this.clock=n.clock??(()=>performance.now()),this.hashesKept=n.hashesKept??nO,this.bodyRule=n.bodyRule,this.headSlide=n.headSlide??(()=>null),this.kinematicRule=n.kinematicRule,this.lifts=n.lifts??(()=>null),this.seatRule=n.seatRule;let o=e.World.create(n.desc.world);if(!o.ok){this.status=je.MISMATCH;return}let i=o.world,a=n.staticWorld;if(!(a==null||a.boxes.length===0&&a.ramps.length===0)&&!i.addStaticWorld(a).ok){i.free(),this.status=je.MISMATCH;return}if(i.physicsHash()!==n.physicsHash){i.free(),this.status=je.MISMATCH;return}this.world=i}get predicting(){return this.status===je.ON||this.status===je.LOADING}get stopped(){return this.world===null}draws(e){return this.status===je.ON&&(this.drawn.has(e)||this.ruledElsewhere(e))}ruledElsewhere(e){return this.base!==null&&!this.drawn.has(e)&&this.ruled(e)}stateHash(){return this.world?.stateHash()??""}stop(e){this.status=e,this.world?.free(),this.world=null,this.drawn.clear()}adopt(e,n,r,s,o=()=>{}){let i={kind:"none",replayed:0,ms:0,pure:0,mismatched:0},a=this.world;if(a===null)return i;let c=this.status===je.CPU;if(c&&s-this.probedAt<JC||!c&&!this.predicting)return i;this.ownPose=r,this.ownVelocity=o;let u=this.choose(e),l=new Set(u.filter(w=>w.epoch!==void 0&&this.epochs.has(w.key)&&this.epochs.get(w.key)!==w.epoch).map(w=>w.key));for(let w of u)w.epoch!==void 0&&this.epochs.set(w.key,w.epoch);let d=c?{...i,kind:"replay"}:this.compare(e,u,l);if(this.world===null)return{...d,kind:"none"};if(d.kind==="match"){this.base={tick:e.tick,ack:e.ack};for(let w of this.seatsOf(e))this.seats.set(w.key,w);for(let w of u)this.kinematic.has(w.key)&&this.kinematic.set(w.key,Array.from(w.row));return this.prune(e.tick),this.status=je.ON,d}c&&this.drawn.clear();let f=this.snapshotDrawn(s),h=this.clock();if(!this.rebuild(a,e,u))return this.stop(je.MISMATCH),i;this.base={tick:e.tick,ack:e.ack},this.seq=e.ack,this.ring.clear(),this.readAll(a);let p=Math.min(n,e.ack+this.leadMax),y=0;for(let w=e.ack+1;w<=p&&(this.stepOnce(a),this.world!==null);w++,y++);let S=this.clock()-h;return this.world===null?{...d,kind:"replay",replayed:y,ms:S}:(this.steppedAt=s,this.ease(f,s,l),c?this.judgeProbe(S,s):(this.status=je.ON,this.judgeBudget(S)),{...d,kind:"replay",replayed:y,ms:S})}advance(e,n){let r=this.world;r===null||this.base===null||this.status!==je.ON||e!==this.seq+1||e-this.base.ack>this.leadMax||(this.stepOnce(r),this.steppedAt=n)}draw(e,n){if(this.status!==je.ON)return null;let r=this.drawn.get(e);if(r===void 0)return this.ruledElsewhere(e)?this.ruledDrawn(e,n):null;let s=r.sleep?0:Math.min(Math.max((n-this.steppedAt)/1e3,0),1/this.tickHz),o=this.lengthUnit,i=[r.p[0]+r.lv[0]*o*s,r.p[1]+r.lv[1]*o*s,r.p[2]+r.lv[2]*o*s],a=cO(r.q,r.av,s),c=Math.max(n-r.since,0),u=Ux(r,c);return{p:[i[0]+u[0][0],i[1]+u[1][0],i[2]+u[2][0]],q:$n(Fi(r.dq,Math.exp(-c/r.tau)),a)}}choose(e){let n=Nx*this.lengthUnit,r=[],s=new Map;for(let p of e.bodies)s.set(p.key,p),r.push({key:p.key,x:p.row[0],y:p.row[1],z:p.row[2],radius:p.desc===null?0:Bc(p.desc)});for(let p of e.outside)r.push(p);let o=[];for(let p of e.joints)typeof p.desc.a=="string"&&typeof p.desc.b=="string"&&o.push([p.desc.a,p.desc.b]);let i=Bx(r,o,n),a=new Map;for(let p of r){let y=i.get(p.key),S=a.get(y);S===void 0?a.set(y,[p.key]):S.push(p.key)}let c=e.seats.find(p=>p.own),u=p=>{let y=s.get(p);return c===void 0?0:Math.hypot(y.row[0]-c.x,y.row[1]-c.y,y.row[2]-c.z)},l=[...a.entries()].filter(([,p])=>p.every(y=>s.get(y)?.desc!=null)).map(([p,y])=>({island:p,keys:y,near:Math.min(...y.map(u))})).sort((p,y)=>p.near-y.near||Wi(p.island,y.island)),d=Kh[this.setSize],f=[];this.pure.clear();let h=[...e.seats,...this.seats.values()];for(let{keys:p}of l){if(f.length+p.length>d)continue;for(let w of p)f.push(s.get(w));let y=h.some(w=>p.some(x=>aO(s.get(x),w,n,this.desc))),S=p.some(w=>s.get(w).desc?.type==="kinematic");if(!y&&!S)for(let w of p)this.pure.add(w)}return f.sort((p,y)=>Wi(p.key,y.key)),this.chosenKeys=new Set(f.map(p=>p.key)),this.chosenCount=l.reduce((p,{keys:y})=>p+y.length,0),f}compare(e,n,r){let s={kind:"replay",replayed:0,ms:0,pure:0,mismatched:0},o=this.base,i=this.ring.get(e.tick);if(o===null||i===void 0)return s;let a=0,c=0,u=!0;for(let p of n){if(p.desc?.type==="kinematic")continue;let y=i.get(p.key),S=y!==void 0&&iO(y,p.row);this.pure.has(p.key)&&!r.has(p.key)&&y!==void 0&&(a++,S||c++),S||(u=!1)}this.noteCanary(a,c);let l=n.length===this.simulated.size&&n.every(p=>this.simulated.get(p.key)?.desc===qh(p.desc)),d=e.ack===o.ack+(e.tick-o.tick)&&this.seq>=e.ack,f={...s,pure:a,mismatched:c};return u&&l&&d&&this.sameJoints(e)&&this.sameSeats(e,i)?{...f,kind:"match"}:f}sameJoints(e){let n=this.jointsOf(e);if(n.size!==this.joints.size)return!1;for(let[r,s]of n){let o=this.joints.get(r);if(o===void 0||o.desc!==s.desc||o.motor!==s.motor)return!1}return!0}sameSeats(e,n){let r=this.seatsOf(e);return r.length!==this.seats.size?!1:r.every(s=>{let o=n.get(`seat:${s.key}`);if(o===void 0||this.seats.get(s.key)?.epoch!==s.epoch)return!1;let i=this.presetPosition(s.x,s.y,s.z);return o[0]===i[0]&&o[1]===i[1]&&o[2]===i[2]})}noteCanary(e,n){for(let s=0;s<e;s++)this.canary.push(s<n);if(this.canary.length>zx&&this.canary.splice(0,this.canary.length-zx),this.canary.length<tO)return;this.canary.filter(Boolean).length/this.canary.length>eO&&this.stop(je.DIVERGED)}judgeBudget(e){if(this.costs.push(e),this.costs.length>Wh&&this.costs.splice(0,this.costs.length-Wh),this.costs.length<KC)return;let n=Fx(this.costs,.5),r=Fx(this.costs,.9);if(n>this.budgetMs||r>XC*this.budgetMs){this.costs=[];let i=QC(this.setSize,this.chosenCount);if(i!==null){this.setSize=i;return}this.fallBack();return}this.costs.length>=Wh&&r<=Lx*this.budgetMs&&this.setSize>0&&(this.setSize--,this.costs=[])}fallBack(){this.status=je.CPU,this.fallbacks++,this.drawn.clear(),this.probedAt=Number.NEGATIVE_INFINITY,this.calmProbes=0}judgeProbe(e,n){if(this.probedAt=n,this.calmProbes=e<=Lx*this.budgetMs?this.calmProbes+1:0,this.calmProbes<ZC){this.drawn.clear();return}this.status=je.ON,this.recoveries++,this.costs=[],this.calmProbes=0}jointsOf(e){let n=new Map;for(let r of e.joints){let s=r.desc.a,o=r.desc.b;!this.simulated.has(s)&&!this.chosenHas(s)||o!==null&&!this.simulated.has(o)&&!this.chosenHas(o)||n.set(r.key,{desc:JSON.stringify(r.desc),motor:r.motor===null?"":JSON.stringify(r.motor),parsed:r})}return n}chosenHas(e){return this.chosenKeys.has(e)}seatsOf(e){if(this.desc.presetBody===null)return[];let n=this.desc.world.limits.worldExtent;return e.seats.filter(r=>this.presetPosition(r.x,r.y,r.z).every(s=>Math.abs(s)<=n)).sort((r,s)=>Wi(r.key,s.key))}presetPosition(e,n,r){let s=this.desc.presetBody?.half[2]??0;return[Math.fround(e),Math.fround(n),Math.fround(Math.fround(r)+s)]}rebuild(e,n,r){let s=this.jointsOf(n);for(let c of[...this.joints.keys()]){let u=s.get(c);u!==void 0&&u.desc===this.joints.get(c).desc||(e.removeJoint(c),this.joints.delete(c))}for(let[c,u]of[...this.simulated]){let l=r.find(d=>d.key===c);l!==void 0&&qh(l.desc)===u.desc||(e.remove(c),this.simulated.delete(c),this.kinematic.delete(c),this.drawn.delete(c))}for(let c of r)if(!(this.simulated.has(c.key)||c.desc===null)){if(!e.spawn(c.desc).ok)return!1;this.kinds.set(c.key,c.desc.kind),this.simulated.set(c.key,{type:String(c.desc.type),desc:qh(c.desc)})}this.kinematic.clear();for(let c of r)c.desc?.type==="kinematic"&&(this.kinematic.set(c.key,Array.from(c.row)),this.ruled(c.key)||this.drawn.delete(c.key));if(this.propStates=null,!this.rebuildSeats(e,n))return!1;let o=this.rebuildLifts(e,n.tick);if(o===null)return!1;for(let[c,u]of s){if(!this.joints.has(c)&&!e.addJoint(u.parsed.desc).ok)return!1;let l=this.joints.get(c);if(u.parsed.motor!==null&&l?.motor!==u.motor&&!e.setMotor(c,u.parsed.motor).ok)return!1;this.joints.set(c,{desc:u.desc,motor:u.motor})}let i=[],a=[];for(let c of r){i.push(c.key);for(let u=0;u<Ro;u++)a.push(c.row[u])}for(let c of this.seats.values())i.push(c.key),a.push(...this.presetPosition(c.x,c.y,c.z),...rO);for(let[c,u]of o)i.push(c),a.push(...u);return i.length>0&&!e.importWire(i,a).ok?!1:e.canonicalize({quantize:!0}).ok}rebuildLifts(e,n){let r=this.lifts(),s=this.liftBodies;if(s!==null&&s.policy!==r?.policy){for(let o of s.keys)e.remove(o);this.liftBodies=null}if(r===null||r.policy.platforms.length===0)return[];if(this.liftBodies===null){for(let o of r.policy.platforms)if(!e.spawn(kx(o,n+1,r.starts)).ok)return null;this.liftBodies={policy:r.policy,keys:r.policy.platforms.map(o=>Ic(o.id))}}return r.policy.platforms.map(o=>{let{p:i,q:a}=Sd(o,n+1,r.starts);return[Ic(o.id),[...i,...a.map(oO),...sO]]})}rebuildSeats(e,n){let r=new Map(this.seatsOf(n).map(o=>[o.key,o]));for(let[o,i]of[...this.seats])r.get(o)?.epoch!==i.epoch&&(e.remove(o),this.seats.delete(o));let s=this.desc.presetBody;for(let[o,i]of r){if(!this.seats.has(o)&&s!==null){let a={key:"hull",shape:{kind:"box",half:[...s.half]},events:s.events,...this.headSlide()===null?{}:{friction:0}};if(!e.spawn({key:o,type:"kinematic",pose:{p:this.presetPosition(i.x,i.y,i.z),q:[...Lc]},colliders:[a]}).ok)return!1}this.seats.set(o,i)}return!0}stepOnce(e){let n=this.base,r=this.seq+1,s=n.tick+(r-n.ack),o=[],i=!1;for(let l of this.seats.values())o.push(this.seatAt(l,r,s-n.tick)),i||(i=this.posedBySeats);i||this.passSeats(o);for(let l of o)e.setNextKinematicPose(l.key,{p:this.presetPosition(l.x,l.y,l.z),q:[...Lc]});for(let[l,d]of this.kinematic){let f=this.kinematicRule?.(l,s+1)??null;e.setNextKinematicPose(l,f===null?uO(d):{p:[...f.p],q:[...f.q]})}let a=this.liftBodies===null?null:this.lifts();for(let l of a?.policy.platforms??[])e.setNextKinematicPose(Ic(l.id),Sd(l,s+1,a?.starts));this.applyBodyRule(e,s,o);let c=e.tick,u=e.step();if(!u.ok){this.stop(je.DIVERGED);return}for(let l of u.escaped)e.remove(l),this.simulated.delete(l),this.drawn.delete(l);this.clamp(e,c),s%this.desc.keyframeTicks===0&&(e.canonicalize({quantize:!0}),this.propStale=!0,this.ring.set(s,this.rowsNow(e))),this.seq=r,this.readDrawn(e,c),this.hashes.push({tick:s,hash:e.stateHash()}),this.hashes.length>this.hashesKept&&this.hashes.splice(0,this.hashes.length-this.hashesKept)}seatAt(e,n,r){this.posedBySeats=!1;let s=e.own?this.ownPose(n):void 0;if(s!==void 0){let f=this.ownVelocity(n)??[e.vx,e.vy,e.vz];return{key:e.key,x:s[0],y:s[1],z:s[2],vx:f[0],vy:f[1],vz:f[2]}}let o=e.own?void 0:this.seatPose?.(e.key,n);if(o!==void 0)return this.posedBySeats=!0,{...o,key:e.key};let i=this.remoteStep;if(e.own||i===void 0||e.input===void 0){let f=r/this.tickHz;return{key:e.key,x:e.x+e.vx*f,y:e.y+e.vy*f,z:e.z+e.vz*f,vx:e.vx,vy:e.vy,vz:e.vz}}let a=this.remoteBodies.get(e.key),c=a!==void 0&&a.from===e&&a.j<=r,u=c?a.body:{...e.body??{},x:e.x,y:e.y,z:e.z},l=1/this.tickHz,d=this.base?.tick??0;for(let f=(c?a.j:0)+1;f<=r;f++){this.seatRule?.(u,d+f);let h=this.desc.remotePredict===Xt.HOLD;i(u,h?e.input:Rd(e.input,f,this.tickHz,this.desc.remoteDecayMs),l,d+f)}return this.remoteBodies.set(e.key,{from:e,j:r,body:u}),{key:e.key,x:u.x,y:u.y,z:u.z,vx:u.vx??e.vx,vy:u.vy??e.vy,vz:u.vz??e.vz,...u.yaw===void 0?{}:{yaw:u.yaw}}}passSeats(e){let n=this.contactPass;if(n===void 0||e.length<2)return;let r=e.map(o=>({id:o.key,x:o.x,y:o.y,z:o.z,vx:o.vx,vy:o.vy,vz:o.vz,yaw:o.yaw??0}));r.sort((o,i)=>Wi(o.id,i.id)),n(r);let s=new Map(r.map(o=>[o.id,o]));for(let o of e){let i=s.get(o.key);o.x=i.x,o.y=i.y,o.z=i.z,o.vx=i.vx,o.vy=i.vy,o.vz=i.vz}}applyBodyRule(e,n,r){let s=this.bodyRule,o=this.headSlide(),i=this.liftBodies===null?null:this.lifts(),a=i!==null&&i.policy.platforms.some(d=>d.surface!==null)?i:null;if(s===void 0&&o===null&&a===null)return;r.sort((d,f)=>Wi(d.key,f.key));let c=d=>{if(this.simulated.get(d)?.type!=="dynamic")return null;let f=e.exportBodyState(d);return f===null?null:{p:[f.p[0],f.p[1],f.p[2]],v:[f.v[0],f.v[1],f.v[2]]}};for(let d of s?.({tick:n,seats:r,body:c})??[])this.simulated.get(d.key)?.type==="dynamic"&&e.setVelocity(d.key,[d.v[0],d.v[1],d.v[2]]);let u=this.desc.presetBody?.half;if(o===null&&a===null||u===void 0)return;if(this.propStates===null){this.propStates=new Map;for(let d of this.simulated.keys()){let f=c(d);f!==null&&this.propStates.set(d,{key:d,p:f.p,v:f.v})}this.propStale=!1}this.propStale&&this.freshenPicked(r,u,a===null?null:Hh(a.policy,n,a.starts,2*u[2]),o!==null,c);let l=[...this.propStates.values()].filter(d=>this.simulated.get(d.key)?.type==="dynamic").sort((d,f)=>Wi(d.key,f.key));if(a!==null)for(let d of Ax(a.policy,n,a.starts,this.tickHz,l,2*u[2]))e.setVelocity(d.key,d.v);if(o!==null)for(let d of nx(r,u,l,o))e.setVelocity(d.key,d.v)}freshenPicked(e,n,r,s,o){let i=this.propStates;if(this.propStale=!1,i!==null)for(let[a,c]of i){if(!(s&&Fh(e,n,c.p)!==void 0||r!==null&&r(c.p)!==void 0))continue;let l=o(a);l!==null&&i.set(a,{key:a,p:l.p,v:l.v})}}clamp(e,n){let{keys:r,data:s}=e.exportChanged(n,{rest:!0});for(let o=0;o<r.length;o++){let i=r[o];if(this.simulated.get(i)?.type!=="dynamic")continue;let a=o*Ro,c=[s[a+7],s[a+8],s[a+9]],u=[s[a+10],s[a+11],s[a+12]],l=Ix(c,u,this.lengthUnit,this.desc.maxLinear,this.desc.maxAngular);l!==null&&e.setVelocity(i,l.linvel,l.angvel),this.propStates?.set(i,{key:i,p:[s[a],s[a+1],s[a+2]],v:l===null?c:[l.linvel[0],l.linvel[1],l.linvel[2]]})}}rowsNow(e){let n=new Map,r=(s,o)=>{let i=e.exportBodyState(s,{rest:!0});i!==null&&n.set(o,Ox(i,this.lengthUnit,this.innerDt))};for(let s of this.simulated.keys())r(s,s);for(let s of this.seats.keys())r(s,`seat:${s}`);return n}ruledDrawn(e,n){let r=this.kinematicRule,s=this.ruledTick(n);if(r===void 0||s===null)return null;let o=Math.floor(s),i=r(e,o),a=r(e,o+1);if(i===null||a===null)return null;let c=s-o;return{p:[i.p[0]+(a.p[0]-i.p[0])*c,i.p[1]+(a.p[1]-i.p[1])*c,i.p[2]+(a.p[2]-i.p[2])*c],q:Hr([...i.q])}}ruledTick(e){let n=this.base;if(n===null)return null;let r=Math.min(Math.max((e-this.steppedAt)/1e3*this.tickHz,0),1),s=n.tick+(this.seq-n.ack)+1+r,o=this.ruledClock;if(o===null||e<o.at||Math.abs(s-o.tick)>YC)return this.ruledClock={at:e,tick:s},s;let i=(e-o.at)/1e3*this.tickHz,a=o.tick+i,c=GC*i,u=a+Math.min(Math.max(s-a,-c),c);return this.ruledClock={at:e,tick:u},u}ruled(e){if(this.kinematicRule===void 0)return!1;let n=this.base,r=n===null?0:n.tick+(this.seq-n.ack);return this.kinematicRule(e,r)!==null}prune(e){for(let n of this.ring.keys())n<=e&&this.ring.delete(n)}readDrawn(e,n){let{keys:r,data:s}=e.exportChanged(n,{rest:!0});for(let o=0;o<r.length;o++){let i=r[o];if(!this.simulated.has(i)||this.kinematic.has(i)&&!this.ruled(i))continue;let a=o*Ro,c=this.drawn.get(i);this.drawn.set(i,{p:[s[a],s[a+1],s[a+2]],q:Hr([s[a+3],s[a+4],s[a+5],s[a+6]]),lv:[s[a+7]/this.lengthUnit,s[a+8]/this.lengthUnit,s[a+9]/this.lengthUnit],av:[s[a+10],s[a+11],s[a+12]],sleep:s[a+13]===1,dp:c?.dp??ji,dv:c?.dv??ji,dq:c?.dq??Lc,since:c?.since??0,tau:c?.tau??$i(0),snap:c?.snap??this.snapOf(i)})}}builtInRules(){if(!this.desc.presetBody)return!1;if(this.headSlide()!==null)return!0;let e=this.liftBodies===null?null:this.lifts();return e!==null&&e.policy.platforms.some(n=>n.surface!==null)}readAll(e){let n=this.builtInRules()?new Map:null;for(let r of this.simulated.keys()){let s=this.kinematic.has(r)&&!this.ruled(r)?null:e.exportBodyState(r,{rest:!0});if(s===null)continue;n!==null&&this.simulated.get(r)?.type==="dynamic"&&n.set(r,{key:r,p:[s.p[0],s.p[1],s.p[2]],v:[s.v[0],s.v[1],s.v[2]]});let o=this.drawn.get(r),i=this.lengthUnit;this.drawn.set(r,{p:[s.p[0],s.p[1],s.p[2]],q:Hr([s.q[0],s.q[1],s.q[2],s.q[3]]),lv:[s.v[0]/i,s.v[1]/i,s.v[2]/i],av:[s.w[0],s.w[1],s.w[2]],sleep:s.sleeping,dp:o?.dp??ji,dv:o?.dv??ji,dq:o?.dq??Lc,since:o?.since??0,tau:o?.tau??$i(0),snap:o?.snap??this.snapOf(r)})}n!==null&&(this.propStates=n,this.propStale=!1)}snapshotDrawn(e){let n=new Map;for(let[r,s]of this.drawn){let o=Math.max(e-s.since,0),i=Ux(s,o);n.set(r,{p:[s.p[0]+i[0][0],s.p[1]+i[1][0],s.p[2]+i[2][0]],q:$n(Fi(s.dq,Math.exp(-o/s.tau)),s.q),rate:[i[0][1],i[1][1],i[2][1]]})}return n}snapOf(e){return kd(this.kinds.get(e))*this.lengthUnit}ease(e,n,r){for(let[s,o]of this.drawn){let i=e.get(s),a={...o,dp:ji,dv:ji,dq:Lc,since:n,tau:$i(0)};if(i===void 0||r.has(s)){this.drawn.set(s,a);continue}let c=[i.p[0]-o.p[0],i.p[1]-o.p[1],i.p[2]-o.p[2]],u=Math.hypot(c[0],c[1],c[2]);if(u>o.snap){this.drawn.set(s,a);continue}let l=$n(i.q,[-o.q[0],-o.q[1],-o.q[2],o.q[3]]),d=l[3]<0?[-l[0],-l[1],-l[2],-l[3]]:l;this.drawn.set(s,{...o,dp:c,dv:i.rate,dq:d,since:n,tau:$i(u/this.lengthUnit)})}}},qh=t=>t===null?"":JSON.stringify(t);function aO(t,e,n,r){let s=r.presetBody?.half??[0,0,0],o=Math.hypot(s[0],s[1],s[2])+(t.desc===null?0:Bc(t.desc))+n;return Math.hypot(t.row[0]-e.x,t.row[1]-e.y,t.row[2]-(e.z+s[2]))<=o}function cO(t,e,n){let r=Math.hypot(e[0],e[1],e[2]);if(r===0||n===0)return t;let s=r*n/2,o=Math.sin(s)/r;return Hr($n([e[0]*o,e[1]*o,e[2]*o,Math.cos(s)],t))}function uO(t){let e=r=>-1+r/65534*2,n=Hr([e(t[3]),e(t[4]),e(t[5]),e(t[6])]);return{p:[t[0],t[1],t[2]],q:[n[0],n[1],n[2],n[3]]}}var Gh={contract:"1.0",dt:1/60,substeps:1,gravity:[0,0,-9.81],upAxis:"z",lengthUnit:1},Yh=12;function lO(){let t=(e,n,r)=>({key:e,type:"dynamic",pose:{p:n,q:[0,0,0,1]},linvel:[1,0,0],colliders:[{key:"c",shape:{kind:"box",half:[r,r,r]}}]});return[t("a",[0,0,.5],.5),t("b",[0,0,1.6],.5),{key:"c",type:"dynamic",pose:{p:[2,0,1],q:[0,0,0,1]},angvel:[0,3,0],colliders:[{key:"c",shape:{kind:"sphere",radius:.4}}]}]}function $x(t){let n=[t.World.create(Gh),t.World.create(Gh)].flatMap(r=>r.ok?[r.world]:[]);try{if(n.length!==2)return!1;let[r,s]=n,o={boxes:[[-20,-20,-1,20,20,0]],ramps:[]};if(!r.addStaticWorld(o).ok||!s.addStaticWorld(o).ok)return!1;for(let l of lO())if(!r.spawn(l).ok||!s.spawn(l).ok)return!1;for(let l=0;l<Yh;l++)r.step();s.canonicalize({});for(let l=0;l<Yh;l++)s.step();if(!r.canonicalize({quantize:!0}).ok)return!1;let{keys:i,data:a}=r.exportChanged(r.tick,{rest:!0}),c=[],u=$h(Gh);for(let l=0;l<i.length;l++)jh(a,l*Ro,1,u,c,l*Ro);if(i.length!==3||!s.importWire(i,c).ok||!s.canonicalize({quantize:!0}).ok)return!1;for(let l=0;l<Yh;l++)if(r.step(),s.step(),r.stateHash()!==s.stateHash())return!1;return!0}finally{for(let r of n)r.free()}}var sV=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);var Eo=["x","y","z","vx","vy","vz","yaw","spin"],dO=(t,e)=>t.body.id<e.body.id?-1:t.body.id>e.body.id?1:0,Td=class{constructor(e,n){m(this,"pass",null);m(this,"rule");m(this,"others");this.rule=e,this.others=n}apply(e,n,r,s){(this.pass===null||this.pass.ack!==n||e<=this.pass.last)&&(this.pass={ack:n,last:n,others:this.others().map(u=>({body:{...u},from:0})).sort(dO)});let i=this.pass,a=e-n,c={...r};i.others=i.others.map(u=>{let l=(a-u.from)/s,d=u.body,f={...d,x:d.x+d.vx*l,y:d.y+d.vy*l,z:d.z+d.vz*l},h=JSON.stringify(f);return c.id<f.id?this.rule(c,f):this.rule(f,c),JSON.stringify(f)===h?u:{body:f,from:a}});for(let u of Eo){let l=c[u];typeof l=="number"&&l!==r[u]&&(r[u]=Math.fround(l))}i.last=e}seatAt(e,n,r,s){let o=this.pass!==null&&this.pass.ack===n?this.pass.others.find(l=>l.body.id===e):void 0,i=o===void 0?this.others().find(l=>l.id===e):void 0,a=o?.from??0,c=o?.body??i;if(c===void 0)return;let u=(r-a)/s;return{...c,x:c.x+c.vx*u,y:c.y+c.vy*u,z:c.z+c.vz*u}}};function ko(t,e,n){let r={x:n.x,y:n.y,z:n.z};for(let s=0;s<fO;s++){let o={...e,vx:0,vy:0,vz:0},i={...n,...r,vx:0,vy:0,vz:0};o.id<i.id?t(o,i):t(i,o);let a={x:r.x+(i.x-r.x)-(o.x-e.x),y:r.y+(i.y-r.y)-(o.y-e.y),z:r.z+(i.z-r.z)-(o.z-e.z)};if(s>0&&a.x===r.x&&a.y===r.y&&a.z===r.z||(r=a,s===0&&vd(t,e,n,r)<=pO))break}return vd(t,e,n,r)>Yx?gO(t,e,n,r):r}var fO=8,pO=.01,Yx=.001,hO=30,mO=8,yO=1;function gO(t,e,n,r){let s={x:n.x,y:n.y,z:n.z},o={x:r.x-s.x,y:r.y-s.y,z:r.z-s.z},i=Math.hypot(o.x,o.y,o.z)>0?o:Kx(t,e,n,s),a=Math.hypot(i.x,i.y,i.z);if(a===0)return r;let c={x:i.x/a,y:i.y/a,z:i.z/a},u=h=>({x:s.x+c.x*h,y:s.y+c.y*h,z:s.z+c.z*h}),l=h=>vd(t,e,n,u(h))>0,d=a,f=a+Math.max(yO,a);for(let h=0;h<mO&&l(f);h++)d=f,f=a+(f-a)*2;if(l(f))return r;for(let h=0;h<hO;h++){let p=(d+f)/2;l(p)?d=p:f=p}return u(f)}function Kx(t,e,n,r){let s={...e,vx:0,vy:0,vz:0},o={...n,...r,vx:0,vy:0,vz:0};return s.id<o.id?t(s,o):t(o,s),{x:o.x-r.x-(s.x-e.x),y:o.y-r.y-(s.y-e.y),z:o.z-r.z-(s.z-e.z)}}function vd(t,e,n,r){let s=Kx(t,e,n,r);return Math.hypot(s.x,s.y,s.z)}var bO=3*Math.PI,wO=Math.PI/2,SO=.05,xO=8,jx=16,_O=30,RO=8,Xx=(t,e,n)=>({...e,x:t.x+n.dx,y:t.y+n.dy,z:t.z+n.dz,vx:0,vy:0,vz:0});function Zh(t,e,n,r){let s=Xx(e,n,r),o=ko(t,e,s);return Math.hypot(o.x-s.x,o.y-s.y,o.z-s.z)}function Md(t,e,n,r,s){let o=Math.hypot(s.dx-r.dx,s.dy-r.dy,s.dz-r.dz),i=Math.min(o,Math.hypot(r.dx,r.dy,r.dz));if(i===0)return!1;for(let a=1;a<jx;a++){let c=a/jx,u={dx:r.dx+(s.dx-r.dx)*c,dy:r.dy+(s.dy-r.dy)*c,dz:r.dz+(s.dz-r.dz)*c};if(Zh(t,e,n,u)>Math.min(SO*i,xO))return!0}return!1}function Jh(t,e,n,r,s,o){let i=Math.cos(r),a=Math.sin(r),c=d=>Zh(t,e,n,{dx:d*i,dy:d*a,dz:s})>0;if(!c(0)||o<=0)return 0;let u=0,l=o;for(let d=0;d<RO&&c(l);d++)u=l,l*=2;for(let d=0;d<_O;d++){let f=(u+l)/2;c(f)?u=f:l=f}return l}var Wx=4,EO=20;function kO(t,e,n){let r=n.z>=e.z?1:-1,s=a=>Zh(t,e,n,{dx:n.x-e.x,dy:n.y-e.y,dz:n.z-e.z+r*a})>0;if(!s(0)||s(Wx))return n;let o=0,i=Wx;for(let a=0;a<EO;a++){let c=(o+i)/2;s(c)?o=c:i=c}return{...n,z:n.z+r*i}}var qx=2*Math.PI,AO=t=>t-qx*Math.floor((t+Math.PI)/qx);function Gx(t,e,n,r,s,o=!1){let i=kO(t,e,n),a=ko(t,e,i),c={dx:a.x-e.x,dy:a.y-e.y,dz:a.z-e.z},u=a.x!==i.x||a.y!==i.y||a.z!==i.z,l=i.x-e.x,d=i.y-e.y,f=(W,B)=>({x:e.x+W.dx,y:e.y+W.dy,z:e.z+W.dz,side:{...W,held:B,bx:l,by:d,at:s}}),h=W=>f(PO(t,e,i,W),!0);if(r===void 0||!(o||Md(t,e,i,r,c)))return f(c,u);let p=Math.hypot(r.dx,r.dy),y=Math.hypot(c.dx,c.dy),S=Math.atan2(r.dy,r.dx);if(!r.held){if(r.dx*c.dx+r.dy*c.dy>=0)return f(c,u);let W=Jh(t,e,i,S,c.dz,Math.max(p,y));return h({dx:W*Math.cos(S),dy:W*Math.sin(S),dz:c.dz})}let w=AO(Math.atan2(c.dy,c.dx)-S),x=p>0?wO*Math.hypot(l-r.bx,d-r.by)/p:0,R=Math.max(x,bO*Math.max(0,s-r.at)/1e3),A=Math.min(Math.abs(w),R),E=w===0?1:A/Math.abs(w),P=S+Math.sign(w)*A,k=c.dz-r.dz,M=R*Math.max(p,y),L=Math.abs(k*E)>M?r.dz+Math.sign(k)*M:r.dz+k*E,K=Math.max(p+(y-p)*E,Jh(t,e,i,P,L,Math.max(p,y)));return h({dx:K*Math.cos(P),dy:K*Math.sin(P),dz:L})}function PO(t,e,n,r){let s=Xx(e,n,r);return vd(t,e,s,s)>Yx?qi(e,ko(t,e,s)):r}function TO(t,e,n,r,s,o,i){let a={dx:i.x-e.x,dy:i.y-e.y,dz:i.z-e.z};for(let c of r){let u=c===n?void 0:s.get(c.id);if(u===void 0)continue;let l={...c,x:e.x+u.dx,y:e.y+u.dy,z:e.z+u.dz,vx:0,vy:0,vz:0},d=f=>({dx:f.dx-u.dx,dy:f.dy-u.dy,dz:f.dz-u.dz});if(Md(t,l,n,d(o),d(a)))return!0}return!1}var Fc=(t,e)=>t<e?`${t}\0${e}`:`${e}\0${t}`,vO=12,Yr=(t,e)=>({...t,x:e.x,y:e.y,z:e.z,vx:0,vy:0,vz:0}),qi=(t,e)=>({dx:e.x-t.x,dy:e.y-t.y,dz:e.z-t.z}),Cd=(t,e)=>t.x===e.x&&t.y===e.y&&t.z===e.z,MO=720,CO=.1,OO=24,IO=8,DO=64;function Qh(t,e,n,r,s){return!Cd(ko(t,Yr(e,r),Yr(n,s)),s)}var Jx=(t,e,n,r)=>[{x:t.x-n.nx*r/2,y:t.y-n.ny*r/2,z:t.z},{x:e.x+n.nx*r/2,y:e.y+n.ny*r/2,z:e.z}];function NO(t,e,n,r,s,o,i){let a=l=>Qh(t,e,n,...Jx(r,s,o,l));if(!a(i))return i;let c=i,u=i+DO;for(let l=0;l<IO&&a(u);l++)c=u,u=i+(u-i)*2;for(let l=0;l<OO;l++){let d=(c+u)/2;a(d)?c=d:u=d}return u}function Xh(t,e){let n=Math.hypot(t,e);return n>0?{nx:t/n,ny:e/n}:null}function BO(t,e,n,r,s,o){let i=ko(t,Yr(e,r),Yr(n,s)),a=(o===void 0?null:Xh(o.dx,o.dy))??Xh(s.x-r.x,s.y-r.y),c=Xh(i.x-s.x,i.y-s.y),u=c!==null&&a!==null&&c.nx*a.nx+c.ny*a.ny<0?-1:1;return{...c===null?a??{nx:1,ny:0}:{nx:u*c.nx,ny:u*c.ny},push:0}}function LO(t,e,n,r){let s=r.get(e.id),o=r.get(n.id),i=ko(t,Yr(e,s),Yr(n,o));if(Cd(i,o))return!1;let a={x:(i.x-o.x)/2,y:(i.y-o.y)/2,z:(i.z-o.z)/2};return r.set(e.id,{x:s.x-a.x,y:s.y-a.y,z:s.z-a.z}),r.set(n.id,{x:o.x+a.x,y:o.y+a.y,z:o.z+a.z}),!0}function Zx(t,e,n,r){return r.nx*(n.x-e.x)+r.ny*(n.y-e.y)<0&&!Qh(t,e,n,e,n)}var Qx=(t,e,n,r,s)=>s.nx*(r.x-n.x-(e.x-t.x))+s.ny*(r.y-n.y-(e.y-t.y));function FO(t,e,n,r,s,o,i){let a=Fc(e.id,n.id),c=r.get(e.id),u=r.get(n.id),l=s.get(a),d=0;if(l===void 0){let y=o?.pair;if(y===void 0?!Qh(t,e,n,e,n):Zx(t,e,n,y))return LO(t,e,n,r);l=y??BO(t,e,n,c,u,o),s.set(a,l);let S=y===void 0?0:y.push-MO*Math.min(i,CO);d=Math.max(0,S-Qx(e,n,c,u,l))}let f=NO(t,e,n,c,u,l,d);if(f<=0)return!1;let[h,p]=Jx(c,u,l,f);return r.set(e.id,h),r.set(n.id,p),!0}function zO(t,e,n,r,s,o){if(s===void 0)return;let i=r.get(e.id),a=r.get(n.id),c=qi(i,a);if(s.dx*c.dx+s.dy*c.dy>=0)return;let u=Yr(e,i),l=Yr(n,a);if(!Md(t,u,l,s,c))return;let d=Math.atan2(s.dy,s.dx),f=Jh(t,u,l,d,s.dz,Math.hypot(s.dx,s.dy)),h={dx:f*Math.cos(d),dy:f*Math.sin(d),dz:s.dz};return o(n.id)>=o(e.id)?(r.set(n.id,{x:i.x+h.dx,y:i.y+h.dy,z:i.z+h.dz}),n.id):(r.set(e.id,{x:a.x-h.dx,y:a.y-h.dy,z:a.z-h.dz}),e.id)}function UO(t,e,n,r,s){let o=Yr(n,r),i=ko(t,e,o);return Cd(i,r)?r:Md(t,e,o,qi(e,s),qi(e,i))?s:i}function VO(t){return t.flatMap((e,n)=>t.slice(n+1).map(r=>[e,r]))}function e_(t,e,n,r,s){let o=[...n].sort((h,p)=>h.id<p.id?-1:h.id>p.id?1:0),i=new Map;for(let h of o){let p=r.get(h.id),y=Gx(t,e,h,p,s),w=p?.held===!0&&!y.side.held&&TO(t,e,h,o,r,p,y)?Gx(t,e,h,p,s,!0):y;i.set(h.id,{x:w.x,y:w.y,z:w.z})}let a=new Map(i),c=h=>{let p=r.get(h),y=a.get(h);return p===void 0?Number.POSITIVE_INFINITY:Math.hypot(y.x-e.x-p.dx,y.y-e.y-p.dy,y.z-e.z-p.dz)},u=VO(o),l=(h,p)=>r.get(Fc(h.id,p.id));for(let[h,p]of u){let y=l(h,p);(y?.pair===void 0||Zx(t,h,p,y.pair))&&zO(t,h,p,i,y,c)}let d=new Map;for(let h=0;;h++){for(let y of o)i.set(y.id,UO(t,e,y,i.get(y.id),a.get(y.id)));if(h===vO)break;let p=!1;for(let[y,S]of u){let w=l(y,S);p=FO(t,y,S,i,d,w,w===void 0?0:Math.max(0,s-w.at)/1e3)||p}if(!p)break}let f=new Map;for(let h of o){let p=i.get(h.id);f.set(h.id,{...qi(e,p),held:!Cd(p,h),bx:h.x-e.x,by:h.y-e.y,at:s})}for(let[h,p]of u){let y=i.get(h.id),S=Fc(h.id,p.id),w=d.get(S),x=w===void 0?0:Qx(h,p,y,i.get(p.id),w),R=w!==void 0&&x>0?{pair:{nx:w.nx,ny:w.ny,push:x}}:{};f.set(S,{...qi(y,i.get(p.id)),held:!1,bx:p.x-h.x,by:p.y-h.y,at:s,...R})}return{drawn:i,sides:f}}var Gi=(t,e,n)=>t+(n-e);var Yi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function HO(t){if(!Yi(t)||typeof t.preset!="string"||!Object.hasOwn(PS,t.preset))return!1;let e=t.shape,n=t.hull;return!Yi(e)||e.kind!==Wn.Box&&e.kind!==Wn.Hull||!Yi(n)?!1:Yi(t.top)&&Yi(t.offWall)&&Array.isArray(t.pairs)&&typeof t.passes=="number"}function t_(t,e){if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}let r=Yi(n)?n.contacts:void 0;if(!HO(r))return null;let s={world:CS(e,r.hull.radius,r.hull.height,r.hull.skin)},o=new Map,i=a=>{let c=o.get(a);if(c!==void 0)return c;let u=Lh(r,{...s,fixed:a});return o.set(a,u),u};return{policy:r,rule:Lh(r,s),pass:ZS(r,s),env:s,drawRule:i}}var Od=[.5,1,5,20],$O=new Set(["x","y","z"]),jO=new Set(["mstate","cap","spin","fuel"]),n_=2*Math.PI;function r_(t,e,n){let r=0,s=0;return t.forEach((o,i)=>{if(jO.has(o))return;let a=(n[i]??0)-(e[i]??0);$O.has(o)?r+=a*a:s=Math.max(s,Math.abs(o==="yaw"?a-n_*Math.floor((a+Math.PI)/n_):a))}),{place:Math.sqrt(r),state:s}}var s_=(t,e)=>t>.05*e;function o_(t,e){let n=Od.findIndex(r=>t<r*e);return n<0?Od.length:n}function i_(t){return Number.isSafeInteger(t)?(t%65536+65536)%65536:0}var p_=500;function WO(t,e,n,r){let s=t.poses.get(n)?.get(e);if(s===void 0)return;let o=t.poses.get(n-1)?.get(e),i=t.poses.get(n-2)?.get(e);if(o===void 0){let h=r/t.tickHz;return{...s,x:s.x+s.vx*h,y:s.y+s.vy*h,z:s.z+s.vz*h}}let a=Math.floor(r),c=h=>h*(h+1)/2,u=(h,p,y)=>{let S=h+p*a+y*c(a),w=h+p*(a+1)+y*c(a+1);return S+(w-S)*(r-a)},l=(h,p,y)=>y===void 0?0:h-2*p+y,d=Ts(s.yaw-o.yaw),f=i===void 0?0:d-Ts(o.yaw-i.yaw);return{...s,x:u(s.x,s.x-o.x,l(s.x,o.x,i?.x)),y:u(s.y,s.y-o.y,l(s.y,o.y,i?.y)),z:u(s.z,s.z-o.z,l(s.z,o.z,i?.z)),yaw:Ts(u(s.yaw,d,f))}}function qO(t,e){let n=t.ack+t.ticks,r=Math.min(Math.max(e,t.ack+1),n),s=Math.floor(r),o=t.own.get(s);if(o===void 0)return;let i=t.own.get(s+1),a=r-s;return i===void 0||a===0?o:{...o,x:o.x+(i.x-o.x)*a,y:o.y+(i.y-o.y)*a,z:o.z+(i.z-o.z)*a,yaw:o.yaw+Ts(i.yaw-o.yaw)*a}}var a_=8,GO=3,em=.5,tm=(t,e)=>t.id<e.id?-1:t.id>e.id?1:0,ke=(t,e=0)=>typeof t=="number"&&Number.isFinite(t)?t:e,c_=2*Math.PI,Ts=t=>t-c_*Math.floor((t+Math.PI)/c_),u_=t=>({x:ke(t.x),y:ke(t.y),z:ke(t.z),yaw:ke(t.yaw),vx:ke(t.vx),vy:ke(t.vy),vz:ke(t.vz)}),l_=(t,e)=>({id:t,x:ke(e.x),y:ke(e.y),z:ke(e.z),vx:ke(e.vx),vy:ke(e.vy),vz:ke(e.vz),yaw:ke(e.yaw),spin:ke(e.spin),...typeof e.flags=="number"?{flags:e.flags}:{}}),d_=(t,e)=>({id:t,x:ke(e.x),y:ke(e.y),z:ke(e.z),vx:ke(e.vx),vy:ke(e.vy),vz:ke(e.vz),yaw:ke(e.yaw),duck:ke(e.duck),flags:ke(e.flags)}),f_=(t,e)=>Eo.every(n=>t[n]===e[n]),Dd=class{constructor(e){m(this,"options");m(this,"serial",0);m(this,"current",null);m(this,"recent",[]);m(this,"applied",new Map);m(this,"missed",new Set);this.options=e}apply(e,n,r,s,o,i=null){let a=this.current,c=a===null||a.ack!==n||a.stateTick!==r||e<=a.last,u=a,l=c?this.start(n,r,o):a,d=e-n;for(let p=l.ticks+1;p<d;p++)this.tick(l,p,u?.ownIn.get(n+p),!1,u?.ownOn.get(n+p)??null),this.noteMissed(l,n+p);let f=d>l.ticks,h=f?this.tick(l,d,s,!0,i):null;f&&this.applied.set(e,l.touching.get(e)??new Set),l.last=e;for(let p of this.recent)this.extend(p,l,e);return h}takeMissed(){let e=[...this.missed].sort();return this.missed.clear(),e}noteMissed(e,n){let r=this.applied.get(n),s=e.touching.get(n);if(!(r===void 0||s===void 0))for(let o of s)r.has(o)||this.missed.add(o)}extend(e,n,r){let s=r-e.ack;for(let o=e.ticks+1;o<=s;o++)this.tick(e,o,n.ownIn.get(e.ack+o),!1,n.ownOn.get(e.ack+o)??null);e.last=Math.max(e.last,r)}poseAt(e,n,r=this.current){if(r===null)return;let s=Math.max(n,r.ack),o=r.ack+r.ticks,i=Math.min(Math.floor(s),o),a=r.poses.get(i)?.get(e);if(a===void 0)return;let c=i<o?r.poses.get(i+1)?.get(e):void 0,u=s-i;if(c===void 0){if(r===this.current){let l=Math.min(u,1)/r.tickHz;return{...a,x:a.x+a.vx*l,y:a.y+a.vy*l,z:a.z+a.vz*l}}return WO(r,e,i,u)??a}return{x:a.x+(c.x-a.x)*u,y:a.y+(c.y-a.y)*u,z:a.z+(c.z-a.z)*u,yaw:a.yaw+Ts(c.yaw-a.yaw)*u,vx:a.vx+(c.vx-a.vx)*u,vy:a.vy+(c.vy-a.vy)*u,vz:a.vz+(c.vz-a.vz)*u}}motionAt(e,n,r=this.current){let s=this.poseAt(e,n,r),o=this.poseAt(e,n-em,r),i=this.poseAt(e,n+em,r);if(s===void 0||o===void 0||i===void 0||r===null)return;let a=r.tickHz/1e3/(2*em);return{pose:s,rate:{vx:(i.x-o.x)*a,vy:(i.y-o.y)*a,vz:(i.z-o.z)*a,vyaw:Ts(i.yaw-o.yaw)*a}}}changeAt(e,n,r){if(this.current===null||this.current===r)return;let s=Math.min(n,r.ack+r.ticks),o=this.motionAt(e,s,r),i=this.motionAt(e,s);return o===void 0||i===void 0?void 0:{before:o,after:i}}touchAheadMs(e,n){let r=this.current;if(r===null)return;let s=Math.floor(Math.max(n,r.ack));if(r.touching.get(s)?.has(e)===!0||r.touching.get(s+1)?.has(e)===!0)return 0;let o=r.seats.find(l=>l.id===e),i=this.poseAt(e,n,r),a=qO(r,n);if(o===void 0||i===void 0||a===void 0)return;let c={...l_(e,o.body),x:i.x,y:i.y,z:i.z,yaw:i.yaw,vx:i.vx,vy:i.vy,vz:i.vz},u={x:(i.vx-a.vx)/1e3,y:(i.vy-a.vy)/1e3,z:(i.vz-a.vz)/1e3};for(let l=0;l<=a_;l++){let d=l/a_*_t.SEAT_CLOCK_TAU_MS;if(this.touches(a,{...c,x:c.x+u.x*d,y:c.y+u.y*d,z:c.z+u.z*d}))return d}}touchingAt(e,n){let r=this.current;return r===null?!1:r.touching.get(Math.round(Math.max(n,r.ack)))?.has(e)===!0}stateRate(e){let n=this.current,r=n?.poses.get(n.ack)?.get(e);if(r!==void 0)return{vx:r.vx/1e3,vy:r.vy/1e3,vz:r.vz/1e3,vyaw:0}}start(e,n,r){let s=this.options.others().map(a=>({id:a.id,epoch:a.epoch,body:{...a.body},input:a.input})).sort(tm),o=new Map([[e,new Map(s.map(a=>[a.id,u_(a.body)]))]]);this.serial+=1,this.current!==null&&(this.recent=[this.current,...this.recent].slice(0,GO));for(let a of this.applied.keys())a<=e&&this.applied.delete(a);let i={id:this.serial,ack:e,stateTick:n,tickHz:r,last:e,ticks:0,seats:s,poses:o,touching:new Map,own:new Map,ownIn:new Map,ownOn:new Map};return this.current=i,i}tick(e,n,r,s,o){let i=Math.ceil(this.options.maxAheadMs()*e.tickHz/1e3),a=n<=i?this.carry(e,n):null;if(n<=i)for(let p of e.seats)this.move(e,p,n,a===null?void 0:Mc(a.t,p.id));let c=r===void 0?void 0:{...r};r!==void 0&&(e.ownIn.set(e.ack+n,{...r}),e.ownOn.set(e.ack+n,o));let u=a===null?null:this.ride(e,a,c,o),l=e.seats.map(p=>l_(p.id,p.body)),d=new Set;if(c!==void 0)for(let p of l)this.touches(c,p)&&d.add(p.id);let f=c===void 0?l:[...l,c].sort(tm);if(this.contactPass(f),e.seats.forEach((p,y)=>{let S=l[y];for(let w of Eo)typeof S[w]=="number"&&(p.body[w]=S[w])}),a!==null&&this.impart(e,a,c),r!==void 0&&c!==void 0&&s)for(let p of Eo){let y=c[p];typeof y=="number"&&y!==r[p]&&(r[p]=Math.fround(y))}let h=e.ack+n;return e.poses.set(h,new Map(e.seats.map(p=>[p.id,u_(p.body)]))),e.touching.set(h,d),c!==void 0&&e.own.set(h,s&&r!==void 0?{...r}:c),e.ticks=n,u}ride(e,n,r,s){let o=n.t,i=new Map(e.seats.map(h=>[h.id,h.body])),a=h=>r!==void 0&&h===r.id?r:i.get(h);for(let h of o.seats){let p=a(h.id);p!==void 0&&(h.x=ke(p.x),h.y=ke(p.y))}xx(n.l.lifts,o);for(let h of o.seats){let p=i.get(h.id);p!==void 0&&(p.x=h.x,p.y=h.y)}if(r===void 0||s===null)return null;let c=o.seats.find(h=>h.id===r.id),u=o.seats.findIndex(h=>h.id===s);if(c===void 0&&u<0)return null;let l=c===void 0?o.report.from[u]:[r.x,r.y],d=c??o.seats[u],f=[d.x-l[0],d.y-l[1]];return r.x=Math.fround(r.x+f[0]),r.y=Math.fround(r.y+f[1]),f}carry(e,n){let r=this.options.lifts?.()??null;if(r===null)return null;let s=e.own.get(e.ack+n-1),o=e.seats.map(c=>d_(c.id,c.body));s!==void 0&&o.push(d_(s.id,s)),o.sort(tm);let i=vc(r.lifts,o,e.stateTick+n,r.starts,1/e.tickHz,r.cache),a=new Map(i.seats.map(c=>[c.id,c]));for(let c of e.seats){let u=a.get(c.id);c.body.x=u.x,c.body.y=u.y,c.body.z=u.z,r.lifts.vehicle&&(c.body.yaw=u.yaw)}return{l:r,t:i}}impart(e,n,r){let s=new Map(e.seats.map(i=>[i.id,i.body]));r!==void 0&&s.set(r.id,r);for(let i of n.t.seats){let a=s.get(i.id);a!==void 0&&(i.x=ke(a.x),i.y=ke(a.y),i.z=ke(a.z),i.vx=ke(a.vx),i.vy=ke(a.vy),i.vz=ke(a.vz))}Cc(n.l.lifts,n.t,n.l.starts);let o=new Map(n.t.seats.map(i=>[i.id,i]));for(let i of e.seats){let a=o.get(i.id);i.body.vx=a.vx,i.body.vy=a.vy,i.body.vz=a.vz}}move(e,n,r,s){let o=1/e.tickHz,{predict:i,decayMs:a}=this.options.remote(),c=i===Xt.EXTRAPOLATE?void 0:this.options.step();if(c===void 0||n.input===void 0){let l=n.body;l.x=ke(l.x)+ke(l.vx)*o,l.y=ke(l.y)+ke(l.vy)*o,l.z=ke(l.z)+ke(l.vz)*o;return}this.options.seatRule?.(n.body,e.stateTick+r);let u=i===Xt.INPUT_DECAY?Rd(n.input,r,e.tickHz,a):n.input;c(n.body,u,o,s)}contactPass(e){if(this.options.pass!==void 0){this.options.pass(e);return}for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++)this.options.rule(e[n],e[r])}touches(e,n){let r={...e},s={...n};return r.id<s.id?this.options.rule(r,s):this.options.rule(s,r),!f_(r,e)||!f_(s,n)}};function h_(t,e,n,r){if(t===void 0||!Number.isFinite(t.seq))return{seq:e,at:n};let s=Math.max(0,n-t.at),o=t.seq+s*r/1e3,i=e-o;if(Math.abs(i)>_t.SEAT_CLOCK_SNAP_INPUTS)return{seq:e,at:n};let a=o+i*(1-Math.exp(-s/_t.SEAT_CLOCK_TAU_MS));return{seq:Math.max(t.seq,a),at:n}}function m_(t,e,n){if(t===void 0||!Number.isFinite(t))return e?1:0;let r=Math.max(0,n)/_t.SEAT_CLOCK_TAU_MS;return e?Math.min(1,t+r):Math.max(0,t-r)}var YO=.01;function y_(t,e){let n=Math.exp(-e/_t.SEAT_TAU_MS),r=Math.max(Math.abs(t.dx),Math.abs(t.dy),Math.abs(t.dz))*n<YO;return{dx:t.dx*n,dy:t.dy*n,dz:t.dz*n,done:r}}var KO=t=>t?_t.SEAT_CONTACT_TAU_MS:_t.SEAT_TAU_MS;function Id(t,e,n,r){let s=1/r,o=Math.exp(-s*n),i=e+s*t;return[(t+i*n)*o,(e-s*i*n)*o]}function g_(t,e,n,r,s,o,i,a,c){let u={ax:s.pose.x,ay:s.pose.y,az:s.pose.z},l={pass:e,epoch:n,dx:0,dy:0,dz:0,dyaw:0,vx:0,vy:0,vz:0,vyaw:0,...u,hx:0,hy:0,hz:0,stillMs:0,stopFound:!1};if(t===void 0||t.epoch!==n)return l;let d=KO(i),f=Math.max(0,o),[h,p]=Id(t.dx,t.vx,f,d),[y,S]=Id(t.dy,t.vy,f,d),[w,x]=Id(t.dz,t.vz,f,d),[R,A]=Id(t.dyaw,t.vyaw,f,d),E=t.pass!==e&&r!==void 0,P=E?r.before:s,k=E?r.after:s,M={x:P.pose.x-k.pose.x,y:P.pose.y-k.pose.y,z:P.pose.z-k.pose.z,yaw:Ts(P.pose.yaw-k.pose.yaw)},L={vx:P.rate.vx-k.rate.vx,vy:P.rate.vy-k.rate.vy,vz:P.rate.vz-k.rate.vz,vyaw:P.rate.vyaw-k.rate.vyaw},K={pose:{...s.pose,x:s.pose.x+M.x,y:s.pose.y+M.y,z:s.pose.z+M.z},rate:{vx:s.rate.vx+L.vx,vy:s.rate.vy+L.vy,vz:s.rate.vz+L.vz,vyaw:s.rate.vyaw+L.vyaw}},W=E?XO(t,L)||t.stopFound&&t.stillMs>0:t.stopFound,B=JO(t,{...t,pass:e,dx:h,dy:y,dz:w,dyaw:R,vx:p,vy:S,vz:x,vyaw:A,stopFound:W},K,s.rate,c),se={dx:B.dx+M.x,dy:B.dy+M.y,dz:B.dz+M.z,dyaw:Ts(B.dyaw+M.yaw)};if(Math.hypot(se.dx,se.dy,se.dz)>a)return l;let v={vx:B.vx+L.vx,vy:B.vy+L.vy,vz:B.vz+L.vz,vyaw:B.vyaw+L.vyaw};return ZO({...B,...se,...v,...u},s.rate,f)}function XO(t,e){return e.vx*t.hx+e.vy*t.hy+e.vz*t.hz>_t.SEAT_MOVING_UNITS_PER_MS}function JO(t,e,n,r,s){let o={x:t.hx,y:t.hy,z:t.hz},i=R=>R.x*o.x+R.y*o.y+R.z*o.z,a=i({x:n.rate.vx,y:n.rate.vy,z:n.rate.vz}),c=n.pose,l=i({x:c.x-t.ax,y:c.y-t.ay,z:c.z-t.az})+i({x:e.dx-t.dx,y:e.dy-t.dy,z:e.dz-t.dz}),d=i({x:r.vx,y:r.vy,z:r.vz})<0,f=s!==void 0&&i({x:s.vx,y:s.vy,z:s.vz})>_t.SEAT_MOVING_UNITS_PER_MS,h=i({x:t.dx,y:t.dy,z:t.dz})>0,p=e.stopFound&&f&&h;if(t.stillMs>=_t.SEAT_HOLD_MS||d&&!p)return e;let S=a+i({x:e.vx,y:e.vy,z:e.vz});if(l>=0&&S>=0)return e;let w=Math.max(0,-l),x=-S;return{...e,dx:e.dx+w*o.x,dy:e.dy+w*o.y,dz:e.dz+w*o.z,vx:e.vx+x*o.x,vy:e.vy+x*o.y,vz:e.vz+x*o.z}}function ZO(t,e,n){let r=e.vx+t.vx,s=e.vy+t.vy,o=e.vz+t.vz,i=Math.hypot(r,s,o);return i>_t.SEAT_MOVING_UNITS_PER_MS?{...t,hx:r/i,hy:s/i,hz:o/i,stillMs:0}:{...t,stillMs:t.stillMs+n}}function QO(t){if(!(t===void 0||typeof t.inMoveX!="number"))return{moveX:Tt(t.inMoveX),moveY:Tt(t.inMoveY),moveZ:Tt(t.inMoveZ),yaw:Tt(t.inYaw),pitch:Tt(t.inPitch),buttons:Tt(t.inButtons)}}var b_=1e3/60,eI=b_,tI=0,Tt=t=>typeof t=="number"&&Number.isFinite(t)?t:tI;function w_(t){let e={status:t.enabled?je.LOADING:je.OFF,matched:0,replayed:0,peakResimMs:0,lastResimMs:0,slowResims:0,fallbacks:0,recoveries:0},n=null,r=null,s=0,o=0,i=new Map,a,c=t.state,u=new Map,l=x=>{e.status=x,n?.stop(x),n=null},d=()=>{if(r!==null||t.loadCore===void 0){t.loadCore===void 0&&(e.status=je.UNAVAILABLE);return}r=t.loadCore().then(x=>{if(e.status!==je.LOADING)return;if(!$x(x))return l(je.SELF_TEST);let R=Nc(c.physDesc);if(R===null)return l(je.MISMATCH);let A=t.staticWorld();n=new Ad(x,{desc:R,staticWorld:{boxes:A.boxes.map(E=>[...E]),ramps:A.ramps.map(E=>[...E])},physicsHash:c.physics??"",tickHz:t.tickHz(),budgetMs:t.budgetMs,remoteStep:t.remoteStep?.(),bodyRule:t.bodyRule,...t.headSlide===void 0?{}:{headSlide:t.headSlide},kinematicRule:t.kinematicRule,...t.lifts===void 0?{}:{lifts:t.lifts},seatRule:t.seatRule,seatPose:t.seatPose,contactPass:t.contactPass,...t.clock===void 0?{}:{clock:t.clock}}),n.predicting||l(n.status)}).catch(()=>l(je.UNAVAILABLE))},f=()=>{let x=c.entities??new Map,R=W=>c.shapes?.get(W)?.data,A=[],E=[],P=W=>c.bodies?.has(W)===!0;for(let[W,B]of c.bodies??[]){let se=B.desc===void 0||B.desc===""?null:Dx(B.desc,R),v=x.get(W);if(v===void 0||t.motionKnown?.(W)===!1){let j=u.get(W)??(v===void 0?[0,0,0]:[v.x,v.y,v.z]);E.push({key:W,x:j[0],y:j[1],z:j[2],radius:se===null?0:Bc(se)});continue}u.set(W,[v.x,v.y,v.z]);let $=new Array(15),Y={x:v.x,y:v.y,z:v.z,qx:Tt(v.qx),qy:Tt(v.qy),qz:Tt(v.qz),qw:Tt(v.qw),lvx:Tt(v.lvx),lvy:Tt(v.lvy),lvz:Tt(v.lvz),avx:Tt(v.avx),avy:Tt(v.avy),avz:Tt(v.avz),sleep:v.sleep===!0,rest:Tt(v.rest)};Cx(Y,$,0),A.push({key:W,desc:se,row:$,epoch:v.epoch})}for(let W of u.keys())c.bodies?.has(W)!==!0&&u.delete(W);let k=[];for(let[W,B]of c.joints??[])try{k.push({key:W,desc:JSON.parse(B.desc),motor:B.motor===""?null:JSON.parse(B.motor)})}catch{}let M=[],L=new Set,K=t.ownId();for(let[W,B]of x){if(B.owner===""||L.has(B.owner)||$r(B)||P(W)||c.players?.has(B.owner)!==!0)continue;L.add(B.owner);let se={...B};M.push({key:W,x:B.x,y:B.y,z:B.z,vx:B.vx,vy:B.vy,vz:B.vz,epoch:B.epoch,own:W===K,input:QO(c.players?.get(B.owner)),body:se})}return{tick:c.keyframe??0,ack:t.acked(),bodies:A,outside:E,joints:k,seats:M}},h=null,p=0,y=t.clock??(()=>performance.now()),S=()=>{let x=h;h=null,p=0,x!==null&&w(x)},w=x=>{if(n===null)return;for(let[A,E]of t.ownPath?.()??[])i.set(A,E);let R=n.adopt(x.keyframe,x.sent,A=>i.get(A)?.p,x.now,A=>i.get(A)?.v);R.kind==="match"&&e.matched++,R.kind==="replay"&&e.replayed++,R.kind==="replay"&&(e.lastResimMs=R.ms,R.ms>b_&&e.slowResims++),e.peakResimMs=Math.max(e.peakResimMs,R.ms),e.fallbacks=n.fallbacks,e.recoveries=n.recoveries,n.stopped?l(n.status):e.status=n.status,o=x.sent};return{status:e,onState(x){if(e.status===je.OFF)return;let R=c.keyframe??0;if(R===0||(c.physDesc??"")==="")return;if(n===null){d();return}if(R===s||c.tick!==R)return;s=R;let A={keyframe:f(),sent:t.sent(),now:x};if(p>=eI){h=A;return}let E=y();w(A),p+=y()-E},settle:S,afterSend(x,R){S();let A=t.sent(),E=a??x,P=A-o;for(let k=1;k<=P;k++){let M=k/P;if(x!==void 0&&E!==void 0){let L=[E.p[0]+(x.p[0]-E.p[0])*M,E.p[1]+(x.p[1]-E.p[1])*M,E.p[2]+(x.p[2]-E.p[2])*M];i.set(o+k,{p:L,v:x.v})}n?.advance(o+k,R)}o=A,a=x;for(let k of i.keys())k<A-256&&i.delete(k)},draw(x,R){return S(),n===null||!n.draws(x)?null:n.draw(x,R)},dispose(){n?.stop(je.OFF),n=null}}}At();var Nd={min:-1,max:1,bits:16,mode:"clamp"},Ki={min:-64,max:64,bits:16,mode:"clamp"},S_=Lt({moveX:X.float32().default(0),moveY:X.float32().default(0),moveZ:X.float32().default(0),yaw:X.float32().default(0),pitch:X.float32().default(0),buttons:X.number().default(0),tick:X.number().default(0)},"AuthorityInput"),nI=1,x_=t=>({kind:X.string().default(""),owner:X.string().default(""),x:t(X.float32().default(0)),y:t(X.float32().default(0)),z:t(X.float32().default(0)),vx:t(X.float32().default(0)),vy:t(X.float32().default(0)),vz:t(X.float32().default(0)),yaw:t(X.float32().default(0)),hp:X.number().default(0),flags:X.number().default(0),epoch:t(X.number().default(0)),data:X.string().default(""),t0:X.number().default(0),g:X.float32().default(0),src:X.string().default(""),pitch:t(X.float32().default(0)),duck:t(X.float32().default(0)),mstate:t(X.number().default(0)),cap:X.float32().default(1),spin:t(X.float32().default(0)),fuel:t(X.float32().default(0)),qx:t(X.quantized(Nd).optional()),qy:t(X.quantized(Nd).optional()),qz:t(X.quantized(Nd).optional()),qw:t(X.quantized(Nd).optional()),lvx:t(X.quantized(Ki).optional()),lvy:t(X.quantized(Ki).optional()),lvz:t(X.quantized(Ki).optional()),avx:t(X.quantized(Ki).optional()),avy:t(X.quantized(Ki).optional()),avz:t(X.quantized(Ki).optional()),sleep:t(X.boolean().optional()),rest:t(X.number().optional())}),rI=Lt(x_(t=>t),"AuthorityEntity"),sI=Lt(x_(t=>t.view(nI)),"AuthorityEntity"),oI=Lt({type:X.string().default(""),kind:X.string().default(""),colliders:X.string().default(""),desc:X.string().optional()},"AuthorityBody"),iI=Lt({data:X.string().default("")},"AuthorityShape"),aI=Lt({desc:X.string().default(""),motor:X.string().default("")},"AuthorityJoint"),cI=Lt({name:X.string().default(""),uid:X.string().default(""),team:X.string().default(""),connected:X.boolean().default(!0),avatarUrl:X.string().default(""),seqBase:X.number().default(0),inMoveX:X.float32().optional(),inMoveY:X.float32().optional(),inMoveZ:X.float32().optional(),inYaw:X.float32().optional(),inPitch:X.float32().optional(),inButtons:X.number().optional(),inRep:X.number().optional(),inStarve:X.number().optional(),inBuf:X.number().optional()},"AuthorityPlayer"),__={players:X.map(cI),entities:X.map(rI),tick:X.number().default(0),clockOrigin:X.float64().default(0),preset:X.string().default(""),moduleSha:X.string().default(""),tickOrigin:X.float64().default(0),physics:X.string().optional(),lengthUnit:X.float32().optional(),bodies:X.map(oI).optional(),physDesc:X.string().optional(),keyframe:X.number().optional(),shapes:X.map(iI).optional(),joints:X.map(aI).optional(),lifts:X.string().optional(),matchKey:X.string().optional()},AV=Lt(__,"AuthorityRoomState"),PV=Lt({...__,entities:X.map(sI).view()},"AuthorityRoomState");var uI=(t,e)=>t+Math.atan2(Math.sin(e-t),Math.cos(e-t)),lI=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n,z:t.z+(e.z-t.z)*n,yaw:t.yaw+(e.yaw-t.yaw)*n,pitch:t.pitch+(e.pitch-t.pitch)*n,duck:t.duck+(e.duck-t.duck)*n}),Bd=class{constructor(){m(this,"rings",new WeakMap)}push(e,n,r,s,o=0){let i=this.rings.get(e);i===void 0&&(i=[],this.rings.set(e,i));let a=i.at(-1);if(a!==void 0&&n<=a.t)return;let c=a!==void 0&&a.life===o,u=c?uI(a.pose.yaw,r.yaw):r.yaw;c&&n-a.t>s*1.5&&i.push({t:n-s,life:o,pose:a.pose}),i.push({t:n,life:o,pose:{...r,yaw:u}}),i.length>80&&i.splice(0,i.length-80)}at(e,n){let r=this.rings.get(e);if(r===void 0||r.length===0)return;let s=r[0],o=r.at(-1);if(n<=s.t)return s.pose;if(n>=o.t)return o.pose;let i=r.length-2;for(;i>0&&r[i].t>n;)i--;let a=r[i],c=r[i+1];return a.life!==c.life?a.pose:lI(a.pose,c.pose,(n-a.t)/(c.t-a.t))}forget(e){this.rings.delete(e)}};var yt={On:"on",Off:"off"};var OV={[jn.Shooter]:{repeat:yt.On},[jn.Platformer]:{repeat:yt.On},[jn.VehicleArena]:{repeat:yt.Off},[jn.PhysicsSandbox]:{repeat:yt.On},[jn.Party]:{repeat:yt.On}},IV={repeat:yt.On};var R_=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);function E_(t){let e;try{e=JSON.parse(t)}catch{return yt.On}let n=R_(e)?e.inputs:void 0;return R_(n)&&n.repeat===yt.Off?yt.Off:yt.On}var k_={IDLE_SEAT_S:1800,IDLE_SEAT_MIN_S:30,IDLE_SEAT_MAX_S:86400,ROOM_AGE_S:86400,ROOM_AGE_MIN_S:60,ROOM_AGE_MAX_S:604800},BV={idleSeatS:k_.IDLE_SEAT_S,maxRoomAgeS:k_.ROOM_AGE_S};var a3={MAX_ENTITIES:256,MAX_HANDOFF_CHARS:256*1024,MAX_ROOM_ENTITIES:1024,MAX_OUTPUT_BYTES:32*1024,MAX_EVENTS_PER_TICK:64,MAX_ENTITY_DATA_BYTES:256,MAX_ENTITY_ID_CHARS:64,MAX_KIND_CHARS:64,MAX_SESSION_ID_CHARS:64,MAX_ABS:1e9,MASK_LIMIT:16777216,MAX_EPOCH:2**32-1,MAX_PROJECTILE_TICK:AS,MAX_PROJECTILE_G:wc,MAX_LAUNCH_UPDATES:224,MAX_LAUNCH_BYTES:28*1024,MAX_EVENT_TYPE_CHARS:Yt.MAX_EVENT_TYPE_CHARS,MAX_EVENT_BYTES:Yt.MAX_EVENT_BYTES,MAX_JSON_DEPTH:Yt.MAX_JSON_DEPTH,MAX_JSON_NODES:Yt.MAX_JSON_NODES,MAX_PLAYERS:Yt.ROOM_MAX_CLIENTS,MAX_PHYS_COMMANDS:256,MAX_PHYS_BYTES:32*1024,MAX_PHYSICS_OUTPUT_BYTES:64*1024,MAX_PHYSICS_WORLD_BOXES:32768,MAX_PHYSICS_WORLD_RAMPS:4096,MAX_WORLD_TEXT_CHARS:1245196};function Xi(t){return{moveX:Vn(t.moveX),moveY:Vn(t.moveY),moveZ:Vn(t.moveZ),yaw:_s(t.yaw)??0,pitch:_s(t.pitch)??0,buttons:fo(t.buttons)}}var c3=2**31-1;var m3=ws.INPUT_REPEAT_MAX_MS,y3=ws.INPUT_REPEAT_RUN_MS;function P_(t,e,n,r=yt.On){return r===yt.Off?t:Math.max(t,Math.min(t+v_(e),n))}function T_(t,e,n=yt.On){return n===yt.Off?t:t+v_(e)}var dI=(t,e,n)=>e<=n?e:Math.min(t,n),v_=t=>typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;function M_(){return{shown:0,heldFrom:null}}function C_(t,e,n,r,s){let o=dI(t.shown,e,n);return o<=t.shown?(o<t.shown&&(t.heldFrom=null),t.shown=o,o):o===n||n-(o+1)<r||s?(t.heldFrom=null,t.shown=o,o):(t.heldFrom??(t.heldFrom=n),n-t.heldFrom<r?t.shown:(t.shown=o,o))}var fI=.03,pI=1,A_=.5;function O_(){return{seenRuns:null,owedMs:0,accMs:0,aheadMs:0}}function I_(t,e,n,r,s=yt.On){if(s===yt.Off||typeof e!="number"||!Number.isFinite(e))return;let o=t.seenRuns!==null&&e>t.seenRuns;if(t.seenRuns=e,!o||!(r>0))return;(typeof n=="number"&&Number.isFinite(n)?n:0)<=pI&&(t.owedMs=Math.max(t.owedMs,r))}function D_(t,e,n,r,s){let o=r>0?n.accMs/r:0;return{raw:t+e+A_*o,at:s+A_*n.aheadMs}}function N_(t,e,n){if(!(n>0)||!(e>0)||t.owedMs<=0)return 0;let r=Math.min(t.owedMs,e*fI);t.owedMs-=r,t.accMs+=r,t.aheadMs+=r;let s=Math.floor(t.accMs/n+.5);return t.accMs-=s*n,s}At();var z_=1,U_=1200,sm=8,hI=170,mI=3,V_=32,om=8;var yI=5e3,gI=32,bI=32,wI=4,SI=1024,Po=1e3,H_=2e3,$_=250,Ld=50,j_=32,W_=20,q_=65536,G_=250,Fd=2,Y_=3,xI=1e3,_I=6e4,K_=3e4;function X_(t,e){let n=Math.min(_I,xI*2**Math.min(t,16));return n/2+n/2*e}var To={Bind:"__fast",Off:"__fast:off",Again:"__fast:again",On:"__fast:on"},J_={Uplink:1,Snapshot:2},Pe={Oversized:"oversized",Truncated:"truncated",Trailing:"trailing",Version:"version",Kind:"kind",Session:"session",Key:"key",Count:"count",Fresh:"fresh",Actions:"actions",Flags:"flags",Order:"order",Field:"field",Ahead:"ahead",Fragment:"fragment",Mismatch:"mismatch",Duplicate:"duplicate",Keyframe:"keyframe",Body:"body",Base:"base",Stale:"stale"};var Z_=29,B_=29,zd=24,im=1,am=2,cm=4,w3=im|am|cm,L_=255,Q_=10,RI=4+zd,zc=4294967295,eR=65536,nm=1;var um=t=>({ok:!0,value:t}),En=t=>({ok:!1,fault:t}),tR=(t,e)=>Math.ceil(t*(Number.isFinite(e)&&e>0?e:0)/1e3),Ao=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function Uc(t){return Math.min(V_,Math.max(mI,tR(hI,t)))}function nR(t){return Z_+om*(Q_+zd)+Uc(t)*RI}var Vc=t=>tR(yI,t);function EI(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function lm(t){return/^(?:[0-9a-fA-F]{2})*$/.test(t)?Uint8Array.from(t.match(/../g)??[],e=>Number.parseInt(e,16)):new Uint8Array(0)}var kI=t=>typeof t=="string"&&t.length===2*sm&&/^[0-9a-f]+$/.test(t),AI=(t,e)=>(e.buttons&~(t?.buttons??0))!==0,PI=t=>[t.moveX,t.moveY,t.moveZ,t.yaw,t.pitch].every(e=>typeof e=="number"&&Number.isFinite(Math.fround(e)))&&Ao(t.buttons,zc),TI=t=>Ao(t.seq,zc)&&t.seq>=1&&Ao(t.tick,eR-1)&&Ao(t.render,zc)&&PI(t.input),vI=t=>t.reduce((e,n)=>Math.max(e,n.render),0),MI=(t,e)=>e.render===0||t-e.render>=L_?L_:t-e.render;function CI(t){let{window:e,actions:n}=t;if(!Ao(t.sid,zc)||!kI(t.key)||!Ao(t.ackSnap,zc))return!1;if(e.length===0)return t.fresh===0&&n.length===0;if(e.length>V_||n.length>om||!Ao(t.fresh,e.length)||t.fresh<1||![...n,...e].every(TI))return!1;let r=e.every((o,i)=>i===0||o.seq===e[i-1].seq+1),s=n.every((o,i)=>o.seq<(i+1<n.length?n[i+1].seq:e[0].seq));return r&&s}function rm(t,e,n){return t.setFloat32(e,n.moveX,!0),t.setFloat32(e+4,n.moveY,!0),t.setFloat32(e+8,n.moveZ,!0),t.setFloat32(e+12,n.yaw,!0),t.setFloat32(e+16,n.pitch,!0),t.setUint32(e+20,n.buttons,!0),e+zd}var F_=t=>{let e=new Uint8Array(zd);return rm(new DataView(e.buffer),0,t),EI(e)};function OI(t,e){if(t===null)return 0;let n=F_(t.input)===F_(e.input)?im:0;return e.tick===t.tick?n|=am:e.tick===(t.tick+1)%eR&&(n|=cm),n}function dm(t){if(!CI(t))return En(Pe.Field);let e=new Uint8Array(U_),n=new DataView(e.buffer);e[0]=z_,e[1]=J_.Uplink,n.setUint32(2,t.sid,!0),e.set(lm(t.key),6),n.setUint32(14,t.ackSnap,!0),n.setUint32(18,t.window.at(-1)?.seq??0,!0),e[22]=t.window.length,e[23]=t.fresh,e[24]=t.actions.length;let r=vI(t.window);n.setUint32(25,r,!0);let s=Z_;for(let o of t.actions)n.setUint32(s,o.seq,!0),n.setUint16(s+4,o.tick,!0),n.setUint32(s+6,o.render,!0),s=rm(n,s+Q_,o.input);return t.window.forEach((o,i)=>{let a=OI(i===0?null:t.window[i-1],o);e[s]=a,s+=1,(a&(am|cm))===0&&(n.setUint16(s,o.tick,!0),s+=2),e[s]=MI(r,o),s+=1,(a&im)===0&&(s=rm(n,s,o.input))}),um(e.slice(0,s))}function II(t,e,n){return t.length>U_?Pe.Oversized:t.length<2?Pe.Truncated:t[0]!==z_?Pe.Version:t[1]!==e?Pe.Kind:t.length<n?Pe.Truncated:null}function rR(t,e){let n=t.slice(-Uc(e.tickHz)),r=n.length>0?n[0].seq:Number.POSITIVE_INFINITY,s=t.filter((o,i)=>o.seq>e.inputAck&&o.seq<r&&AI(i>0?t[i-1].input:null,o.input)).slice(0,om);return{sid:e.sid,key:e.key,ackSnap:e.ackSnap,fresh:Math.min(e.fresh,n.length),actions:s,window:n}}var DI=t=>[...t].sort((e,n)=>e.key-n.key);var S3=new Uint8Array(4096);function NI(t,e){let n=II(t,J_.Snapshot,B_);if(n!==null)return En(n);let r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.getUint32(2,!0)!==e)return En(Pe.Session);let s=r.getUint32(6,!0),o=r.getUint32(10,!0),i=t[22],a=t[23],c=t[24];if(c<1||c>bI||a>=c)return En(Pe.Fragment);if(!((i&~nm)===0&&i===nm==(o===0))||s<1||o>=s)return En(Pe.Keyframe);let l=t.slice(B_);return um({snap:s,base:o,tick:r.getUint32(14,!0),inputAck:r.getUint32(18,!0),sent:r.getUint32(25,!0),keyframe:i===nm,frag:a,frags:c,chunk:l})}function BI(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<2)return En(Pe.Body);let n=e.getUint16(0,!0),r=2,s=[];for(let a=0;a<n;a+=1){if(r+2>t.length)return En(Pe.Body);let c=e.getUint16(r,!0);if(a>0&&c<=s[a-1])return En(Pe.Body);s.push(c),r+=2}if(r+2>t.length)return En(Pe.Body);let o=e.getUint16(r,!0);r+=2;let i=[];for(let a=0;a<o;a+=1){if(r+4>t.length)return En(Pe.Body);let c=e.getUint16(r,!0),u=e.getUint16(r+2,!0);if(u>SI||r+4+u>t.length||a>0&&c<=i[a-1].key)return En(Pe.Body);i.push({key:c,bytes:t.slice(r+4,r+4+u)}),r+=4+u}return r===t.length?um({removed:s,records:i}):En(Pe.Body)}function LI(t,e){let n=new Set(e.removed),r=new Map(t.filter(s=>!n.has(s.key)).map(s=>[s.key,s]));for(let s of e.records)r.set(s.key,s);return DI([...r.values()])}var sR=()=>({partials:[],history:[],newest:0}),FI=(t,e)=>t.base===e.base&&t.tick===e.tick&&t.inputAck===e.inputAck&&t.sent===e.sent&&t.keyframe===e.keyframe&&t.frags===e.frags;function oR(t,e,n){let r=NI(e,n);if(!r.ok)return{rx:t,applied:null,fault:r.fault};let s=r.value;if(s.snap<=t.newest)return{rx:t,applied:null,fault:Pe.Stale};let o=t.partials.find(u=>u.snap===s.snap);if(o!==void 0&&!FI(o,s))return{rx:t,applied:null,fault:Pe.Mismatch};if(o?.chunks[s.frag])return{rx:t,applied:null,fault:Pe.Duplicate};let i=o??{snap:s.snap,base:s.base,tick:s.tick,inputAck:s.inputAck,sent:s.sent,keyframe:s.keyframe,frags:s.frags,chunks:Array(s.frags).fill(null)},a={...i,chunks:i.chunks.map((u,l)=>l===s.frag?s.chunk:u)},c=t.partials.filter(u=>u.snap!==s.snap);if(a.chunks.some(u=>u===null)){let u=[...c,a].sort((l,d)=>l.snap-d.snap).slice(-wI);return{rx:{...t,partials:u},applied:null}}return zI({...t,partials:c},t,a)}function zI(t,e,n){let r=t.partials.length===e.partials.length?e:t,s=BI(UI(n.chunks));if(!s.ok)return{rx:r,applied:null,fault:Pe.Body};let o=n.keyframe?null:e.history.find(u=>u.snap===n.base);if(o===void 0)return{rx:r,applied:null,fault:Pe.Base};if(n.keyframe&&s.value.removed.length>0)return{rx:r,applied:null,fault:Pe.Body};let i=LI(o?.records??[],s.value),a=[...e.history,{snap:n.snap,tick:n.tick,inputAck:n.inputAck,sent:n.sent,records:i}].slice(-gI);return{rx:{partials:t.partials.filter(u=>u.snap>n.snap),history:a,newest:n.snap},applied:n.snap}}function UI(t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}var Ut={Entity:1,Seat:2},_e={F32:"f32",U32:"u32",U16:"u16",Orientation:"q-orientation",Velocity:"q-velocity",Flag:"flag"},VI=[["x",_e.F32],["y",_e.F32],["z",_e.F32],["vx",_e.F32],["vy",_e.F32],["vz",_e.F32],["yaw",_e.F32],["pitch",_e.F32],["duck",_e.F32],["spin",_e.F32],["fuel",_e.F32],["epoch",_e.U32],["mstate",_e.U32],["qx",_e.Orientation],["qy",_e.Orientation],["qz",_e.Orientation],["qw",_e.Orientation],["lvx",_e.Velocity],["lvy",_e.Velocity],["lvz",_e.Velocity],["avx",_e.Velocity],["avy",_e.Velocity],["avz",_e.Velocity],["sleep",_e.Flag],["rest",_e.U16]],HI=[["inMoveX",_e.F32],["inMoveY",_e.F32],["inMoveZ",_e.F32],["inYaw",_e.F32],["inPitch",_e.F32],["inButtons",_e.U32],["inRep",_e.U32],["inStarve",_e.U32],["inBuf",_e.U32],["inAck",_e.U32]],$I=64,Ji=2,fm=4;var pm=65534,jI=pm/2,WI={[_e.Orientation]:1,[_e.Velocity]:64},Ud=()=>({x:0,y:0,z:0,vx:0,vy:0,vz:0,yaw:0,pitch:0,duck:0,spin:0,fuel:0,epoch:0,mstate:0,qx:0,qy:0,qz:0,qw:0,lvx:0,lvy:0,lvz:0,avx:0,avy:0,avz:0,sleep:!1,rest:0}),Vd=()=>({inMoveX:0,inMoveY:0,inMoveZ:0,inYaw:0,inPitch:0,inButtons:0,inRep:0,inStarve:0,inBuf:0,inAck:0});var qI=(t,e)=>-t+e/pm*(2*t),GI=t=>t===Ut.Entity?VI:t===Ut.Seat?HI:null;var aR={f32:4,u32:4,u16:2,"q-orientation":2,"q-velocity":2,flag:0},YI=255,KI=4,XI=32,JI=new Uint8Array(Ji+YI+fm+XI*KI),R3=new DataView(JI.buffer);var E3=new TextEncoder;function ZI(t,e,n){if(e+aR[n]>t.byteLength)return{ok:!1,fault:Pe.Truncated};switch(n){case _e.Flag:return{ok:!0,value:!0};case _e.F32:{let r=t.getFloat32(e,!0);return Number.isFinite(r)&&r!==0?{ok:!0,value:r}:{ok:!1,fault:Pe.Field}}case _e.U32:{let r=t.getUint32(e,!0);return r!==0?{ok:!0,value:r}:{ok:!1,fault:Pe.Field}}case _e.U16:{let r=t.getUint16(e,!0);return r!==0?{ok:!0,value:r}:{ok:!1,fault:Pe.Field}}default:{let r=t.getUint16(e,!0);return r!==jI&&r<=pm?{ok:!0,value:qI(WI[n],r)}:{ok:!1,fault:Pe.Field}}}}var QI=new TextDecoder("utf-8",{fatal:!0});function e1(t){let e=t[1];if(Ji+e>t.length)return{ok:!1,fault:Pe.Truncated};if(e===0)return{ok:!1,fault:Pe.Field};try{let n=QI.decode(t.subarray(Ji,Ji+e));return n.length<=$I?{ok:!0,value:n}:{ok:!1,fault:Pe.Field}}catch{return{ok:!1,fault:Pe.Field}}}function cR(t){if(t.length<Ji)return{ok:!1,fault:Pe.Truncated};let e=GI(t[0]);if(e===null)return{ok:!1,fault:Pe.Kind};let n=e1(t);if(!n.ok)return n;let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=Ji+t[1];if(s+fm>t.length)return{ok:!1,fault:Pe.Truncated};let o=r.getUint32(s,!0);if(s+=fm,e.length<32&&o>>>e.length)return{ok:!1,fault:Pe.Flags};if(t[0]===Ut.Entity){let a=iR(r,s,o,Ud(),e);return a.ok?{ok:!0,value:{kind:Ut.Entity,id:n.value,motion:a.value}}:a}let i=iR(r,s,o,Vd(),e);return i.ok?{ok:!0,value:{kind:Ut.Seat,id:n.value,motion:i.value}}:i}function iR(t,e,n,r,s){let o={},i=e;for(let[a,[c,u]]of s.entries()){if((n&1<<a)===0)continue;let l=ZI(t,i,u);if(!l.ok)return l;o[c]=l.value,i+=aR[u]}return i!==t.byteLength?{ok:!1,fault:Pe.Trailing}:{ok:!0,value:Object.assign(r,o)}}var t1=4294967295,n1=4,at={Unreachable:"unreachable",Handshake:"handshake",Stall:"stall",Server:"server",NoWebTransport:"no-webtransport",NoRelay:"no-relay",NotOffered:"not-offered"},r1=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function hm(t){if(typeof t!="object"||t===null)return!1;let{sid:e,key:n,url:r}=t,s=typeof n=="string"&&n.length===2*sm&&/^[0-9a-f]+$/.test(n);return r1(e,t1)&&s&&typeof r=="string"&&r.length>0}function s1(t,e,n){if(t.length===0)return[];let r=t[t.length-1].seq,s=Math.min(e,r-Uc(n)+1),o=Math.max(s,r-Vc(n)+1);return t.filter(i=>i.seq>=o)}var uR=(t,e)=>`${t}:${e}`;function mm(t){let e=sR(),n=[],r=new Map,s=0,o=!1,i=null,a=null,c=null,u=null,l=typeof t.bind.rev=="number"&&t.bind.rev>=Fd,d=null,f=new Map,h=new Map,p=()=>e.history.at(-1)?.inputAck??0,y=E=>{let P=new Map,k=new Map,M=[];for(let L of E){let K=f.get(L.key),W=K!==void 0&&(K.bytes===L.bytes||a1(K.bytes,L.bytes)),B=W?K.record:i1(L.bytes);P.set(L.key,{bytes:L.bytes,record:B}),B!==null&&(k.set(uR(B.kind,B.id),B),W||M.push(B))}return f=P,h=k,M};function S(E){if(o)return{applied:null};let P=oR(e,E,t.bind.sid);if(e=P.rx,P.fault!==void 0||P.applied===null)return{applied:null,fault:P.fault};let k=e.history.at(-1);if(k===void 0)return{applied:null};let M=x;x=k.snap,a=t.now(),n=s1(n,k.inputAck,t.tickHz);let L={snap:k.snap,tick:k.tick,inputAck:k.inputAck,sent:k.sent,changed:y(k.records)};t.onSnapshot?.(L);let K=L.changed.length>=j_&&(c===null||t.now()-c>=W_);return(k.snap-M>=q_||K)&&w(),{applied:L}}function w(){if(o||!l||R===null)return;let E=dm({sid:t.bind.sid,key:t.bind.key,ackSnap:e.newest,fresh:0,actions:[],window:[]});if(!E.ok)return;let P=t.now();i??(i=P),c=P,R.send(E.value)}let x=0,R=t.open(t.bind.url,E=>{S(E)},t.bind);if(R===null)return null;let A=nR(t.tickHz);return{bind:t.bind,get rx(){return e},get lastQueued(){return n.at(-1)?.seq??0},get closed(){return o},opening:()=>R.opening?.()===!0,queue(E){o||(n.push({seq:E.seq,tick:E.tick,render:E.render,input:{...E.input}}),s+=1)},flush(){if(o||s===0)return;let E=t.now();for(let M of n.slice(-s))r.set(M.seq,E);o1(r,(n.at(-1)?.seq??0)-Vc(t.tickHz)+1);let P=Uc(t.tickHz),k=n.length-s;for(s=0;k<n.length;){let M=Math.min(k+P,n.length),L=rR(n.slice(0,M),{sid:t.bind.sid,key:t.bind.key,ackSnap:e.newest,inputAck:p(),fresh:M-k,tickHz:t.tickHz});k=M;let K=dm(L);K.ok&&(i??(i=E),c=E,R.send(K.value))}},framed(){let E=t.now(),P=u===null?0:E-u;u=E,!(P<=G_)&&(a!==null&&(a=Math.min(E,a+P)),i!==null&&(i=Math.min(E,i+P)))},keepalive(){if(o||!l)return;let E=a===null?Ld:$_;(c===null||t.now()-c>=E)&&w()},inputAt:E=>n.find(P=>P.seq===E),sentAt:E=>r.get(E),motionOf:(E,P)=>h.get(uR(E,P)),records:()=>[...h.values()],due(){if(o)return null;if(R.failed?.()===!0)return at.Unreachable;let E=R.maxDatagramBytes?.();if(E!==void 0&&E<A)return at.Unreachable;let P=t.now();if(a!==null)return P-a>H_?at.Stall:null;if(i===null)return null;let k=R.opening?.();if(k===!0){let L=Math.max(Po,n1*(t.roundTripMs?.()??0));return P-i>L?at.Handshake:null}k===!1&&(d??(d=P));let M=k===!1?Math.max(i,d??P):i;return P-M>Po?at.Handshake:null},receive:S,close(){o||(o=!0,R.close())}}}function o1(t,e){for(let n of t.keys()){if(n>=e)return;t.delete(n)}}function i1(t){let e=cR(t);return e.ok?e.value:null}var a1=(t,e)=>t.length===e.length&&t.every((n,r)=>n===e[r]);var Hc={Udp:"udp",WebSocket:"websocket"},Zi={Off:"off",NoUdp:"no_udp",NotOffered:"not_offered"},c1=Po,u1={[Zi.Off]:"the game turned the fast channel off",[Zi.NoUdp]:"this platform has no UDP",[Zi.NotOffered]:"the room does not offer the fast channel",unreachable:"fell back, the binding could not be used or its socket failed",handshake:"fell back, no UDP snapshot within 1 s of the first datagram (UDP blocked?)",stall:"fell back, no UDP snapshot for 2 s",server:"fell back, the room closed the channel","no-webtransport":"this browser has no WebTransport","no-relay":"the room has no WebTransport relay"},l1=t=>`genex transport: udp fast@1 ${t}`,Hd=t=>`genex transport: websocket, ${t}: ${u1[t]??"unknown"}`;function lR(){let t=new Set,e=n=>t.has(n)?null:(t.add(n),n);return{observe(n){return n.joinedMs===null?null:n.asked?n.udp?n.fallback!==null?e(Hd(n.fallback)):n.url!==null?n.snapshots>0?e(l1(n.url)):null:n.joinedMs>=c1?e(Hd(Zi.NotOffered)):null:e(Hd(Zi.NoUdp)):e(Hd(Zi.Off))},reset(){t.clear()}}}var d1=19,f1=3,p1=31,h1=Object.keys(Ud()),m1=Object.keys(Vd()).filter(t=>t!=="inAck"),y1=t=>t===Ut.Entity?h1:m1,g1=["tick","keyframe"];function pR(t){let e=globalThis.process?.stderr;e?.write!==void 0?e.write(`${t}
|
|
15
|
-
`):console.info(t)}var b1=(t,e)=>{let n=setInterval(e,t);return n.unref?.(),()=>clearInterval(n)};function w1(t){if(typeof t!="object"||t===null)return null;let e=t,n=e._encoder;return typeof e._lastStamp!="number"||typeof n?.reset!="function"?null:t}function S1(t){let e=t;if(typeof e?._sampleStamp!="function")return()=>0;let n=e;return()=>{let r=n._sampleStamp().stamp;return typeof r=="number"&&Number.isInteger(r)&&r>=0&&r<=4294967295?r:0}}function hR(t){let{room:e,handle:n}=t,r={live:!1,snapshots:0,fallback:t.neverAsked,fallbacks:0,returns:0,transport:Hc.WebSocket,line:null},s=0,o=lR(),i=null,a=null,c=0,u=null,l=null,d=0,f=[],h=null,p=null,y=0,S=t.open===void 0?null:R1(e,()=>u?.client??null),w=t.open===void 0?null:(t.every??b1)(Ld,()=>{u?.client.keepalive(),R?.client.keepalive()}),x=t.random??Math.random,R=null,A=!1,E=0,P=null,k=null,M=w1(n),L=S1(n),K=()=>{if(u!==null)return Math.min(n.sentCount,d);if(l===null)return n.lastProcessed;let G=n.lastProcessed-l.wsBefore;return G>0?Math.max(l.ack,l.at+G):l.ack},W=()=>e.state.players?.get(e.sessionId)?.seqBase??0,B=()=>{!A||t.open===void 0||(P=t.now()+X_(E,x()),E+=1)},se=G=>{if(l!==null)return;k!==null&&t.now()-k>=K_&&(E=0),G===at.Server&&(E=Math.max(E,f1)),k=null,r.fallbacks+=1;let ae=u,be=u?.seqBase??W();l={at:n.sentCount,wsBefore:u?.wsBefore??n.sentCount,ack:K(),reason:G},u?.client.close(),u=null,f=[],r.live=!1,r.fallback=G,ae!==null&&M!==null&&(M._encoder.reset(),M._lastStamp=ae.stampAtBind);let Ge={last:be+n.sentCount};e.send(To.Off,Ge),S?.release(),B()},v=G=>{r.fallback===null&&(r.fallbacks+=1),r.fallback=G},$=G=>{if(R===null)return;R.client.close(),R=null,v(G);let ae={last:W()+n.sentCount};e.send(To.Off,ae),B()},Y=G=>{let ae=R;if(ae===null||l===null)return;R=null;let be=W(),Ge=l.wsBefore+(n.sentCount-l.at);d=K(),u={client:ae.client,seqBase:be,wsBefore:Ge,stampAtBind:M?._lastStamp??0},l=null,P=null,k=t.now(),r.live=!0,r.fallback=null,r.fallbacks>0&&(r.returns+=1);let Zt={last:be+n.sentCount};e.send(To.On,Zt),oe({...G,changed:ae.client.records()})},j=G=>{G.opening()&&e.ping(ae=>{y=ae})},q=G=>{if(t.open===void 0)return;if(E=Math.max(0,E-1),A=!0,R?.client.close(),R=null,l===null&&(r.fallback=null),l??(l={at:0,wsBefore:0,ack:0,reason:at.Unreachable}),f=[],!hm(G))return v(at.Unreachable),B();a=G.url;let ae={client:null,applied:0},be=mm({bind:G,tickHz:t.tickHz(),open:t.open,now:t.now,roundTripMs:()=>y,onSnapshot:Ge=>{if(u!==null&&u.client===ae.client)return oe(Ge);ae.applied+=1,ae.applied>=Y_&&Y(Ge)}});if(be===null)return v(t.open.whyNull?.(G)??at.Unreachable),B();j(be),ae.client=be,R=ae,P=null,be.keepalive()},oe=G=>{let ae=u;if(ae===null)return;r.snapshots+=1;let be=ae.client.motionOf(Ut.Seat,e.sessionId),Ge=be?.kind===Ut.Seat?be.motion.inAck:0,Zt=Math.max(0,Math.min(n.sentCount,Ge-ae.seqBase)),Sr=-1;if(Zt>d){let xr=ae.client.sentAt(ae.seqBase+Zt);xr!==void 0&&(Sr=t.now()-xr),d=Zt}e.clock.sample(G.sent,Sr),S?.write(G)},ce=G=>{let ae=G?.probe===!0;if(t.open===void 0||u!==null||l!==null&&!ae)return;if(!t.stateCurrent()){h=G;return}if(h=null,ae)return q(G);if(r.fallback=null,!hm(G))return se(at.Unreachable);a=G.url,A=typeof G.rev=="number"&&G.rev>=Fd;let be=mm({bind:G,tickHz:t.tickHz(),open:t.open,now:t.now,roundTripMs:()=>y,onSnapshot:oe});if(be===null)return se(t.open.whyNull?.(G)??at.Unreachable);j(be),u={client:be,seqBase:W(),wsBefore:n.sentCount,stampAtBind:M?._lastStamp??0},d=0,r.live=!0,k=t.now();for(let Ge of f)be.queue({...Ge,seq:u.seqBase+Ge.seq});f=[],be.flush(),be.keepalive()},ne=()=>{t.open!==void 0&&u===null&&l===null&&h===null&&t.stateCurrent()&&(p??(p=t.now()),t.now()-p>Po&&(r.fallback=at.NotOffered))},Re=()=>{i===null&&t.stateCurrent()&&e.state.players?.get(e.sessionId)!==void 0&&(i=t.now());let G=r.snapshots-c;r.transport=r.live&&G>0?Hc.Udp:Hc.WebSocket,r.returns!==s&&(s=r.returns,o.reset());let ae=r.fallback===at.NotOffered?null:r.fallback,be=o.observe({asked:!t.off,udp:t.open!==void 0,joinedMs:i===null?null:t.now()-i,url:a,snapshots:G,fallback:ae});be!==null&&(r.line=be,t.log(be))};return t.open!==void 0&&(e.onMessage(To.Bind,G=>ce(G)),e.onMessage(To.Off,()=>se(at.Server)),e.onStateChange(()=>{h!==null&&t.stateCurrent()&&ce(h)}),M!==null&&x1(e,()=>u!==null)),{status:r,ack:K,sent(G,ae,be){if(t.open===void 0||l!==null)return;let Ge=L();if(u!==null){u.client.queue({seq:u.seqBase+G,tick:ae,render:Ge,input:be});return}f.push({seq:G,tick:ae,render:Ge,input:{...be}});let Zt=Vc(t.tickHz());f.length>Zt&&(f=f.slice(-Zt))},flush(){u?.client.flush()},poll(){u?.client.framed();let G=u?.client.due()??null;G!==null&&se(G),u?.client.keepalive(),R?.client.framed();let ae=R?.client.due()??null;ae!==null&&$(ae),R?.client.keepalive(),P!==null&&t.now()>=P&&R===null&&l!==null&&(e.send(To.Again,{}),B()),ne(),Re()},motionKnown(G){return u===null||u.client.motionOf(Ut.Entity,G)!==void 0},inputAt(G){if(u===null)return;let ae=u.client.inputAt(u.seqBase+G);return ae===void 0?void 0:{...ae.input,tick:ae.tick}},dropped(){u?.client.close(),u=null,R?.client.close(),R=null,P=null,E=0,k=null,A=!1,S?.forget(),l=null,d=0,f=[],h=null,p=null,r.live=!1,r.fallback=t.neverAsked,r.transport=Hc.WebSocket,o.reset(),i=null,a=null,c=r.snapshots},dispose(){w?.(),R?.client.close(),R=null,u?.client.close(),u=null,r.live=!1,S?.dispose()}}}function x1(t,e){let n=t.connection;if(n===void 0)return;let r=n.send.bind(n);n.send=s=>{e()&&s.length>0&&(s[0]&p1)===d1||r(s)}}var _1={...Ud(),...Vd()};function R1(t,e){let n=t.serializer.decoder,r=t.state,s=new WeakMap,o=new Map,i=!1,a=n.triggerChanges,c=Object.getOwnPropertyDescriptor(n,"decode"),u=n.decode,l=x=>{let R=s.get(x),A=e();return R===void 0||A===null?void 0:A.motionOf(R.kind,R.id)},d=()=>{t.state.entities?.forEach((x,R)=>s.set(x,{kind:Ut.Entity,id:R})),t.state.players?.forEach((x,R)=>s.set(x,{kind:Ut.Seat,id:R}))},f=x=>{if(x===r)return!0;let R=s.get(x);return R===void 0?!1:(R.kind===Ut.Entity?t.state.entities?.get(R.id):t.state.players?.get(R.id))===x},h=(x,R,A,E)=>{let P=o.get(x);P===void 0&&(P=new Map,o.set(x,P));let k=P.get(R);k===void 0?P.set(R,{fast:A,ws:x[R]??_1[R]}):k.fast=A,fR(x,R,A,E)},p=()=>{d();for(let[x,R]of o){if(!f(x)){o.delete(x);continue}for(let[A,E]of R)E.ws!==E.fast&&(x[A]=E.ws)}i=!0},y=()=>{if(i){i=!1;for(let[x,R]of o)for(let[A,E]of R)E.ws!==E.fast&&(x[A]=E.fast)}},S=x=>{let R=x.field;if(R===void 0)return!1;let A=o.get(x.ref)?.get(R);return A===void 0?!1:(A.ws=x.value,!0)},w=x=>{if(e()===null)return a?.(x);d();for(let A of x){let E=A.value;if(A.field!==void 0||typeof E!="object"||E===null)continue;let P=l(E);P!==void 0&&dR(E,P,(k,M,L)=>h(k,M,L,null))}let R=x.filter(A=>!S(A));y(),a?.(R)};return Object.defineProperty(n,"triggerChanges",{configurable:!0,get:()=>w,set:x=>{a=x}}),Object.defineProperty(n,"decode",{configurable:!0,writable:!0,value:(...x)=>{e()!==null&&o.size>0&&p();try{return u.apply(n,x)}finally{y()}}}),{write(x){d();let R=[];for(let E of x.changed){let P=E.kind===Ut.Entity?t.state.entities?.get(E.id):t.state.players?.get(E.id);P!==void 0&&dR(P,E,(k,M,L)=>h(k,M,L,R))}let A=t.state.keyframe===void 0?["tick"]:g1;for(let E of A)h(r,E,x.tick,R);R.length>0&&a?.(R),t.onStateChange.invoke(t.state)},release(){d();let x=[],R=t.state.physics!==void 0;for(let[A,E]of o)if(!(!f(A)||R&&s.get(A)?.kind===Ut.Entity))for(let[P,k]of E)fR(A,P,k.ws,x);o.clear(),x.length!==0&&(a?.(x),t.onStateChange.invoke(t.state))},forget(){o.clear()},dispose(){o.clear(),Object.defineProperty(n,"triggerChanges",{configurable:!0,writable:!0,value:a}),c===void 0?Reflect.deleteProperty(n,"decode"):Object.defineProperty(n,"decode",c)}}}function dR(t,e,n){let r=e.motion;for(let s of y1(e.kind)){let o=r[s];(o===0||o===!1)&&t[s]===void 0||n(t,s,o)}}function fR(t,e,n,r){let s=t[e];s!==n&&(t[e]=n,r?.push({ref:t,refId:t[ee],op:N.REPLACE,field:e,value:n,previousValue:s}))}var mR=new Map,E1="udp:",k1=65535,A1=32,P1=["","/"],T1=t=>t.username===""&&t.password===""&&P1.includes(t.pathname)&&t.search===""&&t.hash==="";function v1(t){let e;try{e=new URL(t)}catch{return null}let n=Number(e.port),r=Number.isInteger(n)&&n>=1&&n<=k1;return e.protocol!==E1||!r||e.hostname===""||!T1(e)?null:{host:e.hostname.replace(/^\[(.*)\]$/,"$1"),port:n}}var yR=({createSocket:t,lookup:e,isIP:n})=>(r,s)=>{let o=v1(r);if(o===null)return null;let i=null,a=!1,c=!1,u=[],l=(h,p)=>{if(c)return;let y=t(p===6?"udp6":"udp4");i=y,y.on("message",S=>s(new Uint8Array(S.buffer,S.byteOffset,S.byteLength))),y.on("error",()=>{}),y.connect(o.port,h,()=>{if(a=!0,!c)for(let S of u)y.send(S);u=[]})},d=n(o.host);return d!==0?l(o.host,d):e(o.host,{all:!0,verbatim:!0},(h,p)=>{if(h!==null||p.length===0)return;let y=(mR.get(o.host)??0)%p.length;mR.set(o.host,y+1),l(p[y].address,p[y].family)}),{send(h){c||(a?i?.send(h):u=[...u,h].slice(-A1))},close(){c||(c=!0,i?.close())}}};function gR(){let t=globalThis.process?.getBuiltinModule,e=t?.("node:dgram"),n=t?.("node:dns"),r=t?.("node:net");if(!(e===void 0||n===void 0||r===void 0))return yR({createSocket:e.createSocket,lookup:n.lookup,isIP:r.isIP})}var M1=64,C1=4,O1="https:",I1=32,D1=/^[0-9a-f]+$/,N1="reliable-only";function bR(t){let e=t.wt;if(typeof e!="object"||e===null)return null;let{url:n,hashes:r}=e;if(typeof n!="string"||!Array.isArray(r)||r.length===0||r.length>C1)return null;let s=a=>typeof a=="string"&&a.length===M1&&D1.test(a);if(!r.every(s))return null;let o;try{o=new URL(n)}catch{return null}let i=o.username===""&&o.password===""&&o.search===""&&o.hash==="";return o.protocol!==O1||o.hostname===""||!i?null:{url:n,hashes:r.map(a=>lm(a))}}function B1(t){return{serverCertificateHashes:t.hashes.map(e=>({algorithm:"sha-256",value:e})),requireUnreliable:!0,allowPooling:!1,congestionControl:"low-latency"}}var L1=t=>t.reliability!==N1;function F1(t){return(t.datagrams.createWritable?.()??t.datagrams.writable)?.getWriter()??null}var Vt={Connecting:"connecting",Open:"open",Failed:"failed",Closed:"closed"};function wR(t){let e=(n,r,s)=>{let o=s===void 0?null:bR(s);if(o===null||t===void 0)return null;let i;try{i=new t(o.url,B1(o))}catch{return null}let a=Vt.Connecting,c=[],u=null,l=()=>{if(!(a===Vt.Closed||a===Vt.Failed)){a=Vt.Failed,u=null,c=[];try{i.close()}catch{}}},d=(p,y)=>{p.write(y).catch(()=>{})},f=async p=>{for(;;){let y=await p.read();if(y.done)return;a===Vt.Open&&r(y.value)}};return i.ready.then(()=>{if(a!==Vt.Connecting)return;if(!L1(i))return l();let p=F1(i);if(p===null)return l();a=Vt.Open,u=p;for(let y of c)d(p,y);c=[],f(i.datagrams.readable.getReader()).then(l,l)},()=>l()),i.closed.then(l,l),{send(p){a===Vt.Open&&u!==null?d(u,p):a===Vt.Connecting&&(c=[...c,p].slice(-I1))},close(){if(a===Vt.Closed)return;let p=a;if(a=Vt.Closed,u=null,c=[],p!==Vt.Failed)try{i.close()}catch{}},failed:()=>a===Vt.Failed,opening:()=>a===Vt.Connecting,maxDatagramBytes(){let p=a===Vt.Open?i.datagrams.maxDatagramSize:void 0;return typeof p=="number"?p:void 0}}};return e.whyNull=n=>t===void 0?at.NoWebTransport:bR(n)===null?at.NoRelay:at.Unreachable,e}var ym=t=>typeof t.WebTransport=="function"?t.WebTransport:void 0,SR=(t,e,n)=>wR(ym(globalThis))(t,e,n);SR.whyNull=t=>wR(ym(globalThis)).whyNull?.(t)??at.Unreachable;function xR(t,e=globalThis){return t===!1?{open:void 0,fallback:null}:t!==void 0?{open:t,fallback:null}:ym(e)!==void 0?{open:SR,fallback:null}:{open:void 0,fallback:e.document!==void 0||typeof e.importScripts=="function"?at.NoWebTransport:null}}var _R=100,$d=["x","y","z","yaw"],z1=.001;function RR(t,e,n,r){if(t===void 0)return[0,0,0,0];let s=t.err.map(o=>o*r);return t.k===e?s:t.shift.map((o,i)=>o+s[i]-n[i])}var U1=[1e3,2e3,4e3],ER=8,V1=250,kR=600,H1=["x","y","z","vx","vy","vz","yaw"],jd={Reconnecting:"reconnecting",Reconnected:"reconnected",Disconnect:"disconnect",...Rs},$1=new Set(Object.values(jd)),AR={protocol:`[multiplayer] the authority server refused protocol ${4} (code 426) \u2014 this game was built with a @genex-ai/multiplayer that the server no longer serves. Update the package and republish.`,notEntitled:"[multiplayer] server-authoritative rooms are not available for this game (code 402): its owner is not entitled to them. This is final; the session does not retry."},Sm=t=>t&&typeof t=="object"?t.code:void 0;function PR(t){throw fc(t)?console.error(AR.protocol):Sm(t)===_n.NOT_ENTITLED&&console.error(AR.notEntitled),t}var CR=t=>t.physicsCore!==void 0&&t.predictPhysics!==!1;function j1(){let t=typeof navigator>"u"?"":String(navigator.userAgent??"");return/Mobi|Android|iPhone|iPad/i.test(t)?Pd.mobile:Pd.desktop}async function W1(t){if(t.url)return[t.url];let e=Qw(t.regions,t.urls);if(e.length===0)throw new Error("genex multiplayer: `urls` must contain at least one authority server URL");return(await rS(e,t.probe===void 0?{}:{probe:t.probe})).map(r=>r.url)}async function q1(t,e){let n=aS(e);if("refused"in n)throw new TypeError(`genex multiplayer: this room cannot be asked for (${n.refused})`);let r=await W1(t),s=t.capacityRetryMs??U1,o={region:0,refused:0,step:0};for(;;){let i=r[o.region];try{return{room:await IR(new Nr(i),t,n),url:i,targets:r}}catch(a){if(n.method===br.JoinById){let d=cS(Sm(a),o.region,r.length);d===null&&PR(a),o={region:d,refused:0,step:0};continue}let c=tS(Sm(a));if(c===Ni.NextRegion&&o.region+1<r.length){o={region:o.region+1,refused:0,step:o.step};continue}let u=c===Ni.Capacity?nS(o,r.length,s):null;u===null&&PR(a);let l=u.attempt.waitMs;l>0&&await new Promise(d=>setTimeout(d,l)),o=u.state}}}var OR=t=>xR(t.fast??gR());function IR(t,e,n){let r=OR(e).open===void 0?[]:[ln.FAST,ln.FAST_RETURN],s={...dc(e.room,e.name,e.auth),...n.options,[jp.CAPS]:CR(e)?[ln.PHYSICS,ln.PHYSICS_PREDICT,ln.INPUT_REPEAT,ln.LIFTS,ln.INPUT_TICK,...r]:[ln.PHYSICS,ln.INPUT_REPEAT,ln.LIFTS,ln.INPUT_TICK,...r],[jp.SDK]:E0,protocol:4};return n.method===br.JoinById?t.joinById(n.roomId,s):n.method===br.Create?t.create(co.AUTHORITY,s):t.joinOrCreate(co.AUTHORITY,s)}function Qi(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e.name,r=bc(n);if(r===void 0)return null;let s=Di(n,e.params);return{name:n,definition:r,params:s}}function gm(t,e){let{definition:n,params:r}=t,s=[...n.fields,...n.reads],o=n.fields;return{fields:s,step:(i,a,c,u)=>{let l=n.step(i,a,c,r,e,u);for(let d of o)i[d]=l[d]}}}var bm=t=>t!==null&&t.definition.world?t.params.world??null:null,de=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e;function G1(t){if(typeof t.inMoveX=="number")return{moveX:de(t.inMoveX,0),moveY:de(t.inMoveY,0),moveZ:de(t.inMoveZ,0),yaw:de(t.inYaw,0),pitch:de(t.inPitch,0),buttons:de(t.inButtons,0)}}var wm={body:!1,qx:0,qy:0,qz:0,qw:1,sleep:!1},TR=new Map,vR=2*Math.PI,vo=t=>t-vR*Math.floor((t+Math.PI)/vR),AH=[mn.Predicted,mn.Separate,mn.Timeline],Y1=mn.Predicted,ea=t=>{let e=t;return typeof e.local=="object"&&typeof e.error=="object"&&typeof e.prev=="object"&&typeof e.renderAlpha=="function"?e:null};async function DR(t){let e=await q1(t,t.matchKey===void 0?{}:{matchKey:t.matchKey});return K1(NR(Ss(e.room),t,e.url),t,e,!1)}function K1(t,e,n,r){if(e.rejoin===!1)return t;let s=n.targets.filter(o=>o!==n.url);return pS(t,{closed:r,targets:[n.url,...s],join:async(o,i,a)=>{let c=await IR(new Nr(o),e,X1(i,a)),u=NR(Ss(c),e,o);return await pc(c,fn.firstStateTimeoutMs),u}})}function X1(t,e){return t===Li.Room?{method:br.JoinById,roomId:e.roomId,options:{}}:t===Li.Successor?{method:br.JoinOrCreate,options:fS({lostRoomId:e.roomId,matchKey:e.matchKey,closed:e.closed})}:{method:br.JoinOrCreate,options:e.matchKey===""?{}:{matchKey:e.matchKey}}}function NR(t,e,n){let r=t.state,s=()=>r.entities??TR,o=()=>r.players??TR,i=e.renderDelayMs??ws.RENDER_DELAY_MS,a=t.input({type:S_,mode:"reliable",renderDelay:i}),c=OR(e),u=hR({room:t,handle:a,open:c.open,neverAsked:c.fallback,off:e.fast===!1,log:e.fastLog??pR,now:e.fastClock??(()=>performance.now()),tickHz:()=>J(),stateCurrent:()=>!Kn}),l=null,d=yt.On,f=()=>{let g=r.preset??"";return g!==l&&(l=g,d=E_(g)),d},h=()=>P_(u.ack(),o().get(t.sessionId)?.inRep,a.sentCount,f()),p=g=>a.at(g)??u.inputAt(g),y=M_(),S=()=>{let g=T_(u.ack(),o().get(t.sessionId)?.inRep,f()),_=a.sentCount,T=g<_&&u.inputAt(g+1)!==void 0;return C_(y,g,_,a.replayBufferSize,T)},w=new Map,x=new Proxy(a,{get(g,_){if(_==="lastProcessed")return S();if(_==="pendingCount")return a.sentCount-u.ack();if(_==="at")return p;let T=Reflect.get(g,_,g);if(typeof T!="function")return T;let z=w.get(_);return z===void 0&&(z=T.bind(g),w.set(_,z)),z}}),R=ao.get(t,{mode:"lerp",delay:i}),A={mode:"lerp",fields:["x","y","z"]},E={mode:"lerp",fields:["yaw"],angle:!0};R.attachAll("entities",A),R.attachAll("entities",E),R.attachAll("entities",{mode:"lerp",fields:["pitch"]}),R.attachAll("entities",{mode:"lerp",fields:["duck"]});let P={moveX:0,moveY:0,moveZ:0,yaw:0,pitch:0,buttons:0},k={inputsSent:0,inputsDropped:0,reconciles:0,visibleCorrections:0,correctionBuckets:Od.map(()=>0).concat(0),peakCorrection:0,lastCorrection:0,peakStateCorrection:0,reseeds:0,bodyStates:0,bodySnaps:0,peakBodyCorrection:0,projectilesPredicted:0,projectilesConfirmed:0,projectilesRejected:0,lastProjectileLeadMs:0},M=new Map,L=(g,..._)=>{for(let T of M.get(g)??[])T(..._)},K=!0,W=!1,B=null,se=!0,v=()=>{B?.predicted?.reconciler.dispose(),B=null},$=e.world===void 0?yc:mo(e.world),Y="no_entity",j="",q=typeof e.physics=="string"?e.physics:"",oe="",ce=()=>{if(e.predict===!1)return{prediction:null,reason:"off"};if(e.predict)return{prediction:e.predict,reason:""};let g=Qi(r.preset);if(g===null)return{prediction:null,reason:"no_preset"};let _=bm(g);if(_!==null&&_!==$.hash){let T=`${_}/${$.hash}`;return j!==T&&(j=T,console.warn(`[multiplayer] the room's ${g.name} world (hash ${_}) is not this client's (hash ${$.hash}): your own entity is drawn from the server without prediction. Pass the room module's world to session.setWorld().`)),{prediction:null,reason:"world_mismatch"}}return{prediction:gm(g,$),reason:""}},ne=()=>{let g=[];for(let[_,T]of s())_===B?.id||T.owner===""||$r(T)||r.bodies?.has(_)===!0||!o().has(T.owner)||g.push({id:_,x:T.x,y:T.y,z:T.z,vx:T.vx,vy:T.vy,vz:T.vz,yaw:T.yaw,spin:de(T.spin,0)});return g},Re=null,G=()=>{if(e.contacts!==void 0)return null;let g=r.preset??"";return(Re===null||Re.text!==g||Re.hash!==$.hash)&&(Re={text:g,hash:$.hash,contacts:t_(g,$)}),Re.contacts},ae=()=>e.contacts!==void 0||G()!==null,be=e.contacts??((g,_)=>G()?.rule(g,_)),Ge=e.contactPass??(e.contacts===void 0?g=>G()?.pass(g):void 0),Zt=new Td(be,()=>Ms(ne())),Sr=()=>e.seatDrawing??G()?.policy.drawing??Y1,xr=e.seatDrawing===void 0||e.seatDrawing===mn.Predicted?Wd(be):null,vs=()=>ae()?xr:null,Co=()=>Sr()===mn.Predicted?vs():null;function Ms(g){return G()===null?g:g.map(_=>({..._,flags:de(s().get(_.id)?.flags,0)}))}let na=(g,_,T=null)=>{if(B===null||!ae())return null;let z={..._,id:B.id,...G()===null?{}:{flags:de(B.entity.flags,0)}},H=vs(),U=null;H!==null?U=H.apply(g,h(),r.tick??0,z,J(),T):Zt.apply(g,h(),z,J());for(let re of Eo)typeof z[re]=="number"&&(_[re]=z[re]);return U};function Wd(g){let _=null,T=()=>{let H=r.preset??"";if(_!==null&&_.text===H&&_.hash===$.hash)return _;let U=Qi(H),re=bm(U),Z=U!==null&&(re===null||re===$.hash)?gm(U,$):null;return _={text:H,hash:$.hash,fields:U===null?[]:[...U.definition.fields,...U.definition.reads],step:Z===null?void 0:(ye,ue,he,bt)=>Z.step(ye,Xi({...ue}),he,bt)},_},z=()=>{let{fields:H}=T(),U=[];for(let[re,te]of s()){if(re===B?.id||te.owner===""||$r(te)||r.bodies?.has(re)===!0)continue;let Z=o().get(te.owner);if(Z===void 0)continue;let ye=te,ue={x:te.x,y:te.y,z:te.z,vx:te.vx,vy:te.vy,vz:te.vz,yaw:te.yaw,spin:de(te.spin,0)};for(let he of H)ue[he]=de(ye[he],he==="cap"?1:0);G()!==null&&(ue.flags=de(te.flags,0)),U.push({id:re,epoch:te.epoch,body:ue,input:G1(Z)})}return U};return new Dd({rule:g,pass:Ge,others:z,step:()=>T().step,seatRule:e.seatRule,lifts:()=>{let H=yn();return H===null?null:{lifts:H,starts:ct(),cache:qd}},remote:()=>{let H=Ls();return{predict:H?.remotePredict??Xt.HOLD,decayMs:H?.remoteDecayMs??wr.DEFAULT_REMOTE_DECAY_MS}},maxAheadMs:()=>(Ls()?.leadMs??wr.DEFAULT_LEAD_MS)+p_})}let kn=null,yn=()=>{let g=r.preset??"",_=G();if(kn===null||kn.text!==g||kn.hash!==$.hash||kn.heads!==_){let T=_!==null&&QS(_.policy)?{policy:_.policy,env:_.env}:void 0;kn={text:g,hash:$.hash,heads:_,lifts:wx(g,$,T,J())}}return kn.lifts},qn={text:void 0,starts:void 0},ct=()=>{let g=r.lifts;return qn.text!==g&&(qn={text:g,starts:Sx(g)}),qn.starts},Gn=new Vi,qd=new Vi,Wc=g=>{let _=vs();return ne().map(T=>{let z=_?.poseAt(T.id,g-1),H=de(s().get(T.id)?.flags,0),U=de(s().get(T.id)?.duck,0);return z===void 0?{...T,duck:U,flags:H}:{id:T.id,x:z.x,y:z.y,z:z.z,vx:z.vx,vy:z.vy,vz:z.vz,yaw:z.yaw,duck:U,flags:H}})},qc=["x","y","z"],Qt=["vx","vy","vz"],An=(g,_,T,z,H)=>{if(B===null)return null;let U=z,re={id:B.id,x:U.x??0,y:U.y??0,z:U.z??0,vx:U.vx??0,vy:U.vy??0,vz:U.vz??0,yaw:U.yaw??0,duck:U.duck??0,flags:de(B.entity.flags,0)},Z=[...g.heads===void 0?[]:Wc(_),re].sort((ue,he)=>ue.id<he.id?-1:ue.id>he.id?1:0),ye=vc(g,Z,T,ct(),H,Gn);for(let ue of qc)U[ue]=re[ue];return g.vehicle&&(U.yaw=re.yaw),{t:ye,mine:re}},gt=Number.NaN,Kr=null,ra=null,Xr=(g,_,T,z,H,U)=>{let re=Gi(r.tick??0,h(),_),te=yn(),Z=te===null?null:An(te,_,U??re,T,H);e.seatRule?.(T,re,_),g(T,Xi(z),H,Z===null?void 0:Mc(Z.t,Z.mine.id));let ye=Z===null?-1:Z.t.seats.indexOf(Z.mine),ue=Z===null?null:Z.t.report.on[ye]??null,he=na(_,T,ue);if(te===null||Z===null)return;he!==null&&_x(te,Z.t,ye,he);let bt=T;Kr=ue;for(let tn of[...qc,...Qt])Z.mine[tn]=bt[tn]??0;Cc(te,Z.t,ct());for(let tn of Qt)bt[tn]=Z.mine[tn]},sa=new Vi,oa=(g,_,T,z,H)=>{let U=yn();U===null||U.policy.platforms.length===0?g(_,T,z):Ex(U,ct(),sa,(re,te)=>g(re,T,z,te),_,H,z)},Cs=g=>{let{prediction:_,reason:T}=ce();if(Y=T,!_)return null;let z=_.fields??H1;return{reconciler:R.reconciler(g,{input:x,fields:z,step:(U,re,te)=>{(U.isReplay||Number.isNaN(gt))&&(gt=Gi(r.tick??0,h(),U.tick)-U.tick),Kr=null,Xr(_.step,U.tick,re,te,U.dt,U.tick+gt),ra=Kr}}),fields:z,step:_.step}},Os=()=>{let g=B?.predicted;if(!B||!g)return null;let _=B.entity,T={};for(let U of g.fields)T[U]=de(_[U],0);let z=a.stepSeconds??g.reconciler.stepMs/1e3,H=new Map;for(let U=h()+1;U<=a.sentCount;U++){let re=p(U);re!==void 0&&(Xr(g.step,U,T,re,z),H.set(U,{p:[T.x??0,T.y??0,T.z??0],v:[T.vx??0,T.vy??0,T.vz??0]}))}return H},Is=g=>{g.predicted&&(k.reseeds++,Oo(g))},Oo=g=>{g.predicted?.reconciler.dispose();let _=Cs(g.entity);if(g.predicted=_,!_)return;let T=_.reconciler.state,z=a.stepSeconds??_.reconciler.stepMs/1e3;gt=Gi(r.tick??0,h(),0);for(let H=h()+1;H<=a.sentCount;H++){let U=p(H);U!==void 0&&Xr(_.step,H,T,U,z)}g.reseeded=!0},ia=(g,_)=>_.owner===t.sessionId&&!$r(_)&&r.bodies?.has(g)!==!0,Jr=g=>s().get(g.id)===g.entity&&ia(g.id,g.entity),Zr=()=>{if(B&&Jr(B)){B.entity.epoch!==B.epoch&&(B.epoch=B.entity.epoch,Is(B));return}if(!(!B&&!se)){v(),se=!1,Y="no_entity";for(let[g,_]of s())if(ia(g,_)){B={id:g,entity:_,epoch:_.epoch,predicted:Cs(_),reseeded:!1};return}}},tt=g=>{let _=g.reconciler.state;return g.fields.map(T=>_[T]??0)},Io=(g,_,T)=>{if(g.reconciler.reconcileSeq===T)return;let{place:z,state:H}=r_(g.fields,_,tt(g));k.reconciles++,k.lastCorrection=z,k.peakCorrection=Math.max(k.peakCorrection,z),k.peakStateCorrection=Math.max(k.peakStateCorrection,H);let U=Om();s_(z,U)&&(k.visibleCorrections++,k.correctionBuckets[o_(z,U)]+=1)},Gc=g=>{if(!g.fields.includes("yaw"))return null;let _=ea(g.reconciler),T=_?.local.yaw;return _&&typeof T=="number"?{local:T,error:_.error.yaw??0}:null},Yc=(g,_,T)=>{if(T===null||g.reconciler.reconcileSeq===_)return;let z=ea(g.reconciler),H=z?.local.yaw,U=z?.error.yaw;if(!z||typeof H!="number"||typeof U!="number")return;let re=T.local+T.error-H;(re<-Math.PI||re>=Math.PI)&&(z.error.yaw=vo(re)*(U/re))},Kc=g=>{let _=ea(g.reconciler);if(_===null||Number.isNaN(gt))return null;let T=z=>Object.fromEntries($d.map(H=>[H,de(z[H],0)]));return{offset:gt,local:T(_.local),error:T(_.error),prev:T(_.prev)}},Xc=(g,_,T,z)=>{if(z===null||g.reconciler.reconcileSeq===_||z.offset===gt)return T;let H=yn(),U=ea(g.reconciler);if(H===null||H.policy.platforms.length===0||U===null)return T;let re=ct(),te=a.sentCount+z.offset+1,Z=a.sentCount+gt+1,ye=We=>({x:We.x??0,y:We.y??0,z:We.z??0,yaw:We.yaw??0,duck:de(U.local.duck,0)}),ue=Oc(H,ye(z.local),te,re);if(ue<0||Oc(H,ye(U.local),Z,re)!==ue)return T;let he=(We,gn,Zn)=>{let Pn=Uh(H.policy,ue,ye(We),gn,Zn,re);return{...Pn,yaw:H.vehicle?Pn.yaw:We.yaw??0}},bt=Object.fromEntries($d.map(We=>[We,(z.local[We]??0)+(z.error[We]??0)])),tn=he(bt,te,Z),Et=he(z.prev,te-1,Z-1),zo=he(z.local,te,Z);for(let We of $d){if(typeof U.local[We]!="number")continue;let gn=de(U.local[We],0),Zn=(bt[We]??0)-gn,Pn=Zn===0?0:(U.error[We]??0)/Zn;U.error[We]=(tn[We]-gn)*Pn,U.prev[We]!==void 0&&(U.prev[We]=Et[We])}return g.fields.map((We,gn)=>$d.includes(We)?zo[We]:T[gn]??0)},Ue=g=>{let _=B?.entity===g?B.predicted:null;if(!_||!_.fields.includes("yaw"))return;let T=ea(_.reconciler),z=T?.local.yaw;if(!T||typeof z!="number")return;let H=z+(T.error.yaw??0),U=T.prev.yaw??H;return U+vo(H-U)*T.renderAlpha()},Qr=O_(),Ds=Number.NaN,Do=g=>{let _=a.stepMs??0,T=o().get(t.sessionId);I_(Qr,T?.inStarve,T?.inBuf,_,f());let z=Number.isNaN(Ds)?0:g-Ds;return Ds=g,N_(Qr,z,_)},Yn,_r=g=>{let _=a.stepMs;if(!_)return 0;if(Yn===void 0)return Yn=g,0;let T=Math.floor((g-Yn)/_);return T>ER?(Yn=g,ER):(Yn+=T*_,T)},No=()=>Gi(r.tick??0,h(),0),Ns=null,Bs=g=>{if(!K)return k.inputsDropped+=g,0;let _=0,T=i_((Ns??No())+a.sentCount+1);for(let z=0;z<g;z++){let H=Xi({...P});Object.assign(a.data,H),a.data.tick=T;let U=a.send();if(U===0){k.inputsDropped++;continue}_++,u.sent(U,T,H)}return u.flush(),k.inputsSent+=_,_},Nt=t.clock,Jc=()=>Nt.lastServerTime()>0?Nt.lastServerTime():performance.now(),Rt=()=>Nt.lastServerTime()>0?Nt.serverNow()-i-Nt.smoothedRtt()/2:performance.now()-i,Bo=new WeakMap,Lo=g=>({x:g.x,y:g.y,z:g.z,yaw:g.yaw,pitch:de(g.pitch,0),duck:de(g.duck,0)}),Zc=g=>{let _=Jc(),T=Bo.get(g);if(T===void 0){Bo.set(g,{at:_,epoch:g.epoch,pose:Lo(g),respawns:[]});return}T.epoch!==g.epoch&&g.owner!==t.sessionId&&T.respawns.push({from:T.at,at:_,epoch:T.epoch,pose:T.pose}),T.at=_,T.epoch=g.epoch,T.pose=Lo(g)},Qc=g=>{let _=Bo.get(g)?.respawns;if(_===void 0||_.length===0)return;let T=Rt();for(;_.length>0&&T>=_[0].at;)_.shift();return _[0]},es=new Bd,ts=new Set,aa={text:"",k:1},eu=g=>(aa.text!==g&&(aa={text:g,k:Nc(g)?.keyframeTicks??1}),aa.k),Fo={text:"\0",desc:null},Ls=()=>{let g=r.physDesc??"";return Fo.text!==g&&(Fo={text:g,desc:Nc(g)}),Fo.desc},b=()=>e.remoteSamples!=="patch"&&(r.physDesc??"")!=="",C=()=>{if(ts.size===0)return;let g=r.tick??0;if(b()&&g===(r.keyframe??-1)){let T=ad(g,we(),J()),z=1e3/J()*eu(r.physDesc??"");for(let H of ts)es.push(H,T,Lo(H),z,H.epoch)}ts.clear()},V=Ja(t);V(r).entities.onAdd(g=>{se=!0,Zc(g),ts.add(g),V(g).onChange(()=>{Zc(g),ts.add(g)})}),t.onStateChange(C),V(r).entities.onRemove(()=>{se=!0});let J=()=>a.stepMs?Math.round(1e3/a.stepMs):ws.TICK_HZ,we=()=>r.tickOrigin??0,fe=()=>Th(Nt.serverNow(),we(),J()),ve=g=>({x:g.x,y:g.y,z:g.z,vx:g.vx,vy:g.vy,vz:g.vz,g:g.g??0,t0:g.t0??0}),ie=g=>ad(g.t0??0,we(),J()),De=R.spawns("entities",{owned:g=>$r(g)&&g.src===t.sessionId,correlate:(g,_)=>s().get(g.id)!==_?!1:(ut.delete(g),k.projectilesConfirmed++,k.lastProjectileLeadMs=ie(_)-g.at,!0),spawnTime:ie,ttl:g=>{let _=Math.max(2*g,kR);if(!K)return _;let T=performance.now(),z=T-nt.endedAt<_+nt.ms?nt.ms:0;return _+Math.max(T-Fe,z)},onReject:g=>{ut.delete(g),k.projectilesRejected++}}),Fe=performance.now(),nt={ms:0,endedAt:0},ut=new Map,Qe=()=>{if(ut.size===0)return;let g=u.ack();for(let[_,T]of ut)_.epoch!==a.epoch||_.seq>g||s().has(_.id)||(ut.delete(_),T(),k.projectilesRejected++)},Kn=!1,Xn=()=>{Kn=!1;for(let[g,_]of ut)g.epoch!==a.epoch&&(ut.delete(g),_(),k.projectilesRejected++)};t.onStateChange(()=>{let g=performance.now();(g-Fe>nt.ms||g-nt.endedAt>kR+nt.ms)&&(nt={ms:g-Fe,endedAt:g}),Fe=g,Kn&&Xn(),Qe()});let rt=new Map,Rr=()=>{let g=de(r.lengthUnit,0);return{tickHz:J(),tickOrigin:we(),lengthUnit:g>0?g:1}},Gd=g=>({x:g.x,y:g.y,z:g.z,qx:de(g.qx,0),qy:de(g.qy,0),qz:de(g.qz,0),qw:de(g.qw,0),lvx:de(g.lvx,0),lvy:de(g.lvy,0),lvz:de(g.lvz,0),avx:de(g.avx,0),avy:de(g.avy,0),avz:de(g.avz,0),sleep:g.sleep===!0,epoch:g.epoch}),tu=()=>{let g=r.bodies;for(let[H,U]of rt)g?.get(H)!==U.descriptor&&rt.delete(H);if(g===void 0||g.size===0)return;let _=Nt.serverNow(),T=Rr(),z=r.tick??0;for(let[H,U]of g){let re=s().get(H);if(re===void 0)continue;let te=rt.get(H),Z=_S(Gd(re),z);if(te!==void 0&&kS(te.last,Z)){te.entity=re;continue}let{drawing:ye,snap:ue}=ES(te?.drawing??null,Z,_,T);k.bodyStates++,ue!==null?k.bodySnaps++:k.peakBodyCorrection=Math.max(k.peakBodyCorrection,Math.hypot(...ye.dp)),rt.set(H,{descriptor:U,entity:re,last:Z,drawing:ye,handoff:te?.handoff??new _d})}};t.onStateChange(tu);let Jn=w_({enabled:CR(e),loadCore:e.physicsCore,state:r,sessionId:t.sessionId,staticWorld:()=>$,tickHz:J,sent:()=>a.sentCount,acked:()=>h(),ownId:()=>B?.id,ownPath:Os,bodyRule:e.bodyRule,headSlide:()=>{let g=G()?.policy;return g?.headFriction===go.Slide?g.propSlide:null},kinematicRule:e.kinematicRule,lifts:()=>{let g=yn();return g===null||g.policy.platforms.length===0?null:{policy:g.policy,starts:ct()}},seatRule:e.seatRule,budgetMs:Hx(e.physicsBudgetMs,j1()),contactPass:g=>G()?.pass(g),motionKnown:g=>u.motionKnown(g),...typeof e.physicsClock=="function"?{clock:e.physicsClock}:{},...xr===null?{}:{seatPose:(g,_)=>{let T=vs()?.poseAt(g,_);return T===void 0?void 0:{key:g,x:T.x,y:T.y,z:T.z,vx:T.vx,vy:T.vy,vz:T.vz}}},remoteStep:()=>{let g=Qi(r.preset??"");if(g===null)return;let{step:_}=gm(g,$);return(T,z,H,U)=>oa(_,T,Xi({...z}),H,U)}});t.onStateChange(()=>Jn.onState(Nt.serverNow()));let UR=()=>{let g=B?.predicted?.reconciler.state;return g===void 0?void 0:{p:[g.x??0,g.y??0,g.z??0],v:[g.vx??0,g.vy??0,g.vz??0]}},Am=g=>(!rt.has(g)&&r.bodies?.has(g)===!0&&tu(),rt.get(g)),Yd=(g,_)=>{let T=Rr(),z=Nt.serverNow(),H=Jn.draw(g,z),U=_.entity,re=_.descriptor?.kind,te=H===null&&e.kinematicRule!==void 0?Vx(e.kinematicRule,g,z,T):null,Z=_.handoff.draw(H??te??Ah(_.drawing,z,T),H!==null,U.epoch,z,kd(re),T.lengthUnit),[ye,ue,he]=_.last.lv;return{id:g,kind:U.kind,owner:U.owner,x:Z.p[0],y:Z.p[1],z:Z.p[2],yaw:vo(U.yaw),vx:ye*T.lengthUnit,vy:ue*T.lengthUnit,vz:he*T.lengthUnit,hp:U.hp,flags:U.flags,epoch:U.epoch,data:U.data,t0:0,g:0,src:"",pitch:0,duck:0,mstate:0,cap:1,spin:0,fuel:0,body:!0,qx:Z.q[0],qy:Z.q[1],qz:Z.q[2],qw:Z.q[3],sleep:_.last.sleep,predicted:H!==null}},nu={epoch:-1,seq:0,n:0},Fs=g=>typeof g=="number"&&Number.isFinite(g)?Ce(Math.fround(g)):0,Pm=g=>{let _=Ph(g.launch,fe(),J());return{id:g.id,kind:g.kind,owner:"",..._,yaw:0,hp:0,flags:0,epoch:0,data:"",t0:g.launch.t0,g:g.launch.g,src:t.sessionId,pitch:0,duck:0,mstate:0,cap:1,spin:0,fuel:0,...wm}},Tm=()=>{let g=new Map;for(let _ of De.entries())_.state==="pending"&&_.local&&g.set(_.local.id,_.local);return g};t.onDrop(g=>{u.dropped(),K=!1,Kn=!0,L(jd.Reconnecting,{code:g})}),t.onReconnect(()=>{if(W){t.leave(!0).catch(()=>{});return}(async()=>(await pc(t,fn.firstStateTimeoutMs),!W&&(Kn&&Xn(),B?.predicted&&(B.predicted.reconciler.reset(),k.reseeds++),Yn=void 0,K=!0,L(jd.Reconnected))))()});let vm=()=>{W=!0,K=!1,u.dispose(),v(),R.dispose(),Jn.dispose()};t.onLeave((g,_)=>{W||(vm(),L(jd.Disconnect,g,k0(_)))}),t.onMessage("*",(g,_)=>{typeof g=="string"&&(e.onEvent?.(g,_),$1.has(g)||L(g,_))});let VR=g=>{if(!B?.reseeded||B.entity!==g||!B.predicted)return;let _=B.predicted.reconciler.state;return{x:_.x??g.x,y:_.y??g.y,z:_.z??g.z,yaw:_.yaw??g.yaw,pitch:_.pitch??de(g.pitch,0),duck:_.duck??de(g.duck,0),epoch:g.epoch}},HR=()=>{if(B===null||B.predicted===null)return null;let g=Fm(B.entity);return{id:B.id,x:g.x,y:g.y,z:g.z,vx:0,vy:0,vz:0,yaw:g.yaw}},Mm=g=>{let T=B?.reseeded===!0&&B.predicted===g?1:ea(g.reconciler)?.renderAlpha()??1;return Math.max(0,a.sentCount-h()-1+T)},ru=new Map,en=0,Cm=()=>ae()&&Sr()!==mn.Timeline,Kd=g=>B?.entity!==g&&g.owner!==""&&!$r(g)&&o().has(g.owner),$R=(g,_)=>{let T=ru.get(g);return T!==void 0&&T.lives===_&&en-T.at<=V1?T:void 0},su=new Map,Xd,ou=new Map,Jd=Number.NaN,ca={tick:Number.NaN,leadMs:Number.NaN},Om=()=>{let g=de(r.lengthUnit,0);return g>0?g:hS[Qi(r.preset??"")?.name??""]??1},jR=()=>{let g=Co(),_=g?.current??null;if(g===null||_===null||B===null||B.predicted===null)return ca={tick:Number.NaN,leadMs:Number.NaN},null;let T=h(),z=Mm(B.predicted),H=D_(T,z,Qr,a.stepMs??0,en);Xd=h_(Xd,H.raw,H.at,J());let U=Xd.seq,re=T+z,te=Number.isNaN(Jd)?0:en-Jd;Jd=en;let Z=_.stateTick+(U-_.ack);ca={tick:Z,leadMs:ad(Z+1,we(),J())-Nt.serverNow()};let ye=_t.SEAT_SNAP_METRES*Om(),ue=new Map;for(let[he,bt]of s()){if(!Kd(bt))continue;let tn=g.motionAt(he,U);if(tn===void 0)continue;let Et=tn.pose,zo=su.get(he),We=zo?.pass!=null&&zo.pass!==_?g.changeAt(he,U,zo.pass):void 0,gn=g_(zo,_,bt.epoch,We,tn,te,g.touchingAt(he,U),ye,g.stateRate(he));su.set(he,gn);let Zn={x:Et.x+gn.dx,y:Et.y+gn.dy,z:Et.z+gn.dz,yaw:Et.yaw+gn.dyaw,pitch:de(bt.pitch,0),duck:de(bt.duck,0),epoch:bt.epoch},Pn=m_(ou.get(he),g.touchAheadMs(he,re)!==void 0,te);ou.set(he,Pn);let ua=Pn>0?g.motionAt(he,re)?.pose:void 0;ua!==void 0&&(Zn.x+=(ua.x-Et.x)*Pn,Zn.y+=(ua.y-Et.y)*Pn,Zn.z+=(ua.z-Et.z)*Pn,Zn.yaw+=vo(ua.yaw-Et.yaw)*Pn),ue.set(he,{pose:Zn,at:Et})}for(let he of[...su.keys()])ue.has(he)||su.delete(he);for(let he of[...ou.keys()])ue.has(he)||ou.delete(he);return ue},WR=g=>{if(!ae())return;let _=e.contacts===void 0?G():null;return _===null||g===null?be:_.drawRule(g.id)},qR=()=>{let g=new Map,_=Cm()?HR():null,T=WR(_);if(T===void 0||_===null||B===null||B.predicted===null)return ru.clear(),ca={tick:Number.NaN,leadMs:Number.NaN},g;let z=Co()===null?null:jR(),H=[];for(let[Z,ye]of s()){if(!Kd(ye))continue;let ue=z?.get(Z)?.pose??au(ye);g.set(Z,ue),H.push({id:Z,x:ue.x,y:ue.y,z:ue.z,vx:0,vy:0,vz:0,yaw:ue.yaw,...G()===null?{}:{flags:de(ye.flags,0)}})}let U=new Map;for(let[Z,ye]of g)U.set(Z,`${B.entity.epoch}/${ye.epoch}`);for(let[Z,ye]of g)for(let[ue,he]of g)Z<ue&&U.set(Fc(Z,ue),`${ye.epoch}/${he.epoch}`);let re=new Map;for(let[Z,ye]of U){let ue=$R(Z,ye);ue!==void 0&&re.set(Z,ue)}let te=e_(T,_,H,re,en);ru.clear();for(let[Z,ye]of te.sides)ru.set(Z,{...ye,lives:U.get(Z)??""});for(let[Z,ye]of te.drawn){let ue=g.get(Z);if(ue===void 0)continue;let he=z?.get(Z)?.at,bt=he===void 0?void 0:Math.hypot(ye.x-he.x,ye.y-he.y,ye.z-he.z);g.set(Z,{...ue,x:ye.x,y:ye.y,z:ye.z,...bt===void 0?{}:{correction:bt}})}return GR(g,_),g},iu=new Map,GR=(g,_)=>{let T=B?.entity;for(let[z,H]of g){let U=s().get(z),re=z===ra&&T!==void 0&&U!==void 0,te=re?[_.x-(T.x-U.x)-H.x,_.y-(T.y-U.y)-H.y,_.z-(T.z-U.z)-H.z,0]:[0,0,0,0],Z=iu.get(z),ye=Z===void 0?0:Math.exp(-Math.max(0,en-Z.at)/_R),ue=RR(Z,re?1:0,te,ye);iu.set(z,{k:re?1:0,shift:te,err:ue,at:en}),!(!re&&ue.every(he=>Math.abs(he)<z1))&&g.set(z,{...H,x:H.x+te[0]+ue[0],y:H.y+te[1]+ue[1],z:H.z+te[2]+ue[2]})}for(let z of[...iu.keys()])g.has(z)||iu.delete(z)},Zd=0;t.onStateChange(()=>{Zd++});let Im,Dm=()=>{let g=Im;if(g!==void 0&&g.at===en&&g.states===Zd)return g.seats;let _=qR();return Im={at:en,states:Zd,seats:_},_},Qd=null,Nm=()=>B?.predicted?(Number.isNaN(gt)?(r.tick??0)-h():gt)+h()+Mm(B.predicted)+1:Bm(),Bm=()=>(Rt()-we())*J()/1e3,Lm=new WeakMap,YR=(g,_)=>{let T=yn();if(T===null||T.policy.platforms.length===0||!B?.predicted)return _;let z=Bm(),H=Nm(),U=ct(),re=(r.tick??0)+1,te=Oc(T,{x:g.x,y:g.y,z:g.z,duck:de(g.duck,0)},re,U),Z=te<0?_:{..._,...Uh(T.policy,te,_,z,H,U)};te>=0&&(Z.z=Vh(T.policy,te,H,U)+(g.z-Vh(T.policy,te,re,U)));let ye=[Z.x-_.x,Z.y-_.y,Z.z-_.z,Z.yaw-_.yaw],ue=Lm.get(g),he=en,bt=ue===void 0?0:Math.max(0,he-ue.at),tn=Math.exp(-bt/_R),Et=RR(ue,te,ye,tn);return Lm.set(g,{k:te,shift:ye,err:Et,at:he}),{..._,x:Z.x+Et[0],y:Z.y+Et[1],z:Z.z+Et[2],yaw:Z.yaw+Et[3]}},ef=null,KR=g=>{let _=au(g.entity);Oo(g);let T=au(g.entity);ef={dx:_.x-T.x,dy:_.y-T.y,dz:_.z-T.z,at:en}},au=g=>{let _=XR(g),T=B?.entity===g?ef:null;if(T===null)return _;let z=y_(T,en-T.at);return z.done?(ef=null,_):{..._,x:_.x+z.dx,y:_.y+z.dy,z:_.z+z.dz}},XR=g=>{let _=VR(g);if(_)return _;let T=Qc(g),z=R.value(g,"yaw"),U=(B?.entity!==g&&b()?es.at(g,Rt()):void 0)??{x:R.value(g,"x"),y:R.value(g,"y"),z:R.value(g,"z"),yaw:Ue(g)??z,pitch:de(R.value(g,"pitch"),de(g.pitch,0)),duck:de(R.value(g,"duck"),de(g.duck,0))};return T===void 0?{...B?.entity===g?U:YR(g,U),epoch:g.epoch}:{...Rt()>T.from?T.pose:U,epoch:T.epoch}},Fm=(g,_,T)=>(_!==void 0&&Cm()&&Kd(g)?(T??Dm()).get(_):void 0)??au(g),JR=(g,_)=>{let T=De.entryFor(_),z=T?.local!==void 0&&_.src===t.sessionId?T.leadMs*J()/1e3:0,H=Ph(ve(_),fe()+z,J());return{id:g,kind:_.kind,owner:_.owner,...H,yaw:vo(_.yaw),hp:_.hp,flags:_.flags,epoch:_.epoch,data:_.data,t0:_.t0,g:_.g,src:_.src,pitch:de(_.pitch,0),duck:de(_.duck,0),mstate:de(_.mstate,0),cap:de(_.cap,1),spin:de(_.spin,0),fuel:de(_.fuel,0),...wm}},tf={text:"",limit:Math.PI},ZR=()=>{let g=r.preset??"";if(tf.text!==g){let _=Qi(g)?.params.pitchLimit;tf={text:g,limit:_===void 0?Math.PI:Math.fround(_)}}return tf.limit},QR=g=>{let _=ZR(),T=vo(g);return T<-_?-_:T>_?_:T},nf=(g,_,T)=>B?.entity===g&&B.predicted?.fields.includes(_)?de(B.predicted.reconciler.state[_],T):de(g[_],T),rf=(g,_,T)=>{let z=Am(g);if(z!==void 0)return Yd(g,z);if($r(_))return JR(g,_);let H=Fm(_,g,T);return{id:g,kind:_.kind,owner:_.owner,x:H.x,y:H.y,z:H.z,yaw:vo(H.yaw),vx:_.vx,vy:_.vy,vz:_.vz,hp:_.hp,flags:_.flags,epoch:H.epoch,data:_.data,t0:_.t0??0,g:_.g??0,src:_.src??"",pitch:QR(H.pitch),duck:H.duck<0?0:H.duck>1?1:H.duck,mstate:nf(_,"mstate",0),cap:de(_.cap,1),spin:nf(_,"spin",0),fuel:nf(_,"fuel",0),...wm,...H.correction===void 0?{}:{predicted:!0,correction:H.correction}}};return{id:t.sessionId,url:n,input:P,frame(g=performance.now()){if(W)return 0;en=g,u.poll(),Jn.settle(),Zr();let _=B?.predicted??null,T=_?tt(_):[],z=_?Gc(_):null,H=_?Kc(_):null,U=_?.reconciler.reconcileSeq??0,re=Do(g),te=R.tick(g)+re;if(!_){let ye=Bs(_r(g)+re);return Jn.afterSend(void 0,Nt.serverNow()),Ns=No(),ye}Yn=void 0,Io(_,Xc(_,U,T,H),U),Yc(_,U,z);let Z=Bs(te);return Jn.afterSend(UR(),Nt.serverNow()),Ns=No(),Z>0&&B&&(B.reseeded=!1),(xr?.takeMissed()??[]).length>0&&B!==null&&KR(B),Z},me(){return W||Zr(),B?rf(B.id,B.entity):void 0},code:t.roomId,get matchKey(){return r.matchKey??""},setWorld(g){let _=mo(g),T=_.hash!==$.hash;return $=_,T&&B&&!W&&Oo(B),$.hash},setPhysics(g){if(typeof g!="string")throw new TypeError("setPhysics: the hash is a string (the world's physicsHash)");return q=g,q},get physics(){let g=r.physics??"",_=g!==""&&g!==q;return _&&oe!==`${g}/${q}`&&(oe=`${g}/${q}`,console.warn(`[multiplayer] the room's physics world (hash ${g}) is not this client's (hash ${q||"none"}): your copy is never stepped from the room's state. Pass your world's physicsHash to session.setPhysics().`)),{reason:_?"physics_mismatch":"",physics:q,roomPhysics:g}},get physicsPrediction(){return Jn.status},drawTick(){return ca.tick},drawLead(){return ca.leadMs},liftPose(g){let _=yn();return _===null?void 0:Rx(_.policy,g,Nm(),ct())},viewCarry(){let g=yn(),_=B?.predicted?B.predicted.reconciler.state:void 0;if(g===null||_===void 0)return Qd=null,0;let T=Gi(r.tick??0,h(),a.sentCount)+1,z=Oc(g,{x:_.x??0,y:_.y??0,z:_.z??0,duck:_.duck??0},T,ct()),H=g.policy.platforms[z],U=Qd;return Qd=H===void 0?null:{k:z,tick:T},H===void 0||U===null||U.k!==z?0:zh(H)*(T-U.tick)},get prediction(){W||Zr();let g=B?.predicted!=null,_=g?"":B?Y:e.predict===!1?"off":"no_entity";return{predicting:g,reason:_,world:$.hash,roomWorld:bm(Qi(r.preset??""))}},predictProjectile(g){if(!K)return"";let _=a.sentCount+1;(nu.epoch!==a.epoch||nu.seq!==_)&&(nu={epoch:a.epoch,seq:_,n:0});let T=o().get(t.sessionId)?.seqBase??0,z=`${t.sessionId}.${T+_}.${nu.n++}`,H=Nt.serverNow(),U=Fs(g.g),re={x:Fs(g.x),y:Fs(g.y),z:Fs(g.z),vx:Fs(g.vx),vy:Fs(g.vy),vz:Fs(g.vz),g:U<0?0:U>wc?wc:U,t0:Th(H,we(),J())},te={id:z,kind:String(g.kind),launch:re,at:H,seq:_,epoch:a.epoch},Z=De.spawn(te);return ut.set(te,()=>Z.cancel()),k.projectilesPredicted++,z},entity(g){let _=s().get(g);if(_)return rf(g,_);let T=Am(g);if(T!==void 0)return Yd(g,T);let z=Tm().get(g);return z?Pm(z):void 0},entities(){let g=new Map,_=Dm();for(let[T,z]of s())g.set(T,rf(T,z,_));for(let[T,z]of rt)g.has(T)||g.set(T,Yd(T,z));for(let[T,z]of Tm())g.has(T)||g.set(T,Pm(z));return g},players(){let g=new Map;for(let[_,T]of o())g.set(_,{id:_,name:T.name,uid:T.uid,team:T.team,connected:T.connected,avatarUrl:T.avatarUrl});return g},get tick(){return r.tick??0},get connected(){return K},telemetry:k,fast:u.status,on(g,_){let T=M.get(g)??new Set;M.set(g,T);let z=_;return T.add(z),()=>{T.delete(z)}},async leave(){W||(vm(),t.reconnection.enabled=!1,await t.leave(!0))}}}var J1=3,BR={ready:t=>ga.ready(t),auth:()=>Au(),urls:()=>Ay(),regions:()=>Py()},$c=BR;function Z1(t){$c=t??BR}var LR;function Q1(t){LR=t??void 0}var eD=ws.MAX_REWIND_MS,tD=5,nD=3e4,rD=["moveX","moveY","moveZ","yaw","pitch","buttons"],ta=t=>typeof t=="number"&&Number.isFinite(t);function sD(t){return!Array.isArray(t)||t.length>tD?void 0:t.every(n=>ta(n)&&n>=0&&n<=nD)?t:void 0}function oD(t){let e=er(t,"options"),n=typeof e.gameId=="string"?e.gameId:"";if(!n)throw new TypeError("genex bridge: `gameId` (the game slug) is required");let r=e.renderDelayMs,s=ta(r)&&r>=0&&r<=eD;return{gameId:n,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:Array.isArray(e.urls)?e.urls.filter(o=>typeof o=="string"&&o!==""):[],predict:e.predict!==!1,predictPhysics:e.predictPhysics!==!1,renderDelayMs:s?r:void 0,capacityRetryMs:sD(e.capacityRetryMs),fast:e.fast===!1?!1:void 0}}var Rm=new Map,iD=2**30,aD=iD,jc=t=>typeof t=="number"?Rm.get(t):void 0,Mo=t=>{let e=jc(t);return e&&!e.closed?e.session:null};function Em(t){t.closed=!0;for(let e of t.unwire.splice(0))e();t.session=null}function cD(t,e,n){bs(e)?e===xe.SERVER_RESTART&&me(t,{type:"serverRestart"}):me(t,{type:"message",kind:e,data:n??null})}async function uD(t){let e=t.opts;if(await $c.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:$c.urls(),r=e.urls.length?[]:$c.regions?.()??[];if(!n.length&&!r.length)throw Object.assign(new Error("genex bridge: no authority server URL (pass urls, or run on a Genex page that serves authority rooms)"),{code:0});let s=await DR({urls:n,regions:r,room:e.gameId,name:e.name,auth:()=>$c.auth(),predict:e.predict?void 0:!1,physicsCore:LR,predictPhysics:e.predictPhysics,renderDelayMs:e.renderDelayMs,capacityRetryMs:e.capacityRetryMs,fast:e.fast,onEvent:(o,i)=>{t.closed||cD(t,o,i)}});if(t.closed){await s.leave();return}t.session=s,t.sessionId=s.id,t.world&&s.setWorld(t.world),t.unwire.push(s.on("reconnecting",({code:o})=>me(t,{type:"reconnecting",code:o})),s.on("reconnected",()=>me(t,{type:"reconnected"})),s.on("disconnect",o=>{Em(t),me(t,{type:"disconnected",code:o,reason:""})})),me(t,{type:"joined",sessionId:s.id})}function lD(t){let e=oD(t),n=++aD,r={opts:e,q:[],overflowed:!1,session:null,unwire:[],roster:new Set,sessionId:"",closed:!1,world:null};return Rm.set(n,r),uD(r).catch(s=>{r.closed||(Em(r),me(r,{type:"joinFailed",code:Jo(s),message:Qn(s)}))}),n}function dD(t,e){let n=er(e,"input"),r=Mo(t);if(!r)return!1;for(let s of rD){let o=n[s];ta(o)&&(r.input[s]=o)}return!0}function fD(t,e){let n=er(e,"projectile"),r=Mo(t);if(!r)return"";let s=o=>ta(o)?o:0;return r.predictProjectile({kind:typeof n.kind=="string"?n.kind:"",x:s(n.x),y:s(n.y),z:s(n.z),vx:s(n.vx),vy:s(n.vy),vz:s(n.vz),...ta(n.g)?{g:n.g}:{}})}function pD(t,e){let n=er(e,"world"),r=jc(t);if(!r||r.closed)return!1;let s;try{s=mo(n)}catch(o){return me(r,Xo(Qn(o))),!1}return r.world=s,r.session?.setWorld(s),!0}var hD=JSON.stringify({tick:0,sent:0,connected:!1,me:null,entities:[]});function mD(t,e){let n=Mo(t);if(!n)return hD;let r=n.frame(ta(e)?e:performance.now());return JSON.stringify({tick:n.tick,sent:r,connected:n.connected,me:n.me()??null,entities:[...n.entities().values()]})}var xm=8,_m={PREDICTED:1,ASLEEP:2},yD=new Float32Array(0);function FR(t){return[...t.entities().values()].filter(e=>e.body).sort((e,n)=>e.id<n.id?-1:e.id>n.id?1:0)}function gD(t){let e=Mo(t);if(!e)return yD;let n=FR(e),r=new Float32Array(n.length*xm);return n.forEach((s,o)=>{let i=o*xm;r.set([s.x,s.y,s.z,s.qx,s.qy,s.qz,s.qw],i),r[i+7]=(s.predicted?_m.PREDICTED:0)|(s.sleep?_m.ASLEEP:0)}),r}function bD(t){let e=Mo(t);return JSON.stringify(e?FR(e).map(n=>n.id):[])}function wD(t){let e=jc(t),n=Mo(t);return JSON.stringify({sessionId:e?.sessionId??"",connected:!!n&&n.connected,closed:!e||e.closed,tick:n?.tick??0,queued:e?.q.length??0,players:n?[...n.players().values()]:[],telemetry:n?{...n.telemetry}:null,prediction:n?n.prediction:null,fast:n?n.fast:null,physicsPrediction:n?n.physicsPrediction:null})}function SD(t,e){let n=new Set(e.players().keys());for(let r of n)t.roster.has(r)||me(t,{type:"playerJoined",id:r});for(let r of t.roster)n.has(r)||me(t,{type:"playerLeft",id:r});t.roster=n}function xD(t){let e=jc(t);if(!e)return"[]";try{let n=Mo(t);n&&SD(e,n)}catch(n){me(e,Xo(Qn(n)))}return Mu(e)}function zR(t){let e=jc(t);if(!e||e.closed)return;let n=e.session;Em(e),n?.leave().catch(()=>{}),me(e,{type:"disconnected",code:dn.CONSENTED,reason:"left"})}function _D(t){zR(t),typeof t=="number"&&Rm.delete(t)}var RD=Object.freeze({...nh,...km,initEmbed:ku});globalThis.GenexMultiplayerBridge=RD;})();
|
|
12
|
+
`);let s=new Uint8Array(r);return s.set(e),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeAll(e={offset:0},n=this.sharedBuffer){return this.encodeFullSync(e,n,!1)}encodeAllView(e,n,r,s=this.sharedBuffer){let o=r.offset;return s=this.encodeFullSync(r,s,!0,e,o),qf(s.subarray(0,n),s.subarray(o,r.offset))}ensureCapacity(e,n){if(n+ir.BUFFER_SIZE<=e.byteLength)return e;let r=Math.ceil((n+ir.BUFFER_SIZE)/ir.BUFFER_SIZE)*ir.BUFFER_SIZE,s=new Uint8Array(r);return s.set(e.subarray(0,n)),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeView(e,n,r,s=this.sharedBuffer){let o=r.offset;this._emitStreamPriority(e);for(let i of e.changes.keys()){let a=e.changes.get(i),c=this.root.changeTrees[i];if(c===void 0){e.changes.delete(i);continue}if(a.size===0)continue;let u=c.encDescriptor,l=u.encoder,d=u.metadata,f=c.ref,h=c.refTarget;s=this.ensureCapacity(s,r.offset),s[r.offset++]=255,Se.number(s,f[Q],r);for(let[p,y]of a){let S;if(p===wP){let R=h.tmpItems,A=h.deletedIndexes;for(let E=0;E<R.length;E++)R[E]===void 0||A[E]===!0||l(this,s,c,E,N.ADD,r,!1,!0,d);continue}if(typeof p=="number")S=p;else{let R=p.indexInParent(f);if(R===void 0)continue;if(S=R,y===N.ADD&&c.getChange(S)===N.DELETE){e.changes.delete(p.ref[Q]);continue}}let x=h[st](S)!==void 0&&y||N.DELETE;l(this,s,c,S,x,r,!1,!0,d)}}return e.changes.clear(),s=this.encode(r,e,s),qf(s.subarray(0,n),s.subarray(o,r.offset))}encodeUnreliableView(e,n,r,s=this.sharedBuffer){let o=r.offset;return s=this.encodeUnreliable(r,e,s,o),qf(s.subarray(0,n),s.subarray(o,r.offset))}_emitStreamBroadcast(e,n){let r=this.root.streamTrees;for(let s of r){let o=s,i=o[I],a=o[Q];if(a===void 0)continue;let c=o._stream,u=c.broadcastDeletes,l=c.broadcastPending,d=c.sentBroadcast,f=u.size>0,h=l.size>0,p=i.encDescriptor,y=p.encoder,S=p.metadata;if(f||h){if(e[n.offset++]=255,Se.number(e,a,n),f){for(let E of u)y(this,e,i,E,N.DELETE,n,!1,!1,S);u.clear()}let b=c.maxPerTick,x=[],R=0,A=[];for(let E of l){if(R>=b)break;let P=o[st](E);if(P===void 0){A.push(E);continue}y(this,e,i,E,N.ADD,n,!1,!1,S),d.add(E),x.push(P),A.push(E),R++}for(let E of A)l.delete(E);for(let E of x){let P=E[I];if(P===void 0)continue;let k=E[Q];if(k===void 0)continue;e[n.offset++]=255,Se.number(e,k,n);let M=P.encDescriptor,B=M.encoder,K=M.metadata;P.forEachLive(j=>{De.hasUnreliableAtIndex(K,j)||B(this,e,P,j,N.ADD,n,!1,!1,K)})}}for(let b of d){let x=o[st](b);if(x===void 0)continue;let R=x[I];if(R===void 0||!R.has())continue;let A=x[Q];if(A===void 0)continue;e[n.offset++]=255,Se.number(e,A,n);let E=R.encDescriptor,P=E.encoder,k=E.metadata;R.forEach((M,B)=>{M<0||De.hasUnreliableAtIndex(k,M)||P(this,e,R,M,B,n,!1,!1,k)})}}}_emitStreamPriority(e){let n=this.root.streamTrees;if(n.size===0)return;let r=e.id;for(let s of n){let o=s,i=o._stream,a=i.pendingByView.get(r);if(a===void 0||a.size===0)continue;let c=i.priorityByView?.get(r),u=c!==void 0,l=i.priority,d=i.maxPerTick,f=[],h=[];if(u||l!==void 0){let S=[],b=[],x=0;for(let R of a){let A=o[st](R);if(A===void 0){h.push(R);continue}let E=u?c(A):l(e,A);if(x<d){let P=x++;for(;P>0&&b[P-1]<E;)b[P]=b[P-1],S[P]=S[P-1],P--;b[P]=E,S[P]=R}else if(E>b[d-1]){let P=d-1;for(;P>0&&b[P-1]<E;)b[P]=b[P-1],S[P]=S[P-1],P--;b[P]=E,S[P]=R}}for(let R=0;R<x;R++)f.push(S[R])}else for(let S of a){if(f.length>=d)break;f.push(S)}for(let S of h)a.delete(S);let p=f.length,y=i.sentByView.get(r);y===void 0&&(y=new Set,i.sentByView.set(r,y));for(let S=0;S<p;S++){let b=f[S],x=o[st](b);if(x===void 0){a.delete(b);continue}e._addImmediate(x);let R=x[I];if(R!==void 0){let A=x[Q],E=e.changes.get(A);E===void 0&&(E=new Map,e.changes.set(A,E));let P=R.metadata;R.forEachLive(k=>{De.hasUnreliableAtIndex(P,k)||E.set(k,N.ADD)})}a.delete(b),y.add(b)}}}discardChanges(){let e=this.root.changes,n=e.next,r=this.root;for(;n;){let s=n.next;n.changeTree.endEncode(),r.releaseNode(n),n=s}e.next=void 0,e.tail=void 0}discardUnreliableChanges(){let e=this.root.unreliableChanges,n=e.next,r=this.root;for(;n;){let s=n.next;n.changeTree.endEncodeUnreliable(),r.releaseNode(n),n=s}e.next=void 0,e.tail=void 0}tryEncodeTypeId(e,n,r,s){let o=this.context.getTypeId(n),i=this.context.getTypeId(r);if(i===void 0){console.warn(`@colyseus/schema WARNING: Class "${r.name}" is not registered on TypeRegistry - Please either tag the class with @entity or define a @type() field.`);return}o!==i&&(e[s.offset++]=213,Se.number(e,i,s))}get hasChanges(){return this.root.changes.next!==void 0||this._hasStreamBacklog()}get _isStreamBroadcastMode(){return this.root.activeViews.size===0&&this.root.streamTrees.size>0}_hasStreamBacklog(){let e=this.root;if(e.streamTrees.size===0)return!1;let n=e.activeViews.size===0;for(let r of e.streamTrees)if(n?fA(r):dA(r,e))return!0;return!1}get hasUnreliableChanges(){return this.root.unreliableChanges.next!==void 0}};m(ir,"BUFFER_SIZE",16*1024);Ta=ir,qu=class extends Error{constructor(e){super(e),this.name="DecodingWarning"}},sg={value:0,enumerable:!1,writable:!0},Qf=class{constructor(){m(this,"refs",new Map);m(this,"refCount",{});m(this,"deletedRefs",new Set);m(this,"callbacks",{});m(this,"nextUniqueId",0)}getNextUniqueId(){return this.nextUniqueId++}addRef(e,n,r=!0){this.refs.set(e,n),n[Q]===void 0?(sg.value=e,Object.defineProperty(n,Q,sg)):n[Q]!==e&&(n[Q]=e),r&&(this.refCount[e]=(this.refCount[e]||0)+1),this.deletedRefs.has(e)&&this.deletedRefs.delete(e)}removeRef(e){let n=this.refCount[e];if(n===void 0){try{throw new qu("trying to remove refId that doesn't exist: "+e)}catch(r){console.warn(r)}return}if(n===0){try{let r=this.refs.get(e);throw new qu(`trying to remove refId '${e}' with 0 refCount (${r.constructor.name}: ${JSON.stringify(r)})`)}catch(r){console.warn(r)}return}(this.refCount[e]=n-1)<=0&&this.deletedRefs.add(e)}clearRefs(){this.refs.clear(),this.deletedRefs.clear(),this.callbacks={},this.refCount={}}garbageCollectDeletedRefs(){this.deletedRefs.forEach(e=>{if(this.refCount[e]>0)return;let n=this.refs.get(e),r=n.constructor[Symbol.metadata];if(r!=null)for(let s in r){let o=r[s].name,i=n[o];if(typeof i=="object"&&i){let a=i[Q];a!==void 0&&!this.deletedRefs.has(a)&&this.removeRef(a)}}else typeof n[be]=="function"&&Array.from(n.values()).forEach(s=>{let o=s[Q];o!==void 0&&!this.deletedRefs.has(o)&&this.removeRef(o)});this.refs.delete(e),delete this.refCount[e],delete this.callbacks[e]}),this.deletedRefs.clear()}addCallback(e,n,r){if(e===void 0){let s=typeof n=="number"?N[n]:n;throw new Error(`Can't addCallback on '${s}' (refId is undefined)`)}return this.callbacks[e]||(this.callbacks[e]={}),this.callbacks[e][n]||(this.callbacks[e][n]=[]),this.callbacks[e][n].push(r),()=>this.removeCallback(e,n,r)}removeCallback(e,n,r){let s=this.callbacks?.[e]?.[n]?.indexOf(r);s!==void 0&&s!==-1&&gP(this.callbacks[e][n],s)}},Fn=class{constructor(e,n){m(this,"context");m(this,"state");m(this,"root");m(this,"currentRefId",0);m(this,"triggerChanges");m(this,"resyncVisited",null);m(this,"resyncDamaged",!1);this.setState(e),this.context=n||new Ks(e.constructor)}setState(e){this.state=e,this.root=new Qf,this.root.addRef(0,e)}decode(e,n={offset:0},r=this.state){let s=this.triggerChanges!==void 0?[]:null,o=this.root,i=e.byteLength,a=r.constructor[Dn];for(this.currentRefId=0;n.offset<i;){if(e[n.offset]==255){n.offset++,r[zu]?.();let u=Pe.number(e,n),l=o.refs.get(u);l?(r=l,a=r.constructor[Dn],this.currentRefId=u):(console.error(`"refId" not found: ${u}`,{previousRef:r,previousRefId:this.currentRefId}),console.warn("Please report this issue to the developers."),this.skipCurrentStructure(e,n,i));continue}if(a(this,e,n,r,s)===fb){console.warn("@colyseus/schema: definition mismatch"),this.skipCurrentStructure(e,n,i);continue}}return r[zu]?.(),this.resyncVisited!==null&&YA(this,s),s!==null&&this.triggerChanges?.(s),o.garbageCollectDeletedRefs(),s}decodeResync(e,n={offset:0}){this.resyncVisited=new Map,this.resyncDamaged=!1;try{return this.decode(e,n)}finally{this.resyncVisited=null}}skipCurrentStructure(e,n,r){this.resyncVisited!==null&&(this.resyncDamaged=!0);let s={offset:n.offset};for(;n.offset<r&&!(e[n.offset]===255&&(s.offset=n.offset+1,this.root.refs.has(Pe.number(e,s))));)n.offset++}getInstanceType(e,n,r){let s;if(e[n.offset]===213){n.offset++;let o=Pe.number(e,n);s=this.context.get(o)}return s||r}createInstanceOfType(e){return e.initializeForDecoder()}removeChildRefs(e,n){let r=typeof e[be]!="string",s=e[Q];e.forEach((o,i)=>{n?.push({ref:e,refId:s,op:N.DELETE,field:i,value:void 0,previousValue:o}),r&&this.root.removeRef(o[Q])})}},yb=zt({min:Y.float64(),max:Y.float64(),bits:Y.uint8(),mode:Y.uint8()},"QuantizedDescriptor"),gb=zt({name:Y.string(),type:Y.string(),referencedType:Y.number(),childPrimitive:Y.string(),quantized:Y.ref(yb).optional()},"ReflectionField"),bb=zt({id:Y.number(),extendsId:Y.number(),fields:Y.array(gb)},"ReflectionType"),zn=zt({types:Y.array(bb),rootType:Y.number()},"Reflection");zn.encode=function(t,e={offset:0}){let n=t.context,r=new zn,s=new Ta(r),o=n.schemas.get(t.state.constructor);o>0&&(r.rootType=o);let i=new Set,a={},c=l=>{if(l.extendsId===void 0||i.has(l.extendsId)){i.add(l.id),r.types.push(l);let d=a[l.id];d!==void 0&&(delete a[l.id],d.forEach(f=>c(f)))}else a[l.extendsId]===void 0&&(a[l.extendsId]=[]),a[l.extendsId].push(l)};n.schemas.forEach((l,d)=>{let f=new bb;f.id=Number(l);let h=Object.getPrototypeOf(d);h!==Xe&&(f.extendsId=n.schemas.get(h));let p=d[Symbol.metadata];if(p!==h[Symbol.metadata]){let y=p[At]??-1;for(let S=0;S<=y;S++){let b=p[S];if(b===void 0)continue;let x=b.name;if(!Object.prototype.hasOwnProperty.call(p,x))continue;let R=new gb;R.name=x;let A;if(typeof b.type=="string")A=b.type;else if(Ys(b.type)){let E=b.type.quantized;A="quantized";let P=new yb;P.min=E.min,P.max=E.max,P.bits=E.bits,P.mode=E.wrap?1:0,R.quantized=P}else{let E;Xe.is(b.type)?(A="ref",E=b.type):(A=Object.keys(b.type)[0],typeof b.type[A]=="string"?R.childPrimitive=b.type[A]:E=b.type[A]),R.referencedType=E?n.getTypeId(E):-1}R.type=A,f.fields.push(R)}}c(f)});for(let l in a)a[l].forEach(d=>r.types.push(d));return s.encodeAll(e).slice(0,e.offset)};zn.decode=function(t,e){let n=new zn;new Fn(n).decode(t,e);let s=new Ks;n.types.forEach(a=>{let c=s.get(a.extendsId)??Xe,u=class extends c{};Ks.register(u),s.add(u,a.id)},{});let o=(a,c,u)=>{c.fields.forEach((l,d)=>{let f=u+d;if(l.quantized!==void 0){let h=l.quantized;De.addField(a,f,l.name,{quantized:rp({min:h.min,max:h.max,bits:h.bits,mode:h.mode===1?"wrap":"clamp"})})}else if(l.referencedType!==void 0){let h=l.type,p=s.get(l.referencedType)??l.childPrimitive;h==="ref"?De.addField(a,f,l.name,p):De.addField(a,f,l.name,{[h]:p})}else De.addField(a,f,l.name,l.type)})};n.types.forEach(a=>{let c=s.get(a.id),u=De.initialize(c),l=[],d=a;do l.push(d),d=n.types.find(h=>h.id===d.extendsId);while(d);let f=0;l.reverse().forEach(h=>{o(u,h,f),f+=h.fields.length})});let i=new(s.get(n.rootType||0));return new Fn(i,s)};zn.makeEncodable=function(t){let e=t[Symbol.metadata];if(!e)return t;let n=e[At];if(n===void 0)return t;for(let r=0;r<=n;r++){let s=e[r];s&&De.defineField(t,e,r,s.name,s.type)}return Object.prototype.hasOwnProperty.call(t,xa)&&delete t[xa],t};Yu=class{constructor(e){m(this,"decoder");m(this,"uniqueRefIds",new Set);m(this,"isTriggering",!1);this.decoder=e,this.decoder.triggerChanges=this.triggerChanges.bind(this)}get callbacks(){return this.decoder.root.callbacks}get state(){return this.decoder.state}addCallback(e,n,r){return this.decoder.root.addCallback(e,n,r)}addCallbackOrWaitCollectionAvailable(e,n,r,s,o=!0){let i=()=>{},a=()=>i(),c=e[n];if(!c||c[Q]===void 0){let u;return u=this.addCallback(e[Q],n,(l,d)=>{l!=null&&(u(),i=this.addCallback(l[Q],r,s))}),i=u,a}else return o=o&&this.isTriggering===!1,r===N.ADD&&o&&c.forEach((u,l)=>{s(u,l)}),this.addCallback(c[Q],r,s)}listen(...e){return typeof e[0]=="string"?this.listenInstance(this.state,e[0],e[1],e[2]):this.listenInstance(e[0],e[1],e[2],e[3])}listenInstance(e,n,r,s=!0){s=s&&this.isTriggering===!1;let o=e[n];return s&&o!==null&&o!==void 0&&r(o,void 0),this.addCallback(e[Q],n,r)}onChange(...e){if(e.length===2&&typeof e[0]!="string"){let n=e[0],r=e[1];return this.addCallback(n[Q],N.REPLACE,r)}return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],N.REPLACE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],N.REPLACE,e[2])}onAdd(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],N.ADD,e[1],e[2]!==!1):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],N.ADD,e[2],e[3]!==!1)}onRemove(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],N.DELETE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],N.DELETE,e[2])}bindTo(e,n,r,s=!0){let o=e.constructor[Symbol.metadata];r||(r=Object.keys(o).filter(a=>!isNaN(Number(a))).map(a=>o[a].name));let i=()=>{for(let a of r){let c=e[a];c!==void 0&&(n[a]=c)}};return s&&i(),this.addCallback(e[Q],N.REPLACE,i)}triggerChanges(e){this.uniqueRefIds.clear(),this.isTriggering=!0;for(let n=0,r=e.length;n<r;n++){let s=e[n],o=s.refId,i=s.ref,a=this.callbacks[o];if(a){if((s.op&N.DELETE)===N.DELETE&&Xe.isSchema(s.previousValue)){let c=s.previousValue[Q],u=this.callbacks[c]?.[N.DELETE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l]()}catch(d){console.error(d)}}if(Xe.isSchema(i)){if(!this.uniqueRefIds.has(o)){let u=a[N.REPLACE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l]()}catch(d){console.error(d)}}let c=a[s.field];if(c)for(let u=c.length-1;u>=0;u--)try{c[u](s.value,s.previousValue)}catch(l){console.error(l)}}else{let c=s.dynamicIndex??s.field;if((s.op&N.DELETE)===N.DELETE){if(s.previousValue!==void 0){let u=a[N.DELETE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.previousValue,c)}catch(d){console.error(d)}}if((s.op&N.ADD)===N.ADD){let u=a[N.ADD];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.value,c)}catch(d){console.error(d)}}}else if((s.op&N.ADD)===N.ADD&&s.previousValue!==s.value){let u=a[N.ADD];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.value,c)}catch(d){console.error(d)}}if(s.value!==s.previousValue){let u=a[N.REPLACE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](c,s.value)}catch(d){console.error(d)}}}this.uniqueRefIds.add(o)}}this.isTriggering=!1}},dp={get(t){if(t instanceof Fn)return new Yu(t);if("decoder"in t.serializer)return new Yu(t.serializer.decoder);throw new Error("Invalid room or decoder")},getLegacy(t){if(t instanceof Fn)return Gu(t);if("decoder"in t.serializer)return Gu(t.serializer.decoder);throw new Error("Invalid room or decoder")},getRawChanges(t,e){return _P(t,e)}};Ir("map",{constructor:fs});Ir("array",{constructor:ds});Ir("set",{constructor:Pa});Ir("collection",{constructor:Aa})});function Ct(){return typeof performance<"u"?performance.now():Date.now()}var Ia=ht(()=>{"use strict"});function ol(t,e){let n=globalThis,r=n.__colyseusDebug;if(!r){let s=[];r=n.__colyseusDebug={__buffer:s,publish(o,i){s.push([o,RP(i)]),s.length>EP&&s.shift()}}}r.publish(t,e)}function il(){if(typeof globalThis>"u")return!1;let t=globalThis.__colyseusDebug;return t!=null&&t.__buffer===void 0}var RP,EP,Da=ht(()=>{"use strict";RP=typeof WeakRef<"u"?t=>new WeakRef(t):t=>({deref:()=>t}),EP=64});function qt(t){return t[Q]}function lr(t){return t.constructor[kP]}function Na(t,e){let n=lr(t)?.[e];return typeof n=="number"?n:-1}function Sb(t){let e=lr(t);if(!e)return[];let n=[];for(let r=0;;r++){let s=e[r];if(!s||typeof s.name!="string")break;typeof s.type=="string"&&n.push(s.name)}return n}function Ba(t){let e=lr(t),n=[],r=[];if(e)for(let s=0;;s++){let o=e[s];if(!o||typeof o.name!="string")break;typeof o.type=="string"&&(n.push(o.name),AP[o.type]===void 0&&r.push(o.name))}return{fields:n,numeric:r}}function TP(t){if(Number.isNaN(t))return 0;if(!Number.isFinite(t))return t>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER;if(t!==(t|0)&&Math.abs(t)<=34028235e31){let e=Math.fround(t);if(Math.abs(Math.abs(e)-Math.abs(t))<1e-4)return e}return t}function xb(t,e){let n=lr(t),r=n?.[e];switch((typeof r=="number"?n[r]:void 0)?.type){case"float32":return Math.fround;case"number":return TP;default:return PP}}function _b(t){if(t.length>vP){let b=t;return x=>{let R={};for(let A=0;A<b.length;A++)R[b[A]]=x[b[A]];return R}}let e=t[0],n=t[1],r=t[2],s=t[3],o=t[4],i=t[5],a=t[6],c=t[7],u=t[8],l=t[9],d=t[10],f=t[11],h=t[12],p=t[13],y=t[14],S=t[15];return b=>{let x={};return e!==void 0&&(x[e]=b[e]),n!==void 0&&(x[n]=b[n]),r!==void 0&&(x[r]=b[r]),s!==void 0&&(x[s]=b[s]),o!==void 0&&(x[o]=b[o]),i!==void 0&&(x[i]=b[i]),a!==void 0&&(x[a]=b[a]),c!==void 0&&(x[c]=b[c]),u!==void 0&&(x[u]=b[u]),l!==void 0&&(x[l]=b[l]),d!==void 0&&(x[d]=b[d]),f!==void 0&&(x[f]=b[f]),h!==void 0&&(x[h]=b[h]),p!==void 0&&(x[p]=b[p]),y!==void 0&&(x[y]=b[y]),S!==void 0&&(x[S]=b[S]),x}}var kP,al,AP,PP,vP,La=ht(()=>{"use strict";Pt();kP=Symbol.metadata??Symbol.for("Symbol.metadata"),al=Mt;AP={string:!0,boolean:!0,bigint64:!0,biguint64:!0};PP=t=>t;vP=16});var pp,MP,CP,Gt,oi,hp=ht(()=>{"use strict";Pt();Pr();Ia();Da();La();pp=9,MP=pp,CP=(t,e)=>(e?2:1)*(pp+4+pp*t),Gt=class Gt{constructor(e,n,r,s){m(this,"data");m(this,"_host");m(this,"_encoder");m(this,"_scratch",new Uint8Array(2048));m(this,"_framed",null);m(this,"_sentCount",0);m(this,"_lastProcessed",0);m(this,"_epoch",0);m(this,"_sendTimes");m(this,"_inputBufferSize");m(this,"_inputBuffer",null);m(this,"_reckonTimes",null);m(this,"_pendingReckon",0);m(this,"_lastStamp",0);m(this,"_stampRing",null);m(this,"_renderDeltaRing",null);m(this,"_ringSlots",0);m(this,"_warnedUnknownKeys",null);m(this,"_stampRender",!1);m(this,"_stampReckon",!1);m(this,"_allowRewind");m(this,"_sendListeners",null);m(this,"_renderDelay",0);m(this,"_renderDelayExplicit",!1);m(this,"_renderDelayProvider");m(this,"_tickRate");m(this,"_patchRate");m(this,"_subSteps",1);this._host=e,this.data=n,this._encoder=r,this._stampRender=s?.stampRender??!1,this._stampReckon=s?.stampReckon??!1,this._allowRewind=s?.allowRewind,this._allowRewind!==void 0&&r.mode==="unreliable"&&!Gt._warnedAllowRewindIgnored&&(Gt._warnedAllowRewindIgnored=!0,console.warn('@colyseus/sdk: `allowRewind` is ignored on `mode:"unreliable"` \u2014 a packet stamps its whole redundancy ring or none of it, so excluding one input would cost bandwidth rather than save it. Use `mode:"reliable"` to gate the lag-comp stamp per input.')),this._renderDelay=s?.renderDelay??0,this._renderDelayExplicit=s?.renderDelay!==void 0,this._tickRate=s?.tickRate,this._patchRate=s?.patchRate,this._subSteps=s?.subSteps??1;let o=this._tickRate?1e3/this._tickRate:1e3/60,i=Gt.BUFFER_RTT_BUDGET_MS+(this._patchRate??0);this._inputBufferSize=Math.max(Gt.BUFFER_FLOOR,Math.ceil(i/o*Gt.BUFFER_HEADROOM)),this._sendTimes=new Float64Array(this._inputBufferSize)}get mode(){return this._encoder.mode}get tickRate(){return this._tickRate}get stepSeconds(){return this._tickRate?1/this._tickRate:void 0}get stepMs(){return this._tickRate?1e3/this._tickRate:void 0}get patchRate(){return this._patchRate}get subSteps(){return this._subSteps}get subStepSeconds(){return this._tickRate?1/this._tickRate/this._subSteps:void 0}get subStepMs(){return this._tickRate?1e3/this._tickRate/this._subSteps:void 0}get lastProcessed(){return this._lastProcessed}get sentCount(){return this._sentCount}get pendingCount(){return this._sentCount-this._lastProcessed}get replayBufferSize(){return this._inputBufferSize}get epoch(){return this._epoch}at(e){if(this._inputBuffer!==null&&!(e<=this._lastProcessed||e>this._sentCount)){if(this._sentCount-e>=this._inputBufferSize){Gt._warnedBufferOverflow||(Gt._warnedBufferOverflow=!0,console.warn(`@colyseus/sdk: input replay buffer (${this._inputBufferSize}) overflowed \u2014 RTT exceeds its budget at this input rate; reconciliation may drift.`));return}return this._inputBuffer[e%this._inputBufferSize]}}reckonTimeAt(e){return this._reckonTimes===null||e<=this._lastProcessed||e>this._sentCount||this._sentCount-e>=this._inputBufferSize?0:this._reckonTimes[e%this._inputBufferSize]}reset(){this._encoder.reset(),this._sentCount=this._lastProcessed=this._encoder.seq,this._framed=null,this._lastStamp=0,this._ringSlots=0,this._sendTimes.fill(0),this._epoch++}bindRenderDelay(e){this._renderDelayExplicit||(this._renderDelayProvider=e)}_resolveRenderDelay(){return this._renderDelayProvider?this._renderDelayProvider():this._renderDelay}_warnUnknownFields(){let e=lr(this.data);if(e)for(let n of Object.keys(this.data))e[n]!==void 0||this._warnedUnknownKeys?.has(n)||((this._warnedUnknownKeys??(this._warnedUnknownKeys=new Set)).add(n),console.warn(`@colyseus/sdk input: "${n}" is not a declared field on ${this.data.constructor.name} \u2014 the write is never encoded or sent. Declare it with @type(...) on the input schema, or remove the write.`))}send(){let e=this._host.connection;if(!e?.isOpen)return 0;il()&&this._warnUnknownFields();let n=this._encoder.encode(),r=this._encoder.mode==="reliable",s=this._stampReckon||this._stampRender,o=s&&r&&(this._allowRewind===void 0||this._allowRewind(this.data)),i=s&&!r,a=this._stampReckon&&this._stampRender,u=1+(o?MP+(a?2:0):i?CP(this._encoder.historySize,a):0)+n.length;u>this._scratch.byteLength&&(this._scratch=new Uint8Array(Math.max(u,this._scratch.byteLength*2)),this._framed=null),this._scratch[0]=(r?Ke.ROOM_INPUT_RELIABLE:Ke.ROOM_INPUT_UNRELIABLE)|(o||i?Zo.TIMED:0);let l={offset:1};if(i)this._writeRingStamps(l);else if(o){let{stamp:p,renderDelta:y}=this._sampleStamp();Se.number(this._scratch,p-this._lastStamp,l),this._lastStamp=p,a&&Se.uint16(this._scratch,y,l)}else this._pendingReckon=0;this._scratch.set(n,l.offset);let d=l.offset+n.length;(this._framed===null||this._framed.byteLength!==d)&&(this._framed=this._scratch.subarray(0,d));let f=this._framed,h;return r?(e.send(f),h=++this._sentCount):(e.sendUnreliable(f),h=this._sentCount=this._encoder.seq),this._recordSent(h),h}_writeRingStamps(e){let{stamp:n,renderDelta:r}=this._sampleStamp(),s=this._encoder.historySize,o=this._encoder.seq,i=this._ringSlots=Math.min(this._ringSlots+1,s),a=this._stampRing??(this._stampRing=new Float64Array(s));if(a[o%s]=n,Se.number(this._scratch,i,e),Se.uint32(this._scratch,n,e),this._writeSeriesDeltas(a,o,i,e),this._stampReckon&&this._stampRender){let c=this._renderDeltaRing??(this._renderDeltaRing=new Uint16Array(s));c[o%s]=r,Se.uint16(this._scratch,r,e),this._writeSeriesDeltas(c,o,i,e)}}_writeSeriesDeltas(e,n,r,s){let o=e.length;for(let i=1;i<r;i++)Se.number(this._scratch,e[(n-i+1)%o]-e[(n-i)%o],s)}_sampleStamp(){let e=this._host.clock,n=(e?.lastServerTime?.()??0)>0,r=n?Math.max(0,Math.round(e.serverNow()))>>>0:0,s=n?Math.min(65535,Math.max(0,Math.round(this._resolveRenderDelay()+(e.smoothedRtt?.()??0)/2))):0;return this._pendingReckon=r,{stamp:this._stampReckon?r:r>s?r-s:0,renderDelta:s}}_recordSent(e){if(this._inputBuffer===null){let r=this.data.constructor;this._inputBuffer=Array.from({length:this._inputBufferSize},()=>new r)}this._encoder.copyInto(this._inputBuffer[e%this._inputBufferSize]),this._sendTimes[e%this._inputBufferSize]=Ct(),this._stampReckon&&((this._reckonTimes??(this._reckonTimes=new Float64Array(this._inputBufferSize)))[e%this._inputBufferSize]=this._pendingReckon);let n=this._sendListeners;if(n!==null)for(let r=0;r<n.length;r++)n[r](e)}onSend(e){let n=this._sendListeners;return this._sendListeners=n!==null?[...n,e]:[e],()=>{let r=this._sendListeners;if(r===null)return;let s=r.indexOf(e);if(s<0)return;let o=r.slice();o.splice(s,1),this._sendListeners=o.length>0?o:null}}ackInput(e){if(e<=this._lastProcessed)return-1;let n=this._sentCount-e>=this._inputBufferSize;if(this._lastProcessed=e,n)return-1;let r=this._sendTimes[e%this._inputBufferSize];return r>0?Ct()-r:-1}};m(Gt,"BUFFER_FLOOR",64),m(Gt,"BUFFER_RTT_BUDGET_MS",1e3),m(Gt,"BUFFER_HEADROOM",1.5),m(Gt,"_warnedBufferOverflow",!1),m(Gt,"_warnedAllowRewindIgnored",!1);oi=Gt});var ii,dt,cl,ul=ht(()=>{"use strict";Ia();ii=Object.freeze({now:()=>Ct(),serverNow:()=>Ct(),renderNow:()=>Ct(),rtt:()=>0,smoothedRtt:()=>0,jitter:()=>0,lastServerTime:()=>0,patchInterval:()=>0,setPatchInterval:t=>{},sample:(t,e)=>{}}),dt=class dt{constructor(){m(this,"_clockOffset",0);m(this,"_clockHasSample",!1);m(this,"_offsetCount",0);m(this,"_rttFloorT",[]);m(this,"_rttFloorV",[]);m(this,"_rtt",0);m(this,"_smoothedRtt",0);m(this,"_rttHasSample",!1);m(this,"_jitter",0);m(this,"_lastRecvTime",-1);m(this,"_lastServerTime",0);m(this,"_patchInterval",0);m(this,"_renderTau",dt.RENDER_TAU);m(this,"_renderSn",0);m(this,"_renderSnAt",0)}serverNow(){return Ct()+this._clockOffset}renderNow(){let e=this.serverNow();if(this._renderTau<=0)return e;let n=Ct();if(this._renderSn===0)return this._renderSn=e,this._renderSnAt=n,this._renderSn;let r=Math.min(n-this._renderSnAt,100);return r<.5?this._renderSn:(this._renderSnAt=n,this._renderSn+=r,Math.abs(e-this._renderSn)>dt.RENDER_SNAP?(this._renderSn=e,this._renderSn):(this._renderSn+=(e-this._renderSn)*(1-Math.exp(-r/this._renderTau)),this._renderSn))}setRenderTau(e){this._renderTau=e>0?e:0}now(){return Ct()}rtt(){return this._rtt}smoothedRtt(){return this._smoothedRtt}jitter(){return this._jitter}lastServerTime(){return this._lastServerTime}patchInterval(){return this._patchInterval}setPatchInterval(e){this._patchInterval=e>0?e:0}sample(e,n){let r=Ct(),s=dt.EMA_ALPHA,o=this._patchInterval;if(this._lastRecvTime>=0&&o>0){let a=r-this._lastRecvTime,c=Math.round(a/o);c>=1&&c<=dt.JITTER_STALL_X&&(this._jitter+=(Math.abs(a-c*o)-this._jitter)*dt.JITTER_GAIN)}this._lastRecvTime=r,this._lastServerTime=e,(n<0||this._smoothedRtt>0&&n>this._smoothedRtt*dt.RTT_OUTLIER_X)&&(n=-1);let i=n>=0?e+n/2-r:e-r;if(!this._clockHasSample)this._clockOffset=i,this._clockHasSample=!0,n>=0&&(this.pushRttFloor(n,r),this._offsetCount=1);else if(n>=0){let a=this.pushRttFloor(n,r),c=this._offsetCount<dt.RTT_GATE_WARMUP;this._offsetCount++,(c||n<=a*dt.RTT_GATE_FACTOR)&&(this._clockOffset=this._clockOffset*(1-s)+i*s)}n>=0&&(this._rtt=n,this._rttHasSample?this._smoothedRtt=this._smoothedRtt*(1-s)+n*s:(this._smoothedRtt=n,this._rttHasSample=!0))}pushRttFloor(e,n){let r=this._rttFloorT,s=this._rttFloorV;for(;s.length>0&&s[s.length-1]>=e;)s.pop(),r.pop();s.push(e),r.push(n);let o=n-dt.RTT_GATE_WINDOW;for(;r.length>0&&r[0]<o;)r.shift(),s.shift();return s[0]}reset(){this._clockOffset=0,this._clockHasSample=!1,this._offsetCount=0,this._rtt=0,this._smoothedRtt=0,this._rttHasSample=!1,this._jitter=0,this._lastRecvTime=-1,this._lastServerTime=0,this._rttFloorT.length=0,this._rttFloorV.length=0,this._renderSn=0,this._renderSnAt=0}};m(dt,"EMA_ALPHA",.1),m(dt,"RENDER_TAU",250),m(dt,"RENDER_SNAP",250),m(dt,"RTT_OUTLIER_X",4),m(dt,"JITTER_GAIN",1/16),m(dt,"JITTER_STALL_X",4),m(dt,"RTT_GATE_FACTOR",1.2),m(dt,"RTT_GATE_WINDOW",1e4),m(dt,"RTT_GATE_WARMUP",30);cl=dt});var Yb=cE((GL,Gb)=>{"use strict";Gb.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});function nT(t,e){return{now:()=>t?.serverNow()??performance.now(),ttlMs:typeof e=="function"?()=>e(t?.smoothedRtt()??0):e}}var rc,Tl,Bp=ht(()=>{"use strict";rc=t=>Math.max(t*2,600),Tl=class t{constructor(){m(this,"entries",new Map);m(this,"accepted",new Set);m(this,"cfg",{});m(this,"dead",!1)}static get(e,n={}){let r=new t;return r.configure(nT(e.clock??null,n.ttlMs??rc)),n.onReject&&r.configure({onReject:n.onReject}),r}configure(e){this.cfg={...this.cfg,...e}}predict(e,n){return this.entries.set(e,n??this.cfg.now?.()??performance.now()),{key:e,cancel:()=>{this.entries.delete(e),this.accepted.delete(e)},accept:()=>{this.entries.has(e)&&this.accepted.add(e)}}}has(e){return this.entries.has(e)}confirm(e){this.entries.delete(e),this.accepted.delete(e)}reject(e){this.entries.delete(e)&&(this.accepted.delete(e),this.cfg.onReject?.(e))}prune(e,n){let r=e??this.cfg.now?.()??performance.now(),s=this.cfg.ttlMs,o=n??(typeof s=="function"?s():s)??1/0;for(let[i,a]of this.entries)this.accepted.has(i)||r-a>o&&(this.entries.delete(i),this.cfg.onReject?.(i))}clear(){this.entries.clear(),this.accepted.clear()}get size(){return this.entries.size}dispose(){this.dead=!0,this.entries.clear(),this.accepted.clear()}}});function f0(){return{ema:0,peak:0}}function Lp(t,e){t.ema+=(e-t.ema)*.1,t.peak=Math.max(e,t.peak*.9)}function p0(t){t.ema=0,t.peak=0}function bi(t,e){let n=e!==void 0&&e>d0?e:d0;return t.ema>=n?"diverging":t.peak>=n?"jitter":"matched"}var d0,vl=ht(()=>{"use strict";d0=.001});function sc(){return il()}function m0(){console.warn("@colyseus/sdk predict: a predicted value was read BEFORE this frame's input.send() calls. Reads between predict.tick() and the frame's sends are one fixed step stale and stutter on late frames. Send the frame's due inputs right after predict.tick(now) \u2014 tick and pump in your earliest per-frame callback, before anything reads value()/pose(). For game logic (zone checks, hit-reg) read .state/.world instead. See PREDICTION.md \xA74 (frame order).")}function y0(t,e){console.warn(e===""?`@colyseus/sdk predict: two key-less ctx.memo calls ran in one step (input seq ${t}) \u2014 the key-less form is ONE shared slot per step, so replay returns one frozen value for both (silent re-simulation corruption). Pass distinct keys: ctx.memo("a", \u2026) / ctx.memo("b", \u2026).`:`@colyseus/sdk predict: ctx.memo("${e}") ran twice in one step (input seq ${t}) \u2014 both calls share one slot on replay. Give each call site its own key (include the loop index for a per-iteration memo).`)}function g0(t,e,n,r){let s=Ct();if(s-h0<rT)return;h0=s;let o="",i=-1;for(let c in e){let u=e[c],l=u<0?-u:u;l>i&&(i=l,o=c)}let a=o?e[o]:n;console.warn(`@colyseus/sdk predict: prediction is diverging at input seq ${t} \u2014 rolling drift ${n.toFixed(3)} \u2265 tolerance ${r}; "${o}" currently off by ${a.toFixed(3)}. Most likely the client and server simulations disagree: a different fixed dt, mismatched constants, a step function that isn't shared, or an input the server skipped. See PREDICTION.md \xA75 (Determinism).`)}var h0,rT,Fp=ht(()=>{"use strict";Ia();Da();h0=-1/0,rT=1e3});function b0(){return Up>0}var zp,Up,wi,Ml=ht(()=>{"use strict";vl();Fp();zp=class{constructor(){m(this,"byTick",new Map);m(this,"diagTick",-1);m(this,"diagKeys",new Set);m(this,"warnedKeys",new Set)}run(e,n,r,s){if(n)return this.byTick.get(e)?.get(r);sc()&&(e!==this.diagTick?(this.diagTick=e,this.diagKeys.clear()):this.diagKeys.has(r)&&!this.warnedKeys.has(r)&&(this.warnedKeys.add(r),y0(e,r)),this.diagKeys.add(r));let o=s();if(o!==void 0){let i=this.byTick.get(e);i===void 0&&(i=new Map,this.byTick.set(e,i)),i.set(r,o)}return o}prune(e){for(let n of this.byTick.keys())n<=e&&this.byTick.delete(n)}clear(){this.byTick.clear(),this.diagTick=-1,this.diagKeys.clear()}},Up=0;wi=class{constructor(e){m(this,"lastCorrection",{});m(this,"lastCorrectionMag",0);m(this,"reconcileSeq",0);m(this,"drift",f0());m(this,"error",{});m(this,"prev",{});m(this,"renderedBefore",{});m(this,"lastTick",-1);m(this,"lastAcked",0);m(this,"lastEpoch");m(this,"replayFrom",0);m(this,"predictedSeq",0);m(this,"catching",!1);m(this,"unsubscribeSend",()=>{});m(this,"renderAcc",0);m(this,"tickSeq",0);m(this,"clampedReadTick",-1);m(this,"warnedStaleRead",!1);m(this,"stepCtx");m(this,"ackWatermark",()=>this.input_.lastProcessed);m(this,"memos",new zp);m(this,"smoothMs");m(this,"snapThreshold");m(this,"stepMs");m(this,"input_");m(this,"onReconcile");m(this,"warnTolerance");m(this,"clock");m(this,"dead",!1);m(this,"disposedHooks",[]);this.input_=e.input,this.clock=e.clock,this.smoothMs=e.smoothMs??(this.input_.patchRate?this.input_.patchRate:50),this.snapThreshold=e.snap??0;let n=e.stepMs??this.input_.stepMs??(e.stepSeconds!==void 0?e.stepSeconds*1e3:void 0);if(n===void 0)throw new Error("@colyseus/sdk reconciler: fixed simulation step is unknown. The server room must call setFixedTimestep() (or setTimestep()) so the input handle advertises a tick rate, or pass stepMs/stepSeconds explicitly \u2014 a wrong dt silently diverges rollback-replay.");this.stepMs=n;let r=e.stepSeconds??this.input_.stepSeconds??n/1e3,s=e.subSteps??this.input_.subSteps??1;this.stepCtx={dt:r,dtMs:n,tick:0,isReplay:!1,reckonTime:0,lagCompActive:!1,subSteps:s,subDt:r/s,subDtMs:n/s,memo:(o,i)=>typeof o=="string"?this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,o,i):this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,"",o),predict:(o,i)=>{this.stepCtx.isReplay||o._predictFromSim(this.stepCtx.tick,i,this.ackWatermark)}},this.onReconcile=e.onReconcile,this.warnTolerance=e.warnOnDivergence,this.lastAcked=this.input_.lastProcessed,this.lastEpoch=this.input_.epoch,this.predictedSeq=this.input_.sentCount,this.unsubscribeSend=this.input_.onSend(()=>this.catchUp())}tick(e){this.tickSeq++;let n=this.lastTick<0?0:e-this.lastTick;this.lastTick=e,n>0&&this.stepMs>0&&(this.renderAcc+=n);let r=this.input_.epoch;r!==this.lastEpoch&&(this.lastEpoch=r,this.reset());let s=this.input_.lastProcessed;if(s>this.lastAcked&&(this.lastAcked=s,this.reconcile(s)),this.markDirty(),n<=0)return;let o=this.smoothMs<=0?1:1-Math.exp(-n/this.smoothMs);for(let i of this.smoothedFields())this.error[i]-=this.error[i]*o}renderAlpha(){if(this.stepMs<=0)return 1;let e=this.renderAcc/this.stepMs;return e<0?0:e>1?1:e}noteRenderRead(){this.catching||this.stepMs<=0||this.renderAcc<this.stepMs||(this.clampedReadTick=this.tickSeq)}catchUp(){let e=this.input_.sentCount;if(!(this.predictedSeq>=e||this.catching)){this.clampedReadTick===this.tickSeq&&!this.warnedStaleRead&&(this.warnedStaleRead=!0,m0()),this.catching=!0,this.stepCtx.isReplay=!1;for(let n=this.predictedSeq+1;n<=e;n++){let r=this.input_.at(n);r!==void 0&&(this.snapshotPrev(),this.runStep(n,r),this.refreshRender(),this.renderAcc-=this.stepMs,this.renderAcc<0?this.renderAcc=0:this.renderAcc>=this.stepMs&&(this.renderAcc%=this.stepMs)),this.predictedSeq=n}this.catching=!1}}runStep(e,n){this.stepCtx.tick=e;let r=this.input_.reckonTimeAt(e);this.stepCtx.lagCompActive=r>0,this.stepCtx.reckonTime=r>0?r:this.clock!==void 0?this.clock.serverNow():0,this.applyStep(n)}reconcile(e){let n=this.warnTolerance!==void 0||sc();if(this.truthMatchesAt(e)){if(n){for(let u of this.smoothedFields())this.lastCorrection[u]=0;this.lastCorrectionMag=0,Lp(this.drift,0)}this.reconcileSeq++,this.memos.prune(e),this.onReconcile?.(e);return}let r=this.renderedBefore;for(let u of this.smoothedFields())r[u]=this.readCurrent(u)+this.error[u];this.adoptTruth();let s=Math.max(e,this.replayFrom);this.stepCtx.isReplay=!0,this.catching=!0,Up++;try{for(let u=s+1;u<=this.input_.sentCount;u++){let l=this.input_.at(u);l!==void 0&&this.runStep(u,l)}}finally{Up--}this.catching=!1,this.refreshRender(),this.predictedSeq=this.input_.sentCount;let o=this.smoothMs<=0,i=n||this.snapThreshold>0,a=0;for(let u of this.smoothedFields()){let l=r[u]-this.readCurrent(u);if(this.error[u]=o?0:l,i){let d=l<0?-l:l;d>a&&(a=d)}n&&(this.lastCorrection[u]=l)}let c=this.snapThreshold>0&&a>this.snapThreshold;if(c)for(let u of this.smoothedFields())this.error[u]=0,this.prev[u]=this.readCurrent(u);this.reconcileSeq++,n&&(this.lastCorrectionMag=a,c||(Lp(this.drift,a),this.warnTolerance!==void 0&&bi(this.drift,this.warnTolerance)==="diverging"&&g0(e,this.lastCorrection,this.drift.ema,this.warnTolerance))),this.memos.prune(e),this.onReconcile?.(e)}get pendingCount(){return this.input_.pendingCount}reset(){this.reseedState(),p0(this.drift),this.replayFrom=this.input_.sentCount,this.predictedSeq=this.input_.sentCount,this.lastAcked=this.input_.lastProcessed,this.renderAcc=0,this.memos.clear(),this.markDirty()}onDisposed(e){this.disposedHooks.push(e)}dispose(){this.dead=!0,this.unsubscribeSend();for(let e of this.disposedHooks.splice(0))e()}truthMatchesAt(e){return!1}refreshRender(){}markDirty(){}}});var sT,Vp,Si,Hp=ht(()=>{"use strict";Bp();Ml();sT=0,Vp=10,Si=class{constructor(e,n){m(this,"opts");m(this,"store");m(this,"entries",new Map);m(this,"now");m(this,"cooldownUntil",-1/0);m(this,"warnedReplayPredict",!1);m(this,"dead",!1);m(this,"teardowns",[]);this.opts=e,this.now=()=>n?.serverNow()??performance.now(),this.store=Tl.get({clock:n},{ttlMs:e.ttlMs??rc,onReject:r=>{let s=this.entries.get(r);this.entries.delete(r),s&&this.opts.onReject?.(s.payload)}})}_predictFromSim(e,n,r){this.add(e,n,r)}predict(e){if(b0()){this.warnedReplayPredict||(this.warnedReplayPredict=!0,console.warn(`@colyseus/sdk: PredictedEventChannel${this.opts.label?` "${this.opts.label}"`:""}.predict() was called during a rollback replay and ignored. Inside a reconciler step, use ctx.predict(channel, payload).`));return}this.add(-1,e)}add(e,n,r){let s=this.opts.uniqueBy!==void 0?this.opts.uniqueBy(n):typeof n=="string"||typeof n=="number"?n:sT;if(this.entries.has(s))return;let o=this.now();if(this.opts.cooldownMs!==void 0){if(o<this.cooldownUntil)return;this.cooldownUntil=o+this.opts.cooldownMs}let i=this.store.predict(s,o);r!==void 0&&i.accept(),this.entries.set(s,{payload:n,seq:e,acked:r}),this.opts.onPredict?.(n)}has(e){return e===void 0?this.entries.size>0:this.entries.has(e)}get pendingCount(){return this.entries.size}confirm(e){let n=0;for(let r of this.settleKeys(e)){let s=this.entries.get(r);s!==void 0&&(this.entries.delete(r),this.store.confirm(r),this.opts.onConfirm?.(s.payload),n++)}return n===0&&this.opts.onUnpredicted?.(e),n}reject(e){let n=0;for(let r of this.settleKeys(e))this.entries.has(r)&&(this.store.reject(r),n++);return n}settleKeys(e){return e!==void 0?[e]:[...this.entries.keys()]}clear(){this.entries.clear(),this.store.clear()}prune(){if(this.entries.size>0){let e=this.opts.graceTicks??Vp;for(let[n,r]of[...this.entries])r.acked!==void 0&&r.acked()>=r.seq+e&&this.store.reject(n)}this.store.prune()}_addTeardown(e){this.teardowns.push(e)}dispose(){for(let e of this.teardowns.splice(0))e();this.dead=!0,this.clear(),this.store.dispose()}}});var no,Cl=ht(()=>{"use strict";Bp();no=class{constructor(e={},n=null){m(this,"opts");m(this,"clock");m(this,"correlate");m(this,"ttl");m(this,"byId",new Map);m(this,"byServer",new Map);m(this,"nextId",1);m(this,"lastTickAt");m(this,"detach");m(this,"dead",!1);m(this,"handleAdd",(e,n)=>{if(this.byServer.has(e))return;let r=this.isOwned(e)?this.takeMatch(e):void 0;if(r)this.confirmEntry(r,e);else{let s={id:this.nextId++,server:e,local:void 0,state:"confirmed",at:void 0,leadMs:0,accepted:!1,data:this.makeData()};this.byId.set(s.id,s),this.byServer.set(e,s)}});m(this,"handleRemove",(e,n)=>{let r=this.byServer.get(e);r&&(this.byServer.delete(e),this.byId.delete(r.id))});m(this,"readServer",(e,n)=>e[n]);this.opts=e,this.clock=n,this.correlate=e.correlate??"fifo",this.ttl=e.ttl??rc}attach(e){this.detach?.(),this.detach=e(this.handleAdd,this.handleRemove)}spawn(e){let n=this.nextId++,r=this.makeData(),s={id:n,server:void 0,local:e,state:"pending",at:this.now(),leadMs:0,accepted:!1,data:r};return this.byId.set(n,s),{id:n,local:e,data:r,cancel:()=>{let o=this.byId.get(n);o&&o.state==="pending"&&this.byId.delete(n)},accept:()=>{let o=this.byId.get(n);o&&(o.accepted=!0)}}}confirmEntry(e,n){e.server=n,e.state="confirmed";let r=this.opts.spawnTime;r!==void 0&&e.at!==void 0&&(e.leadMs=r(n)-e.at),this.byServer.set(n,e)}takeMatch(e){let n=this.correlate;if(typeof n!="function"){for(let r of this.byId.values())if(r.state==="pending")return r;return}for(let r of this.byId.values())if(r.state==="pending"&&n(r.local,e))return r}isOwned(e){return this.opts.owned?this.opts.owned(e):!0}makeData(){return this.opts.data?this.opts.data():void 0}tick(e=performance.now()){let n=this.opts.step,r=this.clock!==null?this.clock.serverNow():e;if(n!==void 0&&this.lastTickAt!==void 0){let s=Math.max(0,(r-this.lastTickAt)/1e3);if(s>0)for(let o of this.byId.values())o.state==="pending"&&n(o.local,s)}this.lastTickAt=r}prune(){if(this.byId.size===0)return;let e=this.now(),n=this.ttl(this.clock?.smoothedRtt()??0);for(let r of this.byId.values())r.state==="pending"&&!r.accepted&&r.at!==void 0&&e-r.at>n&&(this.byId.delete(r.id),this.opts.onReject?.(r.local,r.id))}entries(){return this.byId.values()}entryFor(e){return this.byServer.get(e)}value(e,n){return e.server!==void 0?this.readServer(e.server,n):e.local[n]}bindReader(e){this.readServer=e}alive(e){return this.byId.has(e)}get size(){return this.byId.size}clear(){this.byId.clear(),this.byServer.clear()}dispose(){this.dead=!0,this.detach?.(),this.detach=void 0,this.clear()}now(){return this.clock?.serverNow()??performance.now()}}});var w0,ro,Ol=ht(()=>{"use strict";Ml();La();Fp();w0=t=>typeof t=="number"?t:typeof t=="boolean"?t?1:0:NaN,ro=class extends wi{constructor(n,r){super(r);m(this,"local",{});m(this,"fields");m(this,"numericFields",[]);m(this,"step");m(this,"instance");m(this,"wireRound",[]);m(this,"history");m(this,"historySeq");m(this,"historySize");m(this,"historyOn");m(this,"undeclared",null);m(this,"devView",null);this.instance=n;let s=r.fields,o=s??Ba(n).fields;if(s===void 0&&o.length===0)throw new Error("predict.reconciler(): no `fields` given and none derivable \u2014 the instance has no schema metadata (a plain object, or a schema with no scalar fields). Pass the decoded instance from room.state, or list `fields` explicitly.");this.fields=o,this.step=r.step;let i=this.fields.length>0;for(let a of this.fields){let c=n[a];this.local[a]=c,typeof c=="number"?(this.numericFields.push(a),this.prev[a]=c,this.error[a]=0):typeof c!="boolean"&&(i=!1),this.wireRound.push(xb(n,a))}if(this.historyOn=i,this.historySize=this.input_.replayBufferSize??64,this.history=new Float64Array(this.historyOn?this.historySize*this.fields.length:0),this.historySeq=new Float64Array(this.historyOn?this.historySize:0).fill(-1),s!==void 0){let a=new Set(this.fields),c=Ba(n).fields.filter(u=>!a.has(u));c.length>0&&(this.undeclared=new Set(c))}}get state(){return this.local}get boundRegistrations(){return[{source:this.instance,fields:this.numericFields,poseKeys:this.numericFields}]}value(n){this.noteRenderRead();let r=this.local[n];if(typeof r!="number")return r;let s=r+(this.error[n]??0),o=this.prev[n]??s;return o+(s-o)*this.renderAlpha()}smoothedFields(){return this.numericFields}readCurrent(n){return this.local[n]}applyStep(n){let r=this.undeclared!==null&&sc()?this.stepView():this.local;if(this.step(this.stepCtx,r,n),this.historyOn){let s=this.stepCtx.tick,o=s%this.historySize,i=o*this.fields.length;for(let a=0;a<this.fields.length;a++)this.history[i+a]=w0(this.local[this.fields[a]]);this.historySeq[o]=s}}stepView(){if(this.devView!==null)return this.devView;let n=this.undeclared,r=new Set,s=(o,i)=>{typeof i!="string"||!n.has(i)||r.has(i)||(r.add(i),console.warn(`@colyseus/sdk predict: step ${o} "${i}" \u2014 a schema field NOT in this reconciler's \`fields\` list, so it is never mirrored or replayed: prediction integrates on top of a stale value and rubber-bands under latency. Add "${i}" to \`fields\`, or omit \`fields\` to mirror every scalar field. Read adopt-only fields off the raw instance instead of the predicted state.`))};return this.devView=new Proxy(this.local,{get(o,i,a){return s("read",i),Reflect.get(o,i,a)},set(o,i,a,c){return s("wrote",i),Reflect.set(o,i,a,c)}}),this.devView}truthMatchesAt(n){if(!this.historyOn)return!1;let r=n%this.historySize;if(this.historySeq[r]!==n)return!1;let s=r*this.fields.length,o=this.instance;for(let i=0;i<this.fields.length;i++)if(this.wireRound[i](this.history[s+i])!==w0(o[this.fields[i]]))return!1;return!0}snapshotPrev(){for(let n of this.numericFields)this.prev[n]=this.local[n]+this.error[n]}adoptTruth(){let n=this.instance;for(let r of this.fields)this.local[r]=n[r]}reseedState(){let n=this.instance;for(let r of this.fields)this.local[r]=n[r];for(let r of this.numericFields)this.prev[r]=this.local[r],this.error[r]=0;this.historySeq.fill(-1)}}});var so,Il=ht(()=>{"use strict";Ml();La();so=class extends wi{constructor(n){super(n);m(this,"worldHandle");m(this,"bindings",[]);m(this,"curPose",{});m(this,"poseFields",[]);m(this,"customFields",[]);m(this,"fieldsReady",!1);m(this,"poseA",{});m(this,"poseB",{});m(this,"renderPose",{});m(this,"poseDirty",!0);m(this,"step");m(this,"adopt");m(this,"readPose");m(this,"interpolate");let r=n.world;for(let s of Object.keys(r)){let o=r[s];if(o===null||typeof o!="object")continue;if(qt(o)===void 0){if(lr(o)!==void 0)throw new Error(`predict.sim(): world.${s} is a schema instance that hasn't been decoded (no refId). Pass the decoded instance from room.state (e.g. inside onAdd), or a plain object for opaque scratch.`);continue}let{fields:i,numeric:a}=Ba(o);if(i.length===0)throw new Error(`predict.sim(): world.${s} is a decoded ref with no scalar fields to bind. Binding a whole COLLECTION isn't supported (yet) \u2014 spread its children into world parts (one entry per entity, fixed at construction). Nest a scalar-less instance below a plain wrapper if you meant it as an opaque handle.`);let c={};for(let l of i)c[l]=o[l];r[s]=c;let u=a.map(l=>`${s}.${l}`);this.bindings.push({source:o,mirror:c,fields:i,numeric:a,poseKeys:u})}if(this.bindings.length===0&&n.adopt===void 0)throw new Error("predict.sim(): no restore point \u2014 world has no schema-bound entries and no adopt() was provided. Put decoded schema instances in world (auto-bound), or provide adopt().");this.worldHandle=n.world,this.step=n.step,this.adopt=n.adopt,this.readPose=n.pose,this.interpolate=n.interpolate,this.refreshPose();for(let s of this.poseFields)this.prev[s]=this.curPose[s],this.error[s]=0}refreshPose(){let n=this.curPose;for(let r of this.bindings){let{mirror:s,numeric:o,poseKeys:i}=r;for(let a=0;a<o.length;a++)n[i[a]]=s[o[a]]}if(this.readPose!==void 0){let r=this.readPose(this.worldHandle);this.fieldsReady||(this.customFields=Object.keys(r));for(let s of this.customFields)n[s]=r[s]}if(!this.fieldsReady){let r=[];for(let s of this.bindings)for(let o of s.poseKeys)r.push(o);for(let s of this.customFields)r.includes(s)||r.push(s);this.poseFields=r,this.fieldsReady=!0}this.poseDirty=!0}get world(){return this.worldHandle}get boundRegistrations(){return this.bindings.map(n=>({source:n.source,fields:n.numeric,poseKeys:n.poseKeys}))}value(n){if(this.noteRenderRead(),this.interpolate)return this.pose()[n];let r=this.curPose[n]+(this.error[n]??0),s=this.prev[n]??r;return s+(r-s)*this.renderAlpha()}pose(){if(this.noteRenderRead(),!this.poseDirty)return this.renderPose;let n=this.renderAlpha(),r=this.poseA,s=this.poseB;for(let o of this.poseFields)r[o]=this.prev[o]??this.curPose[o],s[o]=this.curPose[o]+(this.error[o]??0);if(this.interpolate){let o=this.interpolate(r,s,n);for(let i of this.poseFields)this.renderPose[i]=o[i]}else for(let o of this.poseFields)this.renderPose[o]=r[o]+(s[o]-r[o])*n;return this.poseDirty=!1,this.renderPose}smoothedFields(){return this.poseFields}readCurrent(n){return this.curPose[n]}applyStep(n){this.step(this.stepCtx,this.worldHandle,n)}adoptTruth(){for(let n of this.bindings){let{source:r,mirror:s,fields:o}=n;for(let i=0;i<o.length;i++)s[o[i]]=r[o[i]]}this.adopt?.(this.worldHandle)}refreshRender(){this.refreshPose()}markDirty(){this.poseDirty=!0}snapshotPrev(){for(let n of this.poseFields)this.prev[n]=this.curPose[n]+this.error[n]}reseedState(){this.adoptTruth(),this.refreshPose();for(let n of this.poseFields)this.prev[n]=this.curPose[n],this.error[n]=0}}});function S0(t,e,n,r){let s=[];if(n.field!==void 0){let o=new Map;s.push(t.onAdd(n.collection,(i,a)=>{o.has(i)||o.set(i,t.listen(i,n.field,c=>{c===n.equals&&e.confirm(a)},!1))})),s.push(t.onRemove(n.collection,i=>{o.get(i)?.(),o.delete(i)})),s.push(()=>{for(let i of o.values())i();o.clear()})}else n.event==="remove"?s.push(t.onRemove(n.collection,(o,i)=>{e.confirm(i)})):s.push(t.onAdd(n.collection,o=>{n.mine!==void 0&&o[n.mine]!==r?.()||e.confirm()},!1));return()=>{for(let o of s.splice(0))o?.()}}var x0=ht(()=>{"use strict"});function R0(t){return t===null||typeof t!="object"?!1:Array.isArray(t.fields)}function uT(){E0||(E0=!0,console.warn("@colyseus/sdk Predict: room.clock isn't server-synced because the server room didn't call defineInput(). Server-time interpolation and lag compensation fall back to local time. Add defineInput() on the server room to enable them \u2014 or ignore this if you only need local smoothing."))}var mt,ln,Rn,Lr,Vn,oc,ic,xi,_i,Ri,ac,It,oT,iT,_0,Kt,Ei,oo,io,ki,Ai,Pi,Ti,mr,uc,Bl,Ll,Fl,aT,Dl,$p,bs,Nl,cT,E0,vi,ao,jp=ht(()=>{"use strict";Pt();Hp();Cl();Ol();Il();hp();vl();ul();Da();La();x0();mt=16,ln=0,Rn=1,Lr=2,Vn=3,oc=4,ic=5,xi=6,_i=7,Ri=8,ac=9,It=ac+mt*2,oT=3,iT=1.5,_0=250,Kt=7,Ei=0,oo=1,io=2,ki=3,Ai=4,Pi=5,Ti=6,mr=0,uc=0,Bl=1,Ll=2,Fl=3,aT=4,Dl=5,$p={lerp:uc,extrapolate:Bl,damped:Ll,reckon:Fl,raw:aT},bs={mode:"lerp",delay:100,smoothMs:50,maxExtrapolate:200,tickInterval:0,snap:0,angle:!1},Nl={step:void 0,smoothMs:50,substep:16,snap:0};cT=0,E0=!1;vi=class vi{constructor(e,n){m(this,"callbacks");m(this,"sessionSource");m(this,"slotBuf",new Float64Array(64*It));m(this,"slotCount",0);m(this,"slotDetach",[]);m(this,"slotAngle",[]);m(this,"freeSlots",[]);m(this,"slotByRef",new Map);m(this,"simByRef",new Map);m(this,"boundBySlot",new Map);m(this,"boundProfileIdx",-1);m(this,"renderTime",0);m(this,"defaultMode");m(this,"reckonDefaults");m(this,"clock");m(this,"useRenderClock",!1);m(this,"fixedStepMs");m(this,"stepAcc",0);m(this,"lastFrameNow",-1);m(this,"profileBuf",new Float64Array(8*Kt));m(this,"profileCount",0);m(this,"profileKeys",new Map);m(this,"profileLabels",[]);m(this,"profileComputers",[]);m(this,"trackListeners",[]);m(this,"name");m(this,"disposeListeners",[]);m(this,"driven",[]);m(this,"computeDamped",e=>{let n=this.slotBuf,r=e*It,s=this.profileBuf,o=(n[r+Vn]|0)*Kt,i=this.renderTime,a=n[r+ln],c=n[r+Lr],u=i-c;n[r+Lr]=i;let l=n[r+Rn];if(u>0){let d=s[o+io],f=d>0?1-Math.exp(-u/d):1;l+=(a-l)*f,n[r+Rn]=l}return l});m(this,"computeLerp",e=>{let n=this.computeLerpRaw(e),r=this.slotBuf,s=e*It,o=this.profileBuf[(r[s+Vn]|0)*Kt+Ti],i=this.renderTime;if(o<=0)return r[s+Rn]=n,r[s+Ri]=n,r[s+Lr]=i,n;let a=r[s+Lr],c=i-a;if(c<=0)return r[s+Rn];let u=r[s+Ri],l=r[s+Rn],d=c/o,f=(n-u)/d,h=n-f+(l-u+f)*Math.exp(-d);return r[s+Rn]=h,r[s+Ri]=n,r[s+Lr]=i,h});m(this,"computeExtrapolate",e=>{let n=this.slotBuf,r=e*It,s=this.profileBuf,o=(n[r+Vn]|0)*Kt,i=this.renderTime,a=n[r+_i]|0;if(a===0)return n[r+ln];let c=n[r+xi]|0,u=r+ac,l=(c-a+mt)%mt,d=(l+a-1)%mt,f=u+d*2,h=n[f],p=n[f+1],y;if(a===1)y=p;else{let A=a>=3?2:1,E=(l+a-1-A+mt)%mt,P=u+E*2,k=n[P],M=n[P+1],B=h-k;if(B<=0)y=p;else{let K=(p-M)/B,j=s[o+ki],L=i-h;L<0?L=0:L>j&&(L=j),y=p+K*L}}let S=n[r+Lr];n[r+Lr]=i;let b=s[o+io];if(b<=0)return n[r+Rn]=y,y;let x=i-S,R=n[r+Rn];if(x>0){let A=1-Math.exp(-x/b);R+=(y-R)*A,n[r+Rn]=R}return R});m(this,"computeReckon",e=>{let n=this.slotBuf,r=e*It,s=n[r+oc],o=n[r+ic]|0,i=this.simByRef.get(s);if(i!==void 0){let a=o<i.posOf.length?i.posOf[o]:-1;if(a>=0)return this.applySimulation(i,a)}return n[r+ln]});m(this,"computeRaw",e=>this.slotBuf[e*It+ln]);m(this,"computeBound",e=>{let n=this.boundBySlot.get(e);return n!==void 0?n.ctrl.value(n.key):this.slotBuf[e*It+ln]});this.callbacks=dp.get(e),this.sessionSource=e;let{clock:r,...s}=n;this.defaultMode=s.mode??"lerp";let o=this.defaultMode!=="reckon"&&this.defaultMode!=="raw",i=o?(()=>{let u=s;return{mode:u.mode??bs.mode,delay:u.delay??bs.delay,smoothMs:u.smoothMs??bs.smoothMs,maxExtrapolate:u.maxExtrapolate??bs.maxExtrapolate,tickInterval:u.tickInterval??bs.tickInterval,snap:u.snap??bs.snap,angle:u.angle??bs.angle}})():{...bs},a=o?s.smoothMs??0:0;if(this.allocProfile(this.defaultMode,i.delay,i.smoothMs,a,i.maxExtrapolate,i.tickInterval,i.snap,!1)!==mr)throw new Error("Predict: defaults profile must be at index 0");if(this.defaultMode==="reckon"){let u=s;this.reckonDefaults={step:u.step,smoothMs:u.smoothMs??Nl.smoothMs,substep:u.substep??Nl.substep,snap:u.snap??Nl.snap}}else this.reckonDefaults={...Nl};this.clock=r??e.clock??void 0,this.useRenderClock=s.renderPresent!==!1,this.clock===ii&&uT(),this.name=s.name??`predict#${++cT}`,ol("predict",this.makeCoreHandle())}static get(e,n={}){return new vi(e,n)}get mode(){return this.defaultMode}presentFn(){let e=this.clock;if(e)return this.useRenderClock&&e.renderNow?e.renderNow.bind(e):e.serverNow.bind(e)}makeCoreHandle(){return{name:this.name,mode:()=>this.defaultMode,smoothingDefaults:()=>this.readSmoothingDefaults(),reckonDefaults:()=>({...this.reckonDefaults}),reconcilers:()=>this.snapshotReconcilers(),attachedCount:()=>this.slotByRef.size,setDefaults:e=>this.setDefaults(e),profiles:()=>this.snapshotProfiles(),setProfile:(e,n)=>this.setProfile(e,n),onTrack:e=>(this.trackListeners.push(e),()=>{let n=this.trackListeners.indexOf(e);n>=0&&this.trackListeners.splice(n,1)}),onDispose:e=>(this.disposeListeners.push(e),()=>{let n=this.disposeListeners.indexOf(e);n>=0&&this.disposeListeners.splice(n,1)})}}snapshotReconcilers(){let e=[],n=0;for(let r of this.driven){let s=r;if(!s.drift)continue;let o=s.warnTolerance;e.push({label:`reconciler #${n++}`,status:bi(s.drift,o),severity:o!==void 0&&o>0?s.drift.ema/o:void 0,ema:s.drift.ema,peak:s.drift.peak,lastCorrectionMag:s.lastCorrectionMag??0,reconcileSeq:s.reconcileSeq??0})}return e}readSmoothingDefaults(){let e=this.profileBuf,n=mr*Kt,r=e[n+Ei]|0;return{mode:r===uc?"lerp":r===Bl?"extrapolate":r===Ll?"damped":r===Fl?"reckon":"raw",delay:e[n+oo],smoothMs:e[n+io],lerpSmoothMs:e[n+Ti],maxExtrapolate:e[n+ki],tickInterval:e[n+Ai],snap:e[n+Pi]}}allocProfile(e,n,r,s,o,i,a,c,u){let l=typeof e=="number"?e:$p[e],d="";if(c){d=`${u??""}|${l}|${n}|${r}|${s}|${o}|${i}|${a}`;let y=this.profileKeys.get(d);if(y!==void 0)return y}let f=this.profileCount++;if((f+1)*Kt>this.profileBuf.length){let y=new Float64Array(this.profileBuf.length*2);y.set(this.profileBuf),this.profileBuf=y}let p=f*Kt;return this.profileBuf[p+Ei]=l,this.profileBuf[p+oo]=n,this.profileBuf[p+io]=r,this.profileBuf[p+Ti]=s,this.profileBuf[p+ki]=o,this.profileBuf[p+Ai]=i,this.profileBuf[p+Pi]=a,this.profileLabels[f]=u,this.profileComputers[f]=this.computerForMode(l),c&&this.profileKeys.set(d,f),f}computerForMode(e){return e===uc?this.computeLerp:e===Bl?this.computeExtrapolate:e===Ll?this.computeDamped:e===Fl?this.computeReckon:e===Dl?this.computeBound:this.computeRaw}profileFromOpts(e){if(e.mode===void 0&&e.delay===void 0&&e.smoothMs===void 0&&e.maxExtrapolate===void 0&&e.tickInterval===void 0&&e.snap===void 0)return mr;let n=this.readSmoothingDefaults(),r=e.mode??n.mode,s=e.delay??n.delay,o=e.smoothMs??n.smoothMs,i=e.smoothMs??n.lerpSmoothMs,a=e.maxExtrapolate??n.maxExtrapolate,c=e.tickInterval??n.tickInterval,u=e.snap??n.snap;return r===n.mode&&s===n.delay&&o===n.smoothMs&&i===n.lerpSmoothMs&&a===n.maxExtrapolate&&c===n.tickInterval&&u===n.snap?mr:this.allocProfile(r,s,o,i,a,c,u,!0)}groupProfile(e,n){let r=this.readSmoothingDefaults(),s=e.mode??this.defaultMode;return this.allocProfile(s,e.delay??r.delay,e.smoothMs??r.smoothMs,e.smoothMs??r.lerpSmoothMs,e.maxExtrapolate??r.maxExtrapolate,e.tickInterval??r.tickInterval,e.snap??r.snap,!0,n)}setDefaults(e){let n=e.mode;if(n!==void 0){this.defaultMode=n;let a=mr*Kt,c=$p[n];this.profileBuf[a+Ei]=c,this.profileComputers[mr]=this.computerForMode(c)}let r=e,s=mr*Kt,o=this.profileBuf;r.delay!==void 0&&(o[s+oo]=r.delay),r.smoothMs!==void 0&&(o[s+io]=r.smoothMs,o[s+Ti]=r.smoothMs),r.maxExtrapolate!==void 0&&(o[s+ki]=r.maxExtrapolate),r.tickInterval!==void 0&&(o[s+Ai]=r.tickInterval),r.snap!==void 0&&(o[s+Pi]=r.snap,this.reckonDefaults.snap=r.snap);let i=e;i.step!==void 0&&(this.reckonDefaults.step=i.step),i.smoothMs!==void 0&&(this.reckonDefaults.smoothMs=i.smoothMs),i.substep!==void 0&&(this.reckonDefaults.substep=i.substep)}snapshotProfiles(){let e=[];for(let n=0;n<this.profileCount;n++){let r=n*Kt,s=this.profileBuf[r+Ei]|0;if(s===Dl)continue;let o=s===uc?"lerp":s===Bl?"extrapolate":s===Ll?"damped":s===Fl?"reckon":"raw";e.push({id:n,isDefault:n===mr,label:this.profileLabels[n],mode:o,delay:this.profileBuf[r+oo],smoothMs:this.profileBuf[r+(s===uc?Ti:io)],maxExtrapolate:this.profileBuf[r+ki],tickInterval:this.profileBuf[r+Ai],snap:this.profileBuf[r+Pi]})}return e}setProfile(e,n){if(e<0||e>=this.profileCount)return;let r=e*Kt,s=this.profileBuf;if((s[r+Ei]|0)!==Dl){if(n.mode!==void 0){let o=$p[n.mode];s[r+Ei]=o,this.profileComputers[e]=this.computerForMode(o),e===mr&&(this.defaultMode=n.mode)}n.delay!==void 0&&(s[r+oo]=n.delay),n.smoothMs!==void 0&&(s[r+io]=n.smoothMs,s[r+Ti]=n.smoothMs),n.maxExtrapolate!==void 0&&(s[r+ki]=n.maxExtrapolate),n.tickInterval!==void 0&&(s[r+Ai]=n.tickInterval),n.snap!==void 0&&(s[r+Pi]=n.snap)}}dispose(){for(let e of new Set([...this.slotByRef.keys(),...this.simByRef.keys()]))this.detachByRef(e);this.trackListeners.length=0;for(let e of this.driven.splice(0))e.dispose?.();for(let e of this.disposeListeners.splice(0))e()}track(e,n,r={}){return this.trackWithProfile(e,n,this.profileFromOpts(r),r.angle??!1)}trackWithProfile(e,n,r,s=!1){let o=qt(e);if(o===void 0)throw new Error("Predict.track(): instance has no refId \u2014 track/attach must run AFTER the decoder delivers the instance (e.g. inside onAdd).");let i=Na(e,n),a=e[n]??0,c,u=this.slotByRef.get(o)?.get(n);u!==void 0&&(c=this.boundBySlot.get(u),c!==void 0?this.freeStash(c):this.untrackSlot(o,n));let l=this.allocSlot(),d=this.slotBuf,f=l*It;if(d[f+ln]=a,d[f+Rn]=a,d[f+Lr]=performance.now(),d[f+Ri]=a,d[f+Vn]=r,d[f+oc]=o,d[f+ic]=i,d[f+xi]=0,d[f+_i]=0,this.slotAngle[l]=s,c!==void 0)c.stash=l;else{let p=this.slotByRef.get(o);p===void 0&&(p=new Map,this.slotByRef.set(o,p)),p.set(n,l)}for(let p=0;p<this.trackListeners.length;p++)this.trackListeners[p](r,n);let h=this.callbacks.listen(e,n,p=>{let y=this.clock&&this.clock.lastServerTime()>0?this.clock.lastServerTime():performance.now(),S=this.slotBuf,b=l*It;if(s){let j=S[b+ln];p=j+Math.atan2(Math.sin(p-j),Math.cos(p-j))}let x=(S[b+Vn]|0)*Kt,R=this.profileBuf[x+Ai],A=S[b+xi]|0,E=S[b+_i]|0,P=this.profileBuf[x+Pi];P>0&&E>0&&Math.abs(p-S[b+ln])>P&&(A=0,E=0,S[b+Rn]=p,S[b+Ri]=p);let k=E===0?Number.NEGATIVE_INFINITY:S[b+ac+(A===0?mt-1:A-1)*2],M=y;if(R>0&&isFinite(k)){let j=y-k,L=j>0?Math.max(1,Math.round(j/R)):1;M=k+L*R;let se=y+R;M>se&&(M=se)}S[b+ln]=p;let B=b+ac;if(E>=2&&isFinite(k)){let j=A===0?mt-1:A-1,L=j===0?mt-1:j-1,se=k-S[B+L*2],v=this.clock?.patchInterval?this.clock.patchInterval():0,$=v>0?v:se,G=v>0?iT*v:oT*se;if($>0&&M-k>G){let W=$<_0?$:_0,q=B+A*2;S[q]=M-W,S[q+1]=S[B+j*2+1],A=A+1>=mt?0:A+1,E<mt&&E++}}let K=B+A*2;S[K]=M,S[K+1]=p,S[b+xi]=A+1>=mt?0:A+1,E<mt&&(S[b+_i]=E+1)},!0);return this.slotDetach[l]=h,()=>this.untrackSlot(o,n)}untrack(e,n){let r=qt(e);r!==void 0&&this.untrackSlot(r,n)}untrackSlot(e,n){let r=this.slotByRef.get(e),s=r?.get(n);if(s===void 0)return;let o=this.boundBySlot.get(s);if(o!==void 0){this.freeStash(o);return}this.slotDetach[s]?.(),this.slotDetach[s]=void 0,this.freeSlots.push(s),r.delete(n),r.size===0&&this.slotByRef.delete(e)}freeStash(e){e.stash<0||(this.slotDetach[e.stash]?.(),this.slotDetach[e.stash]=void 0,this.freeSlots.push(e.stash),e.stash=-1)}allocSlot(){if(this.freeSlots.length>0)return this.freeSlots.pop();let e=this.slotCount++;if((e+1)*It>this.slotBuf.length){let r=new Float64Array(this.slotBuf.length*2);r.set(this.slotBuf),this.slotBuf=r}return e}registerBound(e,n,r,s,o){let i=qt(n),a=this.slotByRef.get(i);a===void 0&&(a=new Map,this.slotByRef.set(i,a));let c=[];for(let u=0;u<r.length;u++){let l=r[u],d=a.get(l),f=-1;if(d!==void 0){let b=this.boundBySlot.get(d);b!==void 0?(console.warn(`@colyseus/sdk Predict: "${l}" (refId ${i}) is already bound to a controller \u2014 the newer registration wins.`),f=b.stash,this.boundBySlot.delete(d),this.freeSlots.push(d)):f=d}let h=this.allocSlot(),p=this.slotBuf,y=h*It,S=n[l]??0;p[y+ln]=S,p[y+Rn]=S,p[y+Lr]=0,p[y+Ri]=S,p[y+Vn]=o,p[y+oc]=i,p[y+ic]=Na(n,l),p[y+xi]=0,p[y+_i]=0,this.slotAngle[h]=!1,this.boundBySlot.set(h,{ctrl:e,key:s[u],stash:f}),a.set(l,h),c.push(h);for(let b=0;b<this.trackListeners.length;b++)this.trackListeners[b](o,l)}return()=>{for(let u=0;u<c.length;u++){let l=c[u],d=this.boundBySlot.get(l);if(d===void 0||d.ctrl!==e)continue;this.boundBySlot.delete(l),this.freeSlots.push(l);let f=this.slotByRef.get(i);f?.get(r[u])===l&&(d.stash>=0?f.set(r[u],d.stash):(f.delete(r[u]),f.size===0&&this.slotByRef.delete(i)))}}}installBoundOverlay(e){let n=[];for(let r of e.boundRegistrations)r.fields.length===0||qt(r.source)===void 0||(this.boundProfileIdx<0&&(this.boundProfileIdx=this.allocProfile(Dl,0,0,0,0,0,0,!1,"bound")),n.push(this.registerBound(e,r.source,r.fields,r.poseKeys,this.boundProfileIdx)));n.length>0&&e.onDisposed(()=>{for(let r of n)r()})}trackStepped(e,n){let r=n.substep??16,s=n.fields,o=s.map(p=>Na(e,p)),i=n.step,a=this.clock,c=this.presentFn(),u=n.forwardMs??(c?()=>{let p=a.lastServerTime();return p>0?Math.max(0,c()-p):0}:()=>0),l=n.elapsedMs??c??(()=>performance.now()),d=e[al],f=n.snapshot===void 0&&Array.isArray(d)&&o.every(p=>p>=0&&p<d.length),h;if(f){let p=new e.constructor,y=p[al];h=(S,b,x,R)=>{let A=S[al];for(let k=0;k<A.length;k++)y[k]=A[k];let E=b,P=R-b;for(;E>0;){let k=E<r?E:r;P+=k,i(p,k/1e3,P),E-=k}for(let k=0;k<o.length;k++)x[k]=y[o[k]]}}else{let p=Sb(e),y=n.snapshot??(p.length>0?_b(p):b=>({...b})),S=[...s];h=(b,x,R,A)=>{let E=y(b),P=x,k=A-x;for(;P>0;){let M=P<r?P:r;k+=M,i(E,M/1e3,k),P-=M}for(let M=0;M<S.length;M++)R[M]=E[S[M]]}}return this.trackSimulated(e,{fields:s,forwardMs:u,elapsedMs:l,smoothMs:n.smoothMs,snap:n.snap,advance:h})}trackSimulated(e,n){let r=qt(e);if(r===void 0)throw new Error("Predict.trackStepped(): instance has no refId \u2014 must run AFTER the decoder delivers the instance (e.g. inside onAdd).");let s=n.fields,o=s.length,i=s.map(h=>Na(e,h)),a=0;for(let h of i)h>a&&(a=h);let c=new Int8Array(a+1).fill(-1);for(let h=0;h<o;h++)i[h]>=0&&(c[i[h]]=h);let u=new Float64Array(o);for(let h=0;h<o;h++)u[h]=e[s[h]]??0;let l=this.presentFn(),d=n.elapsedMs??l??(()=>performance.now()),f={instance:e,fieldIds:i,posOf:c,forwardMs:n.forwardMs,elapsedMs:d,advance:n.advance,smoothMs:n.smoothMs??50,snap:n.snap??0,smoothed:u,out:new Float64Array(o),valueOut:new Float64Array(o),offset:new Float64Array(o),outPrev:new Float64Array(o),frameVel:new Float64Array(o),lastBaseT:NaN,lastApplyTime:-1/0};return this.simByRef.set(r,f),()=>this.untrackSimulated(r)}untrackSimulated(e){this.simByRef.delete(e)}attach(e,n){let r=this.makeGroup("(attach)",n);return this.attachWithPlan(e,this.planFor(r,e))}makeGroup(e,n){return{label:e,config:n,basePlan:this.buildGroupPlan(n,e),planByCtor:new Map}}planFor(e,n){let r=n.constructor,s=e.planByCtor.get(r);return s===void 0&&(s=this.resolveCtorPlan(e,n),e.planByCtor.set(r,s)),s}resolveCtorPlan(e,n){let r=lr(n),s=n.constructor?.name||"?",o=e.config;if(!R0(o)){if(r===void 0)return e.basePlan;let c=Object.keys(o).filter(l=>o[l]!==void 0);if(c.every(l=>typeof r[l]=="number"))return e.basePlan;let u={};for(let l of c)typeof r[l]=="number"&&(u[l]=o[l]);return this.buildGroupPlan(u,`${e.label}:${s}`)}let i=o,a=i.fields;if(r!==void 0){let c=a.filter(u=>typeof r[u]=="number");c.length!==a.length&&(a=c)}return a===i.fields?e.basePlan:this.buildGroupPlan({...i,fields:a},`${e.label}:${s}`)}buildGroupPlan(e,n){let r=[];if(R0(e)){let o=e;if(!Array.isArray(o.fields))throw new Error("Predict.attach(): `fields` must be a numeric-key array.");let i=o.mode??this.defaultMode,a=o.step??this.reckonDefaults.step,c=i==="reckon";if(c&&typeof a!="function")throw new Error("Predict.attach(): reckon mode requires a 'step' function. Either pass `step` in the attach config OR construct the Predict with `Predict.get(room, { mode: 'reckon', step: yourStepFn })` so it can be inherited.");let u=this.groupProfile({mode:i,snap:o.snap,smoothMs:o.smoothMs},n);for(let l of o.fields)r.push({field:l,profileIdx:u,angle:o.angle});return{label:n,isReckon:c,reckonFields:c?o.fields:void 0,reckonStep:c?a:void 0,reckonSmoothMs:o.smoothMs??this.reckonDefaults.smoothMs,reckonSubstep:o.substep??this.reckonDefaults.substep,reckonSnap:o.snap??this.reckonDefaults.snap,reckonSnapshot:o.snapshot,fieldProfiles:r}}let s=e;for(let o of Object.keys(s)){let i=s[o];if(i===void 0)continue;let a=typeof i=="string"?{mode:i}:i;r.push({field:o,profileIdx:this.groupProfile(a,n),angle:a.angle})}return{label:n,isReckon:!1,fieldProfiles:r}}attachToGroup(e,n,r){let s=[];n.isReckon&&s.push(this.trackStepped(e,{fields:n.reckonFields,step:n.reckonStep,smoothMs:n.reckonSmoothMs,substep:n.reckonSubstep,snap:n.reckonSnap,snapshot:n.reckonSnapshot,forwardMs:r}));for(let{field:o,profileIdx:i,angle:a}of n.fieldProfiles)s.push(this.trackWithProfile(e,o,i,!!a));return()=>{for(let o of s)o()}}attachWithPlan(e,n){let r=qt(e);if(r===void 0)throw new Error("Predict.attach(): instance has no refId \u2014 attach must run AFTER the decoder delivers the instance (e.g. inside onAdd).");return this.attachToGroup(e,n),()=>this.detachByRef(r)}detach(e){let n=qt(e);n!==void 0&&this.detachByRef(n)}detachByRef(e){let n=this.slotByRef.get(e);if(n){for(let r of[...n.keys()]){let s=n.get(r);if(s===void 0)continue;let o=this.boundBySlot.get(s);o!==void 0?(this.freeStash(o),this.boundBySlot.delete(s),this.freeSlots.push(s),n.delete(r)):this.untrackSlot(e,r)}n.size===0&&this.slotByRef.delete(e)}this.simByRef.delete(e)}attachAll(...e){let n=typeof e[0]=="string",r=n?void 0:e[0],s=n?e[0]:e[1],o=n?e[1]:e[2],i=this.makeGroup(s,o),a=new Set,c=f=>{this.attachWithPlan(f,this.planFor(i,f)),a.add(f)},u=f=>{a.delete(f),this.detach(f)},l=n?this.callbacks.onAdd(s,c):this.callbacks.onAdd(r,s,c),d=n?this.callbacks.onRemove(s,u):this.callbacks.onRemove(r,s,u);return()=>{l?.(),d?.();for(let f of a)this.detach(f);a.clear()}}tick(e=performance.now()){this.renderTime=e;let n=0,r=this.fixedStepMs;if(r!==void 0&&r>0){let i=this.lastFrameNow<0?0:e-this.lastFrameNow;this.stepAcc+=i,n=Math.floor(this.stepAcc/r),n>vi.MAX_STEPS_PER_FRAME?(this.stepAcc=0,n=vi.MAX_STEPS_PER_FRAME):this.stepAcc-=n*r}this.lastFrameNow=e;let s=this.driven,o=0;for(let i=0;i<s.length;i++){let a=s[i];a.dead||(a.tick?.(e),a.prune?.(),o!==i&&(s[o]=a),o++)}return o!==s.length&&(s.length=o),n}defineEvent(e){let{confirmOn:n,...r}=e,s=new Si(r,this.clock??null);if(n!==void 0){if(n.mine!==void 0&&typeof this.sessionSource.sessionId!="string")throw new Error(`Predict.defineEvent: confirmOn.mine ("${n.mine}") requires a Predict built from a Room (it compares against room.sessionId); confirm manually instead.`);s._addTeardown(S0(this.callbacks,s,n,()=>this.sessionSource.sessionId))}return this.driven.push(s),s}spawns(e,n={}){let r=new no(n,this.clock??null),s=n.fields,o=n.step,i=s!==void 0&&o!==void 0?this.makeGroup(String(e),{mode:"reckon",fields:s,step:o,smoothMs:n.smoothMs??0,substep:n.substep}):void 0,a=i!==void 0?new Map:void 0,c=this.clock;return r.attach((u,l)=>{let d=this.callbacks.onAdd(e,(h,p)=>{if(u(h,p),i===void 0||a.has(h))return;let y=r.entryFor(h)?.leadMs??0,S=c?()=>{let b=c.lastServerTime(),x=b>0?Math.max(0,c.serverNow()-b):0;return Math.max(0,x+y)}:()=>Math.max(0,y);a.set(h,this.attachToGroup(h,this.planFor(i,h),S))}),f=this.callbacks.onRemove(e,(h,p)=>{a?.get(h)?.(),a?.delete(h),l(h,p)});return()=>{if(d?.(),f?.(),a!==void 0){for(let h of a.values())h();a.clear()}}}),i!==void 0&&r.bindReader((u,l)=>this.value(u,l)),this.driven.push(r),r}canonicalDelay(){return this.profileBuf[mr*Kt+oo]}bindInputRenderDelay(e){e instanceof oi&&e.bindRenderDelay(()=>this.canonicalDelay())}reconciler(e,n){let r=new ro(e,{...n,clock:n.clock??this.clock});return this.adoptFixedStep(r.stepMs),this.bindInputRenderDelay(n.input),this.installBoundOverlay(r),this.driven.push(r),r}sim(e){let n=new so({...e,clock:e.clock??this.clock});return this.adoptFixedStep(n.stepMs),this.bindInputRenderDelay(e.input),this.installBoundOverlay(n),this.driven.push(n),n}adoptFixedStep(e){if(this.fixedStepMs===void 0){this.fixedStepMs=e,this.stepAcc=0,this.lastFrameNow=-1;return}Math.abs(this.fixedStepMs-e)>1e-6&&console.warn(`@colyseus/sdk Predict: a reconciler's fixed step (${e}ms) differs from this Predict's (${this.fixedStepMs}ms). tick() paces one rate for the whole room; use a separate Predict per rate.`)}value(e,n){let r=qt(e),s=r===void 0?void 0:this.slotByRef.get(r)?.get(n);if(s===void 0)return e[n];let o=this.slotBuf[s*It+Vn]|0;return this.profileComputers[o](s)}valueAt(e,n,r){let s=qt(e),o=s===void 0?void 0:this.slotByRef.get(s)?.get(n);if(o===void 0)return e[n];let i=o*It,a=this.slotBuf[i+Vn]|0;if(this.profileComputers[a]!==this.computeReckon)return this.profileComputers[a](o);let c=this.simByRef.get(this.slotBuf[i+oc]);if(c!==void 0){let u=this.slotBuf[i+ic]|0,l=u<c.posOf.length?c.posOf[u]:-1;if(l>=0){let d=this.clock?.lastServerTime?.()??NaN,f=Number.isNaN(d)?0:Math.max(0,r-d);return c.advance(c.instance,f,c.valueOut,r),c.valueOut[l]}}return this.slotBuf[i+ln]}read(e,n,r){let s=r??{},o=qt(e),i=o===void 0?void 0:this.slotByRef.get(o);for(let a=0;a<n.length;a++){let c=n[a],u=i?.get(c);s[c]=u===void 0?e[c]:this.profileComputers[this.slotBuf[u*It+Vn]|0](u)}return s}readAt(e,n,r,s){let o=s??{},i=qt(e),a=i===void 0?void 0:this.slotByRef.get(i),c,u=!1;for(let l=0;l<n.length;l++){let d=n[l],f=a?.get(d);if(f===void 0){o[d]=e[d];continue}let h=f*It,p=this.slotBuf[h+Vn]|0;if(this.profileComputers[p]!==this.computeReckon){o[d]=this.profileComputers[p](f);continue}if(!u&&(u=!0,c=this.simByRef.get(this.slotBuf[h+oc]),c!==void 0)){let y=this.clock?.lastServerTime?.()??NaN,S=Number.isNaN(y)?0:Math.max(0,r-y);c.advance(c.instance,S,c.valueOut,r)}if(c!==void 0){let y=this.slotBuf[h+ic]|0,S=y<c.posOf.length?c.posOf[y]:-1;if(S>=0){o[d]=c.valueOut[S];continue}}o[d]=this.slotBuf[h+ln]}return o}computeLerpRaw(e){let n=this.slotBuf,r=e*It,s=this.profileBuf,o=(n[r+Vn]|0)*Kt,i=this.renderTime,a=n[r+_i]|0;if(a===0)return n[r+ln];let c=n[r+xi]|0,u=r+ac,l=(c-a+mt)%mt,d=(l+a-1)%mt,f=u+d*2;if(a===1)return n[f+1];let h=s[o+oo],p=this.clock&&this.clock.lastServerTime()>0?this.clock.serverNow()-h-this.clock.smoothedRtt()/2:i-h,y=u+l*2;if(p<=n[y])return n[y+1];if(p>=n[f])return n[f+1];let S=a-2,b=(l+S)%mt;for(;S>0&&!(n[u+b*2]<=p);)S--,b=b===0?mt-1:b-1;let x=u+b*2,R=b+1>=mt?0:b+1,A=u+R*2,E=n[x],k=n[A]-E;if(k<=0)return n[A+1];let M=(p-E)/k,B=n[x+1],K=n[A+1];return B+(K-B)*M}applySimulation(e,n){let r=this.renderTime;if(e.lastApplyTime!==r){let s=e.out,o=e.smoothed,i=e.offset,a=o.length,c=this.clock?.lastServerTime?.()??NaN;if(e.advance(e.instance,e.forwardMs(),s,e.elapsedMs()),e.lastApplyTime===-1/0||e.smoothMs<=0)for(let d=0;d<a;d++)i[d]=0,o[d]=s[d];else if(Number.isNaN(c)){let d=Math.max(0,Math.min(r-e.lastApplyTime,100)),f=1-Math.exp(-d/e.smoothMs);for(let h=0;h<a;h++)o[h]+=(s[h]-o[h])*f}else{let d=Math.max(0,Math.min(r-e.lastApplyTime,100));if(c!==e.lastBaseT&&!Number.isNaN(e.lastBaseT)){let h=e.snap,p=e.frameVel;for(let y=0;y<a;y++){let S=o[y]+p[y]*d-s[y];i[y]=h>0&&Math.abs(S)>h?0:S}}else if(d>0){let h=e.outPrev,p=e.frameVel;for(let y=0;y<a;y++)p[y]=(s[y]-h[y])/d}let f=Math.exp(-d/e.smoothMs);for(let h=0;h<a;h++)i[h]*=f,o[h]=s[h]+i[h]}let l=e.outPrev;for(let d=0;d<a;d++)l[d]=s[d];e.lastBaseT=c,e.lastApplyTime=r}return e.smoothed[n]}};m(vi,"MAX_STEPS_PER_FRAME",5);ao=vi});var Y0={};of(Y0,{DEFAULT_GRACE_TICKS:()=>Vp,Predict:()=>ao,PredictedEventChannel:()=>Si,PredictedSpawns:()=>no,Reconciler:()=>ro,SimReconciler:()=>so,classifyDrift:()=>bi});var Zp=ht(()=>{"use strict";jp();Ol();vl();Il();Hp();Cl()});var la="genex-native";var uu="genex_native";var lu="genex_protocol",du="genex_attempt",fu="genex_nonce",cf="genex_caps";var Uo="genex_";var uf="genex_r";var lf="entryRef",df="genex_hash",ff="genex_referrer",pf="genex_ref";var pu="__genexNative";var dE=/^[0-9a-f]{32}$/,fE=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function kr(t){return typeof t=="string"&&dE.test(t)}function hf(t){return typeof t=="string"&&fE.test(t)}var Vo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",pE=(()=>{let t=new Array(128).fill(-1);for(let e=0;e<Vo.length;e++)t[Vo.charCodeAt(e)]=e;return t})();function Vm(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r>=55296&&r<=56319){let s=n+1<t.length?t.charCodeAt(n+1):0;s>=56320&&s<=57343?(r=65536+(r-55296<<10)+(s-56320),n++):r=65533}else r>=56320&&r<=57343&&(r=65533);r<128?e.push(r):r<2048?e.push(192|r>>6,128|r&63):r<65536?e.push(224|r>>12,128|r>>6&63,128|r&63):e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return e}function hE(t){let e="";for(let n=0;n<t.length;){let r=t[n],s,o;if(r<128)s=r,o=1;else if((r&224)===192)s=r&31,o=2;else if((r&240)===224)s=r&15,o=3;else if((r&248)===240)s=r&7,o=4;else return null;if(n+o>t.length)return null;for(let i=1;i<o;i++){let a=t[n+i];if((a&192)!==128)return null;s=s<<6|a&63}if(o===2&&s<128||o===3&&(s<2048||s>=55296&&s<=57343)||o===4&&(s<65536||s>1114111))return null;if(s>65535){let i=s-65536;e+=String.fromCharCode(55296+(i>>10),56320+(i&1023))}else e+=String.fromCharCode(s);n+=o}return e}function mf(t){return Vm(t).length}function yf(t){let e=Vm(JSON.stringify(t)),n="";for(let r=0;r<e.length;r+=3){let s=e[r],o=e[r+1],i=e[r+2];if(n+=Vo[s>>2],n+=Vo[(s&3)<<4|(o??0)>>4],o===void 0||(n+=Vo[(o&15)<<2|(i??0)>>6],i===void 0))break;n+=Vo[i&63]}return n}function gf(t){if(t.length%4===1)return;let e=[],n=0,r=0;for(let o=0;o<t.length;o++){let i=t.charCodeAt(o),a=i<128?pE[i]:-1;if(a<0)return;n=n<<6|a,r+=6,r>=8&&(r-=8,e.push(n>>r&255))}if(r>0&&(n&(1<<r)-1)!==0)return;let s=hE(e);if(s!==null)try{return JSON.parse(s)}catch{return}}var Hm=2048,$m=32;var yE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;function gE(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function hu(t,e){if(Object.keys(t).length!==e.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(t,r))return!1;return!0}var mu=["channel","v","type","slug","attemptId","nonce"];function bE(t){return t.channel===la&&t.v===1&&hf(t.slug)&&kr(t.attemptId)&&kr(t.nonce)}function bf(t){if(!(!gE(t)||!bE(t)))switch(t.type){case"ticket":return!hu(t,[...mu,"ticket","expiresAt"])||typeof t.ticket!="string"||t.ticket.length===0||t.ticket.length>Hm||typeof t.expiresAt!="string"||t.expiresAt.length>$m||!yE.test(t.expiresAt)?void 0:t;case"guest":case"cancel":return hu(t,mu)?t:void 0;case"foreground":return!hu(t,[...mu,"active"])||typeof t.active!="boolean"?void 0:t;case"network":return!hu(t,[...mu,"online"])||typeof t.online!="boolean"?void 0:t;default:return}}function SE(t,e){if(typeof t!="string"||t.length===0)return{ok:!1,reason:"undecodable"};if(mf(t)>4096)return{ok:!1,reason:"too-large"};let n=gf(t);if(n===void 0)return{ok:!1,reason:"undecodable"};let r=e(n);return r===void 0?{ok:!1,reason:"invalid"}:{ok:!0,message:r}}function Sf(t){return SE(t,bf)}function xf(t){let e=yf(t);if(!(e.length>4096))return e}function yu(t,e){let n=t.charAt(0)==="?"?t.slice(1):t;if(n.length===0)return null;for(let r of n.split("&")){let s=r.indexOf("=");if(s!==-1&&r.slice(0,s)===e)return r.slice(s+1)}return null}function gu(t){return yu(t,uu)==="1"}function Rf(t){if(!gu(t))return null;let e=yu(t,du),n=yu(t,fu),r=Number(yu(t,lu));return!kr(e)||!kr(n)||r!==1?null:{attemptId:e,nonce:n,protocol:r}}function Ym(t){return t.indexOf("%")===-1?t:t.replace(/%([0-9A-Fa-f]{2})/g,(e,n)=>{let r=parseInt(n,16);return r<128?String.fromCharCode(r):e})}function Km(t){let e=t.indexOf("="),n=e===-1?t:t.slice(0,e);return Ym(n.indexOf("+")===-1?n:n.split("+").join(" "))}function bu(t){return Xm(t,[uf])}var _E=[uu,lu,du,fu,cf];function Ef(t){return Xm(t,_E)}function Xm(t,e){let n=t.charAt(0)==="?"?t.slice(1):t;if(n.length===0)return"";let r=n.split("&"),s=r.filter(i=>!e.includes(Km(i)));if(s.length===r.length)return`?${n}`;let o=s.join("&");return o.length===0?"":`?${o}`}var RE=/^[!$-&(-;=?-~]+$/;function wu(t,e){if(typeof t!="string")return"";let n=t.charAt(0)==="?"?t.slice(1):t,r=n.indexOf("#");if(r!==-1&&(n=n.slice(0,r)),n.length===0||!RE.test(n))return"";let o=n.split("&").filter(i=>{if(i.length===0)return!1;let a=Km(i);return!a.startsWith(Uo)&&!e.includes(a)}).join("&");return o.length>1024?"":o}var EE=/^#[!#-;=?-_a-~]+$/;function Su(t){return typeof t!="string"||t.length<2||t.length>4096||!EE.test(t)||Ym(t).includes(Uo)?"":t}var kE=/^[a-z0-9._-]+$/,AE=/^\[[0-9a-f:.]+\]$/;function PE(t){return kE.test(t)&&/[a-z0-9]/.test(t)||AE.test(t)}function _f(t){let e=t.slice(0,8).toLowerCase(),n=e==="https://"?"https":e.slice(0,7)==="http://"?"http":null;if(n===null)return null;let r=n.length+3,s=t.length;for(let u=r;u<t.length;u++){let l=t.charAt(u);if(l==="/"||l==="?"||l==="#"||l==="\\"){s=u;break}}if(s-r>255)return null;let o=t.slice(r,s).toLowerCase();if(o.length===0||o.indexOf("@")!==-1)return null;let i=o,a="",c=o.lastIndexOf(":");if(c!==-1&&o.charAt(o.length-1)!=="]"&&(i=o.slice(0,c),a=o.slice(c+1)),!PE(i))return null;if(a.length>0){if(!/^[0-9]{1,5}$/.test(a))return null;let u=Number(a);if(u>65535)return null;a=u===(n==="https"?443:80)?"":`:${u}`}return`${n}://${i}${a}`}function $o(t,e){if(typeof t!="string"||t.length===0)return null;let n=_f(t);return n===null||n.length>255||typeof e=="string"&&_f(e)===n?null:n}var Jm=["open","save","fullscreen"];var Zm=50*1024*1024,TE=16;function Qm(t){return typeof t=="string"&&Jm.includes(t)}function kf(t){if(!Array.isArray(t))return[];let e=[],n=Math.min(t.length,TE);for(let r=0;r<n;r++){let s=t[r];Qm(s)&&!e.includes(s)&&e.push(s)}return e}var UE=null;function ty(t){UE=t}var HE=null;function ny(t){HE=t}var $E=null;function ry(t){$E=t}var ha=1,Mf="genex:embed:retry",gy="genex:guest:popover-dismissed",by="genex:embed:local-auth",wy="genex:embed:entry-referrer",jE="none",sy="genex:player",WE="0.35.0",Be=null,Ue="pending",sn=null,os=!1,rs=null,jo=!1,ss,Wo,Sy=0,jt,xy,Cf,_y,Ry=!1,is=null,Ey=[],Go=!1,Vs=!1,fa=!1,rn=0,Yo=1e4,qE=2e3,GE=10*6e4,YE=6e4,oy=500,KE=3e4,XE=3e4,Ye,vn,qo,iy=!1,ay,xu=null,cy=new Set;var uy=!1,JE=new Map,ky=[],ma=[],pa=null,_u=null,Us,Af,Pf=!1,Ru=new Map;function et(){return globalThis.window}function Of(){return globalThis.document}function ya(t,e,n){let r;if(n!==void 0)try{let s=globalThis.AbortSignal;s&&typeof s.timeout=="function"&&(r=s.timeout(n))}catch{}return globalThis.fetch(t,r?{...e,signal:r}:e)}function ZE(){try{return et()?.sessionStorage?.getItem(Mf)==="1"}catch{return!1}}function QE(){try{et()?.sessionStorage?.setItem(Mf,"1")}catch{}}function If(){try{et()?.sessionStorage?.removeItem(Mf)}catch{}}function ek(){try{return et()?.sessionStorage?.getItem(by)==="1"}catch{return!1}}function tk(){try{et()?.sessionStorage?.setItem(by,"1")}catch{}}function nk(){try{let t=et()?.sessionStorage?.getItem(wy);return t==null?void 0:$o(t)}catch{return}}function rk(t){try{et()?.sessionStorage?.setItem(wy,t??jE)}catch{}}function sk(){try{return et()?.sessionStorage?.getItem(gy)==="1"}catch{return!1}}function ok(){try{et()?.sessionStorage?.setItem(gy,"1")}catch{}}function ik(){try{let t=et()?.localStorage;if(!t)return"no-storage";let e=t.getItem(sy);return e||(e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,t.setItem(sy,e)),e}catch{return"no-storage"}}function ku(t){let e=et();if(!e||Go)return;if(Go=!0,qo!==void 0&&(clearTimeout(qo),qo=void 0),Be={slug:t.slug,apiUrl:t.apiUrl.replace(/\/$/,""),dashboardOrigins:[...t.dashboardOrigins]},Ue="pending",Oy(e),ny({apiUrl:Be.apiUrl,dashboardOrigins:Be.dashboardOrigins,getToken:()=>jt,getParentOrigin:()=>is,isEmbedded:Wt,isNative:Sn,isLocalTest:()=>os}),ry({apiUrl:Be.apiUrl,dashboardOrigins:Be.dashboardOrigins,getToken:()=>jt,getParentOrigin:()=>is,isEmbedded:Wt,isNative:Sn,isLocalTest:()=>os}),zf(e)){Ik(e);return}Tu("connecting");let n=Iy(e);if(n){xk(e,n);return}Wt()?wk(e):Ek(e)}function Wt(){let t=et();if(!t)return!1;try{return t.self!==t.top}catch{return!0}}function ak(){let t=et();return t?Wt()?"page":Sn()||Nf(t)?"app":Go?os?"local":"standalone":zf(t,!1)?"local":"standalone":"standalone"}function Au(){return Ry?{embedToken:Tk}:jt?{embedToken:jt}:void 0}function Ay(){return xy??[]}function Py(){return Vy(Cf)??[]}function Ty(){return Ck(_y)}function Df(){return(Ue==="authenticated"||Ue==="guest")&&sn?Promise.resolve({user:sn,guest:Ue==="guest"}):Ue==="blocked"?Promise.reject(new Error("genex embed auth: blocked")):(ck("waitForPlayer"),new Promise((t,e)=>{ma.push({resolve:t,reject:e})}))}function ck(t){if(!Go){if(!iy){iy=!0;try{console.error(`[genex] ${t}() called before initEmbed() \u2014 identity can never resolve and the game will sit black. Call initEmbed({ slug, apiUrl, dashboardOrigins }) first (genex-threejs-embed-auth), and draw a frame before you await identity.`)}catch{}}qo===void 0&&(qo=setTimeout(()=>{qo=void 0,Go||Ar("no-identity")},Yo))}}var uk=32*1024;async function vy(){if(!Be)throw new Error("genex embed: call initEmbed() first");if(Ue==="pending"&&await Df(),Ue==="blocked")throw new Error("genex embed auth: blocked")}function My(t,e={}){let n={Authorization:`Bearer ${jt}`};return e.body!==void 0&&(n["Content-Type"]="application/json"),e.ifVersion!==void 0&&(n["If-Match"]=String(e.ifVersion)),ya(`${Be.apiUrl}/api/projects/${encodeURIComponent(Be.slug)}${t}`,{method:e.method??"GET",headers:n,body:e.body,keepalive:e.body!==void 0&&e.body.length<=uk?!0:void 0})}async function lk(t){return t.status!==403?!1:(await t.json().catch(()=>null))?.error==="staging_no_save"}async function dk(t){return t.status===409?{saved:!1,conflict:!0,version:(await t.json().catch(()=>({}))).version}:t.ok?{saved:!0,version:(await t.json()).version}:await lk(t)?{saved:!1,staging:!0}:(on("error",{error:new Error(`genex state save failed (${t.status})`)}),{saved:!1})}async function fk(t,e){return await vy(),Ue==="guest"?(Af=t,Pf=!0,{saved:!1,guest:!0,queued:!0}):dk(await My("/state/me",{method:"PUT",body:JSON.stringify(t),ifVersion:e?.ifVersion}))}async function pk(t,e){let n=e?.board??"main",r=e?.mode??"max";if(await vy(),Ue==="guest"){let i=Ru.get(n);return(!i||(r==="min"?t<i.score:t>i.score))&&Ru.set(n,{score:t,mode:r}),{submitted:!1,guest:!0,queued:!0}}let s=await My("/scores",{method:"POST",body:JSON.stringify({score:t,board:n,mode:r})});if(!s.ok)return on("error",{error:new Error(`genex score submit failed (${s.status})`)}),{submitted:!1};let o=await s.json();return{submitted:!0,best:o.best,improved:o.improved}}async function hk(){try{if(Pf){let e=Af;Af=void 0,Pf=!1,await fk(e)}let t=[...Ru.entries()];Ru.clear();for(let[e,{score:n,mode:r}]of t)await pk(n,{board:e,mode:r})}catch(t){on("error",{error:t})}}function on(t,e){let n=JE.get(t);if(n)for(let r of[...n])try{r(e)}catch{}}var mk=["embed"];function Cy(t,e){let n={ticket:null,guest:!1,entryHash:"",entryReferrer:null};if(!t||t.length<2)return n;try{let r=new URLSearchParams(t.slice(1));return{ticket:r.get("genex_ticket"),guest:r.get("genex_guest")==="1",entryHash:Su(r.get(df)),entryReferrer:$o(r.get(ff),e)}}catch{return n}}function yk(t,e){try{return new URLSearchParams(t).get(e)}catch{return null}}function Oy(t){if(xu)return xu;let e="",n="",r=null;try{e=t.location.search??"",n=Eu??t.location.hash??"",r=t.location.origin??null}catch{}let s=Wt(),o=Cy(n,r),i=!s&&(!!o.ticket||o.guest),a=wu(e,mk);return xu={search:a?`?${a}`:"",hash:i?o.entryHash:n.includes(Uo)?"":n,referrer:gk(e,s,i,o.entryReferrer,r)},xu}function gk(t,e,n,r,s){let o=nk();if(o!==void 0)return o;let i;return e?i=$o(yk(t,pf),s):n?i=r:i=$o(Of()?.referrer,s),rk(i),i}function bk(){if(!(uy||cy.size===0)){uy=!0;for(let t of[...cy])try{t()}catch{}}}function wk(t){ay=e=>{Sk(e)},t.addEventListener("message",ay),t.parent.postMessage({type:"genex:embed:ready",v:ha},"*"),Ye=setTimeout(()=>{Ko()},Yo)}function ly(){return(Ue==="pending"||Ue==="guest")&&!Vs}async function Sk(t){if(!Be)return;let e=t.data;if(!e||e.v!==ha)return;let n=e.type==="genex:embed:ticket",r=e.type==="genex:embed:guest";if(!(!n&&!r)&&!(n&&(!ly()||typeof e.ticket!="string"||!e.ticket))&&!(r&&(Ue!=="pending"||Vs||fa))){if(!Be.dashboardOrigins.includes(t.origin)){let s=await Tf();if(n&&!ly()||r&&(Ue!=="pending"||Vs||fa)||!s.includes(t.origin))return}if(Ye!==void 0&&clearTimeout(Ye),is=t.origin,Ey=kf(e.caps),r){await Ko();return}await Ff(e.ticket)}}function Nf(t){let e=t.ReactNativeWebView;return!e||typeof e!="object"?null:typeof e.postMessage=="function"?e:null}function Iy(t){if(Wt())return null;let e;try{e=t.location.search??""}catch{return null}return!gu(e)||!Nf(t)?null:Rf(e)}function Sn(){return rs!==null}function Hs(t){let e=et();if(!e||!Be||!rs)return;let n=Nf(e);if(!n)return;let r=xf({channel:la,v:1,slug:Be.slug,attemptId:rs.attemptId,nonce:rs.nonce,...t});if(r)try{n.postMessage(r)}catch{}}function Dy(t){Sn()&&Hs({type:"error",code:t})}function xk(t,e){rs=e,Sy=Date.now(),t[pu]=r=>{_k(r)},Hs({type:"ready",sdkVersion:WE,capabilities:["native-ticket","native-guest","heartbeat"]}),Ye=setTimeout(()=>{Ko()},Yo)}async function _k(t){if(!Be||!rs)return;let e=Sf(t);if(!e.ok)return;let n=e.message;if(!(n.slug!==Be.slug||n.attemptId!==rs.attemptId||n.nonce!==rs.nonce))switch(n.type){case"ticket":Ye!==void 0&&clearTimeout(Ye),await Ff(n.ticket);return;case"guest":Ye!==void 0&&clearTimeout(Ye),await Ko();return;case"cancel":Ny(),bk();return;case"foreground":case"network":return}}function Ny(){Ye!==void 0&&clearTimeout(Ye),Ye=void 0,vn!==void 0&&clearTimeout(vn),vn=void 0,ss!==void 0&&clearTimeout(ss),ss=void 0,Wo!==void 0&&clearInterval(Wo),Wo=void 0}function By(){!Sn()||Wo!==void 0||(Wo=setInterval(()=>{Hs({type:"heartbeat",uptimeMs:Math.max(0,Date.now()-Sy)})},XE),Wo.unref?.())}function Rk(){!Sn()||jo||(jo=!0,Hs({type:"reauth-required"}),ss=setTimeout(()=>{ss=void 0,jo&&(jo=!1,on("error",{error:new Error("embed session expired")}),Ar("session-expired"))},KE))}function Bf(){jo=!1,ss!==void 0&&clearTimeout(ss),ss=void 0}function Lf(t,e){let n=et();if(!(!n||!Wt()))try{n.parent.postMessage(t,e)}catch{}}async function Ek(t){let e=Ly(t);if(e.ticket){dy(),await Ff(e.ticket);return}if(e.guest){dy(),await Ko();return}Tu("redirecting"),await Pu(t,{guestOk:!0})}function dy(){Ye!==void 0&&clearTimeout(Ye),Ye=setTimeout(()=>{Ye=void 0,Ue==="pending"&&Ar("no-identity")},Yo+qE)}var Eu=null;function kk(t){return t.location.pathname+bu(t.location.search)}function Ly(t){let e=Eu??t.location.hash;Eu=null;let{ticket:n,guest:r,entryHash:s}=Cy(e);if(n||r)try{t.history.replaceState(t.history.state??null,"",kk(t)+s)}catch{}return{ticket:n,guest:r}}async function Pu(t,e){if(!Be||os||Sn())return;let n=e?.guestOk?Be.dashboardOrigins[0]??(await Tf())[0]:(await Tf())[0]??Be.dashboardOrigins[0];if(!n){Ar();return}let r=t.location.origin+t.location.pathname,s=Ef(bu(t.location.search));s.length-1<=1024&&r.length+s.length<=2048&&s.indexOf("#")===-1&&(r+=s);let o=e?.guestOk?"&guest=ok":"",i=`${n}/play/authorize?returnTo=${encodeURIComponent(r)}&slug=${encodeURIComponent(Be.slug)}${o}`,a=Oy(t).referrer;a&&(i+=`&${lf}=${encodeURIComponent(a)}`),i+=Su(t.location.hash),t.location.replace(i)}async function Tf(){if(!Be)return[];try{let t=await ya(`${Be.apiUrl}/api/embed/dashboard-origins`);if(!t.ok)return Be.dashboardOrigins;let e=await t.json();if(Array.isArray(e.origins)&&e.origins.every(n=>typeof n=="string"))return e.origins}catch{}return Be.dashboardOrigins}async function Ff(t){if(!Be||os||Vs||Ue!=="pending"&&Ue!=="guest"&&!(jo&&Ue==="authenticated"))return;let n=Ue==="guest",r=++rn;Vs=!0;try{let s=await ya(`${Be.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ticket:t})},Yo);if(r!==rn)return;if(!s.ok){on("error",{error:new Error(`ticket redemption failed (${s.status})`)}),n||await fy();return}let o=await s.json();if(r!==rn)return;jt=o.embedToken,sn=o.user,Uy(o.colyseus),Ue="authenticated",Ye!==void 0&&clearTimeout(Ye),Ye=void 0,If(),vu(),Vf(),Uf(),Wt()&&is&&Lf({type:"genex:embed:authenticated",v:ha},is),Sn()&&(Bf(),Hs({type:"authenticated",guest:!1}),By()),n&&await hk();let i={user:sn};for(let a of ky.splice(0))a.resolve(i);for(let a of ma.splice(0))a.resolve({user:sn,guest:!1});on("authenticated",i)}catch(s){if(r!==rn)return;on("error",{error:s}),n||await fy()}finally{Vs=!1}}async function Ko(){if(!Be||os||fa||Vs||Ue!=="pending"&&Ue!=="guest")return;let t=++rn;fa=!0;try{let e=await ya(`${Be.apiUrl}/api/embed/guest-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:Be.slug,playerId:ik()})},Yo);if(t!==rn)return;if(!e.ok){on("error",{error:new Error(`guest session failed (${e.status})`)}),Dy("guest-failed"),Ar(e.status===404?"not-available":"no-identity");return}let n=await e.json();if(t!==rn)return;jt=n.embedToken,sn=n.user,Uy(n.colyseus),Ak()}catch(e){if(t!==rn)return;on("error",{error:e}),Ar()}finally{fa=!1}}function Ak(){let t=Ue!=="guest";if(Ue="guest",Ye!==void 0&&clearTimeout(Ye),vu(),Uf(),Wt()?Lf({type:"genex:embed:authenticated",v:ha,guest:!0},is??"*"):Sn()?(Hs({type:"authenticated",guest:!0}),By()):t&&!sk()&&Uk(),sn){let e={user:sn};for(let n of ma.splice(0))n.resolve({user:sn,guest:!0});on("guest",e)}}function Fy(t){try{let e=new URL(t.location.origin);return e.protocol==="http:"&&zy.has(e.hostname)}catch{return!1}}var zy=new Set(["localhost","127.0.0.1","[::1]"]),Pk="genex_authority_url",Tk="local:test",vk=64;function Mk(t){if(!t||t.length>vk)return null;let e;try{e=new URL(t)}catch{return null}let n=!e.username&&!e.password&&e.pathname==="/"&&!e.search&&!e.hash;return e.protocol!=="ws:"||!zy.has(e.hostname)||!n?null:`ws://${e.host}`}function Uy(t){xy=t?.urls,Cf=t?.authorityUrls,_y=t?.authorityRegions}function Vy(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string"&&e.length>0)}function Ck(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(n===null||typeof n!="object")continue;let{region:r,urls:s}=n,o=Vy(s)??[];typeof r=="string"&&r.length>0&&o.length>0&&e.push({region:r,urls:o})}return e}function zf(t,e=!0){if(Wt()||Iy(t)||!Fy(t))return!1;let n=null;try{n=new URLSearchParams(t.location.search)}catch{}return n?.get("genex_local_test")==="1"?!0:n?.get("genex_auth")==="1"?(e&&tk(),!1):ek()?!1:!Ok(t)}function Ok(t){let e=Eu??t.location.hash;return!!e&&e.includes("genex_")}function Ik(t){os=!0,Ly(t),Dk(t);let e={id:"local:test",name:"Local Tester"};sn=e,Ue="guest",vu();try{console.info("[genex] local test mode \u2014 local visuals and controls only. Auth, saves, leaderboards, and multiplayer are NOT validated here; no Genex credential exists.")}catch{}for(let n of ma.splice(0))n.resolve({user:e,guest:!0});on("guest",{user:e})}function Dk(t){if(!Fy(t))return;let e=null;try{e=new URLSearchParams(t.location.search).get(Pk)}catch{return}let n=Mk(e);n&&(Cf=[n],Ry=!0)}async function fy(){let t=et();if(Ye!==void 0&&clearTimeout(Ye),Ye=void 0,Sn()){Bf(),Dy("ticket-rejected"),Ar();return}if(t&&!Wt()&&!ZE()){QE(),Tu("redirecting"),await Pu(t,{guestOk:!0});return}Ar()}function Uf(){vn!==void 0&&clearTimeout(vn),vn=setTimeout(()=>{Hy()},GE)}async function Hy(){if(!Be||Ue!=="authenticated"&&Ue!=="guest"||!jt)return;let t=rn,e=jt,n;try{let r=await ya(`${Be.apiUrl}/api/embed/session/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`},keepalive:!0});if(n=r.status,t!==rn||jt!==e)return;if(r.ok){let s=await r.json();if(t!==rn||jt!==e)return;jt=s.embedToken,Uf();return}}catch{n=void 0}if(!(t!==rn||jt!==e)){if(n===401){if(Ue==="guest"){Ko();return}if(Sn()){Rk();return}on("error",{error:new Error("embed session expired")}),Ar("session-expired");return}vn!==void 0&&clearTimeout(vn),vn=setTimeout(()=>{Hy()},YE)}}function Ar(t="no-identity"){if(Ue==="blocked")return;rn++,Ue="blocked",sn=null,jt=void 0,Ye!==void 0&&clearTimeout(Ye),vn!==void 0&&clearTimeout(vn),Vf(),Sn()?(Ny(),Bf(),vu(),Hs({type:"blocked",reason:t})):Tu(Wt()?"blocked-embedded":"blocked-standalone"),Wt()&&Lf({type:"genex:embed:blocked",v:ha},is??"*");let e=new Error("genex embed auth: blocked");for(let n of ky.splice(0))n.reject(e);for(let n of ma.splice(0))n.reject(e);on("blocked")}var Nk={connecting:{title:"GENEX",wordmark:!0},redirecting:{title:"GENEX",wordmark:!0},"blocked-standalone":{title:"Sign in to play",button:"Sign in",instant:!0},"blocked-embedded":{title:"Sign in on the Genex dashboard to continue",instant:!0}},Bk="https://cdn.genex.technology/fonts/GeistMono-variable.woff2",$y="'Geist Mono',ui-monospace,SFMono-Regular,Menlo,monospace",py=!1,hy="!<>-_/[]{}=+*^?#$%&@",jy=50,my=10,yy=[{name:"churn",ticks:5},{name:"settle",ticks:10},{name:"hold",ticks:12},{name:"dissolve",ticks:8}];function vf(t){let e="";for(let n=0;n<t;n++)e+=hy[Math.floor(Math.random()*hy.length)];return e}function Wy(){try{let t=et();return!t||typeof t.matchMedia!="function"?!0:t.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!0}}function Lk(t,e){if(Wy())return t.textContent=e,()=>{};let n=0;t.textContent=vf(e.length);let r=setInterval(()=>{if(n++,n>=my){t.textContent=e,clearInterval(r);return}let s=Math.floor(n/my*e.length);t.textContent=e.slice(0,s)+vf(e.length-s)},jy);return()=>clearInterval(r)}function Fk(t,e){if(Wy())return t.textContent=e,()=>{};let n=0,r=0,s=()=>{let i=yy[n],a;i.name==="churn"?a=0:i.name==="settle"?a=Math.floor(r/i.ticks*e.length):i.name==="hold"?a=e.length:a=e.length-Math.floor(r/i.ticks*e.length),t.textContent=e.slice(0,a)+vf(e.length-a),r++,r>=i.ticks&&(r=0,n=(n+1)%yy.length)};s();let o=setInterval(s,jy);return()=>clearInterval(o)}function qy(t){if(!py){py=!0;try{let e=et()?.FontFace,n=t.fonts;if(!e||!n?.add)return;new e("Geist Mono",`url(${Bk}) format('woff2')`,{weight:"100 900",display:"swap"}).load().then(s=>n.add(s)).catch(()=>{})}catch{}}}function Tu(t){let e=Of();if(e?.createElement)try{pa||(pa=zk(e)),pa.setContent(t)}catch{}}function vu(t=!1){try{let e=pa;if(pa=null,!e)return;e.stopText();let n=e.root;if(t||!n.style){n.remove?.();return}n.style.pointerEvents="none",n.style.transition="opacity 180ms ease",n.style.opacity="0",setTimeout(()=>{try{n.remove?.()}catch{}},220)}catch{}}function zk(t){qy(t);let e=t.createElement("div");e.setAttribute("data-genex-embed-overlay",""),e.style.cssText=`position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:14px;background:#000;color:#fff;font-family:${$y};text-align:center;pointer-events:auto;user-select:none`;let n=t.createElement("div");n.style.cssText="font-size:13px;font-weight:400;line-height:1.3;padding:0 24px;opacity:0;min-height:1.3em;font-variant-ligatures:none",e.appendChild(n);let r=t.createElement("button");r.style.cssText="font-family:inherit;font-size:13px;font-weight:500;line-height:1.3;padding:8px 22px;border-radius:9px;border:none;cursor:pointer;background:#4b60bf;color:#fff;display:none",r.addEventListener("mouseenter",()=>{r.style.background="#3f51a8"}),r.addEventListener("mouseleave",()=>{r.style.background="#4b60bf"}),r.addEventListener("click",()=>{let c=et();c&&(r.disabled=!0,If(),Pu(c))}),e.appendChild(r);let s=()=>{t.body&&!e.isConnected&&t.body.appendChild(e)};t.body?s():t.addEventListener?.("DOMContentLoaded",s);let o,i,a=()=>{o!==void 0&&(clearTimeout(o),o=void 0),i&&(i(),i=void 0)};return{root:e,stopText:a,setContent(c){let u=Nk[c];a(),n.textContent=u.title,n.style.letterSpacing=u.wordmark?"0.22em":"",n.style.marginRight=u.wordmark?"-0.22em":"";let l=()=>{n.style.opacity="1",i=u.wordmark?Fk(n,u.title):Lk(n,u.title)};u.instant||oy<=0?l():(n.style.opacity="0",o=setTimeout(()=>{o=void 0,l()},oy)),r.style.display=u.button?"inline-block":"none",u.button&&(r.textContent=u.button),s()}}}function Uk(){let t=Of();if(!(!t?.createElement||_u))try{_u=Vk(t)}catch{}}function Vf(){Us!==void 0&&(clearTimeout(Us),Us=void 0);try{_u?.root?.remove?.()}catch{}_u=null}function Vk(t){qy(t);let e=!1;try{let c=et(),u=c?.navigator;if(c&&u){let l=c.matchMedia?.("(pointer: coarse)").matches??!1,d=(u.maxTouchPoints??0)>1,f=u.userAgentData?u.userAgentData.mobile:/Mobi|Android/i.test(u.userAgent??"");e=d&&l||f}}catch{}let n=t.createElement("div");n.setAttribute("data-genex-guest-popover",""),n.style.cssText="position:fixed;top:calc(12px + env(safe-area-inset-top));right:calc(12px + env(safe-area-inset-right));z-index:2147483646;display:flex;justify-content:flex-end;pointer-events:none";let r=t.createElement("div");r.style.cssText=`display:flex;align-items:center;border-radius:12px;background:rgba(0,0,0,0.85);color:#fff;font-family:${$y};box-shadow:0 4px 24px rgba(0,0,0,0.4);pointer-events:auto;user-select:none;`+(e?"gap:8px;padding:8px 8px 8px 12px;font-size:12px;max-width:calc(100vw - 88px)":"gap:12px;padding:10px 12px 10px 16px;font-size:13px"),n.appendChild(r);let s=t.createElement("span");s.textContent=!e&&sn?.name?`Playing as ${sn.name} \u2014 sign in to save progress`:"Sign in to save progress",e&&(s.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap"),r.appendChild(s);let o=t.createElement("button");o.textContent="Sign in",o.style.cssText="font-family:inherit;font-weight:500;border-radius:9px;border:none;cursor:pointer;background:#4b60bf;color:#fff;"+(e?"font-size:12px;padding:5px 12px":"font-size:13px;padding:6px 16px"),o.addEventListener("mouseenter",()=>{o.style.background="#3f51a8"}),o.addEventListener("mouseleave",()=>{o.style.background="#4b60bf"}),o.addEventListener("click",()=>{let c=et();c&&(o.disabled=!0,If(),Pu(c))}),r.appendChild(o);let i=t.createElement("button");if(i.textContent="\xD7",i.setAttribute("aria-label","Dismiss"),i.style.cssText="font-size:16px;line-height:1;padding:6px 8px;border:none;cursor:pointer;background:transparent;color:rgba(255,255,255,0.6)",i.addEventListener("click",()=>{ok(),Vf()}),r.appendChild(i),e){let c=t.createElement("button");c.setAttribute("aria-label","Sign in to save progress"),c.style.cssText="display:none;width:44px;height:44px;border-radius:50%;border:none;cursor:pointer;background:rgba(0,0,0,0.55);color:#fff;align-items:center;justify-content:center;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);pointer-events:auto",c.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>',n.appendChild(c);let u=l=>{r.style.display=l?"none":"flex",c.style.display=l?"flex":"none"};Us=setTimeout(()=>u(!0),5e3),r.addEventListener("pointerdown",()=>{Us!==void 0&&clearTimeout(Us),Us=void 0}),c.addEventListener("click",()=>u(!1))}let a=()=>{t.body&&!n.isConnected&&t.body.appendChild(n)};return t.body?a():t.addEventListener?.("DOMContentLoaded",a),{root:n}}ty({getShell:ak,isLocalTest:()=>{let t=et();return!t||Wt()?!1:Go?os:zf(t,!1)},getConfig:()=>Be,getParentOrigin:()=>is,getShellCaps:()=>Ey});var rh={};of(rh,{chatSend:()=>yv,claim:()=>gv,claimAsHost:()=>bv,connect:()=>ov,destroy:()=>Sv,dispose:()=>iv,drainEventsJson:()=>Mv,leave:()=>lw,listen:()=>pv,objectsJson:()=>Tv,open:()=>sv,playersJson:()=>Pv,release:()=>wv,reportEliminated:()=>xv,reportFinish:()=>Rv,reportScore:()=>_v,send:()=>fv,sendInput:()=>hv,serverNow:()=>Ev,sessionJson:()=>Av,setIdentity:()=>ev,setMe:()=>av,setObject:()=>lv,setRoomOpen:()=>mv,setShared:()=>uv,sharedJson:()=>vv,snapMe:()=>cv,snapObject:()=>dv,timeUntil:()=>kv,version:()=>QT});var ga={ready(t){let e=globalThis.__GENEX__;return t&&e&&typeof e.apiUrl=="string"&&Array.isArray(e.dashboardOrigins)&&ku({slug:t,apiUrl:e.apiUrl,dashboardOrigins:e.dashboardOrigins.filter(n=>typeof n=="string")}),Df()},auth:()=>Au(),urls:()=>Ay()},Hk=4096;function ye(t,e){t.q.length>=Hk&&(t.overflowed?t.q.splice(1,1):(t.overflowed=!0,t.q.splice(0,2,{type:"warning",message:"genex bridge: event queue full; drain it every frame (oldest events dropped)"}))),t.q.push(e)}var Xo=t=>({type:"warning",message:`genex bridge: ${t}`});function $k(t){try{return JSON.stringify(t)}catch(e){let n=typeof t.kind=="string"?t.kind:t.type;return JSON.stringify(Xo(`event ${JSON.stringify(n)} dropped: JSON cannot carry it (${tr(e)})`))}}function Mu(t){return t.overflowed=!1,`[${t.q.splice(0).map($k).join(",")}]`}var Mn=t=>!!t&&typeof t=="object"&&!Array.isArray(t),Jo=t=>{let e=Mn(t)||t instanceof Error?t.code:void 0;return typeof e=="number"&&Number.isFinite(e)?e:0},tr=t=>t instanceof Error?t.message:typeof t=="string"?t:"join failed";function ba(t,e){if(typeof t!="string")throw new TypeError(`genex bridge: ${e} must be a JSON string`);return JSON.parse(t)}function nr(t,e){let n=ba(t,e);if(!Mn(n))throw new TypeError(`genex bridge: ${e} must be a JSON object`);return n}ArrayBuffer.isView||(ArrayBuffer.isView=t=>t!==null&&typeof t=="object"&&t.buffer instanceof ArrayBuffer);typeof globalThis>"u"&&typeof window<"u"&&(window.globalThis=window);typeof FormData>"u"&&(globalThis.FormData=class{});Pr();var rr=class extends Error{constructor(n,r,s){super(r);m(this,"code");m(this,"headers");m(this,"status");m(this,"response");m(this,"data");this.name="ServerError",this.code=n,s&&(this.headers=s.headers,this.status=s.status,this.response=s.response,this.data=s.data)}};var wa=class t extends Error{constructor(n,r){super(n);m(this,"code");this.code=r,this.name="MatchMakeError",Object.setPrototypeOf(this,t.prototype)}};Pr();Pt();Pt();Pt();Pt();Pt();Pt();Pt();Pt();var wb=256,fp=5,Js=class Js{constructor(e,n={}){m(this,"instance");m(this,"mode");m(this,"historySize");m(this,"_desc");m(this,"_numFields");m(this,"_slots");m(this,"_slotLens");m(this,"_slotHead",0);m(this,"_slotCount",0);m(this,"_outBuffer");m(this,"_seq",0);m(this,"_encoder");this.instance=e,this.mode=n.mode??"reliable",this.historySize=this.mode==="unreliable"?Math.max(1,n.historySize??3):1,this._desc=sp(e);let r=this._desc.metadata?.[At];if(r===void 0)throw new Error(`InputEncoder: '${e.constructor.name}' has no fields`);this._numFields=r;for(let s=0;s<=r;s++)if(this._desc.names[s]!==void 0&&this._desc.encoders[s]===void 0)throw new Error(`InputEncoder: non-primitive field '${this._desc.names[s]}' on '${e.constructor.name}' is not supported. Use Encoder for state containing refs/collections.`);if(this.mode==="unreliable"){this._slots=new Array(this.historySize),this._slotLens=new Array(this.historySize).fill(0);for(let s=0;s<this.historySize;s++)this._slots[s]=new Uint8Array(wb);this._outBuffer=new Uint8Array((wb+fp)*this.historySize)}this._encoder=new Ta(e)}get seq(){return this._seq}encode(){let e=this._produceDelta();return this.mode==="reliable"?e:this._pushAndEmitRing(e)}reset(){this._slotHead=0,this._slotCount=0,this._encoder.discardChanges();let e=this.instance[I],n=this.instance[Mt];for(let r=0;r<=this._numFields;r++)n[r]===void 0||n[r]===null||e.markDirty(r)}copyInto(e){let n=this.instance[Mt],r=e[Mt];for(let s=0;s<=this._numFields;s++)r[s]=n[s]}_produceDelta(){let e=this._encoder.encode();return this._encoder.discardChanges(),e}_pushAndEmitRing(e){this._seq++;let n=this._slots[this._slotHead];return e.length>n.byteLength&&(n=this._slots[this._slotHead]=Js._grow(n,e.length,"unreliable ring slot")),n.set(e),this._slotLens[this._slotHead]=e.length,this._slotHead=(this._slotHead+1)%this.historySize,this._slotCount<this.historySize&&this._slotCount++,this._emitRing()}_emitRing(){let e=this._seq-this._slotCount+1,n=fp;for(let i=0;i<this._slotCount;i++)n+=this._slotLens[i]+fp;let r=this._outBuffer;n>r.byteLength&&(r=this._outBuffer=Js._grow(r,n,"unreliable output packet"));let s={offset:0};Se.number(r,e,s);let o=(this._slotHead-this._slotCount+this.historySize)%this.historySize;for(let i=0;i<this._slotCount;i++){let a=(o+i)%this.historySize,c=this._slotLens[a];Se.number(r,c,s),r.set(this._slots[a].subarray(0,c),s.offset),s.offset+=c}return r.subarray(0,s.offset)}static _grow(e,n,r){let s=Math.max(n,e.byteLength*2);return Js._warned||(Js._warned=!0,console.warn(`@colyseus/schema/input: InputEncoder buffer overflow in ${r}. Growing to ${s} bytes.`)),new Uint8Array(s)}};m(Js,"_warned",!1);var sl=Js;Pr();hp();ul();var Zs,Un,ai,Fa,za,Ua,Va,Ha,$a,ci,ja,ll,Rb,ui=class{constructor(e){He(this,ll);He(this,Zs);He(this,Un);He(this,ai);He(this,Fa);He(this,za,!1);He(this,Ua);He(this,Va,!1);He(this,Ha,!1);He(this,$a);He(this,ci);He(this,ja);$e(this,Zs,e)}get patchRate(){return de(this,ci)}applyReflection(e,n,r){let s=zn.decode(e.subarray(0,r),n);zn.makeEncodable(s.state.constructor),$e(this,Ua,s.state.constructor),de(this,Zs).clock===ii&&(de(this,Zs).clock=new cl)}applyOptions(e,n){let r=e[n.offset++];$e(this,Va,(r&$s.RENDER_TIME)!==0),$e(this,Ha,(r&$s.RECKON_TIME)!==0),r&$s.FIXED_TIMESTEP&&$e(this,$a,Pe.number(e,n)),r&$s.PATCH_RATE&&$e(this,ci,Pe.number(e,n)),r&$s.SUB_STEPS&&$e(this,ja,Pe.number(e,n))}ackInput(e){return de(this,Un)?de(this,Un).ackInput(e):-1}reset(){de(this,Un)?.reset()}handle(e){if(de(this,Un))return e!==void 0&&zs(this,ll,Rb).call(this,e),de(this,Un);let n=e?.type??de(this,Ua);if(!n)throw new Error("room.input(): no input schema available. The server room must call `defineInput(YourInput)`, or you can pass `{ type: YourInput }` explicitly.");let r=new n,s=new sl(r,e);return $e(this,Un,new oi(de(this,Zs),r,s,{stampRender:de(this,Va),stampReckon:de(this,Ha),renderDelay:e?.renderDelay,allowRewind:e?.allowRewind,tickRate:de(this,$a),patchRate:de(this,ci),subSteps:de(this,ja)})),$e(this,ai,e),$e(this,Fa,s),de(this,Un)}};Zs=new WeakMap,Un=new WeakMap,ai=new WeakMap,Fa=new WeakMap,za=new WeakMap,Ua=new WeakMap,Va=new WeakMap,Ha=new WeakMap,$a=new WeakMap,ci=new WeakMap,ja=new WeakMap,ll=new WeakSet,Rb=function(e){if(de(this,za))return;let n=de(this,Un),r=[];e.type!==void 0&&e.type!==n.data?.constructor&&r.push("type"),e.mode!==void 0&&e.mode!==n.mode&&r.push("mode"),e.historySize!==void 0&&n.mode==="unreliable"&&e.historySize!==de(this,Fa).historySize&&r.push("historySize"),e.renderDelay!==void 0&&e.renderDelay!==de(this,ai)?.renderDelay&&r.push("renderDelay"),e.allowRewind!==void 0!=(de(this,ai)?.allowRewind!==void 0)&&r.push("allowRewind"),r.length!==0&&($e(this,za,!0),console.warn(`@colyseus/sdk: room.input() options ignored \u2014 the input handle was already created by an earlier call (first call wins). Differing: ${r.join(", ")}.`))};var yp;try{yp=new TextDecoder}catch{}var Z,_n,O=0;var Db=[],gp=Db,bp=0,Le={},Ce,hs,xn=0,dr=0,_t,Dr,Yt=[],ve,Eb={useRecords:!1,mapsAsObjects:!0},Wa=class{},Sp=new Wa;Sp.name="MessagePack 0xC1";var ms=!1,kb=2;var ys=class t{constructor(e){e&&(e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.sequential&&e.trusted!==!1&&(e.trusted=!0,!e.structures&&e.useRecords!=!1&&(e.structures=[],e.maxSharedStructures||(e.maxSharedStructures=0))),e.structures?e.structures.sharedLength=e.structures.length:e.getStructures&&((e.structures=[]).uninitialized=!0,e.structures.sharedLength=0),e.int64AsNumber&&(e.int64AsType="number")),Object.assign(this,e)}unpack(e,n){if(Z)return zb(()=>(fl(),this?this.unpack(e,n):t.prototype.unpack.call(Eb,e,n)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof n=="object"?(_n=n.end||e.length,O=n.start||0):(O=0,_n=n>-1?n:e.length),bp=0,dr=0,hs=null,gp=Db,_t=null,Z=e;try{ve=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw Z=null,e instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof t){if(Le=this,this.structures)return Ce=this.structures,dl(n);(!Ce||Ce.length>0)&&(Ce=[])}else Le=Eb,(!Ce||Ce.length>0)&&(Ce=[]);return dl(n)}unpackMultiple(e,n){let r,s=0;try{ms=!0;let o=e.length,i=this?this.unpack(e,o):hl.unpack(e,o);if(n){if(n(i,s,O)===!1)return;for(;O<o;)if(s=O,n(dl(),s,O)===!1)return}else{for(r=[i];O<o;)s=O,r.push(dl());return r}}catch(o){throw o.lastPosition=s,o.values=r,o}finally{ms=!1,fl()}}_mergeStructures(e,n){this._onLoadedStructures&&(e=this._onLoadedStructures(e)),e=e||[],Object.isFrozen(e)&&(e=e.map(r=>r.slice(0)));for(let r=0,s=e.length;r<s;r++){let o=e[r];o&&(o.isShared=!0,r>=32&&(o.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in n||[])if(r>=0){let s=e[r],o=n[r];o&&(s&&((e.restoreStructures||(e.restoreStructures=[]))[r]=s),e[r]=o)}return this.structures=e}decode(e,n){return this.unpack(e,n)}};function dl(t){try{if(!Le.trusted&&!ms){let n=Ce.sharedLength||0;n<Ce.length&&(Ce.length=n)}let e;if(Le._readStruct&&Z[O]<64&&Z[O]>=32?(e=Le._readStruct(Z,O,_n),Z=null,!(t&&t.lazy)&&e&&(e=e.toJSON()),O=_n):e=ot(),_t&&(O=_t.postBundlePosition,_t=null),ms&&(Ce.restoreStructures=null),O==_n)Ce&&Ce.restoreStructures&&Ab(),Ce=null,Z=null,Dr&&(Dr=null);else{if(O>_n)throw new Error("Unexpected end of MessagePack data");if(!ms){let n;try{n=JSON.stringify(e,(r,s)=>typeof s=="bigint"?`${s}n`:s).slice(0,100)}catch(r){n="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+n)}}return e}catch(e){throw Ce&&Ce.restoreStructures&&Ab(),fl(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||O>_n)&&(e.incomplete=!0),e}}function Ab(){for(let t in Ce.restoreStructures)Ce[t]=Ce.restoreStructures[t];Ce.restoreStructures=null}function ot(){let t=Z[O++];if(t<160)if(t<128){if(t<64)return t;{let e=Ce[t&63]||Le.getStructures&&Nb()[t&63];return e?(e.read||(e.read=xp(e,t&63)),e.read()):t}}else if(t<144)if(t-=128,Le.mapsAsObjects){let e={};for(let n=0;n<t;n++){let r=Lb();r==="__proto__"&&(r="__proto_"),e[r]=ot()}return e}else{let e=new Map;for(let n=0;n<t;n++)e.set(ot(),ot());return e}else{t-=144;let e=new Array(t);for(let n=0;n<t;n++)e[n]=ot();return Le.freezeData?Object.freeze(e):e}else if(t<192){let e=t-160;if(dr>=O)return hs.slice(O-xn,(O+=e)-xn);if(dr==0&&_n<140){let n=e<16?_p(e):Bb(e);if(n!=null)return n}return wp(e)}else{let e;switch(t){case 192:return null;case 193:return _t?(e=ot(),e>0?_t[1].slice(_t.position1,_t.position1+=e):_t[0].slice(_t.position0,_t.position0-=e)):Sp;case 194:return!1;case 195:return!0;case 196:if(e=Z[O++],e===void 0)throw new Error("Unexpected end of buffer");return mp(e);case 197:return e=ve.getUint16(O),O+=2,mp(e);case 198:return e=ve.getUint32(O),O+=4,mp(e);case 199:return Qs(Z[O++]);case 200:return e=ve.getUint16(O),O+=2,Qs(e);case 201:return e=ve.getUint32(O),O+=4,Qs(e);case 202:if(e=ve.getFloat32(O),Le.useFloat32>2){let n=pl[(Z[O]&127)<<1|Z[O+1]>>7];return O+=4,(n*e+(e>0?.5:-.5)>>0)/n}return O+=4,e;case 203:return e=ve.getFloat64(O),O+=8,e;case 204:return Z[O++];case 205:return e=ve.getUint16(O),O+=2,e;case 206:return e=ve.getUint32(O),O+=4,e;case 207:return Le.int64AsType==="number"?(e=ve.getUint32(O)*4294967296,e+=ve.getUint32(O+4)):Le.int64AsType==="string"?e=ve.getBigUint64(O).toString():Le.int64AsType==="auto"?(e=ve.getBigUint64(O),e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=ve.getBigUint64(O),O+=8,e;case 208:return ve.getInt8(O++);case 209:return e=ve.getInt16(O),O+=2,e;case 210:return e=ve.getInt32(O),O+=4,e;case 211:return Le.int64AsType==="number"?(e=ve.getInt32(O)*4294967296,e+=ve.getUint32(O+4)):Le.int64AsType==="string"?e=ve.getBigInt64(O).toString():Le.int64AsType==="auto"?(e=ve.getBigInt64(O),e>=BigInt(-2)<<BigInt(52)&&e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=ve.getBigInt64(O),O+=8,e;case 212:if(e=Z[O++],e==114)return Ob(Z[O++]&63);{let n=Yt[e];if(n)return n.read?(O++,n.read(ot())):n.noBuffer?(O++,n()):n(Z.subarray(O,++O));throw new Error("Unknown extension "+e)}case 213:return e=Z[O],e==114?(O++,Ob(Z[O++]&63,Z[O++])):Qs(2);case 214:return Qs(4);case 215:return Qs(8);case 216:return Qs(16);case 217:return e=Z[O++],dr>=O?hs.slice(O-xn,(O+=e)-xn):IP(e);case 218:return e=ve.getUint16(O),O+=2,dr>=O?hs.slice(O-xn,(O+=e)-xn):DP(e);case 219:return e=ve.getUint32(O),O+=4,dr>=O?hs.slice(O-xn,(O+=e)-xn):NP(e);case 220:return e=ve.getUint16(O),O+=2,Tb(e);case 221:return e=ve.getUint32(O),O+=4,Tb(e);case 222:return e=ve.getUint16(O),O+=2,vb(e);case 223:return e=ve.getUint32(O),O+=4,vb(e);default:if(t>=224)return t-256;if(t===void 0){let n=new Error("Unexpected end of MessagePack data");throw n.incomplete=!0,n}throw new Error("Unknown MessagePack token "+t)}}}var OP=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function xp(t,e){function n(){if(n.count++>kb){let s;try{s=t.read=new Function("r","return function(){return "+(Le.freezeData?"Object.freeze":"")+"({"+t.map(o=>o==="__proto__"?"__proto_:r()":OP.test(o)?o+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"})}")(ot)}catch{return kb=1/0,n()}return t.read0=s,t.highByte===0&&(t.read=Pb(e,t.read)),s()}let r={};for(let s=0,o=t.length;s<o;s++){let i=t[s];i==="__proto__"&&(i="__proto_"),r[i]=ot()}return Le.freezeData?Object.freeze(r):r}return n.count=0,t.read0=n,t.highByte===0?Pb(e,n):n}var Pb=(t,e)=>function(){let n=Z[O++];if(n===0)return e();let r=t<32?-(t+(n<<5)):t+(n<<5),s=Ce[r]||Nb()[r];if(!s)throw new Error("Record id is not defined for "+r);return s.read||(s.read=xp(s,t)),s.read()};function Nb(){let t=zb(()=>(Z=null,Le.getStructures()));return Ce=Le._mergeStructures(t,Ce)}var wp=qa,IP=qa,DP=qa,NP=qa;function qa(t){let e;if(t<16&&(e=_p(t)))return e;if(t>64&&yp)return yp.decode(Z.subarray(O,O+=t));let n=O+t,r=[];for(e="";O<n;){let s=Z[O++];if((s&128)===0)r.push(s);else if((s&224)===192){let o=Z[O++]&63,i=(s&31)<<6|o;i<128?r.push(65533):r.push(i)}else if((s&240)===224){let o=Z[O++]&63,i=Z[O++]&63,a=(s&31)<<12|o<<6|i;a<2048||a>=55296&&a<=57343?r.push(65533):r.push(a)}else if((s&248)===240){let o=Z[O++]&63,i=Z[O++]&63,a=Z[O++]&63,c=(s&7)<<18|o<<12|i<<6|a;c<65536||c>1114111?r.push(65533):(c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c))}else r.push(65533);r.length>=4096&&(e+=xt.apply(String,r),r.length=0)}return r.length>0&&(e+=xt.apply(String,r)),e}function Tb(t){let e=new Array(t);for(let n=0;n<t;n++)e[n]=ot();return Le.freezeData?Object.freeze(e):e}function vb(t){if(Le.mapsAsObjects){let e={};for(let n=0;n<t;n++){let r=Lb();r==="__proto__"&&(r="__proto_"),e[r]=ot()}return e}else{let e=new Map;for(let n=0;n<t;n++)e.set(ot(),ot());return e}}var xt=String.fromCharCode;function Bb(t){let e=O,n=new Array(t);for(let r=0;r<t;r++){let s=Z[O++];if((s&128)>0){O=e;return}n[r]=s}return xt.apply(String,n)}function _p(t){if(t<4)if(t<2){if(t===0)return"";{let e=Z[O++];if((e&128)>1){O-=1;return}return xt(e)}}else{let e=Z[O++],n=Z[O++];if((e&128)>0||(n&128)>0){O-=2;return}if(t<3)return xt(e,n);let r=Z[O++];if((r&128)>0){O-=3;return}return xt(e,n,r)}else{let e=Z[O++],n=Z[O++],r=Z[O++],s=Z[O++];if((e&128)>0||(n&128)>0||(r&128)>0||(s&128)>0){O-=4;return}if(t<6){if(t===4)return xt(e,n,r,s);{let o=Z[O++];if((o&128)>0){O-=5;return}return xt(e,n,r,s,o)}}else if(t<8){let o=Z[O++],i=Z[O++];if((o&128)>0||(i&128)>0){O-=6;return}if(t<7)return xt(e,n,r,s,o,i);let a=Z[O++];if((a&128)>0){O-=7;return}return xt(e,n,r,s,o,i,a)}else{let o=Z[O++],i=Z[O++],a=Z[O++],c=Z[O++];if((o&128)>0||(i&128)>0||(a&128)>0||(c&128)>0){O-=8;return}if(t<10){if(t===8)return xt(e,n,r,s,o,i,a,c);{let u=Z[O++];if((u&128)>0){O-=9;return}return xt(e,n,r,s,o,i,a,c,u)}}else if(t<12){let u=Z[O++],l=Z[O++];if((u&128)>0||(l&128)>0){O-=10;return}if(t<11)return xt(e,n,r,s,o,i,a,c,u,l);let d=Z[O++];if((d&128)>0){O-=11;return}return xt(e,n,r,s,o,i,a,c,u,l,d)}else{let u=Z[O++],l=Z[O++],d=Z[O++],f=Z[O++];if((u&128)>0||(l&128)>0||(d&128)>0||(f&128)>0){O-=12;return}if(t<14){if(t===12)return xt(e,n,r,s,o,i,a,c,u,l,d,f);{let h=Z[O++];if((h&128)>0){O-=13;return}return xt(e,n,r,s,o,i,a,c,u,l,d,f,h)}}else{let h=Z[O++],p=Z[O++];if((h&128)>0||(p&128)>0){O-=14;return}if(t<15)return xt(e,n,r,s,o,i,a,c,u,l,d,f,h,p);let y=Z[O++];if((y&128)>0){O-=15;return}return xt(e,n,r,s,o,i,a,c,u,l,d,f,h,p,y)}}}}}function Mb(){let t=Z[O++],e;if(t<192)e=t-160;else switch(t){case 217:e=Z[O++];break;case 218:e=ve.getUint16(O),O+=2;break;case 219:e=ve.getUint32(O),O+=4;break;default:throw new Error("Expected string")}return qa(e)}function mp(t){return Le.copyBuffers?Uint8Array.prototype.slice.call(Z,O,O+=t):Z.subarray(O,O+=t)}function Qs(t){let e=Z[O++];if(Yt[e]){let n;return Yt[e](Z.subarray(O,n=O+=t),r=>{O=r;try{return ot()}finally{O=n}})}else throw new Error("Unknown extension type "+e)}var Cb=new Array(4096);function Lb(){let t=Z[O++];if(t>=160&&t<192){if(t=t-160,dr>=O)return hs.slice(O-xn,(O+=t)-xn);if(!(dr==0&&_n<180))return wp(t)}else return O--,Fb(ot());let e=(t<<5^(t>1?ve.getUint16(O):t>0?Z[O]:0))&4095,n=Cb[e],r=O,s=O+t-3,o,i=0;if(n&&n.bytes==t){for(;r<s;){if(o=ve.getUint32(r),o!=n[i++]){r=1879048192;break}r+=4}for(s+=3;r<s;)if(o=Z[r++],o!=n[i++]){r=1879048192;break}if(r===s)return O=r,n.string;s-=3,r=O}for(n=[],Cb[e]=n,n.bytes=t;r<s;)o=ve.getUint32(r),n.push(o),r+=4;for(s+=3;r<s;)o=Z[r++],n.push(o);let a=t<16?_p(t):Bb(t);return a!=null?n.string=a:n.string=wp(t)}function Fb(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(t==null)return t+"";if(Le.allowArraysInMapKeys&&Array.isArray(t)&&t.flat().every(e=>["string","number","boolean","bigint"].includes(typeof e)))return t.flat().toString();throw new Error(`Invalid property type for record: ${typeof t}`)}var Ob=(t,e)=>{let n=ot().map(Fb),r=t;e!==void 0&&(t=t<32?-((e<<5)+t):(e<<5)+t,n.highByte=e);let s=Ce[t];return s&&(s.isShared||ms)&&((Ce.restoreStructures||(Ce.restoreStructures=[]))[t]=s),Ce[t]=n,n.read=xp(n,r),(n.read0||n.read)()};Yt[0]=()=>{};Yt[0].noBuffer=!0;Yt[66]=t=>{let e=t.byteLength%8||8,n=BigInt(t[0]&128?t[0]-256:t[0]);for(let r=1;r<e;r++)n<<=BigInt(8),n+=BigInt(t[r]);if(t.byteLength!==e){let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=(o,i)=>{let a=i-o;if(a<=40){let d=r.getBigUint64(o);for(let f=o+8;f<i;f+=8)d<<=BigInt(64),d|=r.getBigUint64(f);return d}let c=o+(a>>4<<3),u=s(o,c),l=s(c,i);return u<<BigInt((i-c)*8)|l};n=n<<BigInt((r.byteLength-e)*8)|s(e,r.byteLength)}return n};var Ib={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError=="function"?AggregateError:null};Yt[101]=()=>{let t=ot();if(!Ib[t[0]]){let e=Error(t[1],{cause:t[2]});return e.name=t[0],e}return Ib[t[0]](t[1],{cause:t[2]})};Yt[105]=t=>{if(Le.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=ve.getUint32(O-4);Dr||(Dr=new Map);let n=Z[O],r;n>=144&&n<160||n==220||n==221?r=[]:n>=128&&n<144||n==222||n==223?r=new Map:(n>=199&&n<=201||n>=212&&n<=216)&&Z[O+1]===115?r=new Set:r={};let s={target:r};Dr.set(e,s);let o=ot();if(s.used)Object.assign(r,o);else return s.target=o;if(r instanceof Map)for(let[i,a]of o.entries())r.set(i,a);if(r instanceof Set)for(let i of Array.from(o))r.add(i);return r};Yt[112]=t=>{if(Le.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=ve.getUint32(O-4),n=Dr.get(e);return n.used=!0,n.target};Yt[115]=()=>new Set(ot());var Rp=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(t=>t+"Array"),BP=typeof globalThis=="object"?globalThis:window;Yt[116]=t=>{let e=t[0],n=Uint8Array.prototype.slice.call(t,1).buffer,r=Rp[e];if(!r){if(e===16)return n;if(e===17)return new DataView(n);throw new Error("Could not find typed array for code "+e)}return new BP[r](n)};Yt[120]=()=>{let t=ot();return new RegExp(t[0],t[1])};var LP=[];Yt[98]=t=>{let e=(t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3],n=O;return O+=e-t.length,_t=LP,_t=[Mb(),Mb()],_t.position0=0,_t.position1=0,_t.postBundlePosition=O,O=n,ot()};Yt[255]=t=>t.length==4?new Date((t[0]*16777216+(t[1]<<16)+(t[2]<<8)+t[3])*1e3):t.length==8?new Date(((t[0]<<22)+(t[1]<<14)+(t[2]<<6)+(t[3]>>2))/1e6+((t[3]&3)*4294967296+t[4]*16777216+(t[5]<<16)+(t[6]<<8)+t[7])*1e3):t.length==12?new Date(((t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3])/1e6+((t[4]&128?-281474976710656:0)+t[6]*1099511627776+t[7]*4294967296+t[8]*16777216+(t[9]<<16)+(t[10]<<8)+t[11])*1e3):new Date("invalid");function zb(t){Le&&Le._onSaveState&&Le._onSaveState();let e=_n,n=O,r=bp,s=xn,o=dr,i=hs,a=gp,c=Dr,u=_t,l=new Uint8Array(Z.slice(0,_n)),d=Ce,f=Ce.slice(0,Ce.length),h=Le,p=ms,y=t();return _n=e,O=n,bp=r,xn=s,dr=o,hs=i,gp=a,Dr=c,_t=u,Z=l,ms=p,Ce=d,Ce.splice(0,Ce.length,...f),Le=h,ve=new DataView(Z.buffer,Z.byteOffset,Z.byteLength),y}function fl(){Z=null,Dr=null,Ce=null}var pl=new Array(147);for(let t=0;t<256;t++)pl[t]=+("1e"+Math.floor(45.15-t*.30103));var hl=new ys({useRecords:!1}),ml=hl.unpack,FP=hl.unpackMultiple,zP=hl.unpack,yl={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},UP=new Float32Array(1),_L=new Uint8Array(UP.buffer,0,4);ys.SUPPORTS_STRUCT_HOOKS=!0;var bl;try{bl=new TextEncoder}catch{}var Ap,Pp,di=typeof Buffer<"u",gl=di?function(t){return Buffer.allocUnsafeSlow(t)}:Uint8Array,$b=di?Buffer:Uint8Array,Ub=di?4294967296:2144337920,F,Ga,je,D=0,Ot,Ze=null,VP=21760,HP=/[\u0080-\uFFFF]/,li=Symbol("record-id"),gs=class extends ys{constructor(e){super(e),this.offset=0;let n,r,s,o,i,a=$b.prototype.utf8Write?function(v,$){return F.utf8Write(v,$,F.byteLength-$)}:bl&&bl.encodeInto?function(v,$){return bl.encodeInto(v,F.subarray($)).written}:!1,c=this;e||(e={});let u=e&&e.sequential,l=e.structures||e.saveStructures,d=e.maxSharedStructures;if(d==null&&(d=l?32:0),d>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let f=e.maxOwnStructures;f==null&&(f=l?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let h=d>32||f+d>64,p=d+64,y=d+f+64;if(y>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let S=[],b=0,x=0;this.pack=this.encode=function(v,$){if(F||(F=new gl(8192),je=F.dataView||(F.dataView=new DataView(F.buffer,0,8192)),D=0),Ot=F.length-10,Ot-D<2048?(F=new gl(F.length),je=F.dataView||(F.dataView=new DataView(F.buffer,0,F.length)),Ot=F.length-10,D=0):D=D+7&2147483640,r=D,$&fi&&(D+=$&255),i=c.structuredClone?new Map:null,c.bundleStrings&&typeof v!="string"?(Ze=[],Ze.size=1/0):Ze=null,o=c.structures,o){o.uninitialized&&(o=c._mergeStructures(c.getStructures()));let W=o.sharedLength||0;if(W>d)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+o.sharedLength);if(!o.transitions){o.transitions=Object.create(null);for(let q=0;q<W;q++){let ae=o[q];if(!ae)continue;let ce,ne=o.transitions;for(let Re=0,oe=ae.length;Re<oe;Re++){let ee=ae[Re];ce=ne[ee],ce||(ce=ne[ee]=Object.create(null)),ne=ce}ne[li]=q+64}this.lastNamedStructuresLength=W}u||(o.nextId=W+64)}s&&(s=!1);let G;try{c._writeStruct&&v&&typeof v=="object"?v.constructor===Object?K(v):v.constructor!==Map&&!Array.isArray(v)&&!Pp.some(q=>v instanceof q)?K(v.toJSON?v.toJSON():v):E(v):E(v);let W=Ze;if(Ze&&Hb(r,E,0),i&&i.idsToInsert){let q=i.idsToInsert.sort((Re,oe)=>Re.offset>oe.offset?1:-1),ae=q.length,ce=-1;for(;W&&ae>0;){let Re=q[--ae].offset+r;Re<W.stringsPosition+r&&ce===-1&&(ce=0),Re>W.position+r?ce>=0&&(ce+=6):(ce>=0&&(je.setUint32(W.position+r,je.getUint32(W.position+r)+ce),ce=-1),W=W.previous,ae++)}ce>=0&&W&&je.setUint32(W.position+r,je.getUint32(W.position+r)+ce),D+=q.length*6,D>Ot&&j(D),c.offset=D;let ne=$P(F.subarray(r,D),q);return i=null,ne}return c.offset=D,$&Wb?(F.start=r,F.end=D,F):F.subarray(r,D)}catch(W){throw G=W,W}finally{if(o&&(R(),s&&c.saveStructures)){let W=o.sharedLength||0,q=F.subarray(r,D),ae=(c._prepareStructures||jP)(o,c);if(!G)return c.saveStructures(ae,ae.isCompatible)===!1?(o.uninitialized=!0,c.pack(v,$)):(c.lastNamedStructuresLength=W,F.length>1073741824&&(F=null),q)}F.length>1073741824&&(F=null),$&qb&&(D=r)}};let R=()=>{x<10&&x++;let v=o.sharedLength||0;if(o.length>v&&!u&&(o.length=v),b>1e4)o.transitions=null,x=0,b=0,S.length>0&&(S=[]);else if(S.length>0&&!u){for(let $=0,G=S.length;$<G;$++)S[$][li]=0;S=[]}},A=v=>{var $=v.length;$<16?F[D++]=144|$:$<65536?(F[D++]=220,F[D++]=$>>8,F[D++]=$&255):(F[D++]=221,je.setUint32(D,$),D+=4);for(let G=0;G<$;G++)E(v[G])},E=v=>{D>Ot&&(F=j(D));var $=typeof v,G;if($==="string"){let W=v.length;if(Ze&&W>=4&&W<4096){if((Ze.size+=W)>VP){let ne,Re=(Ze[0]?Ze[0].length*3+Ze[1].length:0)+10;D+Re>Ot&&(F=j(D+Re));let oe;Ze.position?(oe=Ze,F[D]=200,D+=3,F[D++]=98,ne=D-r,D+=4,Hb(r,E,0),je.setUint16(ne+r-3,D-r-ne)):(F[D++]=214,F[D++]=98,ne=D-r,D+=4),Ze=["",""],Ze.previous=oe,Ze.size=0,Ze.position=ne}let ce=HP.test(v);Ze[ce?0:1]+=v,F[D++]=193,E(ce?-W:W);return}let q;W<32?q=1:W<256?q=2:W<65536?q=3:q=5;let ae=W*3;if(D+ae>Ot&&(F=j(D+ae)),W<64||!a){let ce,ne,Re,oe=D+q;for(ce=0;ce<W;ce++)ne=v.charCodeAt(ce),ne<128?F[oe++]=ne:ne<2048?(F[oe++]=ne>>6|192,F[oe++]=ne&63|128):(ne&64512)===55296&&((Re=v.charCodeAt(ce+1))&64512)===56320?(ne=65536+((ne&1023)<<10)+(Re&1023),ce++,F[oe++]=ne>>18|240,F[oe++]=ne>>12&63|128,F[oe++]=ne>>6&63|128,F[oe++]=ne&63|128):(F[oe++]=ne>>12|224,F[oe++]=ne>>6&63|128,F[oe++]=ne&63|128);G=oe-D-q}else G=a(v,D+q);G<32?F[D++]=160|G:G<256?(q<2&&F.copyWithin(D+2,D+1,D+1+G),F[D++]=217,F[D++]=G):G<65536?(q<3&&F.copyWithin(D+3,D+2,D+2+G),F[D++]=218,F[D++]=G>>8,F[D++]=G&255):(q<5&&F.copyWithin(D+5,D+3,D+3+G),F[D++]=219,je.setUint32(D,G),D+=4),D+=G}else if($==="number")if(v>>>0===v)v<32||v<128&&this.useRecords===!1||v<64&&!this._writeStruct?F[D++]=v:v<256?(F[D++]=204,F[D++]=v):v<65536?(F[D++]=205,F[D++]=v>>8,F[D++]=v&255):(F[D++]=206,je.setUint32(D,v),D+=4);else if(v>>0===v)v>=-32?F[D++]=256+v:v>=-128?(F[D++]=208,F[D++]=v+256):v>=-32768?(F[D++]=209,je.setInt16(D,v),D+=2):(F[D++]=210,je.setInt32(D,v),D+=4);else{let W;if((W=this.useFloat32)>0&&v<4294967296&&v>=-2147483648){F[D++]=202,je.setFloat32(D,v);let q;if(W<4||(q=v*pl[(F[D]&127)<<1|F[D+1]>>7])>>0===q){D+=4;return}else D--}F[D++]=203,je.setFloat64(D,v),D+=8}else if($==="object"||$==="function")if(!v)F[D++]=192;else{if(i){let q=i.get(v);if(q){if(!q.id){let ae=i.idsToInsert||(i.idsToInsert=[]);q.id=ae.push(q)}F[D++]=214,F[D++]=112,je.setUint32(D,q.id),D+=4;return}else i.set(v,{offset:D-r})}let W=v.constructor;if(W===Object)B(v);else if(W===Array)A(v);else if(W===Map)if(this.mapAsEmptyObject)F[D++]=128;else{G=v.size,G<16?F[D++]=128|G:G<65536?(F[D++]=222,F[D++]=G>>8,F[D++]=G&255):(F[D++]=223,je.setUint32(D,G),D+=4);for(let[q,ae]of v)E(q),E(ae)}else{for(let q=0,ae=Ap.length;q<ae;q++){let ce=Pp[q];if(v instanceof ce){let ne=Ap[q];if(ne.write){ne.type&&(F[D++]=212,F[D++]=ne.type,F[D++]=0);let Ae=ne.write.call(this,v);Ae===v?Array.isArray(v)?A(v):B(v):E(Ae);return}let Re=F,oe=je,ee=D;F=null;let ue;try{ue=ne.pack.call(this,v,Ae=>(F=Re,Re=null,D+=Ae,D>Ot&&j(D),{target:F,targetView:je,position:D-Ae}),E)}finally{Re&&(F=Re,je=oe,D=ee,Ot=F.length-10)}ue&&(ue.length+D>Ot&&j(ue.length+D),D=Vb(ue,F,D,ne.type));return}}if(Array.isArray(v))A(v);else{if(v.toJSON){let q=v.toJSON();if(q!==v)return E(q)}if($==="function")return E(this.writeFunction&&this.writeFunction(v));B(v)}}}else if($==="boolean")F[D++]=v?195:194;else if($==="bigint"){if(v<9223372036854776e3&&v>=-9223372036854776e3)F[D++]=211,je.setBigInt64(D,v);else if(v<18446744073709552e3&&v>0)F[D++]=207,je.setBigUint64(D,v);else if(this.largeBigIntToFloat)F[D++]=203,je.setFloat64(D,Number(v));else{if(this.largeBigIntToString)return E(v.toString());if(this.useBigIntExtension||this.moreTypes){let W=v<0?BigInt(-1):BigInt(0),q;if(v>>BigInt(65536)===W){let ae=BigInt(18446744073709552e3)-BigInt(1),ce=[];for(;ce.push(v&ae),v>>BigInt(63)!==W;)v>>=BigInt(64);q=new Uint8Array(new BigUint64Array(ce).buffer),q.reverse()}else{let ae=v<0,ce=(ae?~v:v).toString(16);if(ce.length%2?ce="0"+ce:parseInt(ce.charAt(0),16)>=8&&(ce="00"+ce),di)q=Buffer.from(ce,"hex");else{q=new Uint8Array(ce.length/2);for(let ne=0;ne<q.length;ne++)q[ne]=parseInt(ce.slice(ne*2,ne*2+2),16)}if(ae)for(let ne=0;ne<q.length;ne++)q[ne]=~q[ne]}q.length+D>Ot&&j(q.length+D),D=Vb(q,F,D,66);return}else throw new RangeError(v+" 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")this.encodeUndefinedAsNil?F[D++]=192:(F[D++]=212,F[D++]=0,F[D++]=0);else throw new Error("Unknown type: "+$)},P=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?v=>{let $;if(this.skipValues){$=[];for(let q in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(q))&&!this.skipValues.includes(v[q])&&$.push(q)}else $=Object.keys(v);let G=$.length;G<16?F[D++]=128|G:G<65536?(F[D++]=222,F[D++]=G>>8,F[D++]=G&255):(F[D++]=223,je.setUint32(D,G),D+=4);let W;if(this.coercibleKeyAsNumber)for(let q=0;q<G;q++){W=$[q];let ae=Number(W);E(isNaN(ae)?W:ae),E(v[W])}else for(let q=0;q<G;q++)E(W=$[q]),E(v[W])}:v=>{F[D++]=222;let $=D-r;D+=2;let G=0;for(let W in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(W))&&(E(W),E(v[W]),G++);if(G>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');F[$+++r]=G>>8,F[$+r]=G&255},k=this.useRecords===!1?P:e.progressiveRecords&&!h?v=>{let $,G=o.transitions||(o.transitions=Object.create(null)),W=D++-r,q;for(let ae in v)if(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(ae)){if($=G[ae],$)G=$;else{let ce=Object.keys(v),ne=G;G=o.transitions;let Re=0;for(let oe=0,ee=ce.length;oe<ee;oe++){let ue=ce[oe];$=G[ue],$||($=G[ue]=Object.create(null),Re++),G=$}W+r+1==D?(D--,L(G,ce,Re)):se(G,ce,W,Re),q=!0,G=ne[ae]}E(v[ae])}if(!q){let ae=G[li];ae?F[W+r]=ae:se(G,Object.keys(v),W,0)}}:v=>{let $,G=o.transitions||(o.transitions=Object.create(null)),W=0;for(let ae in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(ae))&&($=G[ae],$||($=G[ae]=Object.create(null),W++),G=$);let q=G[li];q?q>=96&&h?(F[D++]=((q-=96)&31)+96,F[D++]=q>>5):F[D++]=q:L(G,G.__keys__||Object.keys(v),W);for(let ae in v)(typeof v.hasOwnProperty!="function"||v.hasOwnProperty(ae))&&E(v[ae])},M=typeof this.useRecords=="function"&&this.useRecords,B=M?v=>{M(v)?k(v):P(v)}:k,K=v=>{let $=c._writeStruct(v,F,r,D,o,j,(G,W,q)=>{if(q)return s=!0;D=W;let ae=F;return E(G),R(),ae!==F?{position:D,targetView:je,target:F}:D});if($===0)return B(v);D=$},j=v=>{let $;if(v>16777216){if(v-r>Ub)throw new Error("Packed buffer would be larger than maximum buffer size");$=Math.min(Ub,Math.round(Math.max((v-r)*(v>67108864?1.25:2),4194304)/4096)*4096)}else $=(Math.max(v-r<<2,F.length-1)>>12)+1<<12;let G=new gl($);return je=G.dataView||(G.dataView=new DataView(G.buffer,0,$)),v=Math.min(v,F.length),F.copy?F.copy(G,0,r,v):G.set(F.slice(r,v)),D-=r,r=0,Ot=G.length-10,F=G},L=(v,$,G)=>{let W=o.nextId;W||(W=64),W<p&&this.shouldShareStructure&&!this.shouldShareStructure($)?(W=o.nextOwnId,W<y||(W=p),o.nextOwnId=W+1):(W>=y&&(W=p),o.nextId=W+1);let q=$.highByte=W>=96&&h?W-96>>5:-1;v[li]=W,v.__keys__=$,o[W-64]=$,W<p?($.isShared=!0,o.sharedLength=W-63,s=!0,q>=0?(F[D++]=(W&31)+96,F[D++]=q):F[D++]=W):(q>=0?(F[D++]=213,F[D++]=114,F[D++]=(W&31)+96,F[D++]=q):(F[D++]=212,F[D++]=114,F[D++]=W),G&&(b+=x*G),S.length>=f&&(S.shift()[li]=0),S.push(v),E($))},se=(v,$,G,W)=>{let q=F,ae=D,ce=Ot,ne=r;F=Ga,D=0,r=0,F||(Ga=F=new gl(8192)),Ot=F.length-10,L(v,$,W),Ga=F;let Re=D;if(F=q,D=ae,Ot=ce,r=ne,Re>1){let oe=D+Re-1;oe>Ot&&j(oe);let ee=G+r;F.copyWithin(ee+Re,ee+1,D),F.set(Ga.slice(0,Re),ee),D=oe}else F[G+r]=Ga[0]}}useBuffer(e){F=e,F.dataView||(F.dataView=new DataView(F.buffer,F.byteOffset,F.byteLength)),je=F.dataView,D=0}set position(e){D=e}get position(){return D}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}};Pp=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Wa];Ap=[{pack(t,e,n){let r=t.getTime()/1e3;if((this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:s,targetView:o,position:i}=e(6);s[i++]=214,s[i++]=255,o.setUint32(i,r)}else if(r>0&&r<4294967296){let{target:s,targetView:o,position:i}=e(10);s[i++]=215,s[i++]=255,o.setUint32(i,t.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),o.setUint32(i+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),n(this.onInvalidDate());let{target:s,targetView:o,position:i}=e(3);s[i++]=212,s[i++]=255,s[i++]=255}else{let{target:s,targetView:o,position:i}=e(15);s[i++]=199,s[i++]=12,s[i++]=255,o.setUint32(i,t.getMilliseconds()*1e6),o.setBigInt64(i+4,BigInt(Math.floor(r)))}}},{pack(t,e,n){if(this.setAsEmptyObject)return e(0),n({});let r=Array.from(t),{target:s,position:o}=e(this.moreTypes?3:0);this.moreTypes&&(s[o++]=212,s[o++]=115,s[o++]=0),n(r)}},{pack(t,e,n){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=101,r[s++]=0),n([t.name,t.message,t.cause])}},{pack(t,e,n){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=120,r[s++]=0),n([t.source,t.flags])}},{pack(t,e){this.moreTypes?Ep(t,16,e):kp(di?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let n=t.constructor;n!==$b&&this.moreTypes?Ep(t,Rp.indexOf(n.name),e):kp(t,e)}},{pack(t,e){this.moreTypes?Ep(t,17,e):kp(di?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let{target:n,position:r}=e(1);n[r]=193}}];function Ep(t,e,n,r){let s=t.byteLength;if(s+1<256){var{target:o,position:i}=n(4+s);o[i++]=199,o[i++]=s+1}else if(s+1<65536){var{target:o,position:i}=n(5+s);o[i++]=200,o[i++]=s+1>>8,o[i++]=s+1&255}else{var{target:o,position:i,targetView:a}=n(7+s);o[i++]=201,a.setUint32(i,s+1),i+=4}o[i++]=116,o[i++]=e,t.buffer||(t=new Uint8Array(t)),o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i)}function kp(t,e){let n=t.byteLength;var r,s;if(n<256){var{target:r,position:s}=e(n+2);r[s++]=196,r[s++]=n}else if(n<65536){var{target:r,position:s}=e(n+3);r[s++]=197,r[s++]=n>>8,r[s++]=n&255}else{var{target:r,position:s,targetView:o}=e(n+5);r[s++]=198,o.setUint32(s,n),s+=4}r.set(t,s)}function Vb(t,e,n,r){let s=t.length;switch(s){case 1:e[n++]=212;break;case 2:e[n++]=213;break;case 4:e[n++]=214;break;case 8:e[n++]=215;break;case 16:e[n++]=216;break;default:s<256?(e[n++]=199,e[n++]=s):s<65536?(e[n++]=200,e[n++]=s>>8,e[n++]=s&255):(e[n++]=201,e[n++]=s>>24,e[n++]=s>>16&255,e[n++]=s>>8&255,e[n++]=s&255)}return e[n++]=r,e.set(t,n),n+=s,n}function $P(t,e){let n,r=e.length*6,s=t.length-r;for(;n=e.pop();){let o=n.offset,i=n.id;t.copyWithin(o+r,o,s),r-=6;let a=o+r;t[a++]=214,t[a++]=105,t[a++]=i>>24,t[a++]=i>>16&255,t[a++]=i>>8&255,t[a++]=i&255,s=o}return t}function Hb(t,e,n){if(Ze.length>0){je.setUint32(Ze.position+t,D+n-Ze.position-t),Ze.stringsPosition=D-t;let r=Ze;Ze=null,e(r[0]),e(r[1])}}function jP(t,e){return t.isCompatible=n=>{let r=!n||(e.lastNamedStructuresLength||0)===n.length;return r||e._mergeStructures(n),r},t}gs.SUPPORTS_STRUCT_HOOKS=!0;var jb=new gs({useRecords:!1}),WP=jb.pack,qP=jb.pack;var{NEVER:GP,ALWAYS:YP,DECIMAL_ROUND:KP,DECIMAL_FIT:XP}=yl,Wb=512,qb=1024,fi=2048;Pt();Pr();var JP=9,wl=class{constructor(){m(this,"pending",new Uint8Array(0))}push(e){if(!e||e.byteLength===0)return[];let n=this.pending.byteLength===0?e:ZP(this.pending,e),r=[],s=0;for(;s<n.byteLength;){let o={offset:s},i;try{i=Pe.number(n,o)}catch(c){if(n.byteLength-s<=JP)break;throw c}let a=o.offset+i;if(a>n.byteLength)break;r.push(n.subarray(o.offset,a)),s=a}return this.pending=s<n.byteLength?n.slice(s):new Uint8Array(0),r}};function ZP(t,e){let n=new Uint8Array(t.byteLength+e.byteLength);return n.set(t,0),n.set(e,t.byteLength),n}var Ya=class{constructor(e){m(this,"wt");m(this,"url");m(this,"isOpen",!1);m(this,"events");m(this,"reader");m(this,"writer");m(this,"unreliableReader");m(this,"unreliableWriter");m(this,"lengthPrefixBuffer",new Uint8Array(9));m(this,"reliableReassembler",new wl);m(this,"unreliableReassembler",new wl);this.events=e}connect(e,n={}){this.url=e;let r=n.fingerprint&&{serverCertificateHashes:[{algorithm:"sha-256",value:new Uint8Array(n.fingerprint)}]}||void 0;this.wt=new WebTransport(e,r),this.wt.ready.then(s=>{console.log("WebTransport ready!",s),this.isOpen=!0,this.unreliableReader=this.wt.datagrams.readable.getReader();let o=this.wt.datagrams;this.unreliableWriter=(o.createWritable?o.createWritable():o.writable).getWriter(),this.wt.incomingBidirectionalStreams.getReader().read().then(a=>{this.reader=a.value.readable.getReader(),this.writer=a.value.writable.getWriter(),this.sendSeatReservation(n.roomId,n.sessionId,n.reconnectionToken,n.skipHandshake),this.readIncomingData(),this.readIncomingUnreliableData()}).catch(a=>{console.error("failed to read incoming stream",a),console.error("TODO: close the connection")})}).catch(s=>{console.log("WebTransport not ready!",s),this._close()}),this.wt.closed.then(s=>{console.log("WebTransport closed w/ success",s),this.events.onclose({code:s.closeCode,reason:s.reason})}).catch(s=>{console.log("WebTransport closed w/ error",s),this.events.onerror(s),this.events.onclose({code:s.closeCode,reason:s.reason})}).finally(()=>{this._close()})}send(e){this.writer.write(this.frame(e))}sendUnreliable(e){this.unreliableWriter.write(this.frame(e))}frame(e){let n=e instanceof Uint8Array?e:new Uint8Array(e),r=Se.number(this.lengthPrefixBuffer,n.length,{offset:0}),s=new Uint8Array(r+n.length);return s.set(this.lengthPrefixBuffer.subarray(0,r),0),s.set(n,r),s}close(e,n){this.isOpen=!1;try{let r=this.wt?.close({closeCode:e,reason:n});r&&typeof r.catch=="function"&&r.catch(()=>{})}catch{}}readIncomingData(){return this.readLoop(this.reader,this.reliableReassembler,"reliable")}readIncomingUnreliableData(){return this.readLoop(this.unreliableReader,this.unreliableReassembler,"unreliable")}async readLoop(e,n,r){for(;this.isOpen;){let s;try{s=await e.read()}catch(o){await this.onChannelFailure(r,o);return}if(s.done||!s.value)return;for(let o of n.push(s.value))this.events.onmessage({data:o})}}async onChannelFailure(e,n){await new Promise(r=>setTimeout(r,0)),this.isOpen&&(console.error(`H3Transport: stopped reading the ${e} channel while the session was open`,n),this.close(St.ABNORMAL_CLOSURE,`h3 ${e} channel failed`))}sendSeatReservation(e,n,r,s){let o={offset:0},i=[];Se.string(i,e,o),Se.string(i,n,o),r&&Se.string(i,r,o),s&&Se.boolean(i,1,o),this.writer.write(new Uint8Array(i).buffer)}_close(){this.isOpen=!1}};var Xb=lE(Yb(),1);Pr();var Tp=globalThis.WebSocket||Xb.default,Kb=!1,Sl=class{constructor(e){m(this,"ws");m(this,"protocols");m(this,"events");this.events=e}send(e){this.ws.send(e)}sendUnreliable(e){Kb||(Kb=!0,console.warn('@colyseus/sdk: the WebSocket transport has no unreliable channel \u2014 sending `mode:"unreliable"` traffic reliably instead. Use @colyseus/h3-transport (WebTransport) for datagram delivery.')),this.send(e)}connect(e,n){try{this.ws=new Tp(e,{headers:n,protocols:this.protocols})}catch{this.ws=new Tp(e,this.protocols)}this.ws.binaryType="arraybuffer",this.ws.onopen=r=>this.events.onopen?.(r),this.ws.onmessage=r=>this.events.onmessage?.(r),this.ws.onclose=r=>this.events.onclose?.(r),this.ws.onerror=r=>this.events.onerror?.(r)}close(e,n){e===St.MAY_TRY_RECONNECT&&this.events.onclose&&(this.ws.onclose=null,this.events.onclose({code:e,reason:n})),this.ws.close(e,n)}get isOpen(){return this.ws.readyState===Tp.OPEN}};Pr();var Ka=[],vp=typeof addEventListener=="function"&&typeof removeEventListener=="function";vp&&addEventListener("offline",()=>{console.warn(`@colyseus/sdk: \u{1F6D1} Network offline. Closing ${Ka.length} connection(s)`),Ka.forEach(t=>t())},!1);var Xa,pi=class{constructor(e){m(this,"transport");m(this,"events",{});m(this,"url");m(this,"options");He(this,Xa,vp?()=>this.close(St.MAY_TRY_RECONNECT):null);e==="h3"?this.transport=new Ya(this.events):this.transport=new Sl(this.events)}connect(e,n){if(vp){let r=this.events.onopen;this.events.onopen=o=>{Ka.push(de(this,Xa)),r?.(o)};let s=this.events.onclose;this.events.onclose=o=>{Ka.splice(Ka.indexOf(de(this,Xa)),1),s?.(o)}}this.url=e,this.options=n,this.transport.connect(e,n)}send(e){this.transport.send(e)}sendUnreliable(e){this.transport.sendUnreliable(e)}reconnect(e){if(this.transport instanceof Ya){this.transport.connect(this.url,{...this.options,...e});return}let n=new URL(this.url);for(let r in e)n.searchParams.set(r,e[r]);this.transport.connect(n.toString(),this.options)}close(e,n){this.transport.close(e,n)}get isOpen(){return this.transport.isOpen}};Xa=new WeakMap;var Jb={};function Mp(t,e){Jb[t]=e}function Cp(t){let e=Jb[t];if(!e)throw new Error("missing serializer: "+t);return e}var xl=()=>({emit(t,...e){let n=this.events[t]||[];for(let r=0,s=n.length;r<s;r++)n[r](...e)},events:{},on(t,e){return this.events[t]?.push(e)||(this.events[t]=[e]),()=>{this.events[t]=this.events[t]?.filter(n=>e!==n)}}});var Zb=new WeakMap,Op=class{constructor(){m(this,"handlers",[])}register(e,n=!1){return this.handlers.push(e),this}invoke(...e){let n=this.handlers;for(let r=0,s=n.length;r<s;r++)n[r].apply(this,e)}invokeAsync(...e){return Promise.all(this.handlers.map(n=>n.apply(this,e)))}remove(e){let n=this.handlers.indexOf(e);n===-1&&(n=this.handlers.findIndex(r=>Zb.get(r)===e)),n!==-1&&(this.handlers=this.handlers.filter((r,s)=>s!==n))}clear(){this.handlers=[]}};function eo(){let t=new Op;function e(n){return t.register(n,this===null)}return e.once=n=>{let r=function(...s){t.remove(r),n.apply(this,s)};Zb.set(r,n),t.register(r)},e.remove=n=>t.remove(n),e.invoke=(...n)=>t.invoke(...n),e.invokeAsync=(...n)=>t.invokeAsync(...n),e.clear=()=>t.clear(),e}Pt();function Ja(t){try{return Gu(t.serializer.decoder)}catch{return}}var hi=class{constructor(){m(this,"state");m(this,"decoder")}setState(e,n){this.decoder.root.refs.size>1&&typeof this.decoder.decodeResync=="function"?this.decoder.decodeResync(e,n):this.decoder.decode(e,n)}getState(){return this.state}patch(e,n){return this.decoder.decode(e,n)}teardown(){this.decoder.root.clearRefs()}handshake(e,n){this.state?(zn.decode(e,n),this.decoder=new Fn(this.state)):(this.decoder=zn.decode(e,n),this.state=this.decoder.state)}};ul();function Qb(){return{enabled:!0,retryCount:0,maxRetries:15,delay:100,minDelay:100,maxDelay:5e3,minUptime:5e3,backoff:QP,maxEnqueuedMessages:10,enqueuedMessages:[],isReconnecting:!1}}var QP=(t,e)=>Math.floor(Math.pow(2,t)*e);function _l(t,e){t.reconnection.enqueuedMessages.push({data:e}),t.reconnection.enqueuedMessages.length>t.reconnection.maxEnqueuedMessages&&t.reconnection.enqueuedMessages.shift()}function e0(t,e){if(!e){let r=new Error("request rejected");return r.name="rejected",r.reason=t,r}let n=new Error(t?.message??"request failed");return t?.name&&(n.name=t.name),t?.code!==void 0&&(n.code=t.code),n}Ia();var Qa,mi,yi,fr,pr,gi,hr,t0,n0,r0,s0,Rl=class Rl{constructor(e,n){He(this,hr);m(this,"roomId");m(this,"sessionId");m(this,"reconnectionToken");m(this,"name");m(this,"connection");m(this,"onStateChange",eo());m(this,"onError",eo());m(this,"onLeave",eo());m(this,"onReconnect",eo());m(this,"onDrop",eo());m(this,"onJoin",eo());m(this,"serializerId");m(this,"serializer");m(this,"reconnection",Qb());m(this,"joinedAtTime",0);m(this,"clock",ii);m(this,"onMessageHandlers",xl());m(this,"packr");m(this,"sharedBuffer");He(this,Qa,0);He(this,mi);He(this,yi,0);He(this,fr,new Map);He(this,pr);He(this,gi,0);if(this.name=e,this.packr=new gs,this.sharedBuffer=new Uint8Array(8192),n){let r=new(Cp("schema"));this.serializer=r;let s=new n;r.state=s,r.decoder=new Fn(s)}this.onLeave(()=>{this.removeAllListeners(),this.destroy()})}connect(e,n,r){this.connection=new pi(n.protocol),this.connection.events.onmessage=this.onMessageCallback.bind(this),this.connection.events.onclose=o=>{if(zs(this,hr,r0).call(this,"connection closed before a response was received."),this.joinedAtTime===0){console.warn?.(`Room connection was closed unexpectedly (${o.code}): ${o.reason}`),this.onError.invoke(o.code,o.reason);return}o.code===St.NO_STATUS_RECEIVED||o.code===St.ABNORMAL_CLOSURE||o.code===St.GOING_AWAY||o.code===St.MAY_TRY_RECONNECT?(this.onDrop.invoke(o.code,o.reason),this.handleReconnection(o.code,o.reason)):this.onLeave.invoke(o.code,o.reason)},this.connection.events.onerror=o=>{this.onError.invoke(o.code,o.reason)};let s=this.serializer?.getState()!==void 0;if(n.protocol==="h3"){let o=new URL(e);this.connection.connect(o.origin,{...n,skipHandshake:s})}else this.connection.connect(`${e}${s?"&skipHandshake=1":""}`,r)}leave(e=!0){return new Promise(n=>{this.onLeave(r=>n(r)),this.connection?e?(this.sharedBuffer[0]=Ke.LEAVE_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1))):this.connection.close():this.onLeave.invoke(St.CONSENTED)})}onMessage(e,n){return this.onMessageHandlers.on(this.getMessageHandlerKey(e),n)}ping(e){this.connection?.isOpen&&($e(this,Qa,Ct()),$e(this,mi,e),this.sharedBuffer[0]=Ke.PING,this.connection.send(this.sharedBuffer.subarray(0,1)))}send(e,n,r){if(r!==void 0){this.request(e,n).then(a=>r(a,void 0),a=>r(void 0,a));return}let s={offset:1};this.sharedBuffer[0]=Ke.ROOM_DATA,typeof e=="string"?Se.string(this.sharedBuffer,e,s):Se.number(this.sharedBuffer,e,s);let o=s.offset,i;n!==void 0?(i=this.packr.pack(n,fi|o),i.set(this.sharedBuffer.subarray(0,o),0)):i=this.sharedBuffer.subarray(0,o),this.connection.isOpen?this.connection.send(i):_l(this,new Uint8Array(i))}request(e,n,r){if(!this.connection.isOpen)return Promise.reject(new Error(`cannot send request "${e}": connection is not open.`));let s=r?.timeout??Rl.defaultRequestTimeout;return new Promise((o,i)=>{let a,c=this.sendRequest(e,n,{mode:r?.mode},(u,l,d)=>{clearTimeout(a),u?o(l):i(e0(l,d))},u=>{clearTimeout(a),i(new Error(u))});a=setTimeout(()=>{this.cancelRequest(c),i(new Error(`request "${e}" timed out after ${s}ms.`))},s)})}sendRequest(e,n,r,s,o){let i=zs(this,hr,t0).call(this),a=zs(this,hr,n0).call(this,i,e,n);if(r.mode==="unreliable"){if(!this.connection.isOpen)return-1;this.connection.sendUnreliable(a)}else this.connection.isOpen?this.connection.send(a):_l(this,new Uint8Array(a));return de(this,fr).set(i,{onReply:s,onClose:o}),i}cancelRequest(e){de(this,fr).delete(e)}sendUnreliable(e,n){if(!this.connection.isOpen)return;let r={offset:1};this.sharedBuffer[0]=Ke.ROOM_DATA,typeof e=="string"?Se.string(this.sharedBuffer,e,r):Se.number(this.sharedBuffer,e,r);let s=r.offset,o;n!==void 0?(o=this.packr.pack(n,fi|s),o.set(this.sharedBuffer.subarray(0,s),0)):o=this.sharedBuffer.subarray(0,s),this.connection.sendUnreliable(o)}sendBytes(e,n){let r={offset:1};this.sharedBuffer[0]=Ke.ROOM_DATA_BYTES,typeof e=="string"?Se.string(this.sharedBuffer,e,r):Se.number(this.sharedBuffer,e,r);let s=r.offset;if(s+n.byteLength>this.sharedBuffer.byteLength){let o=new Uint8Array(s+n.byteLength);o.set(this.sharedBuffer.subarray(0,s)),this.sharedBuffer=o}this.sharedBuffer.set(n,s),this.connection.isOpen?this.connection.send(this.sharedBuffer.subarray(0,s+n.byteLength)):_l(this,this.sharedBuffer.subarray(0,s+n.byteLength))}input(e){return(de(this,pr)??$e(this,pr,new ui(this))).handle(e)}get state(){return this.serializer.getState()}removeAllListeners(){this.onJoin.clear(),this.onStateChange.clear(),this.onError.clear(),this.onLeave.clear(),this.onReconnect.clear(),this.onDrop.clear(),this.onMessageHandlers.events={},this.serializer instanceof hi&&(this.serializer.decoder.root.callbacks={})}onMessageCallback(e){zs(this,hr,s0).call(this,new Uint8Array(e.data))}dispatchMessage(e,n){let r=this.getMessageHandlerKey(e);this.onMessageHandlers.events[r]?this.onMessageHandlers.emit(r,n):this.onMessageHandlers.events["*"]?this.onMessageHandlers.emit("*",e,n):r.startsWith("__")||console.warn?.(`@colyseus/sdk: onMessage() not registered for type '${e}'.`)}destroy(){this.serializer&&this.serializer.teardown()}getMessageHandlerKey(e){switch(typeof e){case"string":return e;case"number":return`i${e}`;default:throw new Error("invalid message type.")}}handleReconnection(e,n){if(!this.reconnection.enabled){this.onLeave.invoke(e,n);return}if(Date.now()-this.joinedAtTime<this.reconnection.minUptime){console.info(`[Colyseus reconnection]: ${String.fromCodePoint(10060)} Room has not been up for long enough for automatic reconnection. (min uptime: ${this.reconnection.minUptime}ms)`),this.onLeave.invoke(St.ABNORMAL_CLOSURE,"Room uptime too short for reconnection.");return}this.reconnection.isReconnecting||(this.reconnection.retryCount=0,this.reconnection.isReconnecting=!0,de(this,pr)?.reset()),this.retryReconnection()}retryReconnection(){if(this.reconnection.retryCount>=this.reconnection.maxRetries){console.info(`[Colyseus reconnection]: ${String.fromCodePoint(10060)} \u274C Reconnection failed after ${this.reconnection.maxRetries} attempts.`),this.reconnection.isReconnecting=!1,this.onLeave.invoke(St.FAILED_TO_RECONNECT,"No more retries. Reconnection failed.");return}this.reconnection.retryCount++;let e=Math.min(this.reconnection.maxDelay,Math.max(this.reconnection.minDelay,this.reconnection.backoff(this.reconnection.retryCount,this.reconnection.delay)));console.info(`[Colyseus reconnection]: ${String.fromCodePoint(9203)} will retry in ${(e/1e3).toFixed(1)} seconds...`),setTimeout(()=>{try{console.info(`[Colyseus reconnection]: ${String.fromCodePoint(128260)} Re-establishing sessionId '${this.sessionId}' with roomId '${this.roomId}'... (attempt ${this.reconnection.retryCount} of ${this.reconnection.maxRetries})`),this.connection.reconnect({reconnectionToken:this.reconnectionToken.split(":")[1],skipHandshake:!0})}catch{this.retryReconnection()}},e)}};Qa=new WeakMap,mi=new WeakMap,yi=new WeakMap,fr=new WeakMap,pr=new WeakMap,gi=new WeakMap,hr=new WeakSet,t0=function(){let e=de(this,yi);return $e(this,yi,de(this,yi)+1>>>0),e},n0=function(e,n,r){let s={offset:1};this.sharedBuffer[0]=Ke.ROOM_REQUEST,Se.number(this.sharedBuffer,e,s),typeof n=="string"?Se.string(this.sharedBuffer,n,s):Se.number(this.sharedBuffer,n,s);let o=s.offset;if(r!==void 0){let i=this.packr.pack(r,fi|o);return i.set(this.sharedBuffer.subarray(0,o),0),i}return this.sharedBuffer.subarray(0,o)},r0=function(e){if(de(this,fr).size!==0){for(let n of de(this,fr).values())n.onClose?.(e);de(this,fr).clear()}},s0=function(e){var o;let n={offset:1},r=e[0],s=r&Hf;if(r&Zo.TIMED){let i=Pe.uint32(e,n),a=Pe.uint32(e,n),c=de(this,pr)?de(this,pr).ackInput(a):-1;this.clock.sample(i,c)}if(s===Ke.JOIN_ROOM){let i=Pe.utf8Read(e,n,e[n.offset++]);if(this.serializerId=Pe.utf8Read(e,n,e[n.offset++]),!this.serializer){let u=Cp(this.serializerId);this.serializer=new u}let a=Pe.number(e,n);if(a>0&&this.serializer.handshake){let u=n.offset+a;this.serializer.handshake(e.subarray(0,u),n),n.offset=u}for(;n.offset<e.byteLength;){let u=e[n.offset++],l=Pe.number(e,n),d=n.offset+l;u===Ou.INPUT_REFLECTION?(de(this,pr)??$e(this,pr,new ui(this))).applyReflection(e,n,d):u===Ou.INPUT_OPTIONS&&(de(this,pr)??$e(this,pr,new ui(this))).applyOptions(e,n),n.offset=d}let c=de(this,pr)?.patchRate;if(c!==void 0&&this.clock.setPatchInterval?.(c),this.joinedAtTime===0?(this.joinedAtTime=Date.now(),this.onJoin.invoke()):(console.info(`[Colyseus reconnection]: ${String.fromCodePoint(9989)} reconnection successful!`),this.reconnection.isReconnecting=!1,this.onReconnect.invoke()),this.reconnectionToken=`${this.roomId}:${i}`,this.sharedBuffer[0]=Ke.JOIN_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1)),this.reconnection.enqueuedMessages.length>0){for(let u of this.reconnection.enqueuedMessages)this.connection.send(u.data);this.reconnection.enqueuedMessages=[]}}else if(s===Ke.ERROR){let i=Pe.number(e,n),a=Pe.string(e,n);this.onError.invoke(i,a)}else if(s===Ke.LEAVE_ROOM)this.leave();else if(s===Ke.ROOM_STATE)$e(this,gi,0),this.serializer.setState(e,n),this.onStateChange.invoke(this.serializer.getState());else if(s===Ke.ROOM_STATE_PATCH){if(r&Zo.UNRELIABLE){let i=Pe.uint16(e,n);if(i-de(this,gi)<<16>>16<=0)return;$e(this,gi,i)}this.serializer.patch(e,n),this.onStateChange.invoke(this.serializer.getState())}else if(s===Ke.ROOM_DATA){let i=Pe.stringCheck(e,n)?Pe.string(e,n):Pe.number(e,n),a=e.byteLength>n.offset?ml(e,{start:n.offset}):void 0;this.dispatchMessage(i,a)}else if(s===Ke.ROOM_DATA_BYTES){let i=Pe.stringCheck(e,n)?Pe.string(e,n):Pe.number(e,n);this.dispatchMessage(i,e.subarray(n.offset))}else if(s===Ke.ROOM_RESPONSE){let i=Pe.number(e,n),a=e[n.offset++],c=e.byteLength>n.offset?ml(e,{start:n.offset}):void 0,u=de(this,fr).get(i);u!==void 0&&(de(this,fr).delete(i),u.onReply(a===Cu.OK,c,a===Cu.ERROR))}else s===Ke.PING&&((o=de(this,mi))==null||o.call(this,Math.round(Ct()-de(this,Qa))),$e(this,mi,void 0))},m(Rl,"defaultRequestTimeout",1e4);var Za=Rl;function o0(t,e){return new Promise((n,r)=>{let s=new XMLHttpRequest,o=e?.method||"GET";s.open(o,t.toString()),s.withCredentials=e?.credentials==="include",e?.headers&&(e.headers instanceof Headers?e.headers:new Headers(e.headers)).forEach((a,c)=>{s.setRequestHeader(c,a)}),s.onload=()=>{let i=new Headers,a=s.getAllResponseHeaders().trim();if(a)for(let u of a.split(/[\r\n]+/)){let l=u.indexOf(": ");l>0&&i.append(u.substring(0,l),u.substring(l+2))}let c=s.response??s.responseText;n(new Ip(c,{status:s.status,statusText:s.statusText,headers:i}))},s.onerror=()=>r(new TypeError("Network request failed")),s.ontimeout=()=>r(new TypeError("Network request timed out")),s.send(e?.body??null)})}var Ip=class{constructor(e,n){m(this,"status");m(this,"statusText");m(this,"headers");m(this,"ok");m(this,"body");this.body=e,this.status=n.status,this.statusText=n.statusText,this.headers=n.headers,this.ok=n.status>=200&&n.status<300}async json(){return typeof this.body=="string"?JSON.parse(this.body):this.body}async text(){return typeof this.body=="string"?this.body:JSON.stringify(this.body)}async blob(){return new Blob([this.body])}};function eT(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function tT(t,e){let{params:n,query:r}=e||{},[s,o]=t.split("?"),i=s;if(n)if(Array.isArray(n)){let u=i.split("/").filter(l=>l.startsWith(":"));for(let[l,d]of u.entries()){let f=n[l];i=i.replace(d,f)}}else for(let[u,l]of Object.entries(n))i=i.replace(`:${u}`,String(l));let a=new URLSearchParams(o);if(r)for(let[u,l]of Object.entries(r))l!=null&&a.set(u,String(l));let c=a.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",`${i}${c}`}var El=class{constructor(e,n,r){m(this,"authToken");m(this,"options");m(this,"sdk");m(this,"_fetchFn");m(this,"del",this.delete);this.sdk=e,this.options=n,this._fetchFn=r}get fetchFn(){return this._fetchFn||(this._fetchFn=typeof globalThis.fetch<"u"?globalThis.fetch.bind(globalThis):o0),this._fetchFn}async request(e,n,r){return this.executeRequest(e,n,r)}get(e,n){return this.request("GET",e,n)}post(e,n){return this.request("POST",e,n)}delete(e,n){return this.request("DELETE",e,n)}patch(e,n){return this.request("PATCH",e,n)}put(e,n){return this.request("PUT",e,n)}async executeRequest(e,n,r){let s=this.options.body?{...this.options.body,...r?.body||{}}:r?.body,o=this.options.query?{...this.options.query,...r?.query||{}}:r?.query,i=this.options.params?{...this.options.params,...r?.params||{}}:r?.params,a=new Headers(this.options.headers?{...this.options.headers,...r?.headers||{}}:r?.headers);if(this.authToken&&!a.has("authorization")&&a.set("authorization",`Bearer ${this.authToken}`),eT(s)&&typeof s=="object"&&s!==null){a.has("content-type")||a.set("content-type","application/json");for(let[h,p]of Object.entries(s))p instanceof Date&&(s[h]=p.toISOString());s=JSON.stringify(s)}let c={credentials:r?.credentials||"include",...this.options,...r,query:o,params:i,headers:a,body:s,method:e},u=tT(this.sdk.getHttpEndpoint(n.toString()),c),l;try{l=await this.fetchFn(u,c)}catch(h){if(h.name==="AbortError")throw h;let p=new rr(h.cause?.code||h.code,h.message);throw p.response=l,p.cause=h.cause,p}let d=l.headers.get("content-type"),f;if(d?.includes("json")?f=await l.json():d?.includes("text")?f=await l.text():f=await l.blob(),!l.ok)throw new rr(l.status,f.message??f.error??l.statusText,{headers:l.headers,status:l.status,response:l,data:f});return{raw:l,data:f,headers:l.headers,status:l.status,statusText:l.statusText}}};var to;function Np(){if(!to)try{to=typeof cc<"u"&&cc.sys&&cc.sys.localStorage?cc.sys.localStorage:window.localStorage}catch{}return!to&&typeof globalThis.indexedDB<"u"&&(to=new Dp),to||(to={cache:{},setItem:function(t,e){this.cache[t]=e},getItem:function(t){return this.cache[t]},removeItem:function(t){delete this.cache[t]}}),to}function i0(t,e){Np().setItem(t,e)}function a0(t){Np().removeItem(t)}function c0(t,e){let n=Np().getItem(t);typeof Promise>"u"||!(n instanceof Promise)?e(n):n.then(r=>e(r))}var Dp=class{constructor(){m(this,"dbPromise",new Promise(e=>{let n=indexedDB.open("_colyseus_storage",1);n.onupgradeneeded=()=>n.result.createObjectStore("store"),n.onsuccess=()=>e(n.result)}))}async tx(e,n){let s=(await this.dbPromise).transaction("store",e).objectStore("store");return n(s)}setItem(e,n){return this.tx("readwrite",r=>r.put(n,e)).then()}async getItem(e){let n=await this.tx("readonly",r=>r.get(e));return new Promise(r=>{n.onsuccess=()=>r(n.result)})}removeItem(e){return this.tx("readwrite",n=>n.delete(e)).then()}};var tc,Nr,nc,ec=class{constructor(e){m(this,"settings",{path:"/auth",key:"colyseus-auth-token"});He(this,tc,!1);He(this,Nr,null);He(this,nc,xl());m(this,"http");this.http=e,c0(this.settings.key,n=>this.token=n)}set token(e){this.http.authToken=e}get token(){return this.http.authToken}onChange(e){let n=de(this,nc).on("change",e);return de(this,tc)||this.getUserData().then(r=>{this.emitChange({...r,token:this.token})}).catch(r=>{this.emitChange({user:null,token:void 0})}),$e(this,tc,!0),n}async getUserData(){if(this.token)return(await this.http.get(`${this.settings.path}/userdata`)).data;throw new Error("missing auth.token")}async registerWithEmailAndPassword(e,n,r){let s=(await this.http.post(`${this.settings.path}/register`,{body:{email:e,password:n,options:r}})).data;return this.emitChange(s),s}async signInWithEmailAndPassword(e,n){let r=(await this.http.post(`${this.settings.path}/login`,{body:{email:e,password:n}})).data;return this.emitChange(r),r}async signInAnonymously(e){let n=(await this.http.post(`${this.settings.path}/anonymous`,{body:{options:e}})).data;return this.emitChange(n),n}async sendPasswordResetEmail(e){return(await this.http.post(`${this.settings.path}/forgot-password`,{body:{email:e}})).data}async signInWithProvider(e,n={}){return new Promise((r,s)=>{let o=n.width||480,i=n.height||768,a=this.token?`?token=${this.token}`:"",c=`Login with ${e[0].toUpperCase()+e.substring(1)}`,u=this.http.sdk.getHttpEndpoint(`${n.prefix||`${this.settings.path}/provider`}/${e}${a}`),l=screen.width/2-o/2,d=screen.height/2-i/2;$e(this,Nr,window.open(u,c,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+o+", height="+i+", top="+d+", left="+l));let f=p=>{if(!(p.data.user===void 0&&p.data.token===void 0))if(clearInterval(h),de(this,Nr)?.close(),$e(this,Nr,null),window.removeEventListener("message",f),p.data.error!==void 0){let y=new Error(String(p.data.error));y.code=p.data.error,p.data.reason!==void 0&&(y.reason=p.data.reason),p.data.until!==void 0&&(y.until=p.data.until),s(y)}else r(p.data),this.emitChange(p.data)},h=setInterval(()=>{(!de(this,Nr)||de(this,Nr).closed)&&($e(this,Nr,null),s("cancelled"),window.removeEventListener("message",f))},200);window.addEventListener("message",f)})}async signOut(){this.emitChange({user:null,token:null})}emitChange(e){e.token!==void 0&&(this.token=e.token,e.token===null?a0(this.settings.key):i0(this.settings.key,e.token)),de(this,nc).emit("change",e)}};tc=new WeakMap,Nr=new WeakMap,nc=new WeakMap;function u0(t){let e=window?.location?.hostname||"localhost",n=t.hostname.split("."),r=!t.hostname.includes("trycloudflare.com")&&!t.hostname.includes("discordsays.com")&&n.length>2?`/${n[0]}`:"";return t.pathname.startsWith("/.proxy")?`${t.protocol}//${e}${r}${t.pathname}${t.search}`:`${t.protocol}//${e}/.proxy/colyseus${r}${t.pathname}${t.search}`}Da();var l0=typeof window<"u"&&typeof window?.location?.hostname<"u"?`${window.location.protocol.replace("http","ws")}//${window.location.hostname}${window.location.port&&`:${window.location.port}`}`:"ws://127.0.0.1:2567",Al=class Al{constructor(e=l0,n){m(this,"http");m(this,"auth");m(this,"settings");m(this,"urlBuilder");if(typeof e=="string"){let r=e.startsWith("/")?new URL(e,l0):new URL(e),s=r.protocol==="https:"||r.protocol==="wss:",o=Number(r.port||(s?443:80));this.settings={hostname:r.hostname,pathname:r.pathname,port:o,secure:s,searchParams:r.searchParams.toString()||void 0}}else e.port===void 0&&(e.port=e.secure?443:80),e.pathname===void 0&&(e.pathname=""),this.settings=e;this.settings.pathname.endsWith("/")&&(this.settings.pathname=this.settings.pathname.slice(0,-1)),n?.protocol&&(this.settings.protocol=n.protocol),this.http=new El(this,{headers:n?.headers||{}},n?.fetchFn),this.auth=new ec(this.http),this.urlBuilder=n?.urlBuilder,!this.urlBuilder&&typeof window<"u"&&window?.location?.hostname?.includes("discordsays.com")&&(this.urlBuilder=u0,console.log("Colyseus SDK: Discord Embedded SDK detected. Using custom URL builder."))}static async selectByLatency(e,n,r={}){let s=e.map(i=>new Al(i,n)),o=(await Promise.allSettled(s.map((i,a)=>i.getLatency(r).then(c=>{let u=s[a].settings;return console.log(`\u{1F6DC} Endpoint Latency: ${c}ms - ${u.hostname}:${u.port}${u.pathname}`),[a,c]})))).filter(i=>i.status==="fulfilled").map(i=>i.value);if(o.length===0)throw new Error("All endpoints failed to respond");return s[o.sort((i,a)=>i[1]-a[1])[0][0]]}async joinOrCreate(e,n={},r){return await this.createMatchMakeRequest("joinOrCreate",e,n,r)}async create(e,n={},r){return await this.createMatchMakeRequest("create",e,n,r)}async join(e,n={},r){return await this.createMatchMakeRequest("join",e,n,r)}async joinById(e,n={},r){return await this.createMatchMakeRequest("joinById",e,n,r)}async reconnect(e,n){if(typeof e=="string"&&typeof n=="string")throw new Error("DEPRECATED: .reconnect() now only accepts 'reconnectionToken' as argument.\nYou can get this token from previously connected `room.reconnectionToken`");let[r,s]=e.split(":");if(!r||!s)throw new Error(`Invalid reconnection token format.
|
|
13
|
+
The format should be roomId:reconnectionToken`);return await this.createMatchMakeRequest("reconnect",r,{reconnectionToken:s},n)}async consumeSeatReservation(e,n){let r=this.createRoom(e.name,n);r.roomId=e.roomId,r.sessionId=e.sessionId;let s={sessionId:r.sessionId};return e.reconnectionToken&&(s.reconnectionToken=e.reconnectionToken),r.connect(this.buildEndpoint(e,s),{...e,protocol:this.settings.protocol},this.http.options.headers),new Promise((o,i)=>{let a=(c,u)=>i(new rr(c,u));r.onError.once(a),r.onJoin.once(()=>{r.onError.remove(a),ol("room",r),o(r)})})}getLatency(e={}){let n=e.protocol??"ws",r=e.pingCount??1,s=e.timeout??1500;return new Promise((o,i)=>{let a=new pi(n),c=[],u=0,l=!1,d,f=p=>{if(!l){l=!0,clearTimeout(d);try{a.close()}catch{}p()}},h=p=>f(()=>i(new rr(St.ABNORMAL_CLOSURE,`Failed to get latency: ${p}`)));d=setTimeout(()=>h(`timed out after ${s}ms`),s),a.events.onopen=()=>{u=Date.now(),a.send(new Uint8Array([Ke.PING]))},a.events.onmessage=p=>{if(c.push(Date.now()-u),c.length<r)u=Date.now(),a.send(new Uint8Array([Ke.PING]));else{let y=c.reduce((S,b)=>S+b,0)/c.length;f(()=>o(y))}},a.events.onclose=p=>h(`connection closed${p?.code?` (${p.code})`:""}${p?.reason?`: ${p.reason}`:""}`),a.events.onerror=p=>h(p.message);try{a.connect(this.getHttpEndpoint())}catch(p){h(p?.message??"failed to connect")}})}async createMatchMakeRequest(e,n,r={},s){try{if(!n)throw new Error("Must provide a room name");let i=(await this.http.post(`/matchmake/${e}/${n}`,{headers:{Accept:"application/json","Content-Type":"application/json"},body:r})).data;return e==="reconnect"&&(i.reconnectionToken=r.reconnectionToken),await this.consumeSeatReservation(i,s)}catch(o){throw o instanceof rr?new wa(o.message,o.code):o}}createRoom(e,n){return new Za(e,n)}buildEndpoint(e,n={}){let r=this.settings.protocol||"ws",s=this.settings.searchParams||"";this.http.authToken&&(n._authToken=this.http.authToken);for(let a in n)n.hasOwnProperty(a)&&(s+=(s?"&":"")+`${a}=${n[a]}`);r==="h3"&&(r="http");let o=this.settings.secure?`${r}s://`:`${r}://`;e.publicAddress?o+=`${e.publicAddress}`:o+=`${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}`;let i=`${o}/${e.processId}/${e.roomId}?${s}`;return this.urlBuilder?this.urlBuilder(new URL(i)):i}getHttpEndpoint(e=""){let n=e.startsWith("/")?e:`/${e}`,r=`${this.settings.secure?"https":"http"}://${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}${n}`;return this.settings.searchParams&&(r+=`?${this.settings.searchParams}`),this.urlBuilder?this.urlBuilder(new URL(r)):r}getEndpointPort(){return this.settings.port!==80&&this.settings.port!==443?`:${this.settings.port}`:""}};m(Al,"VERSION","0.18");var kl=Al,Br=kl;Pr();var Pl=class{setState(e){}getState(){return null}patch(e){}teardown(){}handshake(e){}};Pt();jp();Ol();Il();Cl();Mp("schema",hi);Mp("none",Pl);var Q2=Object.freeze({min:3,max:3}),ez=Object.freeze({min:4,max:4});var co={PLAY:"play",QUEUE:"queue",MATCH:"match",AUTHORITY:"authority"};var Wp={CAPS:"caps",SDK:"sdk",MATCH_KEY:"matchKey",PRIVATE:"private",SUCCESSOR_OF:"successorOf",SUCCESSOR_CLOSED:"successorClosed"},k0="ts/0.17.9",dn={PHYSICS:"physics@1",PHYSICS_PREDICT:"physics@2",INPUT_REPEAT:"repeat@1",LIFTS:"lifts@1",INPUT_TICK:"tick@1",FAST:"fast@1",FAST_RETURN:"fast-return@1",MAX_CAPS:16,MAX_CAP_CHARS:32};var lT=["clients","preset","winCondition","config","matchmade"],tz=[...lT,"moduleSha","tickHz","maxPlayers","lagComp","seed","units","leaseId","region","createdBy"],fn={BAD_OPTION:400,AUTH_REQUIRED:401,FORBIDDEN:403,WRONG_REGION:421,PROTOCOL_UNSUPPORTED:426,NOT_ENTITLED:402,ROOM_QUOTA:429,MODULE_UNAVAILABLE:424,AUTHORITY_CAPACITY:503},A0="free_quota_exhausted";var he={STATE:"state",STATE_SNAP:"__state:snap",SHARED:"shared",CLAIM:"claim",RELEASE:"release",DESTROY:"destroy",OBJECT:"obj",OBJECT_SNAP:"__object:snap",INPUT:"__input",ROOM_OPEN:"__room:open",CHAT:"__chat",CHAT_HISTORY_REQUEST:"__chat:history:request",VOICE_ICE_REQUEST:"__voice:ice:request",VOICE_JOIN:"__voice:join",VOICE_LEAVE:"__voice:leave",VOICE_SIGNAL:"__voice:signal",MATCH_ELIMINATED:"match:eliminated",MATCH_SCORE:"match:score",MATCH_FINISH:"match:finish",POSE:"__pose",POSE_SNAP:"__pose:snap"},xe={OBJECT_RESULT:"__object:result",INPUT:"__input",ROOM_OPEN:"__room:open",CHAT:"__chat",CHAT_HISTORY:"__chat:history",VOICE_ICE:"__voice:ice",VOICE_SIGNAL:"__voice:signal",VOICE_REJECTED:"__voice:rejected",RATE_DROP:"rate:drop",SERVER_RESTART:"server:restart",MATCH_START:"match:start",MATCH_ENDED:"match:ended",MATCH_REQUEUE:"match:requeue",QUEUE:"queue",SEAT:"seat"},dT=["__","match:","server:","rate:"],fT=["state","shared","claim","release","destroy","obj","queue","seat"];function ws(t){return fT.includes(t)||dT.some(e=>t.startsWith(e))}var zl="__",yr="__t";var nz=4*1024;var rz={[he.STATE]:"state",[he.STATE_SNAP]:"state",[he.SHARED]:"bulk",[he.CLAIM]:"control",[he.RELEASE]:"control",[he.DESTROY]:"control",[he.OBJECT]:"bulk",[he.OBJECT_SNAP]:"bulk",[he.INPUT]:"input",[he.ROOM_OPEN]:"control",[he.CHAT]:"chat",[he.CHAT_HISTORY_REQUEST]:"control",[he.VOICE_ICE_REQUEST]:"voice",[he.VOICE_JOIN]:"voice",[he.VOICE_LEAVE]:"voice",[he.VOICE_SIGNAL]:"voice",[he.MATCH_ELIMINATED]:"bulk",[he.MATCH_SCORE]:"bulk",[he.MATCH_FINISH]:"bulk",[he.POSE]:"pose",[he.POSE_SNAP]:"pose"},pn={GOING_AWAY:1001,NO_STATUS:1005,ABNORMAL:1006,MAY_TRY_RECONNECT:4010,NORMAL:1e3,CONSENTED:4e3,MATCH_BOOT:4e3,SERVER_SHUTDOWN:4001,WITH_ERROR:4002,FAILED_TO_RECONNECT:4003,REVOKED:4401,SUPERSEDED:4409,IDLE:4408,MODULE_HALTED:4500,MODULE_FAULT:4501},pT={ModuleTimeout:"module_timeout",ModuleMemory:"module_memory",ModuleError:"module_error",ModuleOutputInvalid:"module_output_invalid",ModuleBudget:"module_budget",Halted:"halted",HostStall:"host_stall",PhysicsBudget:"physics_budget",RoomAge:"room_age",ModuleBandwidth:"module_bandwidth",PhysicsInternal:"physics_internal"};function P0(t){return Object.values(pT).includes(t)?t:null}var Xt={ROOM_MAX_CLIENTS:64,MAX_NAME_CHARS:64,MAX_AVATAR_URL_CHARS:512,MAX_UID_CHARS:64,MAX_STATE_BYTES:16*1024,MAX_SHARED_KEY_CHARS:256,MAX_SHARED_VALUE_BYTES:64*1024,MAX_SHARED_KEYS:256,MAX_OBJECT_ID_CHARS:128,MAX_OBJECT_STATE_BYTES:64*1024,MAX_OBJECTS:128,MAX_REQUEST_ID_CHARS:96,MAX_EVENT_BYTES:16*1024,MAX_EVENT_TYPE_CHARS:128,MAX_JSON_DEPTH:32,MAX_JSON_NODES:4096,MAX_CHAT_CHARS:500,CHAT_HISTORY_MAX:50,CHAT_HISTORY_MAX_BYTES:8*1024,MAX_VOICE_PARTICIPANTS:6,MAX_VOICE_SIGNAL_BYTES:8*1024,MAX_SCORE_DELTA:1e3,CONTROL_RESULTS_PER_SESSION:128,CONTROL_RESULT_TTL_MS:6e4,MAX_TEAMS:8,MAX_ANIM_CHARS:64,MAX_POSE_ABS:1e9},sz={PATCH_INTERVAL_MS:1e3/30,RECONNECT_GRACE_S:30,GOING_AWAY_GRACE_S:5,HOST_FAILOVER_GRACE_MS:1500,MIN_OWNERSHIP_HOLD_MS:300,SHUTDOWN_DRAIN_MS:3e3,REQUEUE_GRACE_MS:5e3,SEAT_RESERVATION_S:15,QUEUE_TICK_MS:1e3,REVOCATION_SWEEP_MS:3e4},Ss={TICK_HZ:30,RENDER_DELAY_MS:100,MAX_REWIND_MS:500,INPUT_BUFFER:32,PATCH_INTERVAL_MS:50,INPUT_REPEAT_MAX_MS:100,INPUT_REPEAT_RUN_MS:33},hn={enabled:!0,minUptime:0,delay:125,minDelay:100,maxDelay:4e3,maxRetries:9,maxEnqueuedMessages:0,firstStateTimeoutMs:2e3},T0=["x","y","z","yaw","vx","vy","vz","anim"],Ge={RATIO:1.5,JITTER_SAFETY:1.25,MIN_MS:90,MAX_MS:300,DEFAULT_MS:100,EASE:.1,CLOCK_WINDOW:80,CLOCK_WINDOW_MS:5e3,CLOCK_WINDOW_MAX:4096,INTERVAL_WINDOW:30,MIN_GAP_MS:5,MAX_GAP_MS:2e3,HISTORY_MS:1500,MAX_EXTRAP_MS:250,ROT_EXTRAP_MS:150,SMOOTH_TAU_POS_MS:30,SMOOTH_TAU_ROT_MS:70,POISON_GUARD_MS:2e3,REBASE_AFTER_GAP_MS:1e3,MAX_HOST_TICK_DT_MS:250},Fr={HEARTBEAT_HZ:10,MIN_HEARTBEAT_HZ:5,MAX_HEARTBEAT_HZ:20,HEARTBEAT_DITHER:.15,RELAY_BUFFER:4,WARMUP_ACKS:30};var uo={SAMPLES:3,TIMEOUT_MS:4e3,GRACE_MS:1e3};async function v0(t,e={}){let n=t[0];if(n===void 0)throw new Error("genex multiplayer: `urls` must contain at least one relay URL");if(t.length===1)return n;let r=e.probe??qp,s=Math.max(1,e.samples??uo.SAMPLES),o=e.timeoutMs??uo.TIMEOUT_MS,i=e.graceMs??uo.GRACE_MS,a=t.map(()=>{});await new Promise(u=>{let l=t.length*s,d,f=setTimeout(h,o);function h(){clearTimeout(f),clearTimeout(d),u()}let p=()=>{--l===0&&h()};t.forEach((y,S)=>{for(let b=0;b<s;b++){let x;try{x=r(y,o)}catch(R){x=Promise.reject(R)}x.then(R=>{Number.isFinite(R)&&R>=0&&(a[S]=Math.min(a[S]??1/0,R),d??(d=setTimeout(h,i))),p()},p)}})});let c=-1;return a.forEach((u,l)=>{u!==void 0&&(c<0||u<a[c])&&(c=l)}),c<0?(console.warn(`genex multiplayer: no relay answered the latency probe \u2014 connecting to ${n}`),n):t[c]}var qp=(t,e)=>new Br(t).getLatency({pingCount:1,timeout:e});var hT=t=>typeof t=="function"?t():t;async function lc(t){return t.url?new Br(t.url):new Br(await v0(t.urls))}function dc(t,e,n){return{gameId:t,name:e,embedToken:hT(n)?.embedToken,protocol:3}}var fc=t=>!!t&&typeof t=="object"&&t.code===fn.PROTOCOL_UNSUPPORTED,Gp=()=>console.error(`[multiplayer] the relay refused protocol ${3} (code 426) \u2014 this game was built with a @genex-ai/multiplayer that this relay no longer serves. Update the package and republish.`),M0=t=>{throw fc(t)&&Gp(),t};function C0(t,e){let n=null,r=null;return{request(){return n||(n=new Promise(s=>{let o,i=a=>{r&&(r=null,n=null,o&&clearTimeout(o),s(a))};r=i,o=setTimeout(()=>i(null),e),t()}),n)},deliver(s){r?.(s)},get pending(){return n!==null}}}var O0=["x","y","z","yaw","vx","vy","vz"],I0=[["x","vx"],["y","vy"],["z","vz"]],Yp=Math.PI*2,mT=t=>T0.includes(t);function Kp(t){if(!Number.isFinite(t))return 0;let e=t%Yp;return e<=-Math.PI?e+=Yp:e>Math.PI&&(e-=Yp),e}var D0=t=>typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=Xt.MAX_POSE_ABS;function N0(t){let e={},n={},r=[];for(let s of Object.keys(t)){let o=t[s];if(!mT(s)){n[s]=o;continue}o!==void 0&&(s==="anim"?typeof o=="string"&&o.length<=Xt.MAX_ANIM_CHARS?e.anim=o:r.push(s):D0(o)?e[s]=o:r.push(s))}return{pose:e,data:n,invalid:r}}function B0(t){for(let e in t)if(t[e]!==void 0)return!0;return!1}function L0(t,e,n){let r={...t},s={t:e},o=n?e-n.t:0,i=n!==void 0&&o>Ge.MIN_GAP_MS&&o<Ge.MAX_GAP_MS;for(let[a,c]of I0){let u=t[a];if(u===void 0||(s[a]=u,t[c]!==void 0))continue;let l=n?.[a],d=i&&l!==void 0?(u-l)/o*1e3:0;r[c]=D0(d)?d:0}return{pose:r,memory:s}}function $l(t){let e=n=>typeof n=="number"&&Number.isFinite(n)?n:0;return{x:e(t.x),y:e(t.y),z:e(t.z),yaw:e(t.yaw),vx:e(t.vx),vy:e(t.vy),vz:e(t.vz),anim:typeof t.anim=="string"?t.anim:""}}var Mi=(t,e)=>{let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0};function F0(t,e){let n=t.length;if(n===0)return;let r=0;for(;r<n&&t[r].t<=e;)r++;if(r===0)return t[0].state;if(r>=n){let u=t[n-1],l={...u.state},d=Math.min(Math.max(0,e-u.t),Ge.MAX_EXTRAP_MS)/1e3;for(let[f,h]of I0)l[f]=Mi(u.state,f)+Mi(u.state,h)*d;if(n>=2){let f=t[n-2],h=u.t-f.t;if(h>0){let p=Math.min(Math.max(0,e-u.t),Ge.ROT_EXTRAP_MS)/h,y=Mi(u.state,"yaw");l.yaw=y+Kp(y-Mi(f.state,"yaw"))*p}}return l}let s=t[r-1],o=t[r],i=o.t-s.t,a=i>0?(e-s.t)/i:1,c={...s.state};for(let u of O0){let l=Mi(s.state,u),d=Mi(o.state,u);c[u]=u==="yaw"?l+Kp(d-l)*a:l+(d-l)*a}return c}function z0(t,e,n,r){let s={...e};for(let o of O0){let i=t[o],a=e[o];typeof i!="number"||typeof a!="number"||!Number.isFinite(i)||!Number.isFinite(a)||(s[o]=o==="yaw"?i+Kp(a-i)*r:i+(a-i)*n)}return s}var Hl=class Hl{constructor(){m(this,"pending",[]);m(this,"current")}push(e,n){for(this.pending.push({t:e,state:n});this.pending.length>Hl.MAX_PENDING;)this.current=this.pending.shift()?.state}at(e){for(;this.pending.length>0;){let n=this.pending[0];if(this.current!==void 0&&e!==void 0&&n.t!==void 0&&n.t>e)break;this.current=n.state,this.pending.shift()}return this.current}flush(){this.at(void 0)}};m(Hl,"MAX_PENDING",64);var Vl=Hl;function U0(t){try{let e=t.input();return e&&typeof e.send=="function"?e:null}catch{return null}}function V0(t,e,n=Fr.HEARTBEAT_HZ,r=Math.random){let o=1e3/Math.min(Fr.MAX_HEARTBEAT_HZ,Math.max(Fr.MIN_HEARTBEAT_HZ,n)),i=1e3/Fr.MAX_HEARTBEAT_HZ,a=1e3/Fr.MIN_HEARTBEAT_HZ,c=!1,u=!1,l,d=()=>{if(u)return;if(e()){try{t.send()}catch{}!c&&t.lastProcessed>=Fr.WARMUP_ACKS&&(c=!0)}let f=o*(1+(r()*2-1)*Fr.HEARTBEAT_DITHER);l=setTimeout(d,Math.min(a,Math.max(i,f)))};return d(),{get synced(){return!c&&t.lastProcessed>=Fr.WARMUP_ACKS&&(c=!0),c},stop(){u=!0,l&&clearTimeout(l)}}}function H0(t,e){return e.synced&&e.clockOrigin>0&&e.serverNow!==void 0&&Number.isFinite(e.serverNow)?t-e.clockOrigin-e.serverNow:t-e.wallNow}function xs(t){let e=t.reconnection;return e.enabled=hn.enabled,e.minUptime=hn.minUptime,e.delay=hn.delay,e.minDelay=hn.minDelay,e.maxDelay=hn.maxDelay,e.maxRetries=hn.maxRetries,e.maxEnqueuedMessages=hn.maxEnqueuedMessages,e.enqueuedMessages.length=0,t}function $0(t){return t.reconnection.enabled=!1,t}function pc(t,e){return new Promise(n=>{let r=()=>{clearTimeout(s),n(!0)},s=setTimeout(()=>{t.onStateChange.remove(r),n(!1)},e);t.onStateChange.once(r)})}function j0(t,e,n){return t!==e&&n!=null}var yT="The microphone was refused by the page that frames this game, not by the player: the frame was not given it, so the browser never asked. On its Genex page a build is given the microphone only when it declares it. An up-to-date genex CLI declares it at `genex preview` and `genex publish` when the game's own source calls voice.join(); to declare it by hand, add \"microphone\" to genex.capabilities in the game's package.json. Then preview or publish again.",Xp=class extends Error{constructor(e){super(yT,{cause:e}),this.name="VoiceNotDelegatedError"}},W0=[{urls:"stun:stun.l.google.com:19302"}],gT=120,q0=.02,bT=.6,jl=class{constructor(e){m(this,"transport");m(this,"peers",new Map);m(this,"listeners",new Set);m(this,"roster",[]);m(this,"local",null);m(this,"audio",null);m(this,"localAnalyser",null);m(this,"levelTimer",null);m(this,"iceServers",W0);m(this,"spatial",!1);m(this,"threshold",q0);m(this,"micOn",!0);m(this,"selfSpeaking",!1);m(this,"running",!1);m(this,"peeringHeld",!1);this.transport=e}get active(){return this.running}get micEnabled(){return this.micOn}get speaking(){return this.selfSpeaking}get participants(){return[...this.peers.values()].map(e=>({id:e.id,name:this.transport.nameOf(e.id),stream:e.stream,speaking:e.speaking,muted:e.muted,volume:e.volume,connection:e.connection}))}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async start(e={},n=!1){if(!this.running){this.peeringHeld=n,this.iceServers=e.iceServers?.length?e.iceServers:W0,this.spatial=e.spatial===!0,this.threshold=e.speakingThreshold??q0,this.micOn=e.startMuted!==!0;try{this.local=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1})}catch(r){throw ST(r)}for(let r of this.local.getAudioTracks())r.enabled=this.micOn;this.audio=new AudioContext,this.localAnalyser=this.makeAnalyser(this.local),this.running=!0,this.levelTimer=setInterval(()=>this.pollLevels(),gT)}}stop(){this.running=!1,this.peeringHeld=!1,this.levelTimer&&(clearInterval(this.levelTimer),this.levelTimer=null);for(let e of[...this.peers.keys()])this.destroyPeer(e);for(let e of this.local?.getTracks()??[])e.stop();this.local=null,this.localAnalyser=null,this.audio?.close().catch(()=>{}),this.audio=null,this.roster=[],this.selfSpeaking=!1,this.emit()}setIceServers(e){if(e.length){this.iceServers=e;for(let n of this.peers.values())try{n.pc.setConfiguration({iceServers:e})}catch{}}}releasePeering(){this.peeringHeld&&(this.peeringHeld=!1,this.setRoster(this.roster))}setRoster(e){if(this.roster=e,!this.running||this.peeringHeld)return;let n=this.transport.selfId(),r=new Set(e.filter(s=>s!==n));for(let s of r)this.peers.has(s)||this.createPeer(s);for(let s of[...this.peers.keys()])r.has(s)||this.destroyPeer(s);this.emit()}setMicEnabled(e){this.micOn=e;for(let n of this.local?.getAudioTracks()??[])n.enabled=e;!e&&this.selfSpeaking&&(this.selfSpeaking=!1,this.emit())}mute(e){this.setMuted(e,!0)}unmute(e){this.setMuted(e,!1)}setVolume(e,n){let r=this.peers.get(e);r&&(r.volume=Math.max(0,Math.min(1,n)),r.el&&(r.el.volume=r.volume),this.emit())}async handleSignal(e,n){if(!this.running)return;let r=n;if(!r||typeof r!="object"||typeof r.t!="string")return;let s=this.peers.get(e)??(this.roster.includes(e)?this.createPeer(e):void 0);if(s)try{if(r.t==="offer"){await s.pc.setRemoteDescription(r.sdp),await this.flushIce(s);let o=await s.pc.createAnswer();await s.pc.setLocalDescription(o),this.transport.sendSignal(e,{t:"answer",sdp:o})}else if(r.t==="answer"){if(s.pc.signalingState!=="have-local-offer")return;await s.pc.setRemoteDescription(r.sdp),await this.flushIce(s)}else r.t==="ice"&&(s.pc.remoteDescription?await s.pc.addIceCandidate(r.c):s.pendingIce.push(r.c))}catch(o){console.warn(`[multiplayer] voice signaling failed with ${e}`,o)}}setMuted(e,n){let r=this.peers.get(e);!r||r.muted===n||(r.muted=n,r.el&&(r.el.muted=n||this.spatial),n&&r.speaking&&(r.speaking=!1),this.emit())}createPeer(e){let n=new RTCPeerConnection({iceServers:this.iceServers}),r={id:e,pc:n,el:null,stream:null,analyser:null,pendingIce:[],speaking:!1,muted:!1,volume:1,connection:"connecting"};this.peers.set(e,r);for(let s of this.local?.getAudioTracks()??[])this.local&&n.addTrack(s,this.local);return n.onicecandidate=s=>{s.candidate&&this.transport.sendSignal(e,{t:"ice",c:s.candidate.toJSON()})},n.ontrack=s=>{let o=s.streams[0]??new MediaStream([s.track]);r.stream=o,r.el=this.attachSink(o,r),r.analyser=this.makeAnalyser(o),this.emit()},n.onconnectionstatechange=()=>{let s=n.connectionState,o=s==="connected"?"connected":s==="failed"||s==="closed"?"failed":"connecting";if(o!==r.connection){if(r.connection=o,o==="failed"){let i=this.iceServers.some(a=>xT(a));console.warn(`[multiplayer] voice connection to ${e} failed`+(i?"":" \u2014 no TURN in the ICE list (relay offered none?)"))}this.emit()}},this.transport.selfId()<e&&this.offer(r),r}async offer(e){try{let n=await e.pc.createOffer();await e.pc.setLocalDescription(n),this.transport.sendSignal(e.id,{t:"offer",sdp:n})}catch(n){console.warn(`[multiplayer] voice offer to ${e.id} failed`,n)}}async flushIce(e){let n=e.pendingIce.splice(0);for(let r of n)try{await e.pc.addIceCandidate(r)}catch{}}destroyPeer(e){let n=this.peers.get(e);if(n){this.peers.delete(e),n.pc.onicecandidate=null,n.pc.ontrack=null,n.pc.onconnectionstatechange=null;try{n.pc.close()}catch{}n.el&&(n.el.srcObject=null,n.el.remove())}}attachSink(e,n){let r=document.createElement("audio");return r.autoplay=!0,r.srcObject=e,r.muted=this.spatial||n.muted,r.volume=n.volume,r.style.display="none",document.body.appendChild(r),r.play().catch(s=>{console.warn("[multiplayer] voice playback was blocked \u2014 join voice from a click/tap",s)}),r}makeAnalyser(e){if(!this.audio)return null;try{let n=this.audio.createMediaStreamSource(e),r=this.audio.createAnalyser();return r.fftSize=512,n.connect(r),r}catch{return null}}pollLevels(){let e=!1,n=this.micOn?G0(this.localAnalyser):0,r=this.crossed(n,this.selfSpeaking);r!==this.selfSpeaking&&(this.selfSpeaking=r,e=!0);for(let s of this.peers.values()){let o=s.muted?!1:this.crossed(G0(s.analyser),s.speaking);o!==s.speaking&&(s.speaking=o,e=!0)}e&&this.emit()}crossed(e,n){return e>=(n?this.threshold*bT:this.threshold)}emit(){for(let e of[...this.listeners])try{e()}catch(n){console.error("[multiplayer] a voice listener threw",n)}}};function wT(){try{return window.self!==window.top}catch{return!0}}function ST(t){if(t?.name!=="NotAllowedError")return t;try{if(!wT()||document.featurePolicy?.allowsFeature?.("microphone")!==!1)return t}catch{return t}return new Xp(t)}function xT(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some(n=>typeof n=="string"&&n.startsWith("turn"))}function G0(t){if(!t)return 0;let e=new Uint8Array(t.fftSize);t.getByteTimeDomainData(e);let n=0;for(let r=0;r<e.length;r++){let s=((e[r]??128)-128)/128;n+=s*s}return Math.sqrt(n/e.length)}var Jp=Symbol("genex.roomRef"),zr=t=>t[Jp]();var _T=Ge.RATIO,RT=Ge.MIN_MS,ET=Ge.MAX_MS,Wl=Ge.DEFAULT_MS,kT=Ge.JITTER_SAFETY,AT=Ge.POISON_GUARD_MS,PT=Ge.EASE,TT=Ge.MAX_EXTRAP_MS,vT=Ge.ROT_EXTRAP_MS,K0=Ge.CLOCK_WINDOW,MT=Ge.CLOCK_WINDOW_MS,CT=Ge.CLOCK_WINDOW_MAX,OT=Ge.INTERVAL_WINDOW,IT=Ge.MIN_GAP_MS,DT=Ge.MAX_GAP_MS,NT=Ge.HISTORY_MS,BT=Ge.SMOOTH_TAU_POS_MS,LT=Ge.SMOOTH_TAU_ROT_MS,X0=Ge.MAX_HOST_TICK_DT_MS,FT=Ge.REBASE_AFTER_GAP_MS,gr="obj:",zT=3e3,UT=5e3,VT=6e4,HT=2e3;function Q0(t){if(t==="predict")return{mode:"lerp"};if(t&&typeof t=="object"&&t.engine==="predict")return{mode:t.mode==="damped"?"damped":"lerp",delay:t.delay,smoothMs:t.smoothMs}}var Yl=async t=>Q0(t)?Promise.resolve().then(()=>(Zp(),Y0)):void 0;function J0(t){if(!t)return{state:{}};try{let e=JSON.parse(t);if(!e||typeof e!="object")return{state:{}};let n=e,r=n[yr];if(typeof r=="number"&&Number.isFinite(r)){let s={...n};return delete s[yr],{state:s,sendTime:r}}return{state:n}}catch{return{state:{}}}}function ql(t){if(t!=null)try{return JSON.parse(t)}catch{return}}var $T=(t,e)=>typeof e=="number"?Number.isFinite(e)?e:0:typeof e=="bigint"?Number(e):e;function Ci(t){return JSON.parse(JSON.stringify(t,$T))}var lo=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function ew(t,e,n){let[r,s,o,i]=e,[a,c,u,l]=t,d=a*r+c*s+u*o+l*i;if(d<0&&(r=-r,s=-s,o=-o,i=-i,d=-d),d>.9995){let S=a+(r-a)*n,b=c+(s-c)*n,x=u+(o-u)*n,R=l+(i-l)*n,A=Math.hypot(S,b,x,R)||1;return[S/A,b/A,x/A,R/A]}let f=Math.acos(d),h=Math.sin(f),p=Math.sin(f-f*n)/h,y=Math.sin(f*n)/h;return[a*p+r*y,c*p+s*y,u*p+o*y,l*p+i*y]}function Gl(t){return Array.isArray(t)&&t.length===4&&t.every(e=>typeof e=="number"&&Number.isFinite(e))}function Z0(t,e,n,r){let s={},o=n<1;for(let i in e){let a=t[i],c=e[i];typeof a=="number"&&typeof c=="number"&&Number.isFinite(a)&&Number.isFinite(c)?s[i]=a+(c-a)*n:Gl(a)&&Gl(c)?s[i]=ew(a,c,r):s[i]=o&&i in t?a:c}return s}function jT(t,e,n,r){let s={};for(let o in e){let i=e[o],a=t[o];typeof a=="number"&&typeof i=="number"&&Number.isFinite(a)&&Number.isFinite(i)?s[o]=a+(i-a)*n:Gl(a)&&Gl(i)?s[o]=ew(a,i,r):s[o]=i}return s}function WT(t,e){let n=t.length;if(n===0)return;if(n===1)return t[0].state;let r=0;for(;r<n&&t[r].t<=e;)r++;if(r===0)return t[0].state;if(r>=n){let c=t[n-2],u=t[n-1],l=u.t-c.t;if(l<=0)return u.state;let d=(Math.min(e,u.t+TT)-c.t)/l,f=(Math.min(e,u.t+vT)-c.t)/l;return Z0(c.state,u.state,d,f)}let s=t[r-1],o=t[r],i=o.t-s.t,a=i>0?(e-s.t)/i:1;return Z0(s.state,o.state,a,a)}function qT(t){if(t.length===0)return 66;let e=[...t].sort((n,r)=>n-r);return e[e.length>>1]}function GT(t,e){if(t.length===0)return 0;let n=[...t].sort((s,o)=>s-o),r=Math.min(n.length-1,Math.max(0,Math.round(e*(n.length-1))));return n[r]}async function tw(t){let e=await lc(t),n=await Yl(t.smoothing),r=xs(await e.joinOrCreate(co.PLAY,{...dc(t.room,t.name,t.auth),...t.options,protocol:3}).catch(M0));return Qp(r,{pose:t.pose,smoothing:t.smoothing,predict:n})}var YT=t=>typeof t=="string"&&t.length>0&&t.length<=Xt.MAX_EVENT_TYPE_CHARS&&!ws(t),KT=new Set(["join","leave","change","shared","object","host","reconnecting","reconnected","disconnect","room:open","voice","voice:rejected"]),XT=new Set([xe.OBJECT_RESULT,xe.INPUT,xe.ROOM_OPEN,xe.CHAT,xe.CHAT_HISTORY,xe.VOICE_ICE,xe.VOICE_SIGNAL,xe.VOICE_REJECTED,xe.RATE_DROP,...Object.values(he)]),JT=[500,1e3,2e3,4e3,8e3];function Qp(t,e={}){let n=new Map,r=new Map,s=new Map,o=new Map,i=new Map,a=new Map,c=new Set,u=new Map,l=new Map,d=new Map,f=new Map,h,p=new Map,y=new Map,S=new Map,b=new Map,x=new Map,R=new Map,A=new Map,E=new Map,P=new Set,k=new Map,M,B=0,K=new Map,j=w=>{for(let C of K.values())if(C.id===w)return!0;return!1},L=typeof globalThis<"u"&&globalThis.__GENEX_MP_TEST_SKEW__||0,se=L?()=>lo()+L:lo,v=(w,C)=>{if(p.get(C)===t.sessionId)return!1;let V=`${w}:${C}`;return P.has(V)||(P.add(V),console.warn(`[multiplayer] objects.${w}('${C}') ignored because this session does not own the object \u2014 await objects.claimConfirmed('${C}') and check accepted before publishing`)),!0},$=(w,C,V,X)=>{let we=se(),pe=V,Me=we-V,ie=o.get(X);ie||o.set(X,ie={samples:[],mins:[],n:0});let Ne=++ie.n;for(ie.samples.push({at:we,n:Ne});ie.mins.length>0&&ie.mins[ie.mins.length-1].v>=Me;)ie.mins.pop();for(ie.mins.push({v:Me,n:Ne});ie.samples.length>CT||ie.samples.length>K0&&ie.samples[0].at<we-MT;)ie.samples.shift();let ze=ie.samples[0].n;for(;ie.mins[0].n<ze;)ie.mins.shift();s.set(X,ie.mins[0].v);let nt=i.get(w);nt||i.set(w,nt=[]),nt.push(Me),nt.length>K0&&nt.shift(),a.set(w,X);let ut=r.get(w);if(r.set(w,pe),ut!=null){let rt=pe-ut;if(rt>IT&&rt<DT){let Er=d.get(w);Er||d.set(w,Er=[]),Er.push(rt),Er.length>OT&&Er.shift();let Yd=nt.length>=8?Math.max(0,GT(nt,.9)-ie.mins[0].v):0,tu=Math.min(ET,Math.max(RT,_T*qT(Er),kT*Yd)),Qn=f.get(w)??Wl;f.set(w,Qn+(tu-Qn)*PT)}}let Qe=n.get(w);Qe||n.set(w,Qe=[]);let Jn=k.get(w);if(Jn&&Qe.length===0){let rt=f.get(w)??Wl;Qe.push({t:pe-Math.max(1,rt),state:Jn})}k.delete(w),Qe.push({t:pe,state:C});let Zn=pe-NT;for(;Qe.length>2&&Qe[0].t<Zn;)Qe.shift();for(;Qe.length>1&&Qe[0].t>Qe[Qe.length-1].t+AT;)Qe.shift()},G=(w,C)=>{let V=a.get(w),X=V===void 0?void 0:s.get(V);if(X!==void 0)return C-X-(f.get(w)??Wl)},W=(w,C)=>{let V=n.get(w),X=G(w,C)??C-Wl,we=c.has(w),pe=V&&(we?F0(V,X):WT(V,X));if(!pe)return u.get(w);let Me=u.get(w),ie;if(Me){let Ne=Math.min(X0,Math.max(0,C-(l.get(w)??C))),ze=1-Math.exp(-Ne/BT),nt=1-Math.exp(-Ne/LT);ie=we?z0(Me,pe,ze,nt):jT(Me,pe,ze,nt)}else ie=pe;return u.set(w,ie),l.set(w,C),ie},q=w=>{n.delete(w),r.delete(w),a.delete(w),u.delete(w),l.delete(w),d.delete(w),f.delete(w),i.delete(w),k.delete(w)},ae=w=>{n.delete(w),r.delete(w),a.delete(w),d.delete(w),f.delete(w),i.delete(w)},ce=w=>{s.delete(w),o.delete(w)},ne=new Map,Re=new Set,oe=(w,...C)=>ne.get(w)?.forEach(V=>{try{V(...C)}catch(X){console.error(`[multiplayer] a '${w}' listener threw:`,X)}}),ee=new Map,ue=(w,C)=>{ee.get(C)!==w&&(ee.set(C,w),oe("shared",C,ql(w)))},Ae=w=>{let C=w||void 0;C!==M&&(M=C,oe("host",M))},pt="",Bt=()=>{let w=t.state?.voice?[...t.state.voice.keys()].sort():[],C=w.join(`
|
|
14
|
+
`);C!==pt&&(pt=C,Ve.setRoster(w),oe("voice",Ve.participants))},_r=(w,C)=>{let V=gr+w,X=t.sessionId,we=b.has(w),pe=C.owner||void 0,Me=Number.isFinite(C.seq)?C.seq:0,ie=Number.isFinite(C.epoch)?C.epoch:0,Ne=Number.isFinite(C.t)?C.t:0,ze=typeof C.d=="string"?C.d:"",ut=pe!==y.get(w)||we&&Me!==b.get(w),Qe=S.has(w)&&ie!==S.get(w),Jn=Ne!==x.get(w);if(b.set(w,Me),S.set(w,ie),x.set(w,Ne),ze!==R.get(w)){R.set(w,ze);let rt=ze?ql(ze):void 0;rt&&typeof rt=="object"&&!Array.isArray(rt)&&A.set(w,rt)}pe?y.set(w,pe):y.delete(w),(ut||p.get(w)!==pe&&!j(w))&&(pe?p.set(w,pe):p.delete(w)),Qe&&q(V),ut&&pe!==X&&(E.delete(w),Qe||ae(V));let Zn=A.get(w);if(Zn&&pe!==X){let rt=Ne!==0&&Jn&&pe!==void 0;Qe?(u.set(V,Zn),l.set(V,se()),rt&&$(V,Zn,Ne,pe)):(ut&&k.set(V,u.get(V)??Zn),rt&&$(V,Zn,Ne,pe))}(!we||ut)&&oe("object",w)},Gn=w=>{let C=b.has(w)||p.has(w)||A.has(w)||E.has(w);q(gr+w),A.delete(w),p.delete(w),y.delete(w),S.delete(w),b.delete(w),x.delete(w),R.delete(w),E.delete(w),C&&oe("object",w)},Co=new Map,Ms=new Map,na=new Map,qd=(w,C)=>{if(!C)return{};let V=Co.get(w);if(V&&V.raw===C)return V.state;let{state:X}=J0(C);return Co.set(w,{raw:C,state:X}),X},An=new Map,bn=new Map,Yn=e.predict?Q0(e.smoothing):void 0,ct,Kn=new Map,Gd=(w,C)=>{if(!Yn||!e.predict)return;ct??(ct=e.predict.Predict.get(t));let V={mode:Yn.mode,delay:Yn.delay,smoothMs:Yn.smoothMs};ct.attach(C,{x:V,y:V,z:V,vx:V,vy:V,vz:V}),ct.attach(C,{yaw:{...V,angle:!0}}),Kn.set(w,C)},Wc=w=>{let C=Kn.get(w);C&&ct&&ct.detach(C),Kn.delete(w)},qc=w=>{let C=ct;return{x:C.value(w,"x"),y:C.value(w,"y"),z:C.value(w,"z"),yaw:C.value(w,"yaw"),vx:C.value(w,"vx"),vy:C.value(w,"vy"),vz:C.value(w,"vz"),anim:w.anim??""}},en=!1,Pn=!1,bt=!0,Xr=!1,ra=0,Jr=0,sa=0,oa=new Set,Cs=()=>oa.forEach(w=>w()),Os=(w,C)=>{if(K.delete(w.requestId),w.timeout&&clearTimeout(w.timeout),w.abort?.(),w.operation==="claim"&&w.optimistic&&!C.accepted){let V=C.owner??y.get(w.id);V?p.set(w.id,V):p.delete(w.id),V!==t.sessionId&&E.delete(w.id)}w.operation==="claim"&&C.accepted&&(p.set(w.id,t.sessionId),ae(gr+w.id)),w.operation==="release"&&C.accepted&&(E.delete(w.id),p.get(w.id)===t.sessionId&&p.delete(w.id),ae(gr+w.id)),w.operation==="remove"&&C.accepted&&(E.delete(w.id),A.delete(w.id),p.delete(w.id),q(gr+w.id)),w.resolve(C)},Is=(w,C)=>{let V=t.state?.objects?.get(w.id);return{requestId:w.requestId,operation:w.operation,id:w.id,accepted:!1,owner:V?.owner||void 0,sequence:V&&Number.isFinite(V.seq)?V.seq:0,reason:C}},Oo=w=>{for(let C of[...K.values()])Os(C,Is(C,w))},ia=(w,C=!1)=>{if(!C&&!bt)return;let V=w.operation==="claim"?he.CLAIM:w.operation==="release"?he.RELEASE:he.DESTROY;tt(V,w.payload)},Zr=(w,C,V={})=>{let X=String(C),we=`${t.sessionId.slice(0,12)}:${Date.now().toString(36)}:${(++B).toString(36)}`,pe=Math.max(250,Math.min(V.timeoutMs??UT,VT));return new Promise(Me=>{let ie={operation:w,id:X,requestId:we,payload:{id:X,requestId:we,...V.authority==="host"?{authority:"host"}:{}},optimistic:w==="claim"&&V.optimistic===!0,resolve:Me,timeout:null,abort:void 0};if(en||Pn){Me(Is(ie,en?"aborted":"disconnected"));return}if(ie.optimistic&&p.set(X,t.sessionId),ie.timeout=setTimeout(()=>Os(ie,Is(ie,"timeout")),pe),V.signal){let Ne=()=>Os(ie,Is(ie,"aborted"));V.signal.addEventListener("abort",Ne,{once:!0}),ie.abort=()=>V.signal?.removeEventListener("abort",Ne)}if(K.set(we,ie),V.signal?.aborted){Os(ie,Is(ie,"aborted"));return}ia(ie)})},Qr=0,tt=(w,C,V=!1)=>{if(t.connection?.isOpen)try{return t.send(w,C),!0}catch{}return V&&Qr++,!1},Io,Gc=0,Yc,Kc=new Set,Xc=(w,C)=>{let{pose:V,data:X,invalid:we}=N0(w);for(let ze of we)Kc.has(ze)||(Kc.add(ze),console.warn(`[multiplayer] me.set: '${ze}' is a typed pose key (pose: true) and its value is not a `+(ze==="anim"?`string of \u2264${Xt.MAX_ANIM_CHARS} chars`:"finite number")+" \u2014 it is not sent."));if(!B0(V))return!1;let pe=se(),Me=L0(V,pe,C?void 0:Yc);Yc=Me.memory;let ie=JSON.stringify(X),Ne=C||ie!==Io||pe-Gc>=HT;return Ne&&tt(he.STATE,JSON.stringify({...X,[yr]:pe}))?(Io=ie,Gc=pe):Ne&&(Io=void 0),tt(C?he.POSE_SNAP:he.POSE,{...Me.pose,t:pe})||(Io=void 0),!0},Ve=new jl({selfId:()=>t.sessionId,nameOf:w=>t.state?.players?.get(w)?.name??"",sendSignal:(w,C)=>tt(he.VOICE_SIGNAL,{to:w,data:C},!0)});Ve.onChange(()=>oe("voice",Ve.participants));let es=null,Ds=C0(()=>tt(he.VOICE_ICE_REQUEST,{},!0),zT),Do=()=>{es&&clearTimeout(es),es=null},Xn=w=>{Do(),!(typeof w!="number"||!Number.isFinite(w)||w<=0)&&(es=setTimeout(()=>{Ve.active&&Ds.request().then(C=>{!Ve.active||!C?.iceServers?.length||(Ve.setIceServers(C.iceServers),Xn(C.ttl))})},Math.max(6e4,Math.floor(w*800))))},Rr=[],No=new Set,Ns=new Set,Bs=new Set,Lt=w=>!!w&&typeof w=="object"&&typeof w.id=="number"&&typeof w.from=="string"&&typeof w.name=="string"&&typeof w.text=="string",Jc=w=>{if(!Lt(w)||No.has(w.id)||Bs.has(w.from))return;No.add(w.id);let C=Rr[Rr.length-1];if(!C||w.id>C.id)Rr.push(w);else{let V=Rr.length;for(;V>0&&(Rr[V-1]?.id??0)>w.id;)V--;Rr.splice(V,0,w)}for(let V of[...Ns])try{V(w)}catch(X){console.error("[multiplayer] a chat listener threw",X)}},Et=Ja(t);if(!Et)throw new Error("genex multiplayer: the relay room has no schema state");let Bo=(w,C,V)=>{let X=w===t.sessionId,{state:we,sendTime:pe}=J0(C.data),Me=Number.isFinite(C.epoch)?C.epoch:0,ie=Ms.has(w)&&Me!==Ms.get(w);Ms.set(w,Me);let Ne=V||C.data!==na.get(w);na.set(w,C.data);let ze=Number.isFinite(C.poseT)?C.poseT:0,nt=ze!==(bn.get(w)??0);bn.set(w,ze);let ut=C.posed===!0;if(!X&&ut&&!c.has(w)&&(q(w),c.add(w),An.set(w,new Vl)),!X&&ie&&(q(w),Kn.has(w)&&Wc(w)),oe(V?"join":"change",w,ut?{...we,...$l(C)}:we),!X){if(ut){let Qe=An.get(w);(Ne||ie)&&(Qe.push(pe,we),(ie||Yn)&&Qe.flush()),Yn?Kn.has(w)||Gd(w,C):ze!==0&&(nt||ie)&&$(w,$l(C),ze,w);return}(Ne||ie)&&j0(w,t.sessionId,pe)&&$(w,we,pe,w)}};Et(t.state).players.onAdd((w,C)=>{Bo(C,w,!0),Et(w).onChange(()=>Bo(C,w,!1))});let Lo=w=>{oe("leave",w),q(w),ce(w),Wc(w),Co.delete(w),Ms.delete(w),na.delete(w),bn.delete(w),c.delete(w),An.delete(w)};Et(t.state).players.onRemove((w,C)=>Lo(C)),Et(t.state).shared.onAdd(ue),Et(t.state).shared.onChange(ue),Et(t.state).objects.onAdd((w,C)=>{_r(C,w),Et(w).onChange(()=>_r(C,w))}),Et(t.state).objects.onRemove((w,C)=>Gn(C)),Et(t.state).listen("host",w=>Ae(w)),Et(t.state).voice.onAdd(Bt),Et(t.state).voice.onRemove(Bt);let Zc=()=>{let w=t.state;if(w){for(let C of new Set([...p.keys(),...A.keys(),...b.keys()]))w.objects?.has(C)||Gn(C);for(let C of[...Ms.keys()])w.players?.has(C)||Lo(C);Ae(w.host),Bt()}};t.onMessage(xe.VOICE_SIGNAL,w=>{w&&typeof w.from=="string"&&Ve.handleSignal(w.from,w.data)}),t.onMessage(xe.VOICE_REJECTED,w=>{Do(),Ve.stop(),oe("voice:rejected",w??{reason:"full"})}),t.onMessage(xe.VOICE_ICE,w=>{Ds.deliver(w??null)}),t.onMessage(xe.CHAT,w=>Jc(w)),t.onMessage(xe.CHAT_HISTORY,w=>{if(Array.isArray(w?.messages))for(let C of w.messages)Jc(C)}),t.onMessage(xe.OBJECT_RESULT,w=>{if(!w||typeof w.requestId!="string")return;let C=K.get(w.requestId);!C||w.operation!==C.operation||w.id!==C.id||Os(C,w)}),t.onMessage(xe.INPUT,w=>{w&&typeof w.from=="string"&&oe(xe.INPUT,w.from,w.d)}),t.onMessage(xe.ROOM_OPEN,w=>{typeof w?.open=="boolean"&&oe("room:open",{open:w.open})}),t.onMessage(xe.RATE_DROP,w=>{console.warn(`[multiplayer] the relay dropped ${w?.dropped??"some"} of your messages in the last second \u2014 you are publishing over budget. Publish idle/unchanged objects at \u22642Hz keepalive, not every tick (see the multiplayer skill's "message budget" section).`)}),t.onMessage(xe.SERVER_RESTART,()=>{}),tt(he.CHAT_HISTORY_REQUEST,{});let Qc=U0(t),ts=Qc?V0(Qc,()=>!Pn&&!en):void 0,ns=()=>ts?t.clock.serverNow():void 0,aa=w=>H0(w,{synced:ts?.synced===!0,clockOrigin:Number.isFinite(t.state?.clockOrigin)?t.state?.clockOrigin:0,serverNow:ns(),wallNow:Date.now()}),eu=()=>{ts?.stop(),ct?.dispose(),ct=void 0,Kn.clear()};t.onDrop(w=>{if(en||Pn)return;sa++,Xr||(Xr=!0,ra=0,Jr=lo()),bt=!1,Cs();let{isReconnecting:C,retryCount:V,maxRetries:X}=t.reconnection;C&&V>=X||oe("reconnecting",{attempt:++ra,code:w})}),t.onReconnect(()=>{if(Pn)return;if(en){t.leave().catch(()=>{});return}let w=sa;if((Jr?lo()-Jr:0)>FT){for(let V of[...n.keys()])q(V);for(let V of[...o.keys()])ce(V)}(async()=>{if(await pc(t,hn.firstStateTimeoutMs),!(w!==sa||Pn||en)){Zc();for(let V of[...K.values()])ia(V,!0);tt(he.CHAT_HISTORY_REQUEST,{}),Xr=!1,Jr=0,bt=!0,Cs(),oe("reconnected"),Qr>0&&(console.warn(`[multiplayer] ${Qr} fire-and-forget event(s)/input(s) were dropped while reconnecting \u2014 they are not buffered; player/object state re-synced automatically.`),Qr=0)}})()}),t.onLeave(w=>{Pn||(Pn=!0,bt=!1,Xr=!1,eu(),Cs(),!en&&(Oo("disconnected"),oe("disconnect",w??1006)))}),t.onError(()=>{});let Fo=((w,C)=>{let V=ne.get(w);return V||ne.set(w,V=new Set),V.add(C),!KT.has(w)&&!XT.has(w)&&!Re.has(w)&&(Re.add(w),t.onMessage(w,X=>oe(w,X))),()=>{V?.delete(C)}}),Ls={id:t.sessionId,get players(){let w=new Map,C=se();return ct&&Kn.size>0&&ct.tick(lo()),t.state?.players?.forEach((V,X)=>{let we=qd(X,V.data),pe=we,Me=we,ie=An.get(X);if(X!==t.sessionId&&ie){let Ne=$l(V);if(Me={...we,...Ne},Kn.has(X))pe={...ie.at(void 0)??we,...qc(V)};else{let ze=W(X,C)??Ne;pe={...ie.at(G(X,C))??we,...ze}}}else X===t.sessionId?h&&(pe=h,Me=h):pe=W(X,C)??we;w.set(X,{id:X,name:V.name??"",avatarUrl:V.avatarUrl??"",connected:V.connected!==!1,uid:V.uid??"",team:Number.isFinite(V.team)?V.team:-1,state:pe,stateRaw:Me})}),w},get activePlayers(){return new Map([...Ls.players].filter(([,w])=>w.connected))},me:{set(w){yr in w&&console.warn(`[multiplayer] '${yr}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let C=Ci(w);h=C,!(e.pose&&Xc(C,!1))&&tt(he.STATE,JSON.stringify({...C,[yr]:se()}))},snap(w){yr in w&&console.warn(`[multiplayer] '${yr}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let C=Ci(w);h=C,!(e.pose&&Xc(C,!0))&&tt(he.STATE_SNAP,JSON.stringify({...C,[yr]:se()}))}},shared:{get(w){return ql(t.state?.shared?.get(w))},set(w,C){w.startsWith(zl)||tt(he.SHARED,{key:w,value:JSON.stringify(Ci(C))})},keys(){return t.state?.shared?Array.from(t.state.shared.keys()):[]}},objects:{claim(w){Zr("claim",w,{optimistic:!0})},claimConfirmed(w,C){return Zr("claim",w,C)},release(w){let C=String(w);E.delete(C),p.get(C)===t.sessionId&&p.delete(C),ae(gr+C),Zr("release",C)},releaseConfirmed(w,C){return Zr("release",w,C)},remove(w){let C=String(w);p.get(C)===t.sessionId&&(E.delete(C),A.delete(C),p.delete(C),q(gr+C)),Zr("remove",C)},removeConfirmed(w,C){return Zr("remove",w,C)},set(w,C){let V=String(w);if(v("set",V))return;let X=Ci(C);p.get(V)===t.sessionId&&E.set(V,X),tt(he.OBJECT,{id:V,d:X,t:se()})},snap(w,C){let V=String(w);if(v("snap",V))return;let X=Ci(C);p.get(V)===t.sessionId&&E.set(V,X),tt(he.OBJECT_SNAP,{id:V,d:X,t:se()})},get(w){let C=String(w),V=p.get(C),X=E.get(C);if(V===void 0&&!A.has(C)&&!X)return;let we=V!==void 0&&V===t.sessionId,pe,Me;return we&&X?(pe=X,Me=X,u.set(gr+C,X),l.set(gr+C,se())):(Me=A.get(C)??{},pe=W(gr+C,se())??Me),{id:C,epoch:S.get(C)??0,owner:V,isMine:we,state:pe,stateRaw:Me}},ids(){return[...new Set([...p.keys(),...A.keys(),...E.keys()])]}},get isHost(){return bt&&!en&&!Pn&&M!==void 0&&M===t.sessionId},get host(){return M},inputs:{send(w){tt(he.INPUT,Ci(w),!0)},on(w){let C=ne.get(xe.INPUT);C||ne.set(xe.INPUT,C=new Set);let V=(X,we)=>w(X,we);return C.add(V),()=>{C?.delete(V)}}},onHostTick(w,C){let V=null,X=0,we=Number.isFinite(w)&&w>0?Math.min(w,100):20,pe=Math.max(10,Math.round(1e3/we)),Me=()=>{let Ne=bt&&!en&&!Pn&&M!==void 0&&M===t.sessionId;Ne&&!V?(X=lo(),V=setInterval(()=>{let ze=lo();C(Math.min(ze-X,X0)),X=ze},pe)):!Ne&&V&&(clearInterval(V),V=null)},ie=Fo("host",Me);return oa.add(Me),Me(),()=>{ie(),oa.delete(Me),V&&clearInterval(V),V=null}},on:Fo,send(w,C){if(!YT(w)){console.warn(`[multiplayer] send('${w}') collides with a relay-internal channel \u2014 use a different event name`);return}tt(w,C,!0)},chat:{send(w){typeof w=="string"&&w.trim()&&tt(he.CHAT,{text:w},!0)},on(w){return Ns.add(w),()=>Ns.delete(w)},get history(){return[...Rr]},mute(w){typeof w=="string"&&w&&Bs.add(w)},unmute(w){Bs.delete(w)},get muted(){return[...Bs]}},voice:{async join(w){if(await Ve.start(w,!0),!w?.iceServers?.length){let C=await Ds.request();Ve.active&&C?.iceServers?.length&&(Ve.setIceServers(C.iceServers),Xn(C.ttl))}Ve.active&&(tt(he.VOICE_JOIN,{},!0),Ve.releasePeering())},leave(){Do(),tt(he.VOICE_LEAVE,{},!0),Ve.stop()},get active(){return Ve.active},get participants(){return Ve.participants},setMicEnabled(w){Ve.setMicEnabled(w===!0)},get micEnabled(){return Ve.micEnabled},get speaking(){return Ve.speaking},mute(w){Ve.mute(w)},unmute(w){Ve.unmute(w)},setVolume(w,C){Ve.setVolume(w,C)},get muted(){return Ve.participants.filter(w=>w.muted).map(w=>w.id)}},setRoomOpen(w){tt(he.ROOM_OPEN,{open:w===!0})},leave(){en=!0,eu(),Ve.stop(),Do(),bt=!1,Cs(),Oo("aborted"),t.reconnection.enabled=!1,t.leave().catch(()=>{})},serverNow:ns,get rtt(){if(!ts)return;let w=t.clock.smoothedRtt();return w>0?w:void 0},get clockSynced(){return ts?.synced===!0},timeUntil:aa};return Object.defineProperty(Ls,Jp,{value:()=>t,enumerable:!1}),Object.defineProperty(Ls,Symbol.for("genex.multiplayer.internals"),{enumerable:!1,value:{senderOf:w=>a.get(w),offsetOf:w=>{let C=a.get(w);return C===void 0?void 0:s.get(C)},offsetSamples:w=>o.get(w)?.samples.length??0,bufferLength:w=>n.get(w)?.length??0}}),Ls}var ZT=[1e3,2e3,4e3],eh=t=>dc(t.room,t.name,t.auth);function nw(t,e,n=r=>r-Date.now()){let r=t?.state?.match,s=r?ql(r):null,o=s&&typeof s=="object"?s:null;if(!o)return{status:t?"waiting":"searching",role:"player",queue:e,players:[],connectedPlayers:[],opponents:[],teams:{},myTeam:null,scores:{},config:{},winCondition:"lastStanding",championId:null,challengerId:null,roundId:0,winnerId:null,message:t?"Waiting for players\u2026":"Finding a match\u2026",startsAt:null,endsBy:null,startsInMs:null,endsInMs:null};let i=t?.sessionId,a=o.championId??null,c=o.challengerId??null,u=o.teams??{},l=Array.isArray(o.players)?o.players:[],d=o.connectedPlayers??l,f=i!=null&&l.includes(i),h=f?o.phase:"spectating",p=l.filter(P=>P!==i),y=i?Object.keys(u).find(P=>u[P]?.includes(i))??null:null,{winCondition:S,...b}=o.cfg??{},x=P=>typeof P=="number"&&Number.isFinite(P)&&P>0?P:null,R=x(o.startsAt),A=x(o.endsBy),E=P=>P===null?null:Math.max(0,n(P));return{status:h,role:f?"player":"spectator",queue:{position:0,size:0},players:l,connectedPlayers:d,opponents:p,teams:u,myTeam:y,scores:o.scores??{},config:b,winCondition:S?.type??"lastStanding",championId:a,challengerId:c,roundId:o.roundId??0,winnerId:o.winnerId??null,message:o.message??"",startsAt:R,endsBy:A,startsInMs:E(R),endsInMs:E(A)}}function Oi(t,e,n){if(t?.connection?.isOpen)try{t.send(e,n)}catch{}}async function rw(t){let e=await lc(t),n=await Yl(t.smoothing),r=new Map,s=(P,...k)=>r.get(P)?.forEach(M=>M(...k)),o=((P,k)=>{let M=r.get(P);return M||r.set(P,M=new Set),M.add(k),()=>{M?.delete(k)}}),i=null,a=null,c=null,u={position:0,size:0},l=!1,d=!1,f=0,h=!1,p=!1,y=async()=>{if(l||d)return;d=!0;let P=++f;try{i=null,a=null;for(let k=0;;k++){c&&(c.leave(),c=null),u={position:0,size:0};let M;try{M=$0(await e.joinOrCreate(co.QUEUE,eh(t)))}catch(B){if(l)return;let K=fc(B);K&&Gp();let j=K?void 0:ZT[k];if(j==null){if(k===0&&await new Promise(L=>setTimeout(L,0)),l)return;s("error",B);return}if(await new Promise(L=>setTimeout(L,j)),l)return;continue}if(l||P!==f){M.leave();return}c=M,M.onMessage(xe.QUEUE,B=>{u={position:B.position,size:B.size},s("queue",B)}),M.onMessage(xe.SEAT,B=>{l||P!==f||c!==M||h||(h=!0,c=null,M.leave(),S(B.reservation,B.role,P))}),M.onLeave(()=>{l||c!==M||(c=null,(async()=>{for(let B of JT)if(await new Promise(K=>setTimeout(K,B)),l||c||i||(await y(),c||i))return})())}),s("searching");return}}finally{d=!1}},S=async(P,k,M)=>{try{let B=xs(await e.consumeSeatReservation(P));if(l||M!==f){B.leave();return}a=B;let K=Qp(B,{pose:t.pose,smoothing:t.smoothing,predict:n});i=K,K.on(xe.MATCH_START,j=>s("matchStart",j)),K.on(xe.MATCH_ENDED,j=>s("matchEnded",j)),K.on(xe.MATCH_REQUEUE,()=>{i===K&&b()}),K.on("disconnect",j=>{if(!(l||i!==K)){if(j===pn.SUPERSEDED||j===pn.REVOKED){f++,h=!1,a=null,i=null,s("disconnect",j);return}b()}}),c&&(c.leave(),c=null),s("matched"),k==="spectator"&&s("spectate")}catch{!l&&M===f&&(h=!1,y())}finally{M===f&&(h=!1)}},b=async()=>{if(!(l||p)){p=!0;try{f++,h=!1,i?.leave(),a=null,i=null,await y()}finally{p=!1}}};y();let x=()=>i?zr(i):null,R=null,A=null,E=()=>{i!==R&&(R=i,A=null);let P=x(),k=!!P?.state?.match;if(!k&&i&&A)return A;let M=nw(P,u,i?i.timeUntil:void 0);return k&&(A=M),M};return{get session(){return i},get matchmaking(){return E()},on:o,eliminated(){Oi(x(),he.MATCH_ELIMINATED,{})},score(P=1){Oi(x(),he.MATCH_SCORE,{delta:P})},finish(){Oi(x(),he.MATCH_FINISH,{})},retry(){l||d||c||a||y()},cancel(){l=!0,f++,h=!1,i?.leave(),!i&&a&&a.leave(),c&&c.leave(),a=null,c=null,i=null}}}function sw(t,e){let n=new Map,r=(c,...u)=>n.get(c)?.forEach(l=>l(...u)),s=((c,u)=>{let l=n.get(c);return l||n.set(c,l=new Set),l.add(u),()=>{l?.delete(u)}}),o=!0,i=Qp(t,e);i.on(xe.MATCH_START,c=>r("matchStart",c)),i.on(xe.MATCH_ENDED,c=>r("matchEnded",c)),i.on(xe.MATCH_REQUEUE,()=>{o=!1}),i.on("disconnect",()=>{o=!1});let a=()=>o?zr(i):null;return{get session(){return o?i:null},get matchmaking(){return nw(a(),{position:0,size:0},i.timeUntil)},on:s,eliminated(){Oi(a(),he.MATCH_ELIMINATED,{})},score(c=1){Oi(a(),he.MATCH_SCORE,{delta:c})},finish(){Oi(a(),he.MATCH_FINISH,{})},retry(){},cancel(){i.leave(),o=!1}}}async function ow(t){let e=await lc(t),n=await Yl(t.smoothing),r=xs(await e.create(co.MATCH,eh(t))),s=sw(r,{pose:t.pose,smoothing:t.smoothing,predict:n});return Object.defineProperty(s,"code",{value:r.roomId,enumerable:!0}),s}async function iw(t,e){let n=await lc(e),r=await Yl(e.smoothing),s=xs(await n.joinById(t,eh(e)));return sw(s,{pose:e.pose,smoothing:e.smoothing,predict:r})}var QT=2,Kl=ga;function ev(t){Kl=t??ga}function tv(t){let e=JSON.parse(t);if(!Mn(e))throw new TypeError("genex bridge: options must be a JSON object");let n=typeof e.gameId=="string"?e.gameId:"";if(!n)throw new TypeError("genex bridge: `gameId` (the game slug) is required");let r=Array.isArray(e.urls)?e.urls.filter(a=>typeof a=="string"&&a!==""):[],s="play";if(e.room==="queue"||e.room==="private")s=e.room;else if(Mn(e.room)&&typeof e.room.joinById=="string"&&e.room.joinById)s={joinById:e.room.joinById};else if(e.room!==void 0&&e.room!==null&&e.room!=="play")throw new TypeError('genex bridge: `room` must be "play", "queue", "private" or {"joinById": code}');let o=typeof e.controlTimeoutMs=="number"&&Number.isFinite(e.controlTimeoutMs)?e.controlTimeoutMs:void 0,i=e.smoothing==="genex"||e.smoothing==="predict"||Mn(e.smoothing)?e.smoothing:void 0;return{gameId:n,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:r,room:s,pose:e.pose===!0,smoothing:i,controlTimeoutMs:o,options:Mn(e.options)?e.options:void 0}}var th=new Map,nv=1,nh=t=>t.closed?null:t.mm?t.mm.session:t.session;function hc(t){t.closed=!0,t.connected=!1;for(let e of t.unwire.splice(0))e();t.wired=null,t.session=null,t.mm=null}function cw(t,e){if(t.wired===e)return;for(let i of t.unwire.splice(0))i();t.wired=e,t.connected=!0,t.lastConnected.clear(),t.lastMatch="";let n=zr(e);t.sessionId=e.id,t.roomId=n.roomId;let r=t.unwire,s=i=>n.state?.players?.get(i)?.connected!==!1,o=i=>{let a=s(i),c=t.lastConnected.get(i);t.lastConnected.set(i,a),c!==void 0&&c!==a&&ye(t,{type:"playerConnection",id:i,connected:a})};ye(t,{type:"joined",sessionId:e.id}),n.state?.players?.forEach((i,a)=>{t.lastConnected.set(a,s(a)),ye(t,{type:"playerJoined",id:a})});for(let i of e.objects.ids())ye(t,{type:"objectChanged",id:i,owner:e.objects.get(i)?.owner??null});e.host!==void 0&&ye(t,{type:"hostChanged",host:e.host}),r.push(e.on("join",i=>{t.lastConnected.set(i,s(i)),ye(t,{type:"playerJoined",id:i})}),e.on("change",i=>{o(i),t.changed.has(i)||(t.changed.add(i),ye(t,{type:"playerChanged",id:i}))}),e.on("leave",i=>{t.lastConnected.delete(i),ye(t,{type:"playerLeft",id:i})}),e.on("host",i=>ye(t,{type:"hostChanged",host:i??null})),e.on("shared",(i,a)=>ye(t,{type:"sharedChanged",key:i,value:a??null})),e.on("object",i=>{let a=e.objects.get(i);ye(t,a?{type:"objectChanged",id:i,owner:a.owner??null}:{type:"objectRemoved",id:i})}),e.on("room:open",({open:i})=>ye(t,{type:"roomOpen",open:i})),e.on("reconnecting",({attempt:i,code:a})=>{t.connected=!1,ye(t,{type:"reconnecting",code:a,attempt:i})}),e.on("reconnected",()=>{t.connected=!0,ye(t,{type:"reconnected"})}),e.on("disconnect",i=>{t.connected=!1,t.opts.room!=="queue"&&(hc(t),ye(t,{type:"disconnected",code:i,reason:""}))}),e.on(xe.SERVER_RESTART,()=>ye(t,{type:"serverRestart"})),e.on(xe.MATCH_START,i=>ye(t,{type:"matchStart",roundId:Mn(i)&&typeof i.roundId=="number"?i.roundId:0})),e.on(xe.MATCH_ENDED,i=>ye(t,{type:"matchEnded",data:i??null})),e.on(xe.MATCH_REQUEUE,i=>ye(t,{type:"matchRequeue",reason:Mn(i)&&typeof i.reason=="string"?i.reason:null})),e.inputs.on((i,a)=>ye(t,{type:"input",from:i,data:a??null})),e.chat.on(i=>ye(t,{type:"chat",id:i.id,from:i.from,name:i.name,text:i.text,at:i.at})),n.onMessage(xe.RATE_DROP,i=>ye(t,{type:"rateDrop",dropped:Mn(i)&&typeof i.dropped=="number"?i.dropped:0})),n.onMessage("*",(i,a)=>{typeof i=="string"&&!ws(i)&&ye(t,{type:"message",kind:i,data:a??null})}))}function Xl(t){let e=nh(t);e&&e!==t.wired&&cw(t,e)}async function rv(t){let e=t.opts;if(await Kl.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:Kl.urls();if(!n.length)throw Object.assign(new Error("genex bridge: no relay URL (pass urls, or run on a Genex page)"),{code:0});let r=()=>Kl.auth(),s={urls:n,room:e.gameId,name:e.name,auth:r,pose:e.pose,smoothing:e.smoothing};if(e.room==="play"){let a=await tw({...s,options:e.options});if(t.closed)return void a.leave();t.session=a,cw(t,a);return}let o=s,i=e.room==="queue"?await rw(o):e.room==="private"?await ow(o):await iw(e.room.joinById,o);if(t.closed)return void i.cancel();t.mm=i,i.on("queue",a=>{Mn(a)&&ye(t,{type:"queue",position:Number(a.position)||0,size:Number(a.size)||0})}),i.on("matched",()=>{ye(t,{type:"seated"}),Xl(t)}),i.on("searching",()=>{if(t.wired){for(let a of t.unwire.splice(0))a();t.wired=null,t.connected=!1}}),i.on("error",a=>{let c=t.mm;hc(t),c?.cancel(),ye(t,{type:"joinFailed",code:Jo(a),message:tr(a)})}),i.on("disconnect",a=>{hc(t),ye(t,{type:"disconnected",code:typeof a=="number"?a:0,reason:""})}),Xl(t)}function uw(t){let e=tv(t),n=nv++,r={opts:e,q:[],overflowed:!1,session:null,mm:null,wired:null,unwire:[],changed:new Set,lastConnected:new Map,lastMatch:"",sessionId:"",roomId:"",connected:!1,closed:!1};th.set(n,r);let s=rv(r).catch(o=>{throw hc(r),ye(r,{type:"joinFailed",code:Jo(o),message:tr(o)}),o});return{handle:n,done:s}}function sv(t){let{handle:e,done:n}=uw(t);return n.catch(()=>{}),e}async function ov(t){let{handle:e,done:n}=uw(t);try{await n}catch(r){let s=new Error(tr(r));throw s.code=Jo(r),s}return e}var _s=t=>th.get(t),Dt=t=>{let e=_s(t);return e?(Xl(e),nh(e)):null};function lw(t){let e=_s(t);if(!e||e.closed)return;let{mm:n,session:r}=e;hc(e),n?n.cancel():r?.leave(),ye(e,{type:"disconnected",code:4e3,reason:"left"})}function iv(t){lw(t),typeof t=="number"&&th.delete(t)}function av(t,e){let n=nr(e,"state"),r=Dt(t);return r?(r.me.set(n),!0):!1}function cv(t,e){let n=nr(e,"state"),r=Dt(t);return r?(r.me.snap(n),!0):!1}function uv(t,e,n){let r=ba(n,"value");if(typeof e!="string"||!e||e.startsWith(zl))return!1;let s=Dt(t);return s?(s.shared.set(e,r),!0):!1}function lv(t,e,n){let r=nr(n,"object state"),s=Dt(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.set(e,r),!0)}function dv(t,e,n){let r=nr(n,"object state"),s=Dt(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.snap(e,r),!0)}function fv(t,e,n){let r=ba(n,"event data");if(typeof e!="string"||!e||e.length>Xt.MAX_EVENT_TYPE_CHARS||ws(e))return!1;let s=Dt(t);return s?(s.send(e,r),!0):!1}function pv(t,e){}function hv(t,e){let n=ba(e,"input"),r=Dt(t);return r?(r.inputs.send(n),!0):!1}function mv(t,e){let n=Dt(t);return n?(n.setRoomOpen(e===!0),!0):!1}function yv(t,e){let n=Dt(t);return!n||typeof e!="string"?!1:(n.chat.send(e),!0)}function Jl(t,e,n,r,s=!1){if(typeof n!="string"||!n)throw new TypeError("genex bridge: object id must be a non-empty string");let o=_s(t),i=Dt(t),a=l=>{if(!o)return;let d={type:"controlResult",requestId:String(r),operation:e,id:n,accepted:l.accepted,owner:l.owner??null,sequence:l.sequence,reason:l.reason};typeof l.retryAfterMs=="number"&&(d.retryAfterMs=l.retryAfterMs),ye(o,d)};if(!i){a({accepted:!1,sequence:0,reason:"disconnected"});return}let c={timeoutMs:o?.opts.controlTimeoutMs,...s?{authority:"host"}:{}};(e==="claim"?i.objects.claimConfirmed(n,c):e==="release"?i.objects.releaseConfirmed(n,c):i.objects.removeConfirmed(n,c)).then(a,()=>a({accepted:!1,sequence:0,reason:"disconnected"}))}function gv(t,e,n){Jl(t,"claim",e,n)}function bv(t,e,n){Jl(t,"claim",e,n,!0)}function wv(t,e,n){Jl(t,"release",e,n)}function Sv(t,e,n){Jl(t,"remove",e,n)}function xv(t){let e=_s(t);return!e?.mm||e.closed?!1:(e.mm.eliminated(),!0)}function _v(t,e=1){let n=_s(t);return!n?.mm||n.closed||typeof e!="number"||!Number.isFinite(e)?!1:(n.mm.score(e),!0)}function Rv(t){let e=_s(t);return!e?.mm||e.closed?!1:(e.mm.finish(),!0)}function Ev(t){return Dt(t)?.serverNow()??null}function kv(t,e){let n=Dt(t);return n?n.timeUntil(e):e-Date.now()}var aw=t=>typeof t=="number"&&Number.isFinite(t)?t:null;function Av(t){let e=_s(t),n=Dt(t),r=n?zr(n):null,s=r?.state?.match,o=null;if(s)try{o=JSON.parse(s)}catch{o=null}return JSON.stringify({sessionId:n?.id??e?.sessionId??"",roomId:r?.roomId??e?.roomId??"",hostId:n?.host??null,isHost:n?.isHost??!1,connected:!!n&&!!e?.connected,closed:!e||e.closed,serverNow:aw(n?.serverNow()),rtt:aw(n?.rtt),clockSynced:n?.clockSynced??!1,clockOrigin:r?.state?.clockOrigin??0,matchState:o})}function Pv(t){let e=Dt(t);if(!e)return"[]";let n=zr(e).state?.players,r=[];for(let[s,o]of e.players){let i=n?.get(s);r.push({id:s,name:o.name,uid:o.uid,team:o.team,connected:o.connected,avatarUrl:o.avatarUrl,state:o.state??{},stateRaw:o.stateRaw??{},epoch:i?.epoch??0,isMe:s===e.id,posed:i?.posed===!0})}return JSON.stringify(r)}function Tv(t){let e=Dt(t);if(!e)return"[]";let n=zr(e).state?.objects,r=[];for(let s of e.objects.ids()){let o=e.objects.get(s);o&&r.push({id:s,owner:o.owner??null,isMine:o.isMine,seq:n?.get(s)?.seq??0,epoch:o.epoch,state:o.state??null,stateRaw:o.stateRaw??null})}return JSON.stringify(r)}function vv(t){let e=Dt(t),n={};if(e)for(let r of e.shared.keys())n[r]=e.shared.get(r)??null;return JSON.stringify(n)}function Mv(t){let e=_s(t);if(!e)return"[]";try{Xl(e);let n=nh(e);if(n){let r=zr(n).state?.match??"";if(r!==e.lastMatch){e.lastMatch=r;let s=null;try{s=r?JSON.parse(r):null}catch{s=null}ye(e,{type:"matchState",state:s})}}e.changed.clear()}catch(n){ye(e,Xo(tr(n)))}return Mu(e)}var Am={};of(Am,{BODY_F32_STRIDE:()=>_m,BodyF32Flag:()=>Rm,authorityJson:()=>ED,bodiesF32:()=>_D,bodyKeysJson:()=>RD,closeAuthority:()=>VR,disposeAuthority:()=>PD,drainAuthorityEventsJson:()=>AD,frame:()=>SD,openAuthority:()=>mD,predictProjectile:()=>gD,setAuthorityIdentity:()=>rD,setAuthorityPhysicsCore:()=>sD,setInput:()=>yD,setWorld:()=>bD,version:()=>nD});var dw=2*Math.PI,fw=Math.fround(Math.PI),Oe=t=>t===0?0:t;function Hn(t){if(typeof t!="number"||!Number.isFinite(t))return 0;let e=t<-1?-1:t>1?1:t;return Oe(Math.fround(e))}function Rs(t){if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>1e9)return null;let e=Math.fround(t-dw*Math.floor((t+Math.PI)/dw));return e===fw?-fw:Oe(e)}function fo(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<16777216?t:0}function Zl(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:t>e?e:t}var mn=(t,e,n)=>t<e?e:t>n?n:t,pw=5734161139222659/2**53,hw=1686629713/2**30,mw=2242054355/2**65,yw=5376105825661043/2**121,gw=-6004799503160649/2**55,bw=0x8888888887c53/2**58,ww=-7320136532976085/2**65,Sw=6506786730409597/2**71,xw=-7571127717829867/2**78,_w=0x5764e96b3f55f/2**83,Rw=0x5555555555553/2**55,Ew=-6405119470031223/2**62,kw=457508533350745/2**64,Aw=-5205429506036397/2**74,Pw=0x47ba7af6d2c71/2**79,Tw=-0x63eba6fa20e35/2**87,$z=Object.freeze({invpio2:pw,pio2_1:hw,pio2_2:mw,pio2_2t:yw,S1:gw,S2:bw,S3:ww,S4:Sw,S5:xw,S6:_w,C1:Rw,C2:Ew,C3:kw,C4:Aw,C5:Pw,C6:Tw});function Ut(t){if(!Number.isFinite(t)||Math.abs(t)>1e9)return[0,1];let e=Math.floor(t*pw+.5),n=e-4*Math.floor(e/4),r=t-e*hw-e*mw-e*yw,s=r*r,o=r+s*r*(gw+s*(bw+s*(ww+s*(Sw+s*(xw+s*_w))))),i=.5*s,a=1-i,c=a+(1-a-i+s*(s*(Rw+s*(Ew+s*(kw+s*(Aw+s*(Pw+s*Tw)))))));return n===0?[Oe(o),Oe(c)]:n===1?[Oe(c),Oe(-o)]:n===2?[Oe(-o),Oe(-c)]:[Oe(-c),Oe(o)]}var vw=t=>Ut(t)[0],Mw=t=>Ut(t)[1];var wr={TOPDOWN:"topdown",FIRSTPERSON:"firstperson",VEHICLE:"vehicle"},ch=.25,Cv=Object.freeze({speed:6,arena:20}),Ov={speed:{min:0,max:1e3,positive:!1},arena:{min:0,max:1e6,positive:!0}};var uh=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.getPrototypeOf(t)===Object.prototype;function Bw(t,e){if(e===void 0)return!0;let n=bc(t)?.ranges;return n===void 0||!uh(e)?!1:Object.keys(e).every(r=>{if(!Object.hasOwn(n,r))return!1;let s=n[r],o=e[r];return typeof o!="number"||!Number.isFinite(o)||o<s.min||o>s.max||s.integer===!0&&!Number.isInteger(o)?!1:!s.positive||o>0&&Math.fround(o)>0})}function Di(t,e){let n=bc(t);if(n===void 0)return{};let r={...n.defaults};if(!uh(e))return r;for(let s of Object.keys(n.ranges))Bw(t,{[s]:e[s]})&&(r[s]=e[s]);return r}var sh=t=>Number.isFinite(t)?t:0;function Iv(t,e,n,r){let s=Hn(e.moveX),o=Hn(e.moveY),i=Zl(n,ch),a=Math.sqrt(s*s+o*o),c=a>1?1/a:1,u=sh(t.x)+s*c*r.speed*i,l=sh(t.y)+o*c*r.speed*i;return{x:Oe(Math.fround(mn(u,-r.arena,r.arena))),y:Oe(Math.fround(mn(l,-r.arena,r.arena))),yaw:Rs(e.yaw)??Oe(Math.fround(sh(t.yaw)))}}var Lw=2615243109,Dv=Object.freeze({maxSpeed:250,walkSpeed:.52,crouchSpeed:.34,accelerate:5.5,airAccelerate:12,airMaxWishSpeed:30,friction:5.2,stopSpeed:80,gravity:800,jumpImpulse:301.993,maxVelocity:3500,radius:16,standHeight:72,crouchHeight:54,duckTime:.4,airDuck:1,stepHeight:18,standable:.7,groundTrace:2.5,groundSnap:1,skin:.03,pitchLimit:1.5533430576324463,jumpBit:1,duckBit:2,walkBit:4,substeps:2,capZeroJump:1,runBit:0,jogSpeed:1,world:Lw}),Ee=(t,e)=>({min:t,max:e,positive:!1}),ho=t=>({min:0,max:t,positive:!0}),Jt=(t,e)=>({min:t,max:e,positive:!1,integer:!0}),Nv={maxSpeed:Ee(0,1e4),walkSpeed:Ee(0,1),crouchSpeed:Ee(0,1),accelerate:Ee(0,1e3),airAccelerate:Ee(0,1e3),airMaxWishSpeed:Ee(0,1e4),friction:Ee(0,1e3),stopSpeed:Ee(0,1e4),gravity:Ee(0,1e5),jumpImpulse:Ee(0,1e5),maxVelocity:Ee(0,1e5),radius:ho(1e4),standHeight:ho(1e4),crouchHeight:ho(1e4),duckTime:ho(100),airDuck:Jt(0,1),stepHeight:Ee(0,1e4),standable:Ee(0,1),groundTrace:Ee(0,1e4),groundSnap:Ee(0,1e4),skin:Ee(0,100),pitchLimit:Ee(0,1.5707963705062866),jumpBit:Jt(0,16777215),duckBit:Jt(0,16777215),walkBit:Jt(0,16777215),substeps:Jt(1,8),capZeroJump:Jt(0,1),runBit:Jt(0,16777215),jogSpeed:Ee(0,1),world:Jt(0,2**32-1)};var Vt={ON_GROUND:1,DUCKING:2,JUMP_HELD:4},Bv=Vt.ON_GROUND|Vt.DUCKING|Vt.JUMP_HELD,Lv={MAX_BOXES:32768,MAX_RAMPS:4096,MAX_ABS:1e9},yn=class extends RangeError{constructor(n,r){super(`firstperson world: ${n} ${r}`);m(this,"path");this.name="WorldError",this.path=n}},mc=new WeakMap,Fv=(t,e)=>{if(typeof t!="number"||!Number.isFinite(t))throw new yn(e,"is not a finite number");if(Math.fround(t)!==t)throw new yn(e,"is not a float32");if(Math.abs(t)>1e9)throw new yn(e,`is past \xB1${1e9}`);return Oe(t)};function Cw(t,e,n){if(!Array.isArray(t)||t.length!==e)throw new yn(n,`is not an array of ${e} numbers`);let r=[];for(let s=0;s<e;s++)r.push(Fv(t[s],`${n}[${s}]`));if(!(r[0]<r[3]&&r[1]<r[4]&&r[2]<r[5]))throw new yn(n,"needs min < max on every axis");return r}function Ow(t,e,n){if(t===void 0)return[];if(!Array.isArray(t))throw new yn(e,"is not an array");if(t.length>n)throw new yn(e,`holds more than ${n}`);return t}function zv(t,e){let n=new DataView(new ArrayBuffer(8+4*(6*t.length+9*e.length)));n.setUint32(0,t.length,!0),n.setUint32(4,e.length,!0);let r=8;for(let o of[...t,...e])for(let i of o)n.setFloat32(r,i,!0),r+=4;let s=2166136261;for(let o=0;o<n.byteLength;o++)s=Math.imul(s^n.getUint8(o),16777619)>>>0;return s}function mo(t,e={}){let n=mc.has(t)?t:void 0;if(n!==void 0&&(e.broadphase===void 0||e.broadphase===n.broadphase))return n;if(t!==void 0&&!uh(t))throw new yn("$","is not an object");let r=t??{},s=e.caps??Lv,o=Ow(r.boxes,"boxes",s.MAX_BOXES).map((c,u)=>Object.freeze(Cw(c,6,`boxes[${u}]`))),i=Ow(r.ramps,"ramps",s.MAX_RAMPS).map((c,u)=>{let l=`ramps[${u}]`,d=Cw(c,9,l);if(d[6]!==0&&d[6]!==1)throw new yn(`${l}[6]`,"is not an axis (0 or 1)");let[f,h,p,y]=[d[2],d[5],d[7],d[8]];if(!(f<=p&&f<=y))throw new yn(l,"needs minZ \u2264 lo and minZ \u2264 hi");if(h!==Math.max(p,y))throw new yn(l,"needs maxZ = max(lo, hi)");return Object.freeze(d)}),a=Object.freeze({boxes:Object.freeze(o),ramps:Object.freeze(i),hash:zv(o,i),broadphase:e.broadphase!==!1});return mc.set(a,Uv(a)),a}var yc=mo(void 0),Hr={Box:0,OBox:1,Disc:2},ih=96,lh=new Int32Array(ih);function gc(t){let e=t.length;if(e>ih)throw new RangeError(`posed solids: at most ${ih} a tick`);let n=()=>new Float64Array(e),r={count:e,kind:new Uint8Array(e),minX:n(),minY:n(),minZ:n(),maxX:n(),maxY:n(),maxZ:n(),cx:n(),cy:n(),hx:n(),hy:n(),sin:n(),cos:n(),radius:n()};return t.forEach((s,o)=>{if(s.kind==="box"){r.kind[o]=Hr.Box,[r.minX[o],r.minY[o],r.minZ[o]]=s.min,[r.maxX[o],r.maxY[o],r.maxZ[o]]=s.max;return}if(r.cx[o]=s.c[0],r.cy[o]=s.c[1],r.minZ[o]=s.c[2]-(s.kind==="disc"?s.half:s.half[2]),r.maxZ[o]=s.c[2]+(s.kind==="disc"?s.half:s.half[2]),s.kind==="disc"){r.kind[o]=Hr.Disc,r.radius[o]=s.radius,r.minX[o]=s.c[0]-s.radius,r.maxX[o]=s.c[0]+s.radius,r.minY[o]=s.c[1]-s.radius,r.maxY[o]=s.c[1]+s.radius;return}r.kind[o]=Hr.OBox,r.hx[o]=s.half[0],r.hy[o]=s.half[1],r.sin[o]=s.sin,r.cos[o]=s.cos;let i=Math.abs(s.cos),a=Math.abs(s.sin),c=s.half[0]*i+s.half[1]*a,u=s.half[0]*a+s.half[1]*i;r.minX[o]=s.c[0]-c,r.maxX[o]=s.c[0]+c,r.minY[o]=s.c[1]-u,r.maxY[o]=s.c[1]+u}),r}var Fw=gc([]);function dh(t){let e=mc.get(t);if(e!==void 0)return e;let n=mo(t,{broadphase:t.broadphase!==!1}),r=mc.get(n);return mc.set(t,r),r}var Ii=8,Iw=2**23;function Uv(t){let e=[...t.boxes,...t.ramps],n=e.length,r=()=>new Float64Array(n),s={boxCount:t.boxes.length,count:n,minX:r(),minY:r(),minZ:r(),maxX:r(),maxY:r(),maxZ:r(),axis:new Uint8Array(n),lo:r(),hi:r(),m0:r(),span:r(),slope:r(),topZ:r()};return e.forEach((o,i)=>{if(s.minX[i]=o[0],s.minY[i]=o[1],s.minZ[i]=o[2],s.maxX[i]=o[3],s.maxY[i]=o[4],s.maxZ[i]=o[5],i<s.boxCount)return;let a=o[6],c=a===0?o[0]:o[1],l=(a===0?o[3]:o[4])-c,d=(o[8]-o[7])/l;s.axis[i]=a,s.lo[i]=o[7],s.hi[i]=o[8],s.m0[i]=c,s.span[i]=l,s.slope[i]=d,s.topZ[i]=1/Math.sqrt(1+d*d)}),{...s,tree:t.broadphase&&n>0?Hv(s):null}}function oh(t){let e=t&1023;return e=(e|e<<16)&50331903,e=(e|e<<8)&50393103,e=(e|e<<4)&51130563,e=(e|e<<2)&153391689,e}function Vv(t,e){let n=1/0,r=1/0,s=1/0,o=-1/0,i=-1/0,a=-1/0;for(let d=0;d<t;d++)n=Math.min(n,e.minX[d]),r=Math.min(r,e.minY[d]),s=Math.min(s,e.minZ[d]),o=Math.max(o,e.maxX[d]),i=Math.max(i,e.maxY[d]),a=Math.max(a,e.maxZ[d]);let c=(d,f,h)=>h>f?Math.min(1023,Math.floor((d-f)/(h-f)*1024)):0,u=new Float64Array(t);for(let d=0;d<t;d++){let f=c((e.minX[d]+e.maxX[d])/2,n,o),h=c((e.minY[d]+e.maxY[d])/2,r,i),p=c((e.minZ[d]+e.maxZ[d])/2,s,a);u[d]=(oh(f)|oh(h)<<1|oh(p)<<2)*Iw+d}u.sort();let l=new Int32Array(t);for(let d=0;d<t;d++)l[d]=u[d]%Iw;return l}function Hv(t){let e=t.count,n=Vv(e,t),r=[e];for(;r[r.length-1]>1;)r.push(Math.ceil(r[r.length-1]/Ii));let s=r.reduce((l,d)=>l+d,0),o=new Float64Array(s*6),i=new Int32Array(s),a=new Int32Array(r.length);for(let l=0;l<e;l++){let d=n[l],f=l*6;o[f]=t.minX[d],o[f+1]=t.minY[d],o[f+2]=t.minZ[d],o[f+3]=t.maxX[d],o[f+4]=t.maxY[d],o[f+5]=t.maxZ[d],i[l]=d}a[0]=e;let c=0,u=e;for(let l=1;l<r.length;l++){let d=a[l-1];for(let f=c;f<d;f+=Ii){let h=Math.min(f+Ii,d),p=1/0,y=1/0,S=1/0,b=-1/0,x=-1/0,R=-1/0;for(let E=f;E<h;E++){let P=E*6;p=Math.min(p,o[P]),y=Math.min(y,o[P+1]),S=Math.min(S,o[P+2]),b=Math.max(b,o[P+3]),x=Math.max(x,o[P+4]),R=Math.max(R,o[P+5])}let A=u*6;o[A]=p,o[A+1]=y,o[A+2]=S,o[A+3]=b,o[A+4]=x,o[A+5]=R,i[u]=f,u++}c=d,a[l]=u}return{boxes:o,ref:i,levelEnd:a,root:s-1}}var zw=16,Uw=50,$v=.5,fh=(t,e)=>t/e<$v?t/e:1,ph=(t,e,n,r,s,o)=>.001+1e-7*(Math.abs(t)+Math.abs(e)+Math.abs(n)+Math.abs(r)+Math.abs(s)+Math.abs(o)),br=null;function hh(t,e,n,r,s,o,i){jv(t,e,n,r,s,o,i);let a=t.w.tree;if(a===null){t.nCand=-1;return}let c=ph(e,n,r,s,o,i),u=t.r+c,l=e-u,d=s+u,f=n-u,h=o+u,p=r-c,y=i+c,{boxes:S,ref:b,levelEnd:x}=a,R=x[0],A=t.cand,E=t.stack,P=0,k=0,M=0;for(E[k++]=a.root;k>0;){let B=E[--k];M+=1;let K=B*6;if(S[K+3]<l||S[K]>d||S[K+4]<f||S[K+1]>h||S[K+5]<p||S[K+2]>y)continue;if(B<R){A[P++]=b[B];continue}let j=b[B],L=j+Ii;for(let se=0;se<x.length;se++)if(j<x[se]){L=Math.min(L,x[se]);break}for(let se=j;se<L;se++)E[k++]=se}t.nCand=P,br!==null&&(br.nodes+=M,br.tests+=P)}function jv(t,e,n,r,s,o,i){let a=t.p,c=0;if(a.count>0){let u=ph(e,n,r,s,o,i),l=t.r+u,d=e-l,f=s+l,h=n-l,p=o+l,y=r-u,S=i+u;for(let b=0;b<a.count;b++)a.maxX[b]<d||a.minX[b]>f||a.maxY[b]<h||a.minY[b]>p||a.maxZ[b]<y||a.minZ[b]>S||(t.pc[c++]=b)}t.nPosed=c}var mh=t=>(t.nCand<0?t.w.count:t.nCand)+t.nPosed,yh=(t,e)=>{let n=t.nCand<0?t.w.count:t.nCand;return e>=n?t.w.count+t.pc[e-n]:t.nCand<0?e:t.cand[e]},Ur=(t,e)=>t.standHeight+(t.crouchHeight-t.standHeight)*e;function Wv(t,e,n,r){let s=t.w,o=s.slope[e],i=s.axis[e]===0?n:r,a=o>0?i+t.r:o<0?i-t.r:i;return s.lo[e]+o*mn(a-s.m0[e],0,s.span[e])}function Vw(t,e,n,r){let s=t.w;return e<s.boxCount?s.maxZ[e]:e<s.count?Wv(t,e,n,r):t.p.maxZ[e-s.count]}var qv=(t,e)=>e<t.w.count?t.w.minZ[e]:t.p.minZ[e-t.w.count];function Hw(t,e,n,r){let s=t.w,o=t.r;return e>=s.count?Gw(t,e-s.count,n,r):n+o>s.minX[e]&&n-o<s.maxX[e]&&r+o>s.minY[e]&&r-o<s.maxY[e]}function $w(t,e,n,r,s){let o=t.w;hh(t,e,n,r,e,n,r+s);let i=mh(t);for(let a=0;a<i;a++){let c=yh(t,a);if(!Hw(t,c,e,n)||!(r+s>qv(t,c)))continue;let u=Vw(t,c,e,n);if(r<u-1e-4)return!1}return!0}function sd(t,e,n,r,s,o){let i=t.w;hh(t,e,n,r-s,e,n,r+o);let a=mh(t),c=Number.NaN,u=Number.NaN;for(let l=0;l<a;l++){let d=yh(t,l);if(!Hw(t,d,e,n))continue;let f=Vw(t,d,e,n);f<=r+o&&f>=r-s&&(d<i.boxCount||d>=i.count||i.topZ[d]>=t.standable?(c!==c||f>c)&&(c=f):(u!==u||f>u)&&(u=f))}return u>c?Number.NaN:c}function td(t){if(t.vz>.1*t.unit){t.onGround=!1;return}let e=sd(t,t.x,t.y,t.z,t.groundTrace,t.groundSnap);e===e?(t.z=e,t.onGround=!0):t.onGround=!1}function ed(t,e,n,r,s,o){if(Math.abs(n)<1e-9)return e>r&&e<s;let i=(r-e)/n,a=(s-e)/n,c=-1;if(i>a){let u=i;i=a,a=u,c=1}return i>=t.tMin&&(t.tMin=i,t.ax=o,t.sg=c),a<t.tMax&&(t.tMax=a),!(t.tMin>t.tMax)}var Je=new Float64Array(4);function Gv(t,e,n,r){let s=t.w,o=t.r,i=0,a=0,c=0,u;switch(n){case 0:i=1,u=s.maxX[e]+o;break;case 1:i=-1,u=-s.minX[e]+o;break;case 2:a=1,u=s.maxY[e]+o;break;case 3:a=-1,u=-s.minY[e]+o;break;case 4:c=-1,u=-s.minZ[e]+r;break;case 5:{let l=s.slope[e];s.axis[e]===0?i=-l:a=-l,c=1,u=s.lo[e]-l*s.m0[e]+o*Math.abs(l);break}default:c=1,u=s.maxZ[e]}Je[0]=i,Je[1]=a,Je[2]=c,Je[3]=u}function nd(t,e,n,r,s,o){let i=t.w,a=t.r,c=t.skin;if(s>=i.count)return Zv(t,e,n,r,s-i.count,o);if(s<i.boxCount)return e-(i.minX[s]-a)>c&&i.maxX[s]+a-e>c&&n-(i.minY[s]-a)>c&&i.maxY[s]+a-n>c&&r-(i.minZ[s]-o)>c&&i.maxZ[s]-r>c;for(let u=0;u<7;u++){Gv(t,s,u,o);let l=Je[0],d=Je[1],f=Je[2];if(!(-(l*e+d*n+f*r-Je[3])*(1/Math.sqrt(l*l+d*d+f*f))>c))return!1}return!0}function gh(t,e,n,r,s,o,i,a,c){let u=t.w.count,l=t.w.tree,d=0,f=0,h=y=>(f+=1,y!==a&&nd(t,e,n,r,y,c)&&!nd(t,s,o,i,y,c)),p=!1;if(l===null)for(let y=0;y<u&&!p;y++)p=h(y);else{let y=ph(e,n,r,e,n,r+c),S=t.r+y,b=e-S,x=e+S,R=n-S,A=n+S,E=r-y,P=r+c+y,{boxes:k,ref:M,levelEnd:B}=l,K=B[0],j=t.stack,L=0;for(j[L++]=l.root;L>0&&!p;){let se=j[--L];d+=1;let v=se*6;if(k[v+3]<b||k[v]>x||k[v+4]<R||k[v+1]>A||k[v+5]<E||k[v+2]>P)continue;if(se<K){p=h(M[se]);continue}let $=M[se],G=$+Ii;for(let W=0;W<B.length;W++)if($<B[W]){G=Math.min(G,B[W]);break}for(let W=$;W<G;W++)j[L++]=W}}for(let y=u;!p&&y<u+t.p.count;y++)p=h(y);return br!==null&&(br.nodes+=d,br.tests+=f),p}function jw(t,e,n,r,s,o,i,a,c,u){return gh(t,e+s*a,n+o*a,r+i*a,e,n,r,c,u)}function Yv(t,e,n,r,s,o,i,a){let c=t.r,u=t.skin,l=e-(s.minX[o]-c),d=s.maxX[o]+c-e,f=n-(s.minY[o]-c),h=s.maxY[o]+c-n,p=r-(s.minZ[o]-i),y=s.maxZ[o]-r;if(!(l>u&&d>u&&f>u&&h>u&&p>u&&y>u))return!1;let S=l,b=-1,x=0,R=0;return d<S&&([S,b,x,R]=[d,1,0,0]),f<S&&([S,b,x,R]=[f,0,-1,0]),h<S&&([S,b,x,R]=[h,0,1,0]),y<S&&!gh(t,e,n,r+y,e,n,r,a,i)&&([S,b,x,R]=[y,0,0,1]),t.tMin=0,t.nx=b,t.ny=x,t.nz=R,t.depth=S,!0}function bh(t,e,n,r,s,o,i,a,c,u=t.w,l=a){let d=t.r;return t.depth=0,Yv(t,e,n,r,u,a,c,l)?!0:(t.tMin=0,t.tMax=1,t.ax=-1,t.sg=0,!ed(t,e,s,u.minX[a]-d,u.maxX[a]+d,0)||!ed(t,n,o,u.minY[a]-d,u.maxY[a]+d,1)||!ed(t,r,i,u.minZ[a]-c,u.maxZ[a],2)||t.tMin>=1||t.ax<0?!1:(t.nx=t.ax===0?t.sg:0,t.ny=t.ax===1?t.sg:0,t.nz=t.ax===2?t.sg:0,!0))}function Kv(t,e,n,r,s,o,i,a,c){let u=t.w,l=t.r,d=u.slope[a],f=u.axis[a]===0,h=0,p=1,y=!1,S=!0,b=Number.POSITIVE_INFINITY,x=0,R=0,A=0;t.depth=0;for(let E=0;E<7;E++){let P=0,k=0,M=0,B;switch(E){case 0:P=1,B=u.maxX[a]+l;break;case 1:P=-1,B=-u.minX[a]+l;break;case 2:k=1,B=u.maxY[a]+l;break;case 3:k=-1,B=-u.minY[a]+l;break;case 4:M=-1,B=-u.minZ[a]+c;break;case 5:f?P=-d:k=-d,M=1,B=u.lo[a]-d*u.m0[a]+l*Math.abs(d);break;default:M=1,B=u.maxZ[a]}let K=P*e+k*n+M*r-B,j=P*s+k*o+M*i,L=1/Math.sqrt(P*P+k*k+M*M),se=-K*L;if(se>t.skin?E!==4&&se<b&&!(S&&E>=5&&jw(t,e,n,r,P*L,k*L,M*L,se,a,c))&&(b=se,x=P*L,R=k*L,A=M*L):S=!1,Math.abs(j)<1e-9){if(K>0)return!1;continue}let v=j<0&&K<=0&&K>-t.skin?0:-K/j;if(j<0?v>=h&&(h=v,t.nx=P*L,t.ny=k*L,t.nz=M*L,y=!0):p=Math.min(p,v),h>p)return!1}return S?(t.tMin=0,t.nx=x,t.ny=R,t.nz=A,t.depth=b,!0):!y||!(h<1)||!(p>=0)?!1:(t.tMin=h,!0)}function Ww(t,e,n,r){let s=t.p,o=s.cos[e],i=s.sin[e],a=s.cx[e],c=s.cy[e],u=s.hx[e],l=s.hy[e],d=t.r,f=d*(Math.abs(o)+Math.abs(i)),h=0,p=0,y=0,S;switch(n){case 0:h=o,p=i,S=o*a+i*c+u+f;break;case 1:h=-o,p=-i,S=-(o*a+i*c)+u+f;break;case 2:h=-i,p=o,S=-i*a+o*c+l+f;break;case 3:h=i,p=-o,S=i*a-o*c+l+f;break;case 4:h=1,S=a+d+u*Math.abs(o)+l*Math.abs(i);break;case 5:h=-1,S=-a+d+u*Math.abs(o)+l*Math.abs(i);break;case 6:p=1,S=c+d+u*Math.abs(i)+l*Math.abs(o);break;case 7:p=-1,S=-c+d+u*Math.abs(i)+l*Math.abs(o);break;case 8:y=-1,S=-s.minZ[e]+r;break;default:y=1,S=s.maxZ[e]}Je[0]=h,Je[1]=p,Je[2]=y,Je[3]=S}var Xv=10,qw=8,Jv=9;function Gw(t,e,n,r){let s=t.p,o=t.r;if(!(n+o>s.minX[e]&&n-o<s.maxX[e]&&r+o>s.minY[e]&&r-o<s.maxY[e]))return!1;let i=s.kind[e];if(i===Hr.Box)return!0;let a=n-s.cx[e],c=r-s.cy[e];if(i===Hr.Disc){let f=Math.max(Math.abs(a)-o,0),h=Math.max(Math.abs(c)-o,0);return f*f+h*h<s.radius[e]*s.radius[e]}let u=s.cos[e],l=s.sin[e],d=o*(Math.abs(u)+Math.abs(l));return Math.abs(u*a+l*c)<s.hx[e]+d&&Math.abs(-l*a+u*c)<s.hy[e]+d}function Yw(t,e,n,r){let s=t.p,o=t.r,i=n-s.cx[e],a=r-s.cy[e],c=Math.abs(i),u=Math.abs(a),l=s.radius[e];if(c<=o&&u<=o){let p=c>=u;return Je[0]=p?i<0?-1:1:0,Je[1]=p?0:a<0?-1:1,l+o-(p?c:u)}let d=c>o?i<0?-(c-o):c-o:0,f=u>o?a<0?-(u-o):u-o:0,h=Math.sqrt(d*d+f*f);return Je[0]=d/h,Je[1]=f/h,l-h}function Zv(t,e,n,r,s,o){let i=t.p,a=t.skin,c=i.kind[s];if(c===Hr.Box){let u=t.r;return e-(i.minX[s]-u)>a&&i.maxX[s]+u-e>a&&n-(i.minY[s]-u)>a&&i.maxY[s]+u-n>a&&r-(i.minZ[s]-o)>a&&i.maxZ[s]-r>a}if(!(r-(i.minZ[s]-o)>a&&i.maxZ[s]-r>a))return!1;if(c===Hr.Disc)return Yw(t,s,e,n)>a;for(let u=0;u<qw;u++){Ww(t,s,u,o);let l=Je[0],d=Je[1];if(!(-(l*e+d*n-Je[3])*(1/Math.sqrt(l*l+d*d))>a))return!1}return!0}function Qv(t,e,n,r,s,o,i,a,c,u){let l=0,d=1,f=!1,h=!0,p=Number.POSITIVE_INFINITY,y=0,S=0,b=0;t.depth=0;for(let x=0;x<Xv;x++){Ww(t,a,x,u);let R=Je[0],A=Je[1],E=Je[2],P=R*e+A*n+E*r-Je[3],k=R*s+A*o+E*i,M=1/Math.sqrt(R*R+A*A+E*E),B=-P*M;if(B>t.skin?x!==qw&&B<p&&!(h&&x===Jv&&jw(t,e,n,r,R*M,A*M,E*M,B,c,u))&&(p=B,y=R*M,S=A*M,b=E*M):h=!1,Math.abs(k)<1e-9){if(P>0)return!1;continue}let K=k<0&&P<=0&&P>-t.skin?0:-P/k;if(k<0?K>=l&&(l=K,t.nx=R*M,t.ny=A*M,t.nz=E*M,f=!0):d=Math.min(d,K),l>d)return!1}return h?(t.tMin=0,t.nx=y,t.ny=S,t.nz=b,t.depth=p,!0):!f||!(l<1)||!(d>=0)?!1:(t.tMin=l,!0)}function eM(t,e,n,r,s,o,i,a,c,u,l,d){t.tMin=0,t.tMax=1,t.ax=-1,t.sg=0;let f=e-a,h=n-c,p=s*s+o*o,y=f*f+h*h-u*u;if(p<1e-18){if(!(y<0))return!1}else{let S=f*s+h*o,b=S*S-p*y;if(b<0)return!1;let x=Math.sqrt(b),R=(-S-x)/p,A=(-S+x)/p;if(R>=t.tMin&&(t.tMin=R,t.ax=3),A<t.tMax&&(t.tMax=A),t.tMin>t.tMax)return!1}if(!ed(t,r,i,l,d,2)||t.tMin>=1||t.ax<0)return!1;if(t.ax===3){let S=f+s*t.tMin,b=h+o*t.tMin,x=Math.sqrt(S*S+b*b);t.nx=S/x,t.ny=b/x,t.nz=0}else t.nx=0,t.ny=0,t.nz=t.sg;return!0}var $n={minX:new Float64Array(2),minY:new Float64Array(2),minZ:new Float64Array(2),maxX:new Float64Array(2),maxY:new Float64Array(2),maxZ:new Float64Array(2)};function tM(t,e,n,r,s,o,i,a,c,u){let l=t.p,d=t.r,f=l.radius[a],h=l.cx[a],p=l.cy[a],y=l.minZ[a]-u,S=l.maxZ[a];t.depth=0;let b=Yw(t,a,e,n),x=r-y,R=S-r;if(b>t.skin&&x>t.skin&&R>t.skin)return t.tMin=0,R<b&&!gh(t,e,n,r+R,e,n,r,c,u)?[t.nx,t.ny,t.nz,t.depth]=[0,0,1,R]:[t.nx,t.ny,t.nz,t.depth]=[Je[0],Je[1],0,b],!0;let A=!1,E=0,P=0,k=0,M=0;$n.minX[0]=h-f,$n.maxX[0]=h+f,$n.minY[0]=p,$n.maxY[0]=p,$n.minX[1]=h,$n.maxX[1]=h,$n.minY[1]=p-f,$n.maxY[1]=p+f;for(let B=0;B<2;B++)$n.minZ[B]=l.minZ[a],$n.maxZ[B]=S,bh(t,e,n,r,s,o,i,B,u,$n,c)&&(!A||t.tMin<E)&&(A=!0,E=t.tMin,P=t.nx,k=t.ny,M=t.nz);for(let B=0;B<4;B++){let K=B%2===0?h-d:h+d,j=B<2?p-d:p+d;eM(t,e,n,r,s,o,i,K,j,f,y,S)&&(!A||t.tMin<E)&&(A=!0,E=t.tMin,P=t.nx,k=t.ny,M=t.nz)}return A?(t.tMin=E,t.nx=P,t.ny=k,t.nz=M,t.depth=0,!0):!1}function nM(t,e,n,r,s,o,i,a,c){let u=a-t.w.count,l=t.p.kind[u];return l===Hr.Box?bh(t,e,n,r,s,o,i,u,c,t.p,a):l===Hr.OBox?Qv(t,e,n,r,s,o,i,u,a,c):tM(t,e,n,r,s,o,i,u,a,c)}function wh(t,e,n,r,s,o,i){let a=t.w,c=Ur(t,t.duck),u=e+s,l=n+o,d=r+i;hh(t,e<u?e:u,n<l?n:l,r<d?r:d,e<u?u:e,n<l?l:n,(r<d?d:r)+c);let f=mh(t),h=!1,p=0,y=0,S=0,b=0,x=0,R=0;br!==null&&(br.sweeps+=f);for(let A=0;A<f;A++){let E=yh(t,A);br!==null&&E>=a.boxCount&&E<a.count&&(br.wedges+=1),(E<a.boxCount?bh(t,e,n,r,s,o,i,E,c):E<a.count?Kv(t,e,n,r,s,o,i,E,c):nM(t,e,n,r,s,o,i,E,c))&&(!h||t.tMin<p||t.tMin===p&&E<y)&&(h=!0,p=t.tMin,y=E,S=t.nx,b=t.ny,x=t.nz,R=t.depth)}t.hit=h,h?(t.tMin=Math.max(0,p-1e-4),t.nx=S,t.ny=b,t.nz=x,t.depth=R):(t.tMin=1,t.depth=0)}function rd(t,e,n=!1){let r=e,s=!1,o=0,i=0,a=0;for(let c=0;c<4&&r>1e-6;c++){if(t.vx*t.vx+t.vy*t.vy+t.vz*t.vz<1e-8)return;wh(t,t.x,t.y,t.z,t.vx*r,t.vy*r,t.vz*r);let u=t.tMin;if(u>0){let y=u*r;t.x=t.x+t.vx*y,t.y=t.y+t.vy*y,t.z=t.z+t.vz*y,r=r-y}if(!t.hit)return;t.depth>0&&(t.x=t.x+t.nx*t.depth,t.y=t.y+t.ny*t.depth,t.z=t.z+t.nz*t.depth);let l=t.nx,d=t.ny,f=t.nz,h=!1;if(n&&f>0)if(f>=t.standable)h=!0;else{let y=1/Math.sqrt(l*l+d*d);l=l*y,d=d*y,f=0}t.x=t.x+l*t.skin,t.y=t.y+d*t.skin,t.z=t.z+f*t.skin;let p=t.vx*l+t.vy*d+t.vz*f;if(p<0&&(h?t.vz=t.vz-p/f:(t.vx=t.vx+l*-p,t.vy=t.vy+d*-p,t.vz=t.vz+f*-p)),s){let y=i*f-a*d,S=a*l-o*f,b=o*d-i*l,x=y*y+S*S+b*b;if(x>1e-6){let R=1/Math.sqrt(x);y=y*R,S=S*R,b=b*R;let A=t.vx*y+t.vy*S+t.vz*b;t.vx=y*A,t.vy=S*A,t.vz=b*A}}if(s=!0,o=l,i=d,a=f,t.vx*t.vx+t.vy*t.vy+t.vz*t.vz<1e-8)return}}function Kw(t,e=!1){let n=t.x,r=t.y,s=t.z,o=t.vx,i=t.vy,a=t.vz;rd(t,t.h,e);let c=t.x,u=t.y,l=t.z,d=t.vx,f=t.vy,h=t.vz,p=c-n,y=u-r,S=p*p+y*y;t.x=n,t.y=r,t.z=s,t.vx=o,t.vy=i,t.vz=a;let b=t.stepHeight+t.skin;wh(t,n,r,s,0,0,b);let x=t.tMin,R=s+b*x;if(x>0&&$w(t,n,r,R,Ur(t,t.duck))){t.z=R,rd(t,t.h,e);let A=sd(t,t.x,t.y,t.z,t.stepHeight*2,.001);A===A&&(t.z=A);let E=t.x-n,P=t.y-r,k=E*E+P*P;if(A===A&&k>S+.001*t.unit*t.unit){t.vz=0;return}}t.x=c,t.y=u,t.z=l,t.vx=d,t.vy=f,t.vz=h}function Xw(t){let e=sd(t,t.x,t.y,t.z,t.stepHeight,t.groundSnap);e===e&&(t.z=e,t.vz=0)}function rM(t){let e=Math.sqrt(t.vx*t.vx+t.vy*t.vy);if(e<.1*t.unit){t.vx=0,t.vy=0;return}let r=(e<t.stopSpeed?t.stopSpeed:e)*t.friction*t.h,s=Math.max(0,e-r)/e;t.vx=t.vx*s,t.vy=t.vy*s}function sM(t){let e=t.wishSpeed-(t.vx*t.dirX+t.vy*t.dirY);if(e<=0)return;let n=t.accelerate*t.h*Math.max(t.wishSpeed,t.maxSpeed);n>e&&(n=e),t.vx=t.vx+n*t.dirX,t.vy=t.vy+n*t.dirY}function Dw(t){let e=Math.min(t.wishSpeed,t.airMaxWishSpeed)-(t.vx*t.dirX+t.vy*t.dirY);if(e<=0)return;let n=t.airAccelerate*t.wishSpeed*t.h;n>e&&(n=e),t.vx=t.vx+n*t.dirX,t.vy=t.vy+n*t.dirY}var En=t=>Oe(Math.fround(mn(t,-1e9,1e9)));function oM(t,e,n){let r=t.h/t.duckTime;if(!(e&&!t.onGround&&!t.airDuck)){if(e){let a=Math.min(1,t.duck+r);t.onGround||(t.z=t.z+(Ur(t,t.duck)-Ur(t,a))),t.duck=a,t.ducking=!0}else if(t.duck>0){let a=Math.max(0,t.duck-r),c=t.onGround?t.z:t.z-(Ur(t,a)-Ur(t,t.duck));$w(t,t.x,t.y,c,Ur(t,a))&&(t.duck=a,t.z=c,t.duck===0&&(t.ducking=!1))}}let s=t.onGround;td(t),t.onGround&&!s&&(t.vz=0),t.base=t.maxSpeed*t.cap;let o=t.ducking?t.base*t.crouchSpeed:n?t.base*t.walkSpeed:t.jogging?t.base*t.jogSpeed:t.base;t.wishSpeed=t.amount*o,t.onGround?t.pressed?(t.vz=t.jumpImpulse,t.onGround=!1,t.pressed=!1,Dw(t)):(rM(t),sM(t),t.vz=0):Dw(t);let i=!t.onGround;i&&(t.vz=t.vz-t.gravity*t.h*.5),t.vx=mn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=mn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=mn(t.vz,-t.maxVelocity,t.maxVelocity),t.onGround?(Kw(t),Xw(t)):rd(t,t.h),td(t),i&&!t.onGround?t.vz=t.vz-t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=En(t.x),t.y=En(t.y),t.z=En(t.z),t.vx=En(t.vx),t.vy=En(t.vy),t.vz=En(t.vz),t.duck=Oe(Math.fround(t.duck))}var Tt=(t,e,n,r)=>Oe(Math.fround(mn(typeof t=="number"&&Number.isFinite(t)?t:e,n,r))),ah=t=>Oe(Math.fround(typeof t=="number"&&Number.isFinite(t)?t:0)),Ql={cand:new Int32Array(0),stack:new Int32Array(Ii*16)};function Sh(t){return Ql.cand.length<t.count&&(Ql={cand:new Int32Array(t.count),stack:Ql.stack}),Ql}function Jw(t,e,n=yc){let r=dh(n),s=Math.fround,o=a=>s(t==="vehicle"?e.height:e[a]),i=(a,c)=>{let u=Sh(r);return{w:r,p:gc(c),r:s(e.radius),unit:fh(s(e.radius),t==="vehicle"?Uw:zw),standHeight:o("standHeight"),crouchHeight:o("crouchHeight"),stepHeight:s(e.stepHeight),standable:s(e.standable),groundTrace:s(e.groundTrace),groundSnap:s(e.groundSnap),skin:s(e.skin),x:a.x,y:a.y,z:a.z,vx:0,vy:0,vz:a.vz??0,duck:t==="vehicle"?0:a.duck??0,onGround:!1,h:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:u.cand,nCand:-1,pc:lh,nPosed:0,stack:u.stack}};return{support(a,c){let u=i(a,c);if(u.vz>.1*u.unit)return-1;let l=sd(u,u.x,u.y,u.z,u.groundTrace,u.groundSnap);if(l!==l)return-1;for(let d=0;d<u.p.count;d++)if(u.p.maxZ[d]===l&&Gw(u,d,u.x,u.y))return d;return-1},inside(a,c,u){let l=i(a,c);return nd(l,l.x,l.y,l.z,r.count+u,Ur(l,l.duck))},pushOut(a,c){let u=i(a,c);for(let f=0;f<4&&(wh(u,u.x,u.y,u.z,0,0,0),!!u.hit);f++)u.x=u.x+u.nx*u.depth,u.y=u.y+u.ny*u.depth,u.z=u.z+u.nz*u.depth,u.x=u.x+u.nx*u.skin,u.y=u.y+u.ny*u.skin,u.z=u.z+u.nz*u.skin;let l=Ur(u,u.duck),d=!1;for(let f=0;f<r.count+u.p.count&&!d;f++)d=nd(u,u.x,u.y,u.z,f,l);return{x:u.x,y:u.y,z:u.z,inside:d}}}}function iM(t,e,n,r,s=yc,o=Fw){let i=dh(s),a=Sh(i),c=Math.fround,u=fo(t.mstate)&Bv,l={w:i,p:o,maxSpeed:c(r.maxSpeed),walkSpeed:c(r.walkSpeed),jogSpeed:c(r.jogSpeed),jogging:!1,crouchSpeed:c(r.crouchSpeed),accelerate:c(r.accelerate),airAccelerate:c(r.airAccelerate),airMaxWishSpeed:c(r.airMaxWishSpeed),friction:c(r.friction),stopSpeed:c(r.stopSpeed),gravity:c(r.gravity),jumpImpulse:c(r.jumpImpulse),maxVelocity:c(r.maxVelocity),r:c(r.radius),unit:fh(c(r.radius),zw),standHeight:c(r.standHeight),crouchHeight:c(r.crouchHeight),duckTime:c(r.duckTime),airDuck:r.airDuck!==0,stepHeight:c(r.stepHeight),standable:c(r.standable),groundTrace:c(r.groundTrace),groundSnap:c(r.groundSnap),skin:c(r.skin),x:Tt(t.x,0,-1e9,1e9),y:Tt(t.y,0,-1e9,1e9),z:Tt(t.z,0,-1e9,1e9),vx:Tt(t.vx,0,-1e9,1e9),vy:Tt(t.vy,0,-1e9,1e9),vz:Tt(t.vz,0,-1e9,1e9),duck:Tt(t.duck,0,0,1),cap:Tt(t.cap,1,0,4),onGround:(u&Vt.ON_GROUND)!==0,ducking:(u&Vt.DUCKING)!==0,jumpHeld:(u&Vt.JUMP_HELD)!==0,pressed:!1,h:0,dirX:0,dirY:0,amount:0,base:0,wishSpeed:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:a.cand,nCand:-1,pc:lh,nPosed:0,stack:a.stack},d=Hn(e.moveX),f=Hn(e.moveY),h=Math.sqrt(d*d+f*f);h>1e-4&&(l.dirX=d/h,l.dirY=f/h,l.amount=Math.min(h,1));let p=fo(e.buttons),y=(p&r.jumpBit)!==0,S=(p&r.duckBit)!==0,b=(p&r.walkBit)!==0;l.jogging=r.runBit!==0&&(p&r.runBit)===0;let x=Zl(n,ch);l.h=x/r.substeps;let R=Rs(e.yaw)??ah(t.yaw),A=c(r.pitchLimit),E=Oe(mn(Rs(e.pitch)??ah(t.pitch),-A,A));if(x>0){l.pressed=y&&!l.jumpHeld&&(r.capZeroJump!==0||l.cap!==0),l.jumpHeld=y;for(let P=0;P<r.substeps;P++)oM(l,S,b)}return{x:l.x,y:l.y,z:l.z,vx:l.vx,vy:l.vy,vz:l.vz,yaw:R,pitch:E,duck:l.duck,mstate:(l.onGround?Vt.ON_GROUND:0)+(l.ducking?Vt.DUCKING:0)+(l.jumpHeld?Vt.JUMP_HELD:0)}}var aM=Object.freeze({maxSpeed:1410,accel:1e3,brake:3500,coast:525,boostAccel:1e3,boostMaxSpeed:2300,boostBurn:.3333333432674408,grip:6e3,driftGrip:1500,turnRate:2.2,turnSpeed:400,spinAccel:30,airTurnRate:5.5,airSpinAccel:9,gravity:650,jumpImpulse:450,maxVelocity:6e3,radius:50,height:36,stepHeight:8,standable:.7,groundTrace:4,groundSnap:2,skin:.03,jumpBit:1,boostBit:2,driftBit:4,substeps:2,capZeroJump:1,world:Lw}),cM={maxSpeed:Ee(0,1e5),accel:Ee(0,1e5),brake:Ee(0,1e5),coast:Ee(0,1e5),boostAccel:Ee(0,1e5),boostMaxSpeed:Ee(0,1e5),boostBurn:Ee(0,1e3),grip:Ee(0,1e5),driftGrip:Ee(0,1e5),turnRate:Ee(0,100),turnSpeed:ho(1e5),spinAccel:Ee(0,1e4),airTurnRate:Ee(0,100),airSpinAccel:Ee(0,1e4),gravity:Ee(0,1e5),jumpImpulse:Ee(0,1e5),maxVelocity:Ee(0,1e5),radius:ho(1e4),height:ho(1e4),stepHeight:Ee(0,1e4),standable:Ee(0,1),groundTrace:Ee(0,1e4),groundSnap:Ee(0,1e4),skin:Ee(0,100),jumpBit:Jt(0,16777215),boostBit:Jt(0,16777215),driftBit:Jt(0,16777215),substeps:Jt(1,8),capZeroJump:Jt(0,1),world:Jt(0,2**32-1)};var uM=Vt.ON_GROUND|Vt.JUMP_HELD,po=(t,e,n)=>t<e?Math.min(e,t+n):t>e?Math.max(e,t-n):t,Zw=t=>Rs(t)??0;function lM(t){let e=t.maxSpeed*t.cap,n=t.boosting?1:t.throttle,r=n*e,s=t.f;if(n===0?s=po(s,0,t.coast*t.h):n>0&&s<0||n<0&&s>0?s=po(s,0,t.brake*t.h):Math.abs(s)<Math.abs(r)?s=po(s,r,t.accel*t.h):t.boosting||(s=po(s,r,t.coast*t.h)),t.boosting){let a=t.boostMaxSpeed*t.cap;s<a&&(s=Math.min(a,s+t.boostAccel*t.h))}let o=po(t.l,0,(t.drift?t.driftGrip:t.grip)*t.h),i=t.steer*t.turnRate*Math.min(1,Math.abs(s)/t.turnSpeed);s<0&&(i=-i),t.spin=po(t.spin,i,t.spinAccel*t.h),t.vx=s*t.c-o*t.s,t.vy=s*t.s+o*t.c,t.vz=0,t.f=s,t.l=o}function dM(t){if(t.spin=po(t.spin,t.steer*t.airTurnRate,t.airSpinAccel*t.h),t.boosting){let e=t.boostMaxSpeed*t.cap;if(t.f<e){let n=Math.min(t.boostAccel*t.h,e-t.f);t.vx=t.vx+n*t.c,t.vy=t.vy+n*t.s}}}function fM(t){let e=t.onGround;td(t),t.onGround&&!e&&(t.vz=0),t.c=Mw(t.yaw),t.s=vw(t.yaw),t.f=t.vx*t.c+t.vy*t.s,t.l=t.vy*t.c-t.vx*t.s,t.boosting=t.boost&&t.fuel>0,t.boosting&&(t.fuel=Math.max(0,t.fuel-t.boostBurn*t.h)),t.onGround&&t.pressed&&(t.vz=t.jumpImpulse,t.onGround=!1,t.pressed=!1),t.onGround?lM(t):dM(t);let n=!t.onGround;n&&(t.vz-=t.gravity*t.h*.5),t.vx=mn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=mn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=mn(t.vz,-t.maxVelocity,t.maxVelocity),t.yaw=Zw(t.yaw+t.spin*t.h),t.onGround?(Kw(t,!0),Xw(t)):rd(t,t.h),td(t),n&&!t.onGround?t.vz-=t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=En(t.x),t.y=En(t.y),t.z=En(t.z),t.vx=En(t.vx),t.vy=En(t.vy),t.vz=En(t.vz),t.spin=Oe(Math.fround(t.spin)),t.fuel=Oe(Math.fround(t.fuel))}function pM(t,e,n,r,s=yc,o=Fw){let i=dh(s),a=Sh(i),c=Math.fround,u=fo(t.mstate)&uM,l=c(r.height),d=Oe(-Hn(e.moveX)),f=Hn(e.moveY),h=fo(e.buttons),p=(h&r.jumpBit)!==0,y=Zl(n,ch),S=ah(t.yaw),b={w:i,p:o,r:c(r.radius),unit:fh(c(r.radius),Uw),standHeight:l,crouchHeight:l,stepHeight:c(r.stepHeight),standable:c(r.standable),groundTrace:c(r.groundTrace),groundSnap:c(r.groundSnap),skin:c(r.skin),maxSpeed:c(r.maxSpeed),accel:c(r.accel),brake:c(r.brake),coast:c(r.coast),boostAccel:c(r.boostAccel),boostMaxSpeed:c(r.boostMaxSpeed),boostBurn:c(r.boostBurn),grip:c(r.grip),driftGrip:c(r.driftGrip),turnRate:c(r.turnRate),turnSpeed:c(r.turnSpeed),spinAccel:c(r.spinAccel),airTurnRate:c(r.airTurnRate),airSpinAccel:c(r.airSpinAccel),gravity:c(r.gravity),jumpImpulse:c(r.jumpImpulse),maxVelocity:c(r.maxVelocity),x:Tt(t.x,0,-1e9,1e9),y:Tt(t.y,0,-1e9,1e9),z:Tt(t.z,0,-1e9,1e9),vx:Tt(t.vx,0,-1e9,1e9),vy:Tt(t.vy,0,-1e9,1e9),vz:Tt(t.vz,0,-1e9,1e9),yaw:Math.abs(S)<=1e9?Zw(S):0,spin:Tt(t.spin,0,-1e3,1e3),fuel:Tt(t.fuel,0,0,1),cap:Tt(t.cap,1,0,4),duck:0,onGround:(u&Vt.ON_GROUND)!==0,jumpHeld:(u&Vt.JUMP_HELD)!==0,pressed:!1,boosting:!1,steer:d,throttle:f,boost:(h&r.boostBit)!==0,drift:(h&r.driftBit)!==0,h:y/r.substeps,c:1,s:0,f:0,l:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:a.cand,nCand:-1,pc:lh,nPosed:0,stack:a.stack};if(y>0){b.pressed=p&&!b.jumpHeld&&(r.capZeroJump!==0||b.cap!==0),b.jumpHeld=p;for(let x=0;x<r.substeps;x++)fM(b)}return{x:b.x,y:b.y,z:b.z,vx:b.vx,vy:b.vy,vz:b.vz,yaw:b.yaw,spin:b.spin,fuel:b.fuel,mstate:(b.onGround?Vt.ON_GROUND:0)+(b.jumpHeld?Vt.JUMP_HELD:0)}}var hM={defaults:Cv,ranges:Ov,fields:["x","y","yaw"],reads:[],world:!1,step:(t,e,n,r)=>Iv(t,e,n,r)},mM={defaults:Dv,ranges:Nv,fields:["x","y","z","vx","vy","vz","yaw","pitch","duck","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>iM(t,e,n,r,s,o)},yM={defaults:aM,ranges:cM,fields:["x","y","z","vx","vy","vz","yaw","spin","fuel","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>pM(t,e,n,r,s,o)},Nw=Object.freeze({[wr.TOPDOWN]:Object.freeze(hM),[wr.FIRSTPERSON]:Object.freeze(mM),[wr.VEHICLE]:Object.freeze(yM)});function bc(t){return typeof t=="string"&&Object.hasOwn(Nw,t)?Nw[t]:void 0}Zp();var gM=2,Qw=t=>typeof t=="string"&&t.length>0;function tS(t,e){let n=[],r=new Set;for(let s of Array.isArray(t)?t:[]){if(s===null||typeof s!="object")continue;let{region:o,urls:i}=s;if(typeof o!="string"||o.length===0||r.has(o))continue;let a=Array.isArray(i)?i.filter(Qw):[];a.length!==0&&(r.add(o),n.push({region:o,urls:a}))}return n.length>0?n:(Array.isArray(e)?e.filter(Qw):[]).map(s=>({region:s,urls:[s]}))}function bM(t,e){return Array.from({length:e},(n,r)=>t[r%t.length])}var nS=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0;function eS(t,e){let n=[],r=[];return t.forEach((s,o)=>{let i=null,a=s.urls[0];s.urls.forEach((c,u)=>{let l=e[o]?.[u];!nS(l)||i!==null&&l>=i||(i=l,a=c)}),(i===null?r:n).push({index:o,ms:i,pick:{region:s.region,url:a}})}),n.sort((s,o)=>s.ms-o.ms||s.index-o.index),[...n,...r].map(s=>s.pick)}var Ni={Capacity:"capacity",NextRegion:"next_region",Final:"final"},wM=new Set([503,4213]),SM=new Set([502,504,520,521,522,523,524,525,526,530]);function rS(t){return typeof t!="number"||t<=0||SM.has(t)?Ni.NextRegion:wM.has(t)?Ni.Capacity:Ni.Final}function sS(t,e,n){let r=t.refused+1;if(r>=gM&&t.region+1<e){let o=t.region+1;return{attempt:{region:o,waitMs:0},state:{region:o,refused:0,step:t.step}}}let s=n[t.step];return s===void 0?null:{attempt:{region:t.region,waitMs:s},state:{region:t.region,refused:r,step:t.step+1}}}async function oS(t,e={}){if(t.length===0)return[];if(t.length===1)return eS(t,[]);let n=Math.max(1,e.samples??uo.SAMPLES),r=t.map(i=>bM(i.urls,n)),s=await xM(r,e),o=t.map((i,a)=>i.urls.map(c=>{let u;return r[a]?.forEach((l,d)=>{let f=s[a]?.[d];l===c&&nS(f)&&(u=Math.min(u??Number.POSITIVE_INFINITY,f))}),u}));return eS(t,o)}async function xM(t,e={}){let n=e.probe??qp,r=e.timeoutMs??uo.TIMEOUT_MS,s=e.graceMs??uo.GRACE_MS,o=t.map(a=>a.map(()=>{})),i=t.reduce((a,c)=>a+c.length,0);return i===0||await new Promise(a=>{let c,u=!1,l=setTimeout(d,r);function d(){u=!0,clearTimeout(l),clearTimeout(c),a()}let f=()=>{--i===0&&d()};t.forEach((h,p)=>{h.forEach((y,S)=>{let b;try{b=n(y,r)}catch(x){b=Promise.reject(x)}b.then(x=>{!u&&Number.isFinite(x)&&x>=0&&(o[p][S]=x,c??(c=setTimeout(d,s))),f()},f)})})}),o}var Rh={MAX_MATCH_KEY_CHARS:32,MAX_CODE_CHARS:32,MAX_WORLDS:16},_M=522,_h=(t,e,n)=>t>=e.charCodeAt(0)&&t<=n.charCodeAt(0),iS=t=>_h(t,"a","z")||_h(t,"0","9"),RM="._:-",EM="_-";function aS(t){if(typeof t!="string"||t.length===0||t.length>Rh.MAX_MATCH_KEY_CHARS)return!1;for(let e=0;e<t.length;e++)if(!iS(t.charCodeAt(e))&&(e===0||!RM.includes(t.charAt(e))))return!1;return!0}function cS(t){if(typeof t!="string"||t.length===0||t.length>Rh.MAX_CODE_CHARS)return!1;for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(!iS(n)&&!_h(n,"A","Z")&&!EM.includes(t.charAt(e)))return!1}return!0}function kM(t){return t===void 0||t===""?"":aS(t)?t:null}var Sr={JoinOrCreate:"joinOrCreate",Create:"create",JoinById:"joinById"},xh={BadMatchKey:"bad_match_key",BadCode:"bad_code",Conflict:"conflict"};function uS(t){let e=t.matchKey??"";if(t.code!==void 0)return t.createPrivate===!0||e!==""?{refused:xh.Conflict}:cS(t.code)?{method:Sr.JoinById,roomId:t.code,options:{}}:{refused:xh.BadCode};let n=kM(e);if(n===null)return{refused:xh.BadMatchKey};let r=n===""?{}:{matchKey:n};return t.createPrivate===!0?{method:Sr.Create,options:{...r,private:!0}}:{method:Sr.JoinOrCreate,options:r}}function lS(t,e,n){return(t===fn.WRONG_REGION||t===_M)&&e+1<n?e+1:null}var Bi={scheduleMs:[0,250,500,1e3,2e3,4e3],jitterMs:250,budgetMs:18e4,regionStayMs:6e4,successorMs:9e4};var Li={Room:"room",Successor:"successor",Pool:"pool"},dS={Final:"final",Budget:"budget"},AM=new Set([pn.GOING_AWAY,pn.NO_STATUS,pn.ABNORMAL,1011,1012,1013,pn.SERVER_SHUTDOWN,pn.FAILED_TO_RECONNECT,pn.MAY_TRY_RECONNECT]),PM=new Set([fn.BAD_OPTION,fn.NOT_ENTITLED,fn.FORBIDDEN,fn.MODULE_UNAVAILABLE,fn.PROTOCOL_UNSUPPORTED]);function fS(t){return AM.has(t)}function pS(t){let{attempt:e,elapsedMs:n,refusal:r,lostCode:s,closed:o,regions:i,jitter:a}=t;if(r!==null&&PM.has(r))return{stop:dS.Final};if(n>=Bi.budgetMs)return{stop:dS.Budget};let c=Bi.scheduleMs.length-1,l=Bi.scheduleMs[Math.min(e,c)]+Math.floor(a*Bi.jitterMs);if(e===0&&s!==pn.SERVER_SHUTDOWN)return{waitMs:l,region:0,way:Li.Room};let d=i<1?0:Math.floor(n/Bi.regionStayMs)%i,f=o||n<Bi.successorMs?Li.Successor:Li.Pool;return{waitMs:l,region:d,way:f}}function hS(t){return{...t.matchKey===""?{}:{matchKey:t.matchKey},successorOf:t.lostRoomId,...t.closed?{successorClosed:!0}:{}}}var Es={Draining:"draining",Rejoining:"rejoining",Rejoined:"rejoined"},od="disconnect",TM=-1,vM=t=>new Promise(e=>setTimeout(e,t)),MM=t=>{let e=t!==null&&typeof t=="object"?t.code:void 0;return typeof e=="number"?e:null};function mS(t,e){let n=e.now??Date.now,r=e.random??Math.random,s=e.sleep??vM,o={...t.input},i=new Map,a=t,c=!1,u=null,l=null,d=(b,...x)=>{for(let R of i.get(b)??[])R(...x)},f=(b,x)=>{x===od||x===Es.Draining||x===Es.Rejoining||x===Es.Rejoined||b.on(x,(...R)=>{b===a&&d(x,...R)})},h=async(b,x)=>{let R=n(),A={roomId:a.code,matchKey:a.matchKey,closed:e.closed},E=e.targets.length,P=0,k=null;for(;!c;){let M=pS({attempt:P,elapsedMs:n()-R,refusal:k,lostCode:b,closed:e.closed,regions:E,jitter:r()});if("stop"in M){d(od,b,x);return}if(P+=1,d(Es.Rejoining,{attempt:P,code:b,waitMs:M.waitMs}),await s(M.waitMs),c)return;try{let B=await e.join(e.targets[M.region],M.way,A);if(c){await B.leave().catch(()=>{});return}p(B),d(Es.Rejoined,{code:B.code,url:B.url});return}catch(B){k=MM(B)}}},p=b=>{a=b,u!==null&&b.setPhysics(u),l!==null&&b.setWorld(l);for(let x of i.keys())f(b,x);y(b)},y=b=>{b.on(xe.SERVER_RESTART,x=>{if(b!==a)return;let R=x?.drainMs;d(Es.Draining,{closesInMs:typeof R=="number"?R:TM})}),b.on(od,(x,R)=>{b!==a||c||(fS(x)?h(x,R):d(od,x,R))})};y(t);let S={input:o,frame(b){return Object.assign(a.input,o),a.frame(b)},setWorld(b){let x=a.setWorld(b);return l=b,x},setPhysics(b){return u=b,a.setPhysics(b)},on(b,x){let R=i.get(b);R===void 0&&(R=new Set,i.set(b,R),f(a,b));let A=x;return R.add(A),()=>{R.delete(A)}},async leave(){c=!0,await a.leave()}};return new Proxy(t,{get(b,x){if(Object.hasOwn(S,x))return S[x];let R=a[x];return typeof R=="function"?R.bind(a):R}})}var Zt={EXTRAPOLATE:"extrapolate",HOLD:"hold",INPUT_DECAY:"inputDecay"};var OM=Object.freeze({bodies:512,collidersPerBody:8,hullVertices:64,triangles:65536,joints:64,ccdBodies:16,queriesPerStep:64,eventsPerStep:64,heightfieldSamples:1048576,staticPieces:4608,memoryBytes:64*1024*1024,worldExtent:1e5,maxSpeed:1e3,maxAngularSpeed:1e3}),cU=Object.freeze(Object.keys(OM)),uU=Object.freeze(["worldExtent","maxSpeed"]),lU=Object.freeze(["worldExtent","maxSpeed","maxAngularSpeed"]);var yS=Object.freeze({[wr.FIRSTPERSON]:39.37,[wr.VEHICLE]:100}),dU=Object.freeze([10,15,20,30,60]);var xr={DEFAULT_REMOTE_PREDICT:Zt.EXTRAPOLATE,DEFAULT_REMOTE_DECAY_MS:50,MAX_REMOTE_DECAY_MS:1e3,DEFAULT_LEAD_MS:250,MIN_LEAD_MS:50,MAX_LEAD_MS:1e3},fU=Object.values(Zt);var gS=64,bS=64;var pU=Object.freeze({20:3,30:2,60:1,120:1});var IM=Object.freeze(["qx","qy","qz","qw","lvx","lvy","lvz","avx","avy","avz","sleep"]),DM=Object.freeze(["x","y","z",...IM]),id={BITS:16,SPAN:65534,ORIENTATION:Object.freeze({min:-1,max:1}),VELOCITY:Object.freeze({min:-64,max:64})};function Qt(t,e){if(Number.isNaN(t))return 0;let n=t<e.min?e.min:t>e.max?e.max:t;return Math.floor((n-e.min)/(e.max-e.min)*id.SPAN+.5)}var wS=250,SS=1,xS=100,_S=1;var Ah=[0,0,0,1];function jn(t,e){return[t[3]*e[0]+t[0]*e[3]+t[1]*e[2]-t[2]*e[1],t[3]*e[1]-t[0]*e[2]+t[1]*e[3]+t[2]*e[0],t[3]*e[2]+t[0]*e[1]-t[1]*e[0]+t[2]*e[3],t[3]*e[3]-t[0]*e[0]-t[1]*e[1]-t[2]*e[2]]}function $r(t){let e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]);return e===0?Ah:[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function RS(t,e,n,r){let s=Math.sin(r/2);return[t*s,e*s,n*s,Math.cos(r/2)]}function Fi(t,e){let n=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(n===0)return Ah;let r=2*Math.atan2(n,t[3]);return RS(t[0]/n,t[1]/n,t[2]/n,e*r)}function ES(t,e){return{tick:e+1,p:[t.x,t.y,t.z],q:$r([t.qx,t.qy,t.qz,t.qw]),lv:[t.lvx,t.lvy,t.lvz],av:[t.avx,t.avy,t.avz],sleep:t.sleep,epoch:t.epoch}}function NM(t,e,n){if(t.sleep||!(n.tickHz>0))return 0;let s=((e-n.tickOrigin)*n.tickHz/1e3-t.tick)/n.tickHz,o=-SS/n.tickHz,i=wS/1e3;return s<o?o:s>i?i:s}function kS(t,e,n){let r=NM(t,e,n),s=n.lengthUnit,o=[t.p[0]+t.lv[0]*s*r,t.p[1]+t.lv[1]*s*r,t.p[2]+t.lv[2]*s*r],[i,a,c]=t.av,u=Math.sqrt(i*i+a*a+c*c);return u===0||r===0?{p:o,q:t.q}:{p:o,q:$r(jn(RS(i/u,a/u,c/u,u*r),t.q))}}var Eh={SPAWNED:"spawned",EPOCH:"epoch",DISTANCE:"distance"},kh=(t,e)=>({state:t,arrivedAt:e,dp:[0,0,0],dq:Ah});function Ph(t,e,n){let r=kS(t.state,e,n),s=e-t.arrivedAt,o=Math.exp(-(s<0?0:s)/xS),{dp:i}=t;return{p:[r.p[0]+i[0]*o,r.p[1]+i[1]*o,r.p[2]+i[2]*o],q:jn(Fi(t.dq,o),r.q)}}function AS(t,e,n,r){if(t===null)return{drawing:kh(e,n),snap:Eh.SPAWNED};if(e.epoch!==t.state.epoch)return{drawing:kh(e,n),snap:Eh.EPOCH};let s=Ph(t,n,r),o=kS(e,n,r),i=[s.p[0]-o.p[0],s.p[1]-o.p[1],s.p[2]-o.p[2]];if(Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2])>_S*r.lengthUnit)return{drawing:kh(e,n),snap:Eh.DISTANCE};let a=jn(s.q,[-o.q[0],-o.q[1],-o.q[2],o.q[3]]),c=a[3]<0?[-a[0],-a[1],-a[2],-a[3]]:a;return{drawing:{state:e,arrivedAt:n,dp:i,dq:c},snap:null}}function PS(t,e){let n=(r,s)=>r.every((o,i)=>Object.is(o,s[i]));return t.sleep===e.sleep&&t.epoch===e.epoch&&n(t.p,e.p)&&n(t.q,e.q)&&n(t.lv,e.lv)&&n(t.av,e.av)}var TS=2**32-1,wc=1e3,jr=t=>typeof t.t0=="number"&&t.t0>0;function Th(t,e,n){let r=(e-t.t0)/n,s=Number.isFinite(r)&&r>=0?r:0;return{x:Oe(Math.fround(t.x+t.vx*s)),y:Oe(Math.fround(t.y+t.vy*s)),z:Oe(Math.fround(t.z+t.vz*s-.5*t.g*s*s)),vx:Oe(t.vx),vy:Oe(t.vy),vz:Oe(Math.fround(t.vz-t.g*s))}}function vh(t,e,n){return(t-e)*n/1e3}function ad(t,e,n){return e+t*1e3/n}var gn={Predicted:"predicted",Separate:"separate",Timeline:"timeline"},yo={Shared:"shared",Mover:"mover"},Wn={Shooter:"shooter",Platformer:"platformer",VehicleArena:"vehicle-arena",PhysicsSandbox:"physics-sandbox",Party:"party"},it={Stand:"stand",Slide:"slide",Bounce:"bounce",Ghost:"ghost"},qn={Box:"box",Hull:"hull"},go={Slide:"slide",Carry:"carry"};var Mh=(t,e,n)=>({speed:t,step:e,share:n}),Sc=t=>({policy:it.Slide,...t}),xc=(t,e,n)=>({policy:it.Stand,ride:t,center:e,slide:n}),zi=Mh(300,150,1),Wr=Mh(950,480,1),BM=Mh(600,null,.5),LM=.25,SU=Object.freeze({speed:300,step:150}),xU={policy:it.Bounce,stompMin:150,bounceSpeed:450,jumpBoost:150,slide:zi},vS={[Wn.Shooter]:{character:xc(!1,LM,zi),vehicle:Sc(Wr),restitution:0,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:gn.Separate,push:yo.Mover,headFriction:go.Slide},[Wn.Platformer]:{character:xc(!0,null,zi),vehicle:Sc(Wr),restitution:0,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:gn.Separate,push:yo.Mover,headFriction:go.Slide},[Wn.VehicleArena]:{character:Sc(zi),vehicle:Sc(Wr),restitution:.6,passes:32,vehicleOffWall:BM,stopSpin:!0,drawing:gn.Predicted,push:yo.Shared,headFriction:go.Carry},[Wn.PhysicsSandbox]:{character:xc(!0,null,zi),vehicle:xc(!0,null,Wr),restitution:.2,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:gn.Separate,push:yo.Shared,headFriction:go.Carry},[Wn.Party]:{character:xc(!0,null,zi),vehicle:Sc(Wr),restitution:.3,passes:16,vehicleOffWall:Wr,stopSpin:!1,drawing:gn.Separate,push:yo.Shared,headFriction:go.Slide}},_U=Object.freeze({supportCos:.7,entrySpeed:1,entryWindow:1/60,slop:.1,roofSkin:.01});var RU={[it.Stand]:new Set(["policy","ride","center","slide"]),[it.Slide]:new Set(["policy","speed","step","share"]),[it.Bounce]:new Set(["policy","stompMin","bounceSpeed","jumpBoost"]),[it.Ghost]:new Set(["policy"])};var FM=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0],[0,0,1],[0,0,-1]],zM=[0,3,1,4,5,2];function UM(t,e,n,r,s){let[o,i,a,c,u,l,d,f,h]=n,p=d===0?o:i,y=(h-f)/((d===0?c:u)-p),S=1/Math.sqrt(y*y+1),b=(f-y*p+r*Math.abs(y))*S,x=[1,0,0,c+r,-1,0,0,-o+r,0,1,0,u+r,0,-1,0,-i+r,d===0?-y*S:0,d===0?0:-y*S,S,b,0,0,1,l,0,0,-1,-a+s];t.set(x,e)}function IS(t,e,n,r){let s=t?.boxes??[],o=t?.ramps??[],i=s.length+o.length,a=new Float64Array(i*6),c=new Float64Array(o.length*28);for(let d=0;d<i;d++){let f=d<s.length?s[d]:o[d-s.length],h=d*6;a[h]=f[0]-e,a[h+1]=f[1]-e,a[h+2]=f[2]-n,a[h+3]=f[3]+e,a[h+4]=f[4]+e,a[h+5]=f[5],d>=s.length&&UM(c,(d-s.length)*28,f,e,n)}let u={count:i,boxCount:s.length,bounds:a,rampPlanes:c,skin:r},l=VM(u);return l===null?u:{...u,grid:l}}function MS(t,e){let n=e*6;return Number.isFinite(t[n])&&Number.isFinite(t[n+3])&&Number.isFinite(t[n+1])&&Number.isFinite(t[n+4])}function ks(t,e,n,r){let s=Math.floor((t-e)/n);return s<0?0:s>r-1?r-1:s}function VM(t){let{count:e,bounds:n}=t,r=0,s=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let x=0;x<e;x++){if(!MS(n,x))continue;r+=1;let R=x*6;s=Math.min(s,n[R]-1),o=Math.min(o,n[R+1]-1),i=Math.max(i,n[R+3]+1),a=Math.max(a,n[R+4]+1)}if(r<32)return null;let c=Math.max(64,(i-s)/32,(a-o)/32);if(!Number.isFinite(c))return null;let u=Math.min(32,Math.floor((i-s)/c)+1),l=Math.min(32,Math.floor((a-o)/c)+1),d=(x,R)=>{for(let A=0;A<e;A++){if(!MS(n,A)){x(A);continue}let E=A*6,P=ks(n[E]-1,s,c,u),k=ks(n[E+3]+1,s,c,u),M=ks(n[E+1]-1,o,c,l),B=ks(n[E+4]+1,o,c,l);if((k-P+1)*(B-M+1)>64){x(A);continue}for(let K=M;K<=B;K++)for(let j=P;j<=k;j++)R(j+K*u,A)}},f=new Int32Array(u*l+1),h=0;d(()=>{h+=1},x=>{f[x+1]+=1});for(let x=0;x<u*l;x++)f[x+1]=f[x+1]+f[x];let p=new Int32Array(f[u*l]),y=new Int32Array(h),S=f.slice(),b=0;return d(x=>{y[b]=x,b+=1},(x,R)=>{p[S[x]]=R,S[x]=S[x]+1}),{x0:s,y0:o,size:c,nx:u,ny:l,cellStart:f,cellSolids:p,wide:y,merged:new Array(b<=64?u*l:0)}}function CS(t,e,n,r){if(r===n)return t;let s=[],o=0,i=n;for(;o<t.length||i<r;){let a=i>=r||o<t.length&&t[o]<=e[i],c=a?t[o]:e[i];a?o+=1:i+=1,s[s.length-1]!==c&&s.push(c)}return s}function DS(t,e,n,r,s){let o=t.grid;if(o===void 0||!(Number.isFinite(e)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(s)))return null;let i=ks(e,o.x0,o.size,o.nx),a=n===e?i:ks(n,o.x0,o.size,o.nx),c=ks(r,o.y0,o.size,o.ny),u=s===r?c:ks(s,o.y0,o.size,o.ny);if((a-i+1)*(u-c+1)>16)return null;if(i===a&&c===u&&o.merged.length>0){let d=i+c*o.nx,f=o.merged[d];if(f!==void 0)return f;let h=CS(o.wide,o.cellSolids,o.cellStart[d],o.cellStart[d+1]);return o.merged[d]=h,h}let l=o.wide;for(let d=c;d<=u;d++)for(let f=i;f<=a;f++){let h=f+d*o.nx;l=CS(l,o.cellSolids,o.cellStart[h],o.cellStart[h+1])}return l}var yt={nx:0,ny:0,nz:0,e:0};function _c(t,e,n){if(e<t.boxCount){let o=FM[n],i=zM[n],a=t.bounds[e*6+i];yt.nx=o[0],yt.ny=o[1],yt.nz=o[2],yt.e=i<3?-a:a;return}let r=(e-t.boxCount)*28+n*4,s=t.rampPlanes;yt.nx=s[r],yt.ny=s[r+1],yt.nz=s[r+2],yt.e=s[r+3]}var cd=(t,e)=>e<t.boxCount?6:7;function Rc(t,e,n,r,s,o){let i=cd(t,e);for(let a=0;a<i;a++)if(_c(t,e,a),!(yt.e-(yt.nx*r+yt.ny*s+yt.nz*o)>n))return!1;return!0}var NS=(t,e,n)=>DS(t,e,e,n,n);function HM(t,e,n,r,s){let o=e*6;for(let i=0;i<3;i++){let a=n[i],c=a+r[i]*s,u=a<c?a:c;if((a<c?c:a)<t.bounds[o+i]-1||u>t.bounds[o+3+i]+1)return!1}return!0}function $M(t,e,n,r,s,o){let i=cd(t,e);for(let a=0;a<i;a++){_c(t,e,a);let{nx:c,ny:u,nz:l,e:d}=yt;if(d-(c*r[0]+u*r[1]+l*r[2])<=n&&c*s[0]+u*s[1]+l*s[2]<0){let h=[c,u,l,d];if(!o?.(h))return{t:0,face:h}}}return null}var BS=(t,e)=>n=>n[2]>=e&&n[0]*t[0]+n[1]*t[1]+n[2]*t[2]>=e;function jM(t,e,n,r,s,o,i){if(Rc(t,e,n,r[0],r[1],r[2]))return null;if(Rc(t,e,-n,r[0],r[1],r[2]))return $M(t,e,n,r,s,i);let a=0,c=o,u=Number.NEGATIVE_INFINITY,l=-1,d=cd(t,e);for(let h=0;h<d;h++){_c(t,e,h);let{nx:p,ny:y,nz:S,e:b}=yt,x=b+n-(p*r[0]+y*r[1]+S*r[2]),R=p*s[0]+y*s[1]+S*s[2];if(R===0){if(!(x>0))return null;continue}let A=x/R;R>0&&A<c&&(c=A),R<0&&A>u&&(u=A,l=h)}if(u>a&&(a=u),l<0||!(a<c))return null;_c(t,e,l);let f=[yt.nx,yt.ny,yt.nz,yt.e];return i?.(f)?null:{t:a,face:f}}function Ec(t,e,n,r,s){let o={t:r,face:null};if(!(r>0))return{t:0,face:null};let i=f=>{if(!HM(t,f,e,n,o.t))return;let h=jM(t,f,t.skin,e,n,o.t,s);h!==null&&h.t<o.t&&(o=h)},[a,c]=[e[0],e[1]],[u,l]=[a+n[0]*r,c+n[1]*r],d=DS(t,Math.min(a,u),Math.max(a,u),Math.min(c,l),Math.max(c,l));if(d===null)for(let f=0;f<t.count;f++)i(f);else for(let f=0;f<d.length;f++)i(d[f]);return o}function ud(t,e,n,r,s){if(t===null)return r;let o=Ec(t,e,n,r,s).t;return o<0?0:o}var OS=[0,0,1],WM=[0,0,-1];function Ch(t,e,n,r,s){if(t===null)return OS;let o=Ec(t,[e,n,r],WM,s);return o.face===null||!(o.face[2]>0)?OS:[o.face[0],o.face[1],o.face[2]]}function qM(t,e,n,r,s,o){let{count:i,skin:a}=t,c=NS(t,o[0],o[1]),u=c===null?i:c.length;for(let l=0;l<u;l++){let d=c===null?l:c[l];if(d!==e&&Rc(t,d,a,o[0],o[1],o[2])&&!Rc(t,d,a,n,r,s))return!0}return!1}function GM(t,e,n,r,s){let o=null,i=cd(t,e);for(let a=0;a<i-1;a++){_c(t,e,a);let{nx:c,ny:u,nz:l,e:d}=yt,f=d-(c*n+u*r+l*s);o!==null&&!(f<o[3])||l>0&&qM(t,e,n,r,s,[n+c*f,r+u*f,s+l*f])||(o=[c,u,l,f])}return o}function YM(t,e,n,r){let{count:s,skin:o}=t,i=NS(t,e,n),a=i===null?s:i.length;for(let c=0;c<a;c++){let u=i===null?c:i[c];if(Rc(t,u,o,e,n,r))return GM(t,u,e,n,r)}return null}function LS(t,e,n){let{x:r,y:s,z:o}=e,i=0;for(let a=0;a<4;a++){let c=YM(t,r,s,o);if(c===null)break;n?.(c);let[u,l,d,f]=c;i=Math.max(i,f),r+=u*(f+t.skin),s+=l*(f+t.skin),o+=d*(f+t.skin)}return i>0&&(e.x=r,e.y=s,e.z=o),i}var wo={Side:"side",Top:"top"},fd={Free:"free",LowerYields:"lower-yields",Pinned:"pinned"},KM={Stomp:"stomp"},Oh={j:0,way:null,w:null},kc=[0,0,1],Fe=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2],So=(t,e)=>[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]],ft=t=>[-t[0],-t[1],-t[2]];function XM(t,e,n){if(n.supportUp!==void 0)return n.supportUp(t.x,t.y,t.z);let r=n.supports;if(r===void 0)return Ch(n.world,t.x,t.y,t.z,e.groundTrace);let s=r.get(t);if(s!==void 0&&s.x===t.x&&s.y===t.y&&s.z===t.z)return s.up;let o=Ch(n.world,t.x,t.y,t.z,e.groundTrace);return r.set(t,{x:t.x,y:t.y,z:t.z,up:o}),o}function qr(t,e,n){let r=e.shape,s=XM(t,e,n);if(r.kind===qn.Hull)return{b:t,up:kc,support:s,hl:r.radius,hw:r.radius,top:r.height,s:0,c:1};let[o,i]=Ut(t.yaw);return{b:t,up:s,support:s,hl:r.length/2,hw:r.width/2,top:r.top,s:o,c:i}}var pd=t=>Math.sqrt(t.hl*t.hl+t.hw*t.hw),ld=(t,e,n)=>t.hl*Math.abs(t.c*e+t.s*n)+t.hw*Math.abs(t.c*n-t.s*e);function JM(t,e){let n=e.b.z-t.b.z+(e.top-t.top)/2,r=(t.top+e.top)/2;if(Math.abs(n)>=r)return null;let s=e.b.x-t.b.x,o=e.b.y-t.b.y,i=pd(t)+pd(e);if(Math.abs(s)>=i||Math.abs(o)>=i)return null;let a=[t.c,t.s,-t.s,t.c,e.c,e.s,-e.s,e.c],c=null,u=[];for(let d=0;d<8;d+=2){let f=a[d],h=a[d+1],p=s*f+o*h,y=ld(t,f,h)+ld(e,f,h)-Math.abs(p);if(y<=0)return null;let S=p<0?{depth:y,n:[-f,-h,0]}:{depth:y,n:[f,h,0]};u.push(S),(c===null||y<c.depth)&&(c=S)}let l=n<0?[0,0,-1]:kc;return{plane:kc,level:!0,side:c,axes:u,across:{depth:r-Math.abs(n),n:l},d:[s,o,0],half:d=>ld(t,d[0],d[1])+ld(e,d[0],d[1])}}function Dh(t,e,n){let r=t*n[0]+e*n[1],s=t-r*n[0],o=e-r*n[1],i=-r*n[2],a=Math.sqrt(s*s+o*o+i*i);return a<1e-9&&(s=-n[2]*n[0],o=-n[2]*n[1],i=1-n[2]*n[2],a=Math.sqrt(s*s+o*o+i*i)),[s/a,o/a,i/a]}function ZM(t,e){let n=[t.up[0]+e.up[0],t.up[1]+e.up[1],t.up[2]+e.up[2]],r=Math.sqrt(Fe(n,n));if(r<1e-9)return null;let s=[n[0]/r,n[1]/r,n[2]/r],o=t.top/2,i=e.top/2,a=[e.b.x+e.up[0]*i-t.b.x-t.up[0]*o,e.b.y+e.up[1]*i-t.b.y-t.up[1]*o,e.b.z+e.up[2]*i-t.b.z-t.up[2]*o],c=Fe(a,s),u=o+i;if(Math.abs(c)>=u)return null;let l=Dh(t.c,t.s,s),d=Dh(e.c,e.s,s),f=So(s,l),h=So(s,d),p=b=>t.hl*Math.abs(Fe(l,b))+t.hw*Math.abs(Fe(f,b))+(e.hl*Math.abs(Fe(d,b))+e.hw*Math.abs(Fe(h,b))),y=null,S=[];for(let b of[l,f,d,h]){let x=Fe(a,b),R=t.hl*Math.abs(Fe(l,b))+t.hw*Math.abs(Fe(f,b))+(e.hl*Math.abs(Fe(d,b))+e.hw*Math.abs(Fe(h,b)))-Math.abs(x);if(R<=0)return null;let A={depth:R,n:x<0?ft(b):b};S.push(A),(y===null||R<y.depth)&&(y=A)}return{plane:s,level:!1,side:y,axes:S,across:{depth:u-Math.abs(c),n:c<0?ft(s):s},d:a,half:p}}var QM=1e-6;function FS(t){let e=Dh(t.c,t.s,t.up),n=t.top/2;return{c:[t.b.x+t.up[0]*n,t.b.y+t.up[1]*n,t.b.z+t.up[2]*n],axes:[e,So(t.up,e),t.up],half:[t.hl,t.hw,n]}}function eC(t,e,n){let r=FS(t),s=FS(e),o=[s.c[0]-r.c[0],s.c[1]-r.c[1],s.c[2]-r.c[2]],i=(f,h)=>f.half[0]*Math.abs(Fe(f.axes[0],h))+f.half[1]*Math.abs(Fe(f.axes[1],h))+f.half[2]*Math.abs(Fe(f.axes[2],h)),a=f=>i(r,f)+i(s,f),c=[...r.axes,...s.axes];for(let f of r.axes)for(let h of s.axes){let p=So(f,h),y=Math.sqrt(Fe(p,p));y>QM&&c.push([p[0]/y,p[1]/y,p[2]/y])}let u=[];for(let f of c){let h=Fe(o,f),p=a(f)-Math.abs(h);if(p<=0)return null;u.push({depth:p,n:h<0?ft(f):f})}let l=u.reduce((f,h)=>h.depth<f.depth?h:f),d=Fe(o,n);return{plane:n,level:!1,side:l,axes:u,across:{depth:a(n)-Math.abs(d),n:d<0?ft(n):n},d:o,half:a}}function Nh(t,e){let n=pd(t)+pd(e),r=(t.top+e.top)/2,s=Math.sqrt(n*n+r*r)+r;if(Math.abs(e.b.x-t.b.x)>=s||Math.abs(e.b.y-t.b.y)>=s||Math.abs(e.b.z-t.b.z)>=s)return null;if(t.up[2]===1&&e.up[2]===1)return JM(t,e);if(t.up[0]===e.up[0]&&t.up[1]===e.up[1]&&t.up[2]===e.up[2])return ZM(t,e);let o=[t.up[0]+e.up[0],t.up[1]+e.up[1],t.up[2]+e.up[2]],i=Math.sqrt(Fe(o,o));return i<1e-9?null:eC(t,e,[o[0]/i,o[1]/i,o[2]/i])}var hd=(t,e,n)=>-((e.vx-t.vx)*n[0]+(e.vy-t.vy)*n[1]+((e.vz??0)-(t.vz??0))*n[2]);function tC(t,e,n,r){let s=t.across.depth/Math.max(hd(e.b,n.b,t.across.n),r.entrySpeed),i=s<=r.entryWindow&&t.across.depth<=(e.top+n.top)/4||!t.level&&t.across.depth<=r.groundTrace;if(!i)return{across:!1,landed:i};let a=t.side.depth/Math.max(hd(e.b,n.b,t.side.n),r.entrySpeed);return{across:s<a||s===a&&t.across.depth<t.side.depth,landed:i}}function zS(t){let e=[...t.tags??[]],n=t.flags??0;for(let r=0;r<24;r++)Math.floor(n/2**r)%2===1&&e.push(`flag:${r}`);return e}function xo(t,e,n){if(t.pairs.length===0)return t.top;let r=zS(e),s=zS(n),o=i=>r.includes(i.a)&&s.includes(i.b)||r.includes(i.b)&&s.includes(i.a);return t.pairs.find(o)?.top??t.top}function md(t,e,n){let r=Nh(t,e);if(r===null)return nC(t,e,n);let s=tC(r,t,e,n);if(!s.across){let l=Fe(r.d,r.plane)>=0;return{contact:{kind:wo.Side,n:r.side.n,depth:r.side.depth,upperIsB:l},g:r}}let o=r.across.n,i=o===r.plane||Fe(o,r.plane)>0,a=i?t:e,c=i?o:ft(o);return{contact:{kind:s.landed&&Fe(c,a.support)>=n.supportCos?wo.Top:wo.Side,n:o,depth:r.across.depth,upperIsB:i},g:r}}function nC(t,e,n){let r=e.b.z>=t.b.z,s=l=>({...l,b:{...l.b,z:l.b.z-n.groundTrace}}),o=r?Nh(t,s(e)):Nh(s(t),e);if(o===null||!(o.across.depth<o.side.depth))return null;let i=r?o.across.n:ft(o.across.n);if(!(Fe(i,o.plane)>0))return null;let a=r?t:e;if(a.support[2]<n.supportCos||Fe(i,a.support)<n.supportCos)return null;let[c,u]=r?[e.b,t.b]:[t.b,e.b];return-hd(u,c,i)>n.entrySpeed?null:{contact:{kind:wo.Top,n:o.across.n,depth:o.across.depth-n.groundTrace,upperIsB:r},g:o}}function rC(t,e,n,r){return yd(t,e,n)?null:md(qr(t,n,r),qr(e,n,r),n)?.contact??null}function sC(t){let e=t.shape;return e.kind===qn.Hull?Math.sqrt(2*e.radius*e.radius+e.height*e.height):Math.sqrt(e.length*e.length/4+e.width*e.width/4+e.top*e.top)}function yd(t,e,n){let r=2*sC(n)+n.groundTrace+1,s=e.x-t.x,o=e.y-t.y,i=e.z-t.z;return s*s+o*o+i*i>r*r}var qS=t=>e=>{let n=t.maxVelocity;return n===null?e:e<-n?-n:e>n?n:e},Gr=t=>[t.x,t.y,t.z],oC=.7,iC=.5,US=.5;function Ui(t,e,n,r,s,o){let i=Ec(t,e,n,r,Fe(n,o)<-iC?void 0:s),a=i.t,c=i.face;if(c===null||!(a<r))return{d:n,straight:a,slide:null,cos:1,sep:a};let u=[c[0],c[1],c[2]],l=aC(u,n,o);if(l===null)return{d:n,straight:a,slide:null,cos:1,sep:a};let d=Fe(l,n),f=[e[0]+n[0]*a,e[1]+n[1]*a,e[2]+n[2]*a],h=Ec(t,f,l,(r-a)/d,s).t;return{d:n,straight:a,slide:l,cos:d,sep:a+h*d}}function aC(t,e,n){if(Fe(t,n)>=oC){let a=Fe(e,t),c=[e[0]-a*t[0],e[1]-a*t[1],e[2]-a*t[2]],u=Math.hypot(c[0],c[1],c[2]);return u>=US?[c[0]/u,c[1]/u,c[2]/u]:null}let r=So(t,n),s=Math.hypot(r[0],r[1],r[2]),o=s>0?Fe(r,e)/s:0;if(!(Math.abs(o)>=US))return null;let i=o>0?1/s:-1/s;return[r[0]*i,r[1]*i,r[2]*i]}function VS(t,e){let n=t.d;if(t.slide===null||!(e>t.straight))return[n[0]*e,n[1]*e,n[2]*e];let r=(e-t.straight)/t.cos,s=t.slide;return[n[0]*t.straight+s[0]*r,n[1]*t.straight+s[1]*r,n[2]*t.straight+s[2]*r]}function cC(t,e,n=.5){let r=Math.min(e,1-Math.min(t,n));return[Math.min(t,1-r),r]}function uC(t,e,n,r,s,o,i,a=kc,c=kc,u=.5){if(s===null)return[u,1-u];let l=Ui(s,Gr(t),ft(n),r,o,a),d=Ui(s,Gr(e),n,r,i,c);return cC(l.sep/r,d.sep/r,u)}function GS(t,e,n,r){if(r.push!==yo.Mover)return .5;let s=t.vx*n[0]+t.vy*n[1],o=e.vx*n[0]+e.vy*n[1];n[2]!==0&&(s+=(t.vz??0)*n[2],o+=(e.vz??0)*n[2]);let i=s>0?s:0,a=o<0?-o:0;return i+a>0?i/(i+a):.5}function Bh(t,e,n,r,s,o){let[i,a]=uC(t.b,e.b,n,r,o.world,bo(t,s),bo(e,s),t.support,e.support,GS(t.b,e.b,n,s));return o.fixed===void 0?[i,a]:t.b.id===o.fixed?[0,o.world===null?1:Ui(o.world,Gr(e.b),n,r,bo(e,s),e.support).sep/r]:e.b.id===o.fixed?[o.world===null?1:Ui(o.world,Gr(t.b),ft(n),r,bo(t,s),t.support).sep/r,0]:[i,a]}var bo=(t,e)=>BS(t.support,e.supportCos);function lC(t,e,n,r,s,o){let i=r.axes.filter(l=>l.n!==n.n).sort((l,d)=>l.depth-d.depth);for(let l of i){let[d,f]=Bh(t,e,l.n,l.depth,s,o);if(!(d+f<1))return{n:l.n,depth:l.depth,sa:d,sb:f}}let[a,c]=Bh(t,e,n.n,n.depth,s,o),u=1-a-c;return t.b.id===o.fixed?{n:n.n,depth:n.depth,sa:a,sb:c+u}:e.b.id===o.fixed?{n:n.n,depth:n.depth,sa:a+u,sb:c}:{n:n.n,depth:n.depth,sa:a+u/2,sb:c+u/2}}function HS(t,e){t.x+=e[0],t.y+=e[1],e[2]!==0&&(t.z+=e[2])}function dC(t,e,n,r,s,o,i,a){let[c,u]=[t.b,e.b],l=a.world,d=ft(n),f=l===null?{d,straight:r,slide:null,cos:1,sep:r}:Ui(l,Gr(c),d,r,bo(t,i),t.support),h=l===null?{d:n,straight:r,slide:null,cos:1,sep:r}:Ui(l,Gr(u),n,r,bo(e,i),e.support);HS(c,VS(f,r*s)),HS(u,VS(h,r*o))}function fC(t,e,n,r,s,o,i){let a=qS(s),[c,u]=[t.b,e.b],[l,d]=Bh(t,e,n.n,n.depth,s,o),f=l+d<1?lC(t,e,n,r,s,o):null,{depth:h,n:p,sa:y,sb:S}=f??{depth:n.depth,n:n.n,sa:l,sb:d},[b,x,R]=p,A=(u.vx-c.vx)*b+(u.vy-c.vy)*x;R!==0&&(A+=((u.vz??0)-(c.vz??0))*R);let E=A<0&&!i?-(1+s.restitution)*A/2:0,P=GS(c,u,p,s),k=2*E*P,M=2*E*(1-P);return dC(t,e,p,h,y,S,s,o),c.vx=a(c.vx-k*b),c.vy=a(c.vy-k*x),s.stopSpin&&(c.spin=0),u.vx=a(u.vx+M*b),u.vy=a(u.vy+M*x),s.stopSpin&&(u.spin=0),R!==0&&(c.vz=a((c.vz??0)-k*R),u.vz=a((u.vz??0)+M*R)),{j:E,n:p,depth:h}}function YS(t,e){let n=e?t.side.n:ft(t.side.n),r=e?t.d:ft(t.d),s=So(t.plane,n);return[n,ft(n),s,ft(s)].map(i=>({w:i,move:t.half(i)-Fe(r,i)})).map((i,a)=>({way:i,k:a})).sort((i,a)=>i.way.move-a.way.move||i.k-a.k).map(i=>i.way)}var $S=(t,e,n)=>t.half(n)-Fe(e?t.d:ft(t.d),n);function pC(t,e,n,r,s){let o=[];for(let i of n){if(i===t.b||i===e||yd(t.b,i,r)||xo(r,t.b,i).policy===it.Ghost)continue;let a=md(t,qr(i,r,s),r);a!==null&&a.contact.kind===wo.Top&&!a.contact.upperIsB&&o.push(a.g)}return o}function hC(t,e,n){if(n.length===0)return YS(t,e);let r=e?t.side.n:ft(t.side.n),s=So(t.plane,r);return[r,ft(r),s,ft(s)].map(i=>({w:i,move:n.reduce((a,c)=>Math.max(a,$S(c,!1,i)),$S(t,e,i))})).map((i,a)=>({way:i,k:a})).sort((i,a)=>i.way.move-a.way.move||i.k-a.k).map(i=>i.way)}var jS=(t,e,n,r)=>n.move<=0||ud(t,Gr(e.b),n.w,n.move,bo(e,r))>=n.move;function Ih(t,e,n,r){t.vx=r(t.vx+n*e[0]),t.vy=r(t.vy+n*e[1]),e[2]!==0&&(t.vz=r((t.vz??0)+n*e[2]))}function WS(t,e){if(!(e<t.speed))return 0;let n=t.speed-e;return t.step===null?n:Math.min(n,t.step)}function dd(t,e,n,r,s,o,i,a){let[c,u]=[t.b,e.b],l=qS(o),d=YS(n,r),f=hC(n,r,pC(t,u,a,o,i)).find(S=>jS(i.world,t,S,o));if(f!==void 0){let S=(c.vx-u.vx)*f.w[0]+(c.vy-u.vy)*f.w[1]+((c.vz??0)-(u.vz??0))*f.w[2],b=WS(s,S);return Ih(c,f.w,b*s.share,l),s.share!==1&&Ih(u,f.w,-b*(1-s.share),l),{j:b,way:fd.Free,w:f.w}}let h=d.map(S=>({w:ft(S.w),move:S.move})).find(S=>jS(i.world,e,S,o));if(h===void 0)return{j:0,way:fd.Pinned,w:null};let p=(u.vx-c.vx)*h.w[0]+(u.vy-c.vy)*h.w[1]+((u.vz??0)-(c.vz??0))*h.w[2],y=WS(s,p);return Ih(u,h.w,y,l),{j:y,way:fd.LowerYields,w:h.w}}function mC(t,e,n,r,s,o,i,a){let c=r+i.roofSkin;if(!(c>0))return;let u=t.id===a.fixed?0:ud(a.world,Gr(t),n,c);if(u>=c&&s.level){t.z=e.z+o+i.roofSkin;return}if(t.x+=n[0]*u,t.y+=n[1]*u,t.z+=n[2]*u,u>=c)return;let l=e.id===a.fixed?0:ud(a.world,Gr(e),ft(n),c-u);e.x-=n[0]*l,e.y-=n[1]*l,e.z-=n[2]*l}function yC(t,e,n){let r=t.vx*n[0]+t.vy*n[1]+(t.vz??0)*n[2],s=e.vx*n[0]+e.vy*n[1]+(e.vz??0)*n[2];if(r<s){if(n[0]===0&&n[1]===0){t.vz=e.vz??0;return}t.vx+=n[0]*(s-r),t.vy+=n[1]*(s-r),t.vz=(t.vz??0)+n[2]*(s-r)}}function gC(t,e,n){let r=t.vx*e[0]+t.vy*e[1]+(t.vz??0)*e[2];t.vx+=e[0]*(n-r),t.vy+=e[1]*(n-r),t.vz=(t.vz??0)+e[2]*(n-r)}function Lh(t,e,n){let r=t.x-e.x,s=t.y-e.y,o=n.shape;if(o.kind===qn.Hull)return Math.max(Math.abs(r),Math.abs(s))/o.radius;let[i,a]=Ut(e.yaw);return Math.max(Math.abs(r*a+s*i)/(o.length/2),Math.abs(s*a-r*i)/(o.width/2))}function bC(t,e,n){if(n)return 0;let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s);return o>0?-(e.vx*r+e.vy*s)/o:0}var wC=100,As={Stand:"stand",Release:"release",Slide:"slide"};function KS(t,e,n,r){if(n.center===null)return As.Stand;let s=Lh(t,e,r);return s<=n.center?As.Stand:(e.vz??0)-(t.vz??0)>wC?As.Slide:bC(t,e,n.ride)>=(n.slide.step??n.slide.speed)/2?As.Release:s>1?As.Slide:As.Stand}var XS=(t,e,n,r)=>n.policy===it.Stand&&KS(t,e,n,r)===As.Stand;function SC(t,e,n,r,s,o,i,a){let[c,u]=n.upperIsB?[e,t]:[t,e],l=c.b,d=u.b,f=n.upperIsB?n.n:ft(n.n),h=hd(d,l,f),p=s.policy===it.Stand&&KS(l,d,s,o)===As.Slide;return mC(l,d,f,n.depth,r,u.top,o,i),yC(l,d,f),u.support[2]<o.supportCos?dd(c,u,r,n.upperIsB,o.offWall,o,i,a):s.policy===it.Stand?p?dd(c,u,r,n.upperIsB,s.slide,o,i,a):Oh:s.policy===it.Slide?dd(c,u,r,n.upperIsB,s,o,i,a):s.policy===it.Bounce&&h>=s.stompMin?(gC(l,f,s.bounceSpeed+(l.jump?s.jumpBoost:0)),i.onContact?.(l,d,KM.Stomp),Oh):s.policy===it.Bounce?dd(c,u,r,n.upperIsB,s.slide,o,i,a):Oh}function JS(t,e,n,r,s=!1,o=[]){let i=xo(n,t,e);if(i.policy===it.Ghost||yd(t,e,n))return null;let a=qr(t,n,r),c=qr(e,n,r),u=md(a,c,n);return u===null?null:ZS(a,c,u,i,n,r,s,o)}function ZS(t,e,n,r,s,o,i,a){let{contact:c,g:u}=n;return c.kind===wo.Side?{...c,...fC(t,e,c,u,s,o,i),way:null,w:null}:{...c,...SC(t,e,c,u,r,s,o,a)}}function xC(t,e,n,r,s,o,i){let a=o.cooling?o.cooling(t,e):!1,c=n===0?o.first?.(t,e,a):void 0;return c===void 0?JS(t,e,r,s,a,i):c}var QS=(t,e)=>t!==null&&(t.depth>e.slop||t.kind===wo.Top&&t.depth>0),_C=t=>({moves:new Int32Array(t),still:new Int32Array(t*t).fill(-1)});function RC(t,e,n,r,s){if(yd(t,e,n))return null;let o=xo(n,t,e);if(o.policy===it.Ghost)return null;let i=qr(t,n,r),a=qr(e,n,r),c=md(i,a,n);return c===null||!QS(c.contact,n)?null:ZS(i,a,c,o,n,r,!1,s)}function EC(t,e,n,r,s,o,i){let a=!1,c=t.length;for(let u=0;u<c;u++)for(let l=u+1;l<c;l++){let d=t[u],f=t[l],h=u*c+l;if(i!==null&&e>0&&i.still[h]===i.moves[u]+i.moves[l])continue;let p;if(i!==null&&e>0)p=RC(d,f,n,r,t);else{if(e>0&&!QS(rC(d,f,n,r),n))continue;p=xC(d,f,e,n,r,s,t)}if(p===null){i!==null&&(i.still[h]=i.moves[u]+i.moves[l]);continue}i!==null&&(i.moves[u]=i.moves[u]+1,i.moves[l]=i.moves[l]+1),a=!0,p.way===fd.Pinned&&(o.pinned+=1),s.onPair?.(d,f,p)}return a}function kC(t,e,n,r={}){let s={passes:0,pushed:new Map,walls:new Map,pinned:0};n={...n,supports:new Map};let o=r.first===void 0&&r.onPair===void 0&&r.cooling===void 0?_C(t.length):null;for(let i=0;i<e.passes&&EC(t,i,e,n,r,s,o);i++)s.passes+=1,n.world!==null&&t.forEach((a,c)=>{let u=d=>{d[2]<e.supportCos&&d[3]>(s.walls.get(a.id)??0)&&s.walls.set(a.id,d[3])},l=LS(n.world,a,u);l>(s.pushed.get(a.id)??0)&&s.pushed.set(a.id,l),o!==null&&l>0&&(o.moves[c]=o.moves[c]+1)});return s}var Fh=(t,e)=>(n,r)=>{JS(n,r,t,e)},ex=(t,e)=>n=>{kC(n,t,e)};function tx(t){return t.top.policy===it.Stand||t.pairs.some(e=>e.top.policy===it.Stand)}function AC(t,e,n){let r=t.x+t.vx*n,s=t.y+t.vy*n,o=t.z+(t.vz??0)*n,i=e.shape,a=e.groundTrace;if(i.kind===qn.Hull){let l=i.radius;return{kind:"box",min:[r-l,s-l,o+i.height-a],max:[r+l,s+l,o+i.height]}}let[c,u]=Ut(t.yaw);return{kind:"obox",c:[r,s,o+i.top-a/2],half:[i.length/2,i.width/2,a/2],sin:c,cos:u}}var nx=t=>t.shape.kind===qn.Hull?t.shape.height:t.shape.top,rx=2;function PC(t,e,n,r){let s=xo(n,t,e);if(s.policy!==it.Stand)return!1;let o=nx(n);return t.z<e.z+o-n.groundTrace||t.z>e.z+2*o||!(Lh(t,e,n)<rx)||qr(e,n,r).support[2]<n.supportCos?!1:XS(t,e,s,n)}var TC=t=>rx*(t.shape.kind===qn.Hull?t.shape.radius:Math.hypot(t.shape.length,t.shape.width)/2);function vC(t,e,n=0){let r=nx(e),s=TC(e);for(let o of t)for(let i of t){if(i===o)continue;let a=i.z+(i.vz??0)*n;if(o.z<a+r-e.groundTrace||o.z>a+2*r)continue;let c=(Math.abs(i.vx)+Math.abs(i.vy))*n;if(Math.abs(o.x-i.x)<s+c&&Math.abs(o.y-i.y)<s+c)return!0}return!1}function Ac(t,e,n,r){return vC(t,e)?t.map(s=>{let o=[],i=[];for(let a of t)a===s||!PC(s,a,e,n)||(o.push(AC(a,e,r)),i.push(a.id));return{solids:o,lowers:i}}):t.map(()=>({solids:[],lowers:[]}))}function zh(t,e,n){let[r,s,o]=[e[0],e[1],e[2]],[i,a,c]=[n[0],n[1],n[2]];return t.find(u=>Math.abs(i-u.x)<=r&&Math.abs(a-u.y)<=s&&c>u.z+2*o&&c<=u.z+4*o)}function sx(t,e,n,r){let s=[];for(let o of n){let[i,a]=[o.p[0],o.p[1]],c=zh(t,e,o.p);if(c===void 0)continue;let u=i-c.x,l=a-c.y,d=Math.hypot(u,l),[f,h]=d>0?[u/d,l/d]:[1,0],[p,y,S]=[o.v[0],o.v[1],o.v[2]],b=(p-c.vx)*f+(y-c.vy)*h;if(!(b<r.speed))continue;let x=Math.min(r.step,r.speed-b);s.push({key:o.key,v:[p+f*x,y+h*x,S]})}return s}var _o={Box:"box",Disc:"disc"},ox={PingPong:"pingpong",Loop:"loop"},ix={Linear:"linear",Smooth:"smooth"},ax={All:"all",None:"none"},cx=Object.freeze({platforms:Object.freeze([]),bodies:!1});var NU=2**24;var BU=2*Math.PI;var dx=2*Math.PI,Nt=Math.fround,fx=(t,e)=>(t%e+e)%e;function MC(t,e,n,r,s){if(s===ix.Linear)return[Nt(t[0]+(e[0]-t[0])*n/r),Nt(t[1]+(e[1]-t[1])*n/r),Nt(t[2]+(e[2]-t[2])*n/r)];let o=n/r,i=o*o*(3-2*o);return[Nt(t[0]+(e[0]-t[0])*i),Nt(t[1]+(e[1]-t[1])*i),Nt(t[2]+(e[2]-t[2])*i)]}function CC(t,e){let n=t.legs.length,r=t.mode===ox.Loop,s=r?n:2*n,o=e;for(let i=0;i<s;i++){let a=i,c=i,u=i+1;r?u=(i+1)%n:i>=n&&(a=2*n-1-i,c=a+1,u=a);let l=t.legs[a],d=t.points[u];if(o<l)return MC(t.points[c],d,o,l,t.ease);o-=l;let f=t.waits[u];if(o<f)return d;o-=f}return t.points[0]}function OC(t,e,n,r){return t.called?r===void 0||n<r||n-r>=e.period?0:n-r:fx(n+e.phase,e.period)}function Ps(t,e,n){let r=t.path===null?t.at:CC(t.path,OC(t,t.path,e,n)),s=t.spin;return s===null?{c:r,yaw:0}:{c:r,yaw:Nt(s.dir*(dx*fx(e+s.phase,s.period)/s.period))}}function ux(t,e,n){return t.platforms.map(r=>Ps(r,e,n?.get(r.id)))}var Uh=t=>t.spin===null?0:t.spin.dir*dx/t.spin.period;function bd(t,e,n,r,s){let o=Ps(t,n,s),i=Ps(t,n+1,s),a=Uh(t),c,u;if(a===0)c=e.x+(i.c[0]-o.c[0]),u=e.y+(i.c[1]-o.c[1]);else{let[d,f]=Ut(a),h=e.x-o.c[0],p=e.y-o.c[1];c=i.c[0]+(f*h-d*p),u=i.c[1]+(d*h+f*p)}let l=e.z+(i.c[2]-o.c[2]);if(t.surface!==null){let[d,f]=t.surface;if(i.yaw===0)c+=d/r,u+=f/r;else{let[h,p]=Ut(i.yaw);c+=(p*d-h*f)/r,u+=(h*d+p*f)/r}}return{x:c,y:u,z:l,yaw:e.yaw+a,v:[(c-e.x)*r,(u-e.y)*r,(l-e.z)*r]}}function gd(t,e){return t.platforms.map((n,r)=>{let{c:s,yaw:o}=e[r],i=n.shape;if(i.kind===_o.Disc)return{kind:"disc",c:s,radius:i.radius,half:i.half};let a=i.half;if(n.spin===null)return{kind:"box",min:[s[0]-a[0],s[1]-a[1],s[2]-a[2]],max:[s[0]+a[0],s[1]+a[1],s[2]+a[2]]};let[c,u]=Ut(o);return{kind:"obox",c:s,half:a,sin:c,cos:u}})}var px=4;function wd(t,e,n){return{now:gd(t,ux(t,e,n)),next:gd(t,ux(t,e+1,n))}}var hx=(t,e)=>t?.get(e.id);function lx(t,e){t.x=Nt(e.x),t.y=Nt(e.y),t.z=Nt(e.z)}function IC(t,e,n,r,s){let o=[],i=[],a=s===void 0?null:Ac(e,s.policy,s.env,0);return e.forEach((c,u)=>{let l=a?.[u];if(n.length===0&&(l===void 0||l.solids.length===0)){o.push(-1),i.push(null);return}let d=l===void 0||l.solids.length===0?r.support(c,n):r.support(c,[...n,...l.solids]),f=d>=t.platforms.length&&l!==void 0?e.find(p=>p.id===l.lowers[d-t.platforms.length])??null:null,h=s!==void 0&&f!==null?xo(s.policy,c,f):null;o.push(d<t.platforms.length?d:-1),i.push(f!==null&&h?.policy==="stand"&&h.ride?f.id:null)}),{bases:o,on:i}}function DC(t,e,n,r,s,o,i){let a=e.map((l,d)=>{let f=n[d];if(f<0)return null;let h=t.platforms[f];return bd(h,l,s,o,hx(i,h))}),c=new Map(e.map((l,d)=>[l.id,d])),u=(l,d)=>{let f=a[l];if(f!=null)return[f.x-e[l].x,f.y-e[l].y,f.z-e[l].z];let h=r[l]===null||r[l]===void 0?void 0:c.get(r[l]);return h===void 0||d>=px?[0,0,0]:u(h,d+1)};return e.map((l,d)=>{if(a[d]!==null)return a[d];if(r[d]===null)return null;let f=u(d,0);return{x:l.x+f[0],y:l.y+f[1],z:l.z+f[2],yaw:l.yaw,v:[f[0]*o,f[1]*o,f[2]*o]}})}function mx(t,e,n,r,s,o,i,a=wd(t,n,s),c){let{now:u,next:l}=a,d=e.map(b=>({...b})),{bases:f,on:h}=IC(t,d,u,o,c),p=DC(t,d,f,h,n,r,s),y=[],S=[];return e.forEach((b,x)=>{let R=f[x],A=p[x]??null;A!==null&&(lx(b,A),i&&R>=0&&(b.yaw=Nt(A.yaw))),y.push(A===null?null:A.v),t.platforms.forEach((E,P)=>{if(P===R||!o.inside(b,l,P))return;let k=bd(E,b,n,r,hx(s,E)),M=o.pushOut({...b,x:k.x,y:k.y,z:k.z},l);lx(b,M),M.inside&&S.push({seat:b.id,lift:E.id})})}),{bases:f,on:h,v:y,crushed:S,from:e.map(b=>[b.x,b.y,b.z])}}function yx(t,e,n){if(e.on.every(c=>c===null))return e;let r=new Map(t.map((c,u)=>[c.id,u])),s=t.map((c,u)=>{let l=e.from[u];return[c.x-l[0],c.y-l[1]]}),o=(c,u)=>{let l=e.on[c],d=l==null?void 0:r.get(l);if(d===void 0||u>=px)return[0,0];let f=s[d],h=o(d,u+1);return[f[0]+h[0],f[1]+h[1]]},i=t.map((c,u)=>o(u,0)),a=e.v.map((c,u)=>{let l=i[u];return c===null||e.on[u]===null?c:[c[0]+l[0]*n,c[1]+l[1]*n,c[2]]});return t.forEach((c,u)=>{let l=i[u];e.on[u]!==null&&(c.x=Nt(c.x+l[0]),c.y=Nt(c.y+l[1]))}),{...e,v:a}}function NC(t,e,n,r,s,o){let i=Ac(t,o.policy,o.env,0)[e];if(i===void 0||i.solids.length===0)return!1;let a=s.support(t[e],[...r,...i.solids]);return a>=r.length&&i.lowers[a-r.length]===n}function gx(t,e,n,r,s,o,i=wd(t,r,s).next,a){if(n.v.every(u=>u===null))return;let c=e.map(u=>({...u}));e.forEach((u,l)=>{let d=n.bases[l]??-1,f=n.v[l],h=n.on[l]??null;if(f!=null){if(h!==null&&a!==void 0){if(NC(c,l,h,i,o,a))return}else if(d<0||t.platforms[d].impart!==ax.All||o.support(u,i)===d)return;u.vx=Nt(u.vx+f[0]),u.vy=Nt(u.vy+f[1]),u.vz=Nt(u.vz+f[2])}})}var Pc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function BC(t){return!Pc(t)||!Array.isArray(t.platforms)||typeof t.bodies!="boolean"?!1:t.platforms.every(e=>Pc(e)&&typeof e.id=="string"&&Pc(e.shape)&&Array.isArray(e.at)&&typeof e.called=="boolean")}function xx(t,e,n,r){if(!t)return null;let s;try{s=JSON.parse(t)}catch{return null}if(!Pc(s)||s.name!==wr.FIRSTPERSON&&s.name!==wr.VEHICLE)return null;let o=BC(s.lifts)?s.lifts:null;if(o===null&&n===void 0)return null;let i=Di(s.name,s.params);return{policy:o??cx,ops:Jw(s.name,i,e),vehicle:s.name===wr.VEHICLE,heads:n,tickHz:r}}function _x(t){if(!t)return;let e;try{e=JSON.parse(t)}catch{return}if(!Pc(e))return;let n=new Map;for(let[r,s]of Object.entries(e))typeof s=="number"&&Number.isInteger(s)&&n.set(r,s);return n}var LC=128,Vi=class{constructor(){m(this,"kept",new Map);m(this,"startsText","")}at(e,n,r){let s=r===void 0?"":JSON.stringify([...r]);s!==this.startsText&&(this.kept.clear(),this.startsText=s);let o=this.kept.get(n);if(o!==void 0)return o;let i=wd(e,n,r),a={solids:i,next:gc(i.next)};return this.kept.size>=LC&&this.kept.delete(this.kept.keys().next().value),this.kept.set(n,a),a}};function vc(t,e,n,r,s,o){let{solids:i,next:a}=o.at(t.policy,n,r),c=mx(t.policy,e,n,t.tickHz,r,t.ops,t.vehicle,i,t.heads),u=new Map;return t.heads!==void 0&&Ac(e,t.heads.policy,t.heads.env,s).forEach((d,f)=>{d.solids.length>0&&u.set(e[f].id,gc([...i.next,...d.solids]))}),{tick:n,solids:i,report:c,seats:e,posed:u,next:a}}function Rx(t,e){e.report=yx(e.seats,e.report,t.tickHz)}function Ex(t,e,n,r){let s=e.report.v;e.report={...e.report,v:s.map((o,i)=>i!==n||o===null?o:[o[0]+r[0]*t.tickHz,o[1]+r[1]*t.tickHz,o[2]])}}var Mc=(t,e)=>t.posed.get(e)??t.next;function Cc(t,e,n){gx(t.policy,e.seats,e.report,e.tick,n,t.ops,e.solids.next,t.heads)}function FC(t,e,n){return t.platforms.map((r,s)=>Tc(t,s,e,n))}function Tc(t,e,n,r){let s=t.platforms[e];if(s===void 0)return{c:[0,0,0],yaw:0};let o=Math.floor(n),i=Ps(s,o,r?.get(s.id)),a=Ps(s,o+1,r?.get(s.id)),c=s.spin===null?0:s.spin.dir*2*Math.PI/s.spin.period,u=n-o;return{c:[i.c[0]+(a.c[0]-i.c[0])*u,i.c[1]+(a.c[1]-i.c[1])*u,i.c[2]+(a.c[2]-i.c[2])*u],yaw:i.yaw+c*u}}function Oc(t,e,n,r){return t.policy.platforms.length===0?-1:t.ops.support({x:e.x,y:e.y,z:e.z,vz:0,duck:e.duck??0},gd(t.policy,FC(t.policy,n,r)))}function Vh(t,e,n,r,s,o){let i=Tc(t,e,r,o),a=Tc(t,e,s,o),c=a.yaw-i.yaw,[u,l]=[Math.sin(c),Math.cos(c)],d=n.x-i.c[0],f=n.y-i.c[1];return{x:a.c[0]+l*d-u*f,y:a.c[1]+u*d+l*f,z:n.z+a.c[2]-i.c[2],yaw:n.yaw+c}}function kx(t,e,n,r){let s=t.platforms.findIndex(i=>i.id===e);if(s<0)return;let o=Tc(t,s,n,r);return{x:o.c[0],y:o.c[1],z:o.c[2],yaw:o.yaw}}function Hh(t,e,n,r){let s=t.platforms[e];if(s===void 0)return 0;let o=s.shape.kind===_o.Box?s.shape.half[2]:s.shape.half;return Tc(t,e,n,r).c[2]+o}var bx=["x","y","z"],wx=["vx","vy","vz"];function Ax(t,e,n,r,s,o,i){let a={...t,heads:void 0},c={id:"",x:s.x??0,y:s.y??0,z:s.z??0,vx:s.vx??0,vy:s.vy??0,vz:s.vz??0,yaw:s.yaw??0,duck:s.duck??0,flags:0},u=vc(a,[c],o,e,i,n);for(let l of bx)s[l]=c[l];t.vehicle&&(s.yaw=c.yaw),r(s,Mc(u,c.id));for(let l of[...bx,...wx])c[l]=s[l]??0;Cc(a,u,e);for(let l of wx)s[l]=c[l]}var Ic=t=>`lift.${t}`,Sx=16;function zC(t){let e=t.surface===null?{}:{friction:0};if(t.shape.kind===_o.Box)return{key:"lift",shape:{kind:"box",half:[t.shape.half[0],t.shape.half[1],t.shape.half[2]]},...e};let{radius:n,half:r}=t.shape,s=[];for(let o=0;o<Sx;o++){let[i,a]=Ut(2*Math.PI*o/Sx);s.push([Math.fround(n*a),Math.fround(n*i),-r],[Math.fround(n*a),Math.fround(n*i),r])}return{key:"lift",shape:{kind:"hull",points:s},...e}}function Sd(t,e,n){let r=Ps(t,e,n?.get(t.id)),[s,o]=Ut(r.yaw/2);return{p:[r.c[0],r.c[1],r.c[2]],q:[0,0,Math.fround(s),Math.fround(o)]}}function Px(t,e,n){return{key:Ic(t.id),type:"kinematic",pose:Sd(t,e,n),colliders:[zC(t)]}}var UC=20;function VC(t,e,n,r){let s=n-e.c[0],o=r-e.c[1],[i,a]=e.yaw===0?[0,1]:Ut(e.yaw),c=a*s+i*o,u=a*o-i*s;return t.shape.kind===_o.Disc?c*c+u*u<=t.shape.radius*t.shape.radius:Math.abs(c)<=t.shape.half[0]&&Math.abs(u)<=t.shape.half[1]}var HC=(t,e)=>e+(t.shape.kind===_o.Disc?t.shape.half:t.shape.half[2]);function $h(t,e,n,r){let s=t.platforms.filter(i=>i.surface!==null),o=s.map(i=>Ps(i,e,n?.get(i.id)));return i=>{let[a,c,u]=[i[0],i[1],i[2]];return s.find((l,d)=>{let f=o[d],h=u-HC(l,f.c[2]);return h>0&&h<=r&&VC(l,f,a,c)})}}function Tx(t,e,n,r,s,o){let i=$h(t,e,n,o),a=Math.min(1,UC/r),c=[];for(let u of s){let[l,d,f]=[u.p[0],u.p[1],u.p[2]],h=i(u.p);if(h===void 0)continue;let p=bd(h,{x:l,y:d,z:f,yaw:0},e,r,n?.get(h.id)),[y,S,b]=[u.v[0],u.v[1],u.v[2]],x=p.v[0]-y,R=p.v[1]-S;x===0&&R===0||c.push({key:u.key,v:[y+x*a,S+R*a,b]})}return c}var Ro=15,$C=65535;var jC=Object.values(Zt),vx=(t,e,n)=>typeof t=="number"&&Number.isFinite(t)&&t>=e&&t<=n,Yr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Mx=t=>typeof t=="number"&&Number.isFinite(t)&&t>0;function Nc(t){if(t===void 0||t==="")return null;let e;try{e=JSON.parse(t)}catch{return null}if(!Yr(e)||!Yr(e.world))return null;let{keyframeTicks:n,maxLinear:r,maxAngular:s}=e;if(!(typeof n=="number"&&Number.isInteger(n)&&n>=1)||!Mx(r)||!Mx(s))return null;let i=e.presetBody,a=Yr(i)&&Array.isArray(i.half)&&i.half.length===3?{half:i.half,events:i.events===!0}:null,c=jC.includes(e.remotePredict)?e.remotePredict:xr.DEFAULT_REMOTE_PREDICT,u=e.remoteDecayMs,l=vx(u,0,xr.MAX_REMOTE_DECAY_MS)?u:xr.DEFAULT_REMOTE_DECAY_MS,d=e.leadMs,f=vx(d,xr.MIN_LEAD_MS,xr.MAX_LEAD_MS)?d:xr.DEFAULT_LEAD_MS;return{world:e.world,keyframeTicks:n,maxLinear:r,maxAngular:s,presetBody:a,remotePredict:c,remoteDecayMs:l,leadMs:f}}function jh(t){return Math.fround(Math.fround(t.dt)/t.substeps)}function WC(t,e){let n=Math.floor(t/e+.5);return Number.isNaN(n)||n<0?0:Math.min(n,$C)}var Dc=id.ORIENTATION,Ts=id.VELOCITY,Hi=t=>t===0?0:t;function Ix(t,e,n){e[n]=Hi(t.x),e[n+1]=Hi(t.y),e[n+2]=Hi(t.z),e[n+3]=Qt(t.qx,Dc),e[n+4]=Qt(t.qy,Dc),e[n+5]=Qt(t.qz,Dc),e[n+6]=Qt(t.qw,Dc),e[n+7]=Qt(t.lvx,Ts),e[n+8]=Qt(t.lvy,Ts),e[n+9]=Qt(t.lvz,Ts),e[n+10]=Qt(t.avx,Ts),e[n+11]=Qt(t.avy,Ts),e[n+12]=Qt(t.avz,Ts),e[n+13]=t.sleep?1:0,e[n+14]=t.rest}function Wh(t,e,n,r,s,o){s[o]=Hi(t[e]),s[o+1]=Hi(t[e+1]),s[o+2]=Hi(t[e+2]);for(let i=3;i<7;i++)s[o+i]=Qt(t[e+i],Dc);for(let i=7;i<10;i++)s[o+i]=Qt(t[e+i]/n,Ts);for(let i=10;i<13;i++)s[o+i]=Qt(t[e+i],Ts);s[o+13]=t[e+13]===1?1:0,s[o+14]=WC(t[e+14],r)}function Dx(t,e,n){let r=[...Array.from(t.p),...Array.from(t.q),...Array.from(t.v),...Array.from(t.w),t.sleeping?1:0,t.rest??0],s=[];return Wh(r,0,e,n,s,0),s}function Cx(t,e){let n=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(!(n>e))return null;let r=e/n;return[t[0]*r,t[1]*r,t[2]*r]}function Nx(t,e,n,r=gS,s=bS){let o=Cx(t,r*n),i=Cx(e,s);return o===null&&i===null?null:{linvel:o??[t[0],t[1],t[2]],angvel:i??[e[0],e[1],e[2]]}}var tV=16*1024;function Bx(t,e){let n;try{n=JSON.parse(t)}catch{return null}if(!Yr(n)||!Array.isArray(n.colliders))return null;for(let r of n.colliders){if(!Yr(r)||!Yr(r.shape))return null;let s=r.shape.ref;if(s===void 0)continue;let o=typeof s=="string"?e(s):void 0;if(o===void 0)return null;try{r.shape=JSON.parse(o)}catch{return null}}return n}var Lx=.5,xd=t=>{if(!Array.isArray(t)||t.length!==3)return 0;let[e,n,r]=t;return Math.sqrt(e*e+n*n+r*r)},Ox=t=>Array.isArray(t)?t.reduce((e,n)=>Math.max(e,xd(n)),0):0;function qC(t){switch(t.kind){case"box":return xd(t.half);case"sphere":return typeof t.radius=="number"?t.radius:0;case"capsule":return(typeof t.halfHeight=="number"?t.halfHeight:0)+(typeof t.radius=="number"?t.radius:0);case"hull":return Ox(t.points);case"trimesh":return Ox(t.vertices);case"heightfield":return xd(t.size);default:return 0}}function Bc(t){let e=Array.isArray(t.colliders)?t.colliders:[],n=0;for(let r of e){if(!Yr(r)||!Yr(r.shape))continue;let s=Yr(r.offset)?xd(r.offset.p):0;n=Math.max(n,s+qC(r.shape))}return n}function Fx(t,e,n){let r=new Map,s=u=>{let l=u;for(;r.get(l)!==l;)l=r.get(l);let d=u;for(;d!==l;){let f=r.get(d);r.set(d,l),d=f}return l},o=(u,l)=>{let d=s(u),f=s(l);d!==f&&(d<f?r.set(f,d):r.set(d,f))};for(let u of t)r.set(u.key,u.key);let i=[...t].sort((u,l)=>u.x-l.x||(u.key<l.key?-1:1)),a=i.reduce((u,l)=>Math.max(u,l.radius),0);for(let u=0;u<i.length;u++){let l=i[u];for(let d=u+1;d<i.length;d++){let f=i[d];if(f.x-l.x>l.radius+a+n)break;let h=f.x-l.x,p=f.y-l.y,y=f.z-l.z,S=l.radius+f.radius+n;h*h+p*p+y*y<=S*S&&o(l.key,f.key)}}for(let[u,l]of e)r.has(u)&&r.has(l)&&o(u,l);let c=new Map;for(let u of t)c.set(u.key,s(u.key));return c}function GC(t,e,n){if(n<=0)return t<=1?1:0;let r=1-(t-1)*(1e3/e)/n;return r<=0?0:r>=1?1:r}function Rd(t,e,n,r){let s=GC(e,n,r);return{...t,moveX:t.moveX*s,moveY:t.moveY*s,moveZ:t.moveZ*s}}var Rt={TAU_SMALL_MS:300,TAU_LARGE_MS:100,SMALL_METRES:.25,LARGE_METRES:1,SNAP_PLAYER_METRES:2,SNAP_OTHER_METRES:6,PLAYER_KINDS:Object.freeze(["player","vehicle"]),SEAT_TAU_MS:70,SEAT_CONTACT_TAU_MS:100,SEAT_SNAP_METRES:6,SEAT_HOLD_MS:120,SEAT_MOVING_UNITS_PER_MS:.2,SEAT_CLOCK_TAU_MS:100,SEAT_CLOCK_SNAP_INPUTS:1.5};function YC(t,e){let n=Math.max(t,0)/e;return(1+n)*Math.exp(-n)}function Ed(t,e,n,r){let s=Math.max(n,0),o=r/2,i=Math.exp(-s/o),a=e+t/o;return[(t+a*s)*i,(e-a*s/o)*i]}function $i(t){let{TAU_SMALL_MS:e,TAU_LARGE_MS:n,SMALL_METRES:r,LARGE_METRES:s}=Rt;return t<=r?e:t>=s?n:e+(t-r)/(s-r)*(n-e)}var _d=class{constructor(){m(this,"last",null);m(this,"offset",null)}draw(e,n,r,s,o,i){let a=this.last;a===null||a.epoch!==r?this.offset=null:a.predicted!==n&&this.startFrom(a,e,s,o,i);let c=this.apply(e,s);return this.last={p:c.p,q:c.q,predicted:n,epoch:r},c}startFrom(e,n,r,s,o){let i=[e.p[0]-n.p[0],e.p[1]-n.p[1],e.p[2]-n.p[2]],a=Math.hypot(i[0],i[1],i[2])/o;if(a>s){this.offset=null;return}let c=jn(e.q,[-n.q[0],-n.q[1],-n.q[2],n.q[3]]),u=c[3]<0?[-c[0],-c[1],-c[2],-c[3]]:c;this.offset={dp:i,dq:u,since:r,tau:$i(a)}}apply(e,n){let r=this.offset;if(r===null)return{p:[e.p[0],e.p[1],e.p[2]],q:[e.q[0],e.q[1],e.q[2],e.q[3]]};let s=YC(n-r.since,r.tau);return{p:[e.p[0]+r.dp[0]*s,e.p[1]+r.dp[1]*s,e.p[2]+r.dp[2]*s],q:jn(Fi(r.dq,s),e.q)}}};function kd(t){return typeof t=="string"&&Rt.PLAYER_KINDS.includes(t)?Rt.SNAP_PLAYER_METRES:Rt.SNAP_OTHER_METRES}function $x(t,e,n,r){let s=(n-r.tickOrigin)*r.tickHz/1e3,o=Math.floor(s),i=t(e,o),a=t(e,o+1);if(i===null||a===null)return null;let c=s-o;return{p:[i.p[0]+(a.p[0]-i.p[0])*c,i.p[1]+(a.p[1]-i.p[1])*c,i.p[2]+(a.p[2]-i.p[2])*c],q:$r([...i.q])}}var KC=.1,XC=30,Pd={desktop:4,mobile:5};function jx(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:e}var Xh=Object.freeze([128,64,32]),qh=60,JC=20,ZC=2,zx=.5,QC=500,eO=4;function tO(t,e){for(let n=t+1;n<Xh.length;n++)if(Xh[n]<e)return n;return null}function Ux(t,e){if(t.length===0)return 0;let n=[...t].sort((r,s)=>r-s);return n[Math.min(n.length-1,Math.floor(e*n.length))]}var Vx=500,nO=.02,rO=200,We={ON:"on",OFF:"off",LOADING:"loading",UNAVAILABLE:"unavailable",MISMATCH:"mismatch",SELF_TEST:"self_test",DIVERGED:"diverged",CPU:"cpu"},sO=600;function Hx(t,e){return[Ed(t.dp[0],t.dv[0],e,t.tau),Ed(t.dp[1],t.dv[1],e,t.tau),Ed(t.dp[2],t.dv[2],e,t.tau)]}var Lc=[0,0,0,1],oO=[32767,32767,32767,65534,32767,32767,32767,32767,32767,32767,0,0],iO=[32767,32767,32767,32767,32767,32767,0,0],aO=t=>Math.floor((t+1)/2*65534+.5),ji=[0,0,0],Wi=(t,e)=>t<e?-1:t>e?1:0,cO=(t,e)=>{for(let n=0;n<Ro;n++)if(!Object.is(t[n],e[n]))return!1;return!0},Ad=class{constructor(e,n){m(this,"status",We.LOADING);m(this,"core");m(this,"desc");m(this,"tickHz");m(this,"innerDt");m(this,"lengthUnit");m(this,"leadMax");m(this,"budgetMs");m(this,"clock");m(this,"remoteStep");m(this,"hashesKept");m(this,"world",null);m(this,"base",null);m(this,"seq",0);m(this,"simulated",new Map);m(this,"seats",new Map);m(this,"kinematic",new Map);m(this,"joints",new Map);m(this,"ring",new Map);m(this,"pure",new Set);m(this,"drawn",new Map);m(this,"kinds",new Map);m(this,"ruledClock",null);m(this,"ownPose",()=>{});m(this,"ownVelocity",()=>{});m(this,"bodyRule");m(this,"headSlide");m(this,"propStates",null);m(this,"propStale",!1);m(this,"kinematicRule");m(this,"lifts");m(this,"liftBodies",null);m(this,"seatRule");m(this,"seatPose");m(this,"contactPass");m(this,"posedBySeats",!1);m(this,"remoteBodies",new Map);m(this,"setSize",0);m(this,"costs",[]);m(this,"probedAt",Number.NEGATIVE_INFINITY);m(this,"calmProbes",0);m(this,"chosenCount",0);m(this,"fallbacks",0);m(this,"recoveries",0);m(this,"steppedAt",0);m(this,"canary",[]);m(this,"epochs",new Map);m(this,"hashes",[]);m(this,"chosenKeys",new Set);this.core=e,this.desc=n.desc,this.tickHz=n.tickHz,this.innerDt=jh(n.desc.world),this.lengthUnit=Math.fround(n.desc.world.lengthUnit);let r=n.leadMs??n.desc.leadMs;this.leadMax=Math.ceil(r*n.tickHz/1e3)+n.desc.keyframeTicks-1;let s=n.desc.remotePredict===Zt.INPUT_DECAY||n.desc.remotePredict===Zt.HOLD;this.remoteStep=s?n.remoteStep:void 0,this.seatPose=n.seatPose,this.contactPass=n.contactPass,this.budgetMs=n.budgetMs??Pd.desktop,this.clock=n.clock??(()=>performance.now()),this.hashesKept=n.hashesKept??sO,this.bodyRule=n.bodyRule,this.headSlide=n.headSlide??(()=>null),this.kinematicRule=n.kinematicRule,this.lifts=n.lifts??(()=>null),this.seatRule=n.seatRule;let o=e.World.create(n.desc.world);if(!o.ok){this.status=We.MISMATCH;return}let i=o.world,a=n.staticWorld;if(!(a==null||a.boxes.length===0&&a.ramps.length===0)&&!i.addStaticWorld(a).ok){i.free(),this.status=We.MISMATCH;return}if(i.physicsHash()!==n.physicsHash){i.free(),this.status=We.MISMATCH;return}this.world=i}get predicting(){return this.status===We.ON||this.status===We.LOADING}get stopped(){return this.world===null}draws(e){return this.status===We.ON&&(this.drawn.has(e)||this.ruledElsewhere(e))}ruledElsewhere(e){return this.base!==null&&!this.drawn.has(e)&&this.ruled(e)}stateHash(){return this.world?.stateHash()??""}stop(e){this.status=e,this.world?.free(),this.world=null,this.drawn.clear()}adopt(e,n,r,s,o=()=>{}){let i={kind:"none",replayed:0,ms:0,pure:0,mismatched:0},a=this.world;if(a===null)return i;let c=this.status===We.CPU;if(c&&s-this.probedAt<QC||!c&&!this.predicting)return i;this.ownPose=r,this.ownVelocity=o;let u=this.choose(e),l=new Set(u.filter(b=>b.epoch!==void 0&&this.epochs.has(b.key)&&this.epochs.get(b.key)!==b.epoch).map(b=>b.key));for(let b of u)b.epoch!==void 0&&this.epochs.set(b.key,b.epoch);let d=c?{...i,kind:"replay"}:this.compare(e,u,l);if(this.world===null)return{...d,kind:"none"};if(d.kind==="match"){this.base={tick:e.tick,ack:e.ack};for(let b of this.seatsOf(e))this.seats.set(b.key,b);for(let b of u)this.kinematic.has(b.key)&&this.kinematic.set(b.key,Array.from(b.row));return this.prune(e.tick),this.status=We.ON,d}c&&this.drawn.clear();let f=this.snapshotDrawn(s),h=this.clock();if(!this.rebuild(a,e,u))return this.stop(We.MISMATCH),i;this.base={tick:e.tick,ack:e.ack},this.seq=e.ack,this.ring.clear(),this.readAll(a);let p=Math.min(n,e.ack+this.leadMax),y=0;for(let b=e.ack+1;b<=p&&(this.stepOnce(a),this.world!==null);b++,y++);let S=this.clock()-h;return this.world===null?{...d,kind:"replay",replayed:y,ms:S}:(this.steppedAt=s,this.ease(f,s,l),c?this.judgeProbe(S,s):(this.status=We.ON,this.judgeBudget(S)),{...d,kind:"replay",replayed:y,ms:S})}advance(e,n){let r=this.world;r===null||this.base===null||this.status!==We.ON||e!==this.seq+1||e-this.base.ack>this.leadMax||(this.stepOnce(r),this.steppedAt=n)}draw(e,n){if(this.status!==We.ON)return null;let r=this.drawn.get(e);if(r===void 0)return this.ruledElsewhere(e)?this.ruledDrawn(e,n):null;let s=r.sleep?0:Math.min(Math.max((n-this.steppedAt)/1e3,0),1/this.tickHz),o=this.lengthUnit,i=[r.p[0]+r.lv[0]*o*s,r.p[1]+r.lv[1]*o*s,r.p[2]+r.lv[2]*o*s],a=lO(r.q,r.av,s),c=Math.max(n-r.since,0),u=Hx(r,c);return{p:[i[0]+u[0][0],i[1]+u[1][0],i[2]+u[2][0]],q:jn(Fi(r.dq,Math.exp(-c/r.tau)),a)}}choose(e){let n=Lx*this.lengthUnit,r=[],s=new Map;for(let p of e.bodies)s.set(p.key,p),r.push({key:p.key,x:p.row[0],y:p.row[1],z:p.row[2],radius:p.desc===null?0:Bc(p.desc)});for(let p of e.outside)r.push(p);let o=[];for(let p of e.joints)typeof p.desc.a=="string"&&typeof p.desc.b=="string"&&o.push([p.desc.a,p.desc.b]);let i=Fx(r,o,n),a=new Map;for(let p of r){let y=i.get(p.key),S=a.get(y);S===void 0?a.set(y,[p.key]):S.push(p.key)}let c=e.seats.find(p=>p.own),u=p=>{let y=s.get(p);return c===void 0?0:Math.hypot(y.row[0]-c.x,y.row[1]-c.y,y.row[2]-c.z)},l=[...a.entries()].filter(([,p])=>p.every(y=>s.get(y)?.desc!=null)).map(([p,y])=>({island:p,keys:y,near:Math.min(...y.map(u))})).sort((p,y)=>p.near-y.near||Wi(p.island,y.island)),d=Xh[this.setSize],f=[];this.pure.clear();let h=[...e.seats,...this.seats.values()];for(let{keys:p}of l){if(f.length+p.length>d)continue;for(let b of p)f.push(s.get(b));let y=h.some(b=>p.some(x=>uO(s.get(x),b,n,this.desc))),S=p.some(b=>s.get(b).desc?.type==="kinematic");if(!y&&!S)for(let b of p)this.pure.add(b)}return f.sort((p,y)=>Wi(p.key,y.key)),this.chosenKeys=new Set(f.map(p=>p.key)),this.chosenCount=l.reduce((p,{keys:y})=>p+y.length,0),f}compare(e,n,r){let s={kind:"replay",replayed:0,ms:0,pure:0,mismatched:0},o=this.base,i=this.ring.get(e.tick);if(o===null||i===void 0)return s;let a=0,c=0,u=!0;for(let p of n){if(p.desc?.type==="kinematic")continue;let y=i.get(p.key),S=y!==void 0&&cO(y,p.row);this.pure.has(p.key)&&!r.has(p.key)&&y!==void 0&&(a++,S||c++),S||(u=!1)}this.noteCanary(a,c);let l=n.length===this.simulated.size&&n.every(p=>this.simulated.get(p.key)?.desc===Gh(p.desc)),d=e.ack===o.ack+(e.tick-o.tick)&&this.seq>=e.ack,f={...s,pure:a,mismatched:c};return u&&l&&d&&this.sameJoints(e)&&this.sameSeats(e,i)?{...f,kind:"match"}:f}sameJoints(e){let n=this.jointsOf(e);if(n.size!==this.joints.size)return!1;for(let[r,s]of n){let o=this.joints.get(r);if(o===void 0||o.desc!==s.desc||o.motor!==s.motor)return!1}return!0}sameSeats(e,n){let r=this.seatsOf(e);return r.length!==this.seats.size?!1:r.every(s=>{let o=n.get(`seat:${s.key}`);if(o===void 0||this.seats.get(s.key)?.epoch!==s.epoch)return!1;let i=this.presetPosition(s.x,s.y,s.z);return o[0]===i[0]&&o[1]===i[1]&&o[2]===i[2]})}noteCanary(e,n){for(let s=0;s<e;s++)this.canary.push(s<n);if(this.canary.length>Vx&&this.canary.splice(0,this.canary.length-Vx),this.canary.length<rO)return;this.canary.filter(Boolean).length/this.canary.length>nO&&this.stop(We.DIVERGED)}judgeBudget(e){if(this.costs.push(e),this.costs.length>qh&&this.costs.splice(0,this.costs.length-qh),this.costs.length<JC)return;let n=Ux(this.costs,.5),r=Ux(this.costs,.9);if(n>this.budgetMs||r>ZC*this.budgetMs){this.costs=[];let i=tO(this.setSize,this.chosenCount);if(i!==null){this.setSize=i;return}this.fallBack();return}this.costs.length>=qh&&r<=zx*this.budgetMs&&this.setSize>0&&(this.setSize--,this.costs=[])}fallBack(){this.status=We.CPU,this.fallbacks++,this.drawn.clear(),this.probedAt=Number.NEGATIVE_INFINITY,this.calmProbes=0}judgeProbe(e,n){if(this.probedAt=n,this.calmProbes=e<=zx*this.budgetMs?this.calmProbes+1:0,this.calmProbes<eO){this.drawn.clear();return}this.status=We.ON,this.recoveries++,this.costs=[],this.calmProbes=0}jointsOf(e){let n=new Map;for(let r of e.joints){let s=r.desc.a,o=r.desc.b;!this.simulated.has(s)&&!this.chosenHas(s)||o!==null&&!this.simulated.has(o)&&!this.chosenHas(o)||n.set(r.key,{desc:JSON.stringify(r.desc),motor:r.motor===null?"":JSON.stringify(r.motor),parsed:r})}return n}chosenHas(e){return this.chosenKeys.has(e)}seatsOf(e){if(this.desc.presetBody===null)return[];let n=this.desc.world.limits.worldExtent;return e.seats.filter(r=>this.presetPosition(r.x,r.y,r.z).every(s=>Math.abs(s)<=n)).sort((r,s)=>Wi(r.key,s.key))}presetPosition(e,n,r){let s=this.desc.presetBody?.half[2]??0;return[Math.fround(e),Math.fround(n),Math.fround(Math.fround(r)+s)]}rebuild(e,n,r){let s=this.jointsOf(n);for(let c of[...this.joints.keys()]){let u=s.get(c);u!==void 0&&u.desc===this.joints.get(c).desc||(e.removeJoint(c),this.joints.delete(c))}for(let[c,u]of[...this.simulated]){let l=r.find(d=>d.key===c);l!==void 0&&Gh(l.desc)===u.desc||(e.remove(c),this.simulated.delete(c),this.kinematic.delete(c),this.drawn.delete(c))}for(let c of r)if(!(this.simulated.has(c.key)||c.desc===null)){if(!e.spawn(c.desc).ok)return!1;this.kinds.set(c.key,c.desc.kind),this.simulated.set(c.key,{type:String(c.desc.type),desc:Gh(c.desc)})}this.kinematic.clear();for(let c of r)c.desc?.type==="kinematic"&&(this.kinematic.set(c.key,Array.from(c.row)),this.ruled(c.key)||this.drawn.delete(c.key));if(this.propStates=null,!this.rebuildSeats(e,n))return!1;let o=this.rebuildLifts(e,n.tick);if(o===null)return!1;for(let[c,u]of s){if(!this.joints.has(c)&&!e.addJoint(u.parsed.desc).ok)return!1;let l=this.joints.get(c);if(u.parsed.motor!==null&&l?.motor!==u.motor&&!e.setMotor(c,u.parsed.motor).ok)return!1;this.joints.set(c,{desc:u.desc,motor:u.motor})}let i=[],a=[];for(let c of r){i.push(c.key);for(let u=0;u<Ro;u++)a.push(c.row[u])}for(let c of this.seats.values())i.push(c.key),a.push(...this.presetPosition(c.x,c.y,c.z),...oO);for(let[c,u]of o)i.push(c),a.push(...u);return i.length>0&&!e.importWire(i,a).ok?!1:e.canonicalize({quantize:!0}).ok}rebuildLifts(e,n){let r=this.lifts(),s=this.liftBodies;if(s!==null&&s.policy!==r?.policy){for(let o of s.keys)e.remove(o);this.liftBodies=null}if(r===null||r.policy.platforms.length===0)return[];if(this.liftBodies===null){for(let o of r.policy.platforms)if(!e.spawn(Px(o,n+1,r.starts)).ok)return null;this.liftBodies={policy:r.policy,keys:r.policy.platforms.map(o=>Ic(o.id))}}return r.policy.platforms.map(o=>{let{p:i,q:a}=Sd(o,n+1,r.starts);return[Ic(o.id),[...i,...a.map(aO),...iO]]})}rebuildSeats(e,n){let r=new Map(this.seatsOf(n).map(o=>[o.key,o]));for(let[o,i]of[...this.seats])r.get(o)?.epoch!==i.epoch&&(e.remove(o),this.seats.delete(o));let s=this.desc.presetBody;for(let[o,i]of r){if(!this.seats.has(o)&&s!==null){let a={key:"hull",shape:{kind:"box",half:[...s.half]},events:s.events,...this.headSlide()===null?{}:{friction:0}};if(!e.spawn({key:o,type:"kinematic",pose:{p:this.presetPosition(i.x,i.y,i.z),q:[...Lc]},colliders:[a]}).ok)return!1}this.seats.set(o,i)}return!0}stepOnce(e){let n=this.base,r=this.seq+1,s=n.tick+(r-n.ack),o=[],i=!1;for(let l of this.seats.values())o.push(this.seatAt(l,r,s-n.tick)),i||(i=this.posedBySeats);i||this.passSeats(o);for(let l of o)e.setNextKinematicPose(l.key,{p:this.presetPosition(l.x,l.y,l.z),q:[...Lc]});for(let[l,d]of this.kinematic){let f=this.kinematicRule?.(l,s+1)??null;e.setNextKinematicPose(l,f===null?dO(d):{p:[...f.p],q:[...f.q]})}let a=this.liftBodies===null?null:this.lifts();for(let l of a?.policy.platforms??[])e.setNextKinematicPose(Ic(l.id),Sd(l,s+1,a?.starts));this.applyBodyRule(e,s,o);let c=e.tick,u=e.step();if(!u.ok){this.stop(We.DIVERGED);return}for(let l of u.escaped)e.remove(l),this.simulated.delete(l),this.drawn.delete(l);this.clamp(e,c),s%this.desc.keyframeTicks===0&&(e.canonicalize({quantize:!0}),this.propStale=!0,this.ring.set(s,this.rowsNow(e))),this.seq=r,this.readDrawn(e,c),this.hashes.push({tick:s,hash:e.stateHash()}),this.hashes.length>this.hashesKept&&this.hashes.splice(0,this.hashes.length-this.hashesKept)}seatAt(e,n,r){this.posedBySeats=!1;let s=e.own?this.ownPose(n):void 0;if(s!==void 0){let f=this.ownVelocity(n)??[e.vx,e.vy,e.vz];return{key:e.key,x:s[0],y:s[1],z:s[2],vx:f[0],vy:f[1],vz:f[2]}}let o=e.own?void 0:this.seatPose?.(e.key,n);if(o!==void 0)return this.posedBySeats=!0,{...o,key:e.key};let i=this.remoteStep;if(e.own||i===void 0||e.input===void 0){let f=r/this.tickHz;return{key:e.key,x:e.x+e.vx*f,y:e.y+e.vy*f,z:e.z+e.vz*f,vx:e.vx,vy:e.vy,vz:e.vz}}let a=this.remoteBodies.get(e.key),c=a!==void 0&&a.from===e&&a.j<=r,u=c?a.body:{...e.body??{},x:e.x,y:e.y,z:e.z},l=1/this.tickHz,d=this.base?.tick??0;for(let f=(c?a.j:0)+1;f<=r;f++){this.seatRule?.(u,d+f);let h=this.desc.remotePredict===Zt.HOLD;i(u,h?e.input:Rd(e.input,f,this.tickHz,this.desc.remoteDecayMs),l,d+f)}return this.remoteBodies.set(e.key,{from:e,j:r,body:u}),{key:e.key,x:u.x,y:u.y,z:u.z,vx:u.vx??e.vx,vy:u.vy??e.vy,vz:u.vz??e.vz,...u.yaw===void 0?{}:{yaw:u.yaw}}}passSeats(e){let n=this.contactPass;if(n===void 0||e.length<2)return;let r=e.map(o=>({id:o.key,x:o.x,y:o.y,z:o.z,vx:o.vx,vy:o.vy,vz:o.vz,yaw:o.yaw??0}));r.sort((o,i)=>Wi(o.id,i.id)),n(r);let s=new Map(r.map(o=>[o.id,o]));for(let o of e){let i=s.get(o.key);o.x=i.x,o.y=i.y,o.z=i.z,o.vx=i.vx,o.vy=i.vy,o.vz=i.vz}}applyBodyRule(e,n,r){let s=this.bodyRule,o=this.headSlide(),i=this.liftBodies===null?null:this.lifts(),a=i!==null&&i.policy.platforms.some(d=>d.surface!==null)?i:null;if(s===void 0&&o===null&&a===null)return;r.sort((d,f)=>Wi(d.key,f.key));let c=d=>{if(this.simulated.get(d)?.type!=="dynamic")return null;let f=e.exportBodyState(d);return f===null?null:{p:[f.p[0],f.p[1],f.p[2]],v:[f.v[0],f.v[1],f.v[2]]}};for(let d of s?.({tick:n,seats:r,body:c})??[])this.simulated.get(d.key)?.type==="dynamic"&&e.setVelocity(d.key,[d.v[0],d.v[1],d.v[2]]);let u=this.desc.presetBody?.half;if(o===null&&a===null||u===void 0)return;if(this.propStates===null){this.propStates=new Map;for(let d of this.simulated.keys()){let f=c(d);f!==null&&this.propStates.set(d,{key:d,p:f.p,v:f.v})}this.propStale=!1}this.propStale&&this.freshenPicked(r,u,a===null?null:$h(a.policy,n,a.starts,2*u[2]),o!==null,c);let l=[...this.propStates.values()].filter(d=>this.simulated.get(d.key)?.type==="dynamic").sort((d,f)=>Wi(d.key,f.key));if(a!==null)for(let d of Tx(a.policy,n,a.starts,this.tickHz,l,2*u[2]))e.setVelocity(d.key,d.v);if(o!==null)for(let d of sx(r,u,l,o))e.setVelocity(d.key,d.v)}freshenPicked(e,n,r,s,o){let i=this.propStates;if(this.propStale=!1,i!==null)for(let[a,c]of i){if(!(s&&zh(e,n,c.p)!==void 0||r!==null&&r(c.p)!==void 0))continue;let l=o(a);l!==null&&i.set(a,{key:a,p:l.p,v:l.v})}}clamp(e,n){let{keys:r,data:s}=e.exportChanged(n,{rest:!0});for(let o=0;o<r.length;o++){let i=r[o];if(this.simulated.get(i)?.type!=="dynamic")continue;let a=o*Ro,c=[s[a+7],s[a+8],s[a+9]],u=[s[a+10],s[a+11],s[a+12]],l=Nx(c,u,this.lengthUnit,this.desc.maxLinear,this.desc.maxAngular);l!==null&&e.setVelocity(i,l.linvel,l.angvel),this.propStates?.set(i,{key:i,p:[s[a],s[a+1],s[a+2]],v:l===null?c:[l.linvel[0],l.linvel[1],l.linvel[2]]})}}rowsNow(e){let n=new Map,r=(s,o)=>{let i=e.exportBodyState(s,{rest:!0});i!==null&&n.set(o,Dx(i,this.lengthUnit,this.innerDt))};for(let s of this.simulated.keys())r(s,s);for(let s of this.seats.keys())r(s,`seat:${s}`);return n}ruledDrawn(e,n){let r=this.kinematicRule,s=this.ruledTick(n);if(r===void 0||s===null)return null;let o=Math.floor(s),i=r(e,o),a=r(e,o+1);if(i===null||a===null)return null;let c=s-o;return{p:[i.p[0]+(a.p[0]-i.p[0])*c,i.p[1]+(a.p[1]-i.p[1])*c,i.p[2]+(a.p[2]-i.p[2])*c],q:$r([...i.q])}}ruledTick(e){let n=this.base;if(n===null)return null;let r=Math.min(Math.max((e-this.steppedAt)/1e3*this.tickHz,0),1),s=n.tick+(this.seq-n.ack)+1+r,o=this.ruledClock;if(o===null||e<o.at||Math.abs(s-o.tick)>XC)return this.ruledClock={at:e,tick:s},s;let i=(e-o.at)/1e3*this.tickHz,a=o.tick+i,c=KC*i,u=a+Math.min(Math.max(s-a,-c),c);return this.ruledClock={at:e,tick:u},u}ruled(e){if(this.kinematicRule===void 0)return!1;let n=this.base,r=n===null?0:n.tick+(this.seq-n.ack);return this.kinematicRule(e,r)!==null}prune(e){for(let n of this.ring.keys())n<=e&&this.ring.delete(n)}readDrawn(e,n){let{keys:r,data:s}=e.exportChanged(n,{rest:!0});for(let o=0;o<r.length;o++){let i=r[o];if(!this.simulated.has(i)||this.kinematic.has(i)&&!this.ruled(i))continue;let a=o*Ro,c=this.drawn.get(i);this.drawn.set(i,{p:[s[a],s[a+1],s[a+2]],q:$r([s[a+3],s[a+4],s[a+5],s[a+6]]),lv:[s[a+7]/this.lengthUnit,s[a+8]/this.lengthUnit,s[a+9]/this.lengthUnit],av:[s[a+10],s[a+11],s[a+12]],sleep:s[a+13]===1,dp:c?.dp??ji,dv:c?.dv??ji,dq:c?.dq??Lc,since:c?.since??0,tau:c?.tau??$i(0),snap:c?.snap??this.snapOf(i)})}}builtInRules(){if(!this.desc.presetBody)return!1;if(this.headSlide()!==null)return!0;let e=this.liftBodies===null?null:this.lifts();return e!==null&&e.policy.platforms.some(n=>n.surface!==null)}readAll(e){let n=this.builtInRules()?new Map:null;for(let r of this.simulated.keys()){let s=this.kinematic.has(r)&&!this.ruled(r)?null:e.exportBodyState(r,{rest:!0});if(s===null)continue;n!==null&&this.simulated.get(r)?.type==="dynamic"&&n.set(r,{key:r,p:[s.p[0],s.p[1],s.p[2]],v:[s.v[0],s.v[1],s.v[2]]});let o=this.drawn.get(r),i=this.lengthUnit;this.drawn.set(r,{p:[s.p[0],s.p[1],s.p[2]],q:$r([s.q[0],s.q[1],s.q[2],s.q[3]]),lv:[s.v[0]/i,s.v[1]/i,s.v[2]/i],av:[s.w[0],s.w[1],s.w[2]],sleep:s.sleeping,dp:o?.dp??ji,dv:o?.dv??ji,dq:o?.dq??Lc,since:o?.since??0,tau:o?.tau??$i(0),snap:o?.snap??this.snapOf(r)})}n!==null&&(this.propStates=n,this.propStale=!1)}snapshotDrawn(e){let n=new Map;for(let[r,s]of this.drawn){let o=Math.max(e-s.since,0),i=Hx(s,o);n.set(r,{p:[s.p[0]+i[0][0],s.p[1]+i[1][0],s.p[2]+i[2][0]],q:jn(Fi(s.dq,Math.exp(-o/s.tau)),s.q),rate:[i[0][1],i[1][1],i[2][1]]})}return n}snapOf(e){return kd(this.kinds.get(e))*this.lengthUnit}ease(e,n,r){for(let[s,o]of this.drawn){let i=e.get(s),a={...o,dp:ji,dv:ji,dq:Lc,since:n,tau:$i(0)};if(i===void 0||r.has(s)){this.drawn.set(s,a);continue}let c=[i.p[0]-o.p[0],i.p[1]-o.p[1],i.p[2]-o.p[2]],u=Math.hypot(c[0],c[1],c[2]);if(u>o.snap){this.drawn.set(s,a);continue}let l=jn(i.q,[-o.q[0],-o.q[1],-o.q[2],o.q[3]]),d=l[3]<0?[-l[0],-l[1],-l[2],-l[3]]:l;this.drawn.set(s,{...o,dp:c,dv:i.rate,dq:d,since:n,tau:$i(u/this.lengthUnit)})}}},Gh=t=>t===null?"":JSON.stringify(t);function uO(t,e,n,r){let s=r.presetBody?.half??[0,0,0],o=Math.hypot(s[0],s[1],s[2])+(t.desc===null?0:Bc(t.desc))+n;return Math.hypot(t.row[0]-e.x,t.row[1]-e.y,t.row[2]-(e.z+s[2]))<=o}function lO(t,e,n){let r=Math.hypot(e[0],e[1],e[2]);if(r===0||n===0)return t;let s=r*n/2,o=Math.sin(s)/r;return $r(jn([e[0]*o,e[1]*o,e[2]*o,Math.cos(s)],t))}function dO(t){let e=r=>-1+r/65534*2,n=$r([e(t[3]),e(t[4]),e(t[5]),e(t[6])]);return{p:[t[0],t[1],t[2]],q:[n[0],n[1],n[2],n[3]]}}var Yh={contract:"1.0",dt:1/60,substeps:1,gravity:[0,0,-9.81],upAxis:"z",lengthUnit:1},Kh=12;function fO(){let t=(e,n,r)=>({key:e,type:"dynamic",pose:{p:n,q:[0,0,0,1]},linvel:[1,0,0],colliders:[{key:"c",shape:{kind:"box",half:[r,r,r]}}]});return[t("a",[0,0,.5],.5),t("b",[0,0,1.6],.5),{key:"c",type:"dynamic",pose:{p:[2,0,1],q:[0,0,0,1]},angvel:[0,3,0],colliders:[{key:"c",shape:{kind:"sphere",radius:.4}}]}]}function Wx(t){let n=[t.World.create(Yh),t.World.create(Yh)].flatMap(r=>r.ok?[r.world]:[]);try{if(n.length!==2)return!1;let[r,s]=n,o={boxes:[[-20,-20,-1,20,20,0]],ramps:[]};if(!r.addStaticWorld(o).ok||!s.addStaticWorld(o).ok)return!1;for(let l of fO())if(!r.spawn(l).ok||!s.spawn(l).ok)return!1;for(let l=0;l<Kh;l++)r.step();s.canonicalize({});for(let l=0;l<Kh;l++)s.step();if(!r.canonicalize({quantize:!0}).ok)return!1;let{keys:i,data:a}=r.exportChanged(r.tick,{rest:!0}),c=[],u=jh(Yh);for(let l=0;l<i.length;l++)Wh(a,l*Ro,1,u,c,l*Ro);if(i.length!==3||!s.importWire(i,c).ok||!s.canonicalize({quantize:!0}).ok)return!1;for(let l=0;l<Kh;l++)if(r.step(),s.step(),r.stateHash()!==s.stateHash())return!1;return!0}finally{for(let r of n)r.free()}}var uV=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);var Eo=["x","y","z","vx","vy","vz","yaw","spin"],pO=(t,e)=>t.body.id<e.body.id?-1:t.body.id>e.body.id?1:0,Td=class{constructor(e,n){m(this,"pass",null);m(this,"rule");m(this,"others");this.rule=e,this.others=n}apply(e,n,r,s){(this.pass===null||this.pass.ack!==n||e<=this.pass.last)&&(this.pass={ack:n,last:n,others:this.others().map(u=>({body:{...u},from:0})).sort(pO)});let i=this.pass,a=e-n,c={...r};i.others=i.others.map(u=>{let l=(a-u.from)/s,d=u.body,f={...d,x:d.x+d.vx*l,y:d.y+d.vy*l,z:d.z+d.vz*l},h=JSON.stringify(f);return c.id<f.id?this.rule(c,f):this.rule(f,c),JSON.stringify(f)===h?u:{body:f,from:a}});for(let u of Eo){let l=c[u];typeof l=="number"&&l!==r[u]&&(r[u]=Math.fround(l))}i.last=e}seatAt(e,n,r,s){let o=this.pass!==null&&this.pass.ack===n?this.pass.others.find(l=>l.body.id===e):void 0,i=o===void 0?this.others().find(l=>l.id===e):void 0,a=o?.from??0,c=o?.body??i;if(c===void 0)return;let u=(r-a)/s;return{...c,x:c.x+c.vx*u,y:c.y+c.vy*u,z:c.z+c.vz*u}}};function ko(t,e,n){let r={x:n.x,y:n.y,z:n.z};for(let s=0;s<hO;s++){let o={...e,vx:0,vy:0,vz:0},i={...n,...r,vx:0,vy:0,vz:0};o.id<i.id?t(o,i):t(i,o);let a={x:r.x+(i.x-r.x)-(o.x-e.x),y:r.y+(i.y-r.y)-(o.y-e.y),z:r.z+(i.z-r.z)-(o.z-e.z)};if(s>0&&a.x===r.x&&a.y===r.y&&a.z===r.z||(r=a,s===0&&vd(t,e,n,r)<=mO))break}return vd(t,e,n,r)>Xx?wO(t,e,n,r):r}var hO=8,mO=.01,Xx=.001,yO=30,gO=8,bO=1;function wO(t,e,n,r){let s={x:n.x,y:n.y,z:n.z},o={x:r.x-s.x,y:r.y-s.y,z:r.z-s.z},i=Math.hypot(o.x,o.y,o.z)>0?o:Jx(t,e,n,s),a=Math.hypot(i.x,i.y,i.z);if(a===0)return r;let c={x:i.x/a,y:i.y/a,z:i.z/a},u=h=>({x:s.x+c.x*h,y:s.y+c.y*h,z:s.z+c.z*h}),l=h=>vd(t,e,n,u(h))>0,d=a,f=a+Math.max(bO,a);for(let h=0;h<gO&&l(f);h++)d=f,f=a+(f-a)*2;if(l(f))return r;for(let h=0;h<yO;h++){let p=(d+f)/2;l(p)?d=p:f=p}return u(f)}function Jx(t,e,n,r){let s={...e,vx:0,vy:0,vz:0},o={...n,...r,vx:0,vy:0,vz:0};return s.id<o.id?t(s,o):t(o,s),{x:o.x-r.x-(s.x-e.x),y:o.y-r.y-(s.y-e.y),z:o.z-r.z-(s.z-e.z)}}function vd(t,e,n,r){let s=Jx(t,e,n,r);return Math.hypot(s.x,s.y,s.z)}var SO=3*Math.PI,xO=Math.PI/2,_O=.05,RO=8,qx=16,EO=30,kO=8,Zx=(t,e,n)=>({...e,x:t.x+n.dx,y:t.y+n.dy,z:t.z+n.dz,vx:0,vy:0,vz:0});function Qh(t,e,n,r){let s=Zx(e,n,r),o=ko(t,e,s);return Math.hypot(o.x-s.x,o.y-s.y,o.z-s.z)}function Md(t,e,n,r,s){let o=Math.hypot(s.dx-r.dx,s.dy-r.dy,s.dz-r.dz),i=Math.min(o,Math.hypot(r.dx,r.dy,r.dz));if(i===0)return!1;for(let a=1;a<qx;a++){let c=a/qx,u={dx:r.dx+(s.dx-r.dx)*c,dy:r.dy+(s.dy-r.dy)*c,dz:r.dz+(s.dz-r.dz)*c};if(Qh(t,e,n,u)>Math.min(_O*i,RO))return!0}return!1}function Zh(t,e,n,r,s,o){let i=Math.cos(r),a=Math.sin(r),c=d=>Qh(t,e,n,{dx:d*i,dy:d*a,dz:s})>0;if(!c(0)||o<=0)return 0;let u=0,l=o;for(let d=0;d<kO&&c(l);d++)u=l,l*=2;for(let d=0;d<EO;d++){let f=(u+l)/2;c(f)?u=f:l=f}return l}var Gx=4,AO=20;function PO(t,e,n){let r=n.z>=e.z?1:-1,s=a=>Qh(t,e,n,{dx:n.x-e.x,dy:n.y-e.y,dz:n.z-e.z+r*a})>0;if(!s(0)||s(Gx))return n;let o=0,i=Gx;for(let a=0;a<AO;a++){let c=(o+i)/2;s(c)?o=c:i=c}return{...n,z:n.z+r*i}}var Yx=2*Math.PI,TO=t=>t-Yx*Math.floor((t+Math.PI)/Yx);function Kx(t,e,n,r,s,o=!1){let i=PO(t,e,n),a=ko(t,e,i),c={dx:a.x-e.x,dy:a.y-e.y,dz:a.z-e.z},u=a.x!==i.x||a.y!==i.y||a.z!==i.z,l=i.x-e.x,d=i.y-e.y,f=(j,L)=>({x:e.x+j.dx,y:e.y+j.dy,z:e.z+j.dz,side:{...j,held:L,bx:l,by:d,at:s}}),h=j=>f(vO(t,e,i,j),!0);if(r===void 0||!(o||Md(t,e,i,r,c)))return f(c,u);let p=Math.hypot(r.dx,r.dy),y=Math.hypot(c.dx,c.dy),S=Math.atan2(r.dy,r.dx);if(!r.held){if(r.dx*c.dx+r.dy*c.dy>=0)return f(c,u);let j=Zh(t,e,i,S,c.dz,Math.max(p,y));return h({dx:j*Math.cos(S),dy:j*Math.sin(S),dz:c.dz})}let b=TO(Math.atan2(c.dy,c.dx)-S),x=p>0?xO*Math.hypot(l-r.bx,d-r.by)/p:0,R=Math.max(x,SO*Math.max(0,s-r.at)/1e3),A=Math.min(Math.abs(b),R),E=b===0?1:A/Math.abs(b),P=S+Math.sign(b)*A,k=c.dz-r.dz,M=R*Math.max(p,y),B=Math.abs(k*E)>M?r.dz+Math.sign(k)*M:r.dz+k*E,K=Math.max(p+(y-p)*E,Zh(t,e,i,P,B,Math.max(p,y)));return h({dx:K*Math.cos(P),dy:K*Math.sin(P),dz:B})}function vO(t,e,n,r){let s=Zx(e,n,r);return vd(t,e,s,s)>Xx?qi(e,ko(t,e,s)):r}function MO(t,e,n,r,s,o,i){let a={dx:i.x-e.x,dy:i.y-e.y,dz:i.z-e.z};for(let c of r){let u=c===n?void 0:s.get(c.id);if(u===void 0)continue;let l={...c,x:e.x+u.dx,y:e.y+u.dy,z:e.z+u.dz,vx:0,vy:0,vz:0},d=f=>({dx:f.dx-u.dx,dy:f.dy-u.dy,dz:f.dz-u.dz});if(Md(t,l,n,d(o),d(a)))return!0}return!1}var Fc=(t,e)=>t<e?`${t}\0${e}`:`${e}\0${t}`,CO=12,Kr=(t,e)=>({...t,x:e.x,y:e.y,z:e.z,vx:0,vy:0,vz:0}),qi=(t,e)=>({dx:e.x-t.x,dy:e.y-t.y,dz:e.z-t.z}),Cd=(t,e)=>t.x===e.x&&t.y===e.y&&t.z===e.z,OO=720,IO=.1,DO=24,NO=8,BO=64;function em(t,e,n,r,s){return!Cd(ko(t,Kr(e,r),Kr(n,s)),s)}var Qx=(t,e,n,r)=>[{x:t.x-n.nx*r/2,y:t.y-n.ny*r/2,z:t.z},{x:e.x+n.nx*r/2,y:e.y+n.ny*r/2,z:e.z}];function LO(t,e,n,r,s,o,i){let a=l=>em(t,e,n,...Qx(r,s,o,l));if(!a(i))return i;let c=i,u=i+BO;for(let l=0;l<NO&&a(u);l++)c=u,u=i+(u-i)*2;for(let l=0;l<DO;l++){let d=(c+u)/2;a(d)?c=d:u=d}return u}function Jh(t,e){let n=Math.hypot(t,e);return n>0?{nx:t/n,ny:e/n}:null}function FO(t,e,n,r,s,o){let i=ko(t,Kr(e,r),Kr(n,s)),a=(o===void 0?null:Jh(o.dx,o.dy))??Jh(s.x-r.x,s.y-r.y),c=Jh(i.x-s.x,i.y-s.y),u=c!==null&&a!==null&&c.nx*a.nx+c.ny*a.ny<0?-1:1;return{...c===null?a??{nx:1,ny:0}:{nx:u*c.nx,ny:u*c.ny},push:0}}function zO(t,e,n,r){let s=r.get(e.id),o=r.get(n.id),i=ko(t,Kr(e,s),Kr(n,o));if(Cd(i,o))return!1;let a={x:(i.x-o.x)/2,y:(i.y-o.y)/2,z:(i.z-o.z)/2};return r.set(e.id,{x:s.x-a.x,y:s.y-a.y,z:s.z-a.z}),r.set(n.id,{x:o.x+a.x,y:o.y+a.y,z:o.z+a.z}),!0}function e_(t,e,n,r){return r.nx*(n.x-e.x)+r.ny*(n.y-e.y)<0&&!em(t,e,n,e,n)}var t_=(t,e,n,r,s)=>s.nx*(r.x-n.x-(e.x-t.x))+s.ny*(r.y-n.y-(e.y-t.y));function UO(t,e,n,r,s,o,i){let a=Fc(e.id,n.id),c=r.get(e.id),u=r.get(n.id),l=s.get(a),d=0;if(l===void 0){let y=o?.pair;if(y===void 0?!em(t,e,n,e,n):e_(t,e,n,y))return zO(t,e,n,r);l=y??FO(t,e,n,c,u,o),s.set(a,l);let S=y===void 0?0:y.push-OO*Math.min(i,IO);d=Math.max(0,S-t_(e,n,c,u,l))}let f=LO(t,e,n,c,u,l,d);if(f<=0)return!1;let[h,p]=Qx(c,u,l,f);return r.set(e.id,h),r.set(n.id,p),!0}function VO(t,e,n,r,s,o){if(s===void 0)return;let i=r.get(e.id),a=r.get(n.id),c=qi(i,a);if(s.dx*c.dx+s.dy*c.dy>=0)return;let u=Kr(e,i),l=Kr(n,a);if(!Md(t,u,l,s,c))return;let d=Math.atan2(s.dy,s.dx),f=Zh(t,u,l,d,s.dz,Math.hypot(s.dx,s.dy)),h={dx:f*Math.cos(d),dy:f*Math.sin(d),dz:s.dz};return o(n.id)>=o(e.id)?(r.set(n.id,{x:i.x+h.dx,y:i.y+h.dy,z:i.z+h.dz}),n.id):(r.set(e.id,{x:a.x-h.dx,y:a.y-h.dy,z:a.z-h.dz}),e.id)}function HO(t,e,n,r,s){let o=Kr(n,r),i=ko(t,e,o);return Cd(i,r)?r:Md(t,e,o,qi(e,s),qi(e,i))?s:i}function $O(t){return t.flatMap((e,n)=>t.slice(n+1).map(r=>[e,r]))}function n_(t,e,n,r,s){let o=[...n].sort((h,p)=>h.id<p.id?-1:h.id>p.id?1:0),i=new Map;for(let h of o){let p=r.get(h.id),y=Kx(t,e,h,p,s),b=p?.held===!0&&!y.side.held&&MO(t,e,h,o,r,p,y)?Kx(t,e,h,p,s,!0):y;i.set(h.id,{x:b.x,y:b.y,z:b.z})}let a=new Map(i),c=h=>{let p=r.get(h),y=a.get(h);return p===void 0?Number.POSITIVE_INFINITY:Math.hypot(y.x-e.x-p.dx,y.y-e.y-p.dy,y.z-e.z-p.dz)},u=$O(o),l=(h,p)=>r.get(Fc(h.id,p.id));for(let[h,p]of u){let y=l(h,p);(y?.pair===void 0||e_(t,h,p,y.pair))&&VO(t,h,p,i,y,c)}let d=new Map;for(let h=0;;h++){for(let y of o)i.set(y.id,HO(t,e,y,i.get(y.id),a.get(y.id)));if(h===CO)break;let p=!1;for(let[y,S]of u){let b=l(y,S);p=UO(t,y,S,i,d,b,b===void 0?0:Math.max(0,s-b.at)/1e3)||p}if(!p)break}let f=new Map;for(let h of o){let p=i.get(h.id);f.set(h.id,{...qi(e,p),held:!Cd(p,h),bx:h.x-e.x,by:h.y-e.y,at:s})}for(let[h,p]of u){let y=i.get(h.id),S=Fc(h.id,p.id),b=d.get(S),x=b===void 0?0:t_(h,p,y,i.get(p.id),b),R=b!==void 0&&x>0?{pair:{nx:b.nx,ny:b.ny,push:x}}:{};f.set(S,{...qi(y,i.get(p.id)),held:!1,bx:p.x-h.x,by:p.y-h.y,at:s,...R})}return{drawn:i,sides:f}}var Gi=(t,e,n)=>t+(n-e);var Yi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function jO(t){if(!Yi(t)||typeof t.preset!="string"||!Object.hasOwn(vS,t.preset))return!1;let e=t.shape,n=t.hull;return!Yi(e)||e.kind!==qn.Box&&e.kind!==qn.Hull||!Yi(n)?!1:Yi(t.top)&&Yi(t.offWall)&&Array.isArray(t.pairs)&&typeof t.passes=="number"}function r_(t,e){if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}let r=Yi(n)?n.contacts:void 0;if(!jO(r))return null;let s={world:IS(e,r.hull.radius,r.hull.height,r.hull.skin)},o=new Map,i=a=>{let c=o.get(a);if(c!==void 0)return c;let u=Fh(r,{...s,fixed:a});return o.set(a,u),u};return{policy:r,rule:Fh(r,s),pass:ex(r,s),env:s,drawRule:i}}var Od=[.5,1,5,20],WO=new Set(["x","y","z"]),qO=new Set(["mstate","cap","spin","fuel"]),s_=2*Math.PI;function o_(t,e,n){let r=0,s=0;return t.forEach((o,i)=>{if(qO.has(o))return;let a=(n[i]??0)-(e[i]??0);WO.has(o)?r+=a*a:s=Math.max(s,Math.abs(o==="yaw"?a-s_*Math.floor((a+Math.PI)/s_):a))}),{place:Math.sqrt(r),state:s}}var i_=(t,e)=>t>.05*e;function a_(t,e){let n=Od.findIndex(r=>t<r*e);return n<0?Od.length:n}function c_(t){return Number.isSafeInteger(t)?(t%65536+65536)%65536:0}var m_=500;function GO(t,e,n,r){let s=t.poses.get(n)?.get(e);if(s===void 0)return;let o=t.poses.get(n-1)?.get(e),i=t.poses.get(n-2)?.get(e);if(o===void 0){let h=r/t.tickHz;return{...s,x:s.x+s.vx*h,y:s.y+s.vy*h,z:s.z+s.vz*h}}let a=Math.floor(r),c=h=>h*(h+1)/2,u=(h,p,y)=>{let S=h+p*a+y*c(a),b=h+p*(a+1)+y*c(a+1);return S+(b-S)*(r-a)},l=(h,p,y)=>y===void 0?0:h-2*p+y,d=vs(s.yaw-o.yaw),f=i===void 0?0:d-vs(o.yaw-i.yaw);return{...s,x:u(s.x,s.x-o.x,l(s.x,o.x,i?.x)),y:u(s.y,s.y-o.y,l(s.y,o.y,i?.y)),z:u(s.z,s.z-o.z,l(s.z,o.z,i?.z)),yaw:vs(u(s.yaw,d,f))}}function YO(t,e){let n=t.ack+t.ticks,r=Math.min(Math.max(e,t.ack+1),n),s=Math.floor(r),o=t.own.get(s);if(o===void 0)return;let i=t.own.get(s+1),a=r-s;return i===void 0||a===0?o:{...o,x:o.x+(i.x-o.x)*a,y:o.y+(i.y-o.y)*a,z:o.z+(i.z-o.z)*a,yaw:o.yaw+vs(i.yaw-o.yaw)*a}}var u_=8,KO=3,tm=.5,nm=(t,e)=>t.id<e.id?-1:t.id>e.id?1:0,ke=(t,e=0)=>typeof t=="number"&&Number.isFinite(t)?t:e,l_=2*Math.PI,vs=t=>t-l_*Math.floor((t+Math.PI)/l_),d_=t=>({x:ke(t.x),y:ke(t.y),z:ke(t.z),yaw:ke(t.yaw),vx:ke(t.vx),vy:ke(t.vy),vz:ke(t.vz)}),f_=(t,e)=>({id:t,x:ke(e.x),y:ke(e.y),z:ke(e.z),vx:ke(e.vx),vy:ke(e.vy),vz:ke(e.vz),yaw:ke(e.yaw),spin:ke(e.spin),...typeof e.flags=="number"?{flags:e.flags}:{}}),p_=(t,e)=>({id:t,x:ke(e.x),y:ke(e.y),z:ke(e.z),vx:ke(e.vx),vy:ke(e.vy),vz:ke(e.vz),yaw:ke(e.yaw),duck:ke(e.duck),flags:ke(e.flags)}),h_=(t,e)=>Eo.every(n=>t[n]===e[n]),Dd=class{constructor(e){m(this,"options");m(this,"serial",0);m(this,"current",null);m(this,"recent",[]);m(this,"applied",new Map);m(this,"missed",new Set);this.options=e}apply(e,n,r,s,o,i=null){let a=this.current,c=a===null||a.ack!==n||a.stateTick!==r||e<=a.last,u=a,l=c?this.start(n,r,o):a,d=e-n;for(let p=l.ticks+1;p<d;p++)this.tick(l,p,u?.ownIn.get(n+p),!1,u?.ownOn.get(n+p)??null),this.noteMissed(l,n+p);let f=d>l.ticks,h=f?this.tick(l,d,s,!0,i):null;f&&this.applied.set(e,l.touching.get(e)??new Set),l.last=e;for(let p of this.recent)this.extend(p,l,e);return h}takeMissed(){let e=[...this.missed].sort();return this.missed.clear(),e}noteMissed(e,n){let r=this.applied.get(n),s=e.touching.get(n);if(!(r===void 0||s===void 0))for(let o of s)r.has(o)||this.missed.add(o)}extend(e,n,r){let s=r-e.ack;for(let o=e.ticks+1;o<=s;o++)this.tick(e,o,n.ownIn.get(e.ack+o),!1,n.ownOn.get(e.ack+o)??null);e.last=Math.max(e.last,r)}poseAt(e,n,r=this.current){if(r===null)return;let s=Math.max(n,r.ack),o=r.ack+r.ticks,i=Math.min(Math.floor(s),o),a=r.poses.get(i)?.get(e);if(a===void 0)return;let c=i<o?r.poses.get(i+1)?.get(e):void 0,u=s-i;if(c===void 0){if(r===this.current){let l=Math.min(u,1)/r.tickHz;return{...a,x:a.x+a.vx*l,y:a.y+a.vy*l,z:a.z+a.vz*l}}return GO(r,e,i,u)??a}return{x:a.x+(c.x-a.x)*u,y:a.y+(c.y-a.y)*u,z:a.z+(c.z-a.z)*u,yaw:a.yaw+vs(c.yaw-a.yaw)*u,vx:a.vx+(c.vx-a.vx)*u,vy:a.vy+(c.vy-a.vy)*u,vz:a.vz+(c.vz-a.vz)*u}}motionAt(e,n,r=this.current){let s=this.poseAt(e,n,r),o=this.poseAt(e,n-tm,r),i=this.poseAt(e,n+tm,r);if(s===void 0||o===void 0||i===void 0||r===null)return;let a=r.tickHz/1e3/(2*tm);return{pose:s,rate:{vx:(i.x-o.x)*a,vy:(i.y-o.y)*a,vz:(i.z-o.z)*a,vyaw:vs(i.yaw-o.yaw)*a}}}changeAt(e,n,r){if(this.current===null||this.current===r)return;let s=Math.min(n,r.ack+r.ticks),o=this.motionAt(e,s,r),i=this.motionAt(e,s);return o===void 0||i===void 0?void 0:{before:o,after:i}}touchAheadMs(e,n){let r=this.current;if(r===null)return;let s=Math.floor(Math.max(n,r.ack));if(r.touching.get(s)?.has(e)===!0||r.touching.get(s+1)?.has(e)===!0)return 0;let o=r.seats.find(l=>l.id===e),i=this.poseAt(e,n,r),a=YO(r,n);if(o===void 0||i===void 0||a===void 0)return;let c={...f_(e,o.body),x:i.x,y:i.y,z:i.z,yaw:i.yaw,vx:i.vx,vy:i.vy,vz:i.vz},u={x:(i.vx-a.vx)/1e3,y:(i.vy-a.vy)/1e3,z:(i.vz-a.vz)/1e3};for(let l=0;l<=u_;l++){let d=l/u_*Rt.SEAT_CLOCK_TAU_MS;if(this.touches(a,{...c,x:c.x+u.x*d,y:c.y+u.y*d,z:c.z+u.z*d}))return d}}touchingAt(e,n){let r=this.current;return r===null?!1:r.touching.get(Math.round(Math.max(n,r.ack)))?.has(e)===!0}stateRate(e){let n=this.current,r=n?.poses.get(n.ack)?.get(e);if(r!==void 0)return{vx:r.vx/1e3,vy:r.vy/1e3,vz:r.vz/1e3,vyaw:0}}start(e,n,r){let s=this.options.others().map(a=>({id:a.id,epoch:a.epoch,body:{...a.body},input:a.input})).sort(nm),o=new Map([[e,new Map(s.map(a=>[a.id,d_(a.body)]))]]);this.serial+=1,this.current!==null&&(this.recent=[this.current,...this.recent].slice(0,KO));for(let a of this.applied.keys())a<=e&&this.applied.delete(a);let i={id:this.serial,ack:e,stateTick:n,tickHz:r,last:e,ticks:0,seats:s,poses:o,touching:new Map,own:new Map,ownIn:new Map,ownOn:new Map};return this.current=i,i}tick(e,n,r,s,o){let i=Math.ceil(this.options.maxAheadMs()*e.tickHz/1e3),a=n<=i?this.carry(e,n):null;if(n<=i)for(let p of e.seats)this.move(e,p,n,a===null?void 0:Mc(a.t,p.id));let c=r===void 0?void 0:{...r};r!==void 0&&(e.ownIn.set(e.ack+n,{...r}),e.ownOn.set(e.ack+n,o));let u=a===null?null:this.ride(e,a,c,o),l=e.seats.map(p=>f_(p.id,p.body)),d=new Set;if(c!==void 0)for(let p of l)this.touches(c,p)&&d.add(p.id);let f=c===void 0?l:[...l,c].sort(nm);if(this.contactPass(f),e.seats.forEach((p,y)=>{let S=l[y];for(let b of Eo)typeof S[b]=="number"&&(p.body[b]=S[b])}),a!==null&&this.impart(e,a,c),r!==void 0&&c!==void 0&&s)for(let p of Eo){let y=c[p];typeof y=="number"&&y!==r[p]&&(r[p]=Math.fround(y))}let h=e.ack+n;return e.poses.set(h,new Map(e.seats.map(p=>[p.id,d_(p.body)]))),e.touching.set(h,d),c!==void 0&&e.own.set(h,s&&r!==void 0?{...r}:c),e.ticks=n,u}ride(e,n,r,s){let o=n.t,i=new Map(e.seats.map(h=>[h.id,h.body])),a=h=>r!==void 0&&h===r.id?r:i.get(h);for(let h of o.seats){let p=a(h.id);p!==void 0&&(h.x=ke(p.x),h.y=ke(p.y))}Rx(n.l.lifts,o);for(let h of o.seats){let p=i.get(h.id);p!==void 0&&(p.x=h.x,p.y=h.y)}if(r===void 0||s===null)return null;let c=o.seats.find(h=>h.id===r.id),u=o.seats.findIndex(h=>h.id===s);if(c===void 0&&u<0)return null;let l=c===void 0?o.report.from[u]:[r.x,r.y],d=c??o.seats[u],f=[d.x-l[0],d.y-l[1]];return r.x=Math.fround(r.x+f[0]),r.y=Math.fround(r.y+f[1]),f}carry(e,n){let r=this.options.lifts?.()??null;if(r===null)return null;let s=e.own.get(e.ack+n-1),o=e.seats.map(c=>p_(c.id,c.body));s!==void 0&&o.push(p_(s.id,s)),o.sort(nm);let i=vc(r.lifts,o,e.stateTick+n,r.starts,1/e.tickHz,r.cache),a=new Map(i.seats.map(c=>[c.id,c]));for(let c of e.seats){let u=a.get(c.id);c.body.x=u.x,c.body.y=u.y,c.body.z=u.z,r.lifts.vehicle&&(c.body.yaw=u.yaw)}return{l:r,t:i}}impart(e,n,r){let s=new Map(e.seats.map(i=>[i.id,i.body]));r!==void 0&&s.set(r.id,r);for(let i of n.t.seats){let a=s.get(i.id);a!==void 0&&(i.x=ke(a.x),i.y=ke(a.y),i.z=ke(a.z),i.vx=ke(a.vx),i.vy=ke(a.vy),i.vz=ke(a.vz))}Cc(n.l.lifts,n.t,n.l.starts);let o=new Map(n.t.seats.map(i=>[i.id,i]));for(let i of e.seats){let a=o.get(i.id);i.body.vx=a.vx,i.body.vy=a.vy,i.body.vz=a.vz}}move(e,n,r,s){let o=1/e.tickHz,{predict:i,decayMs:a}=this.options.remote(),c=i===Zt.EXTRAPOLATE?void 0:this.options.step();if(c===void 0||n.input===void 0){let l=n.body;l.x=ke(l.x)+ke(l.vx)*o,l.y=ke(l.y)+ke(l.vy)*o,l.z=ke(l.z)+ke(l.vz)*o;return}this.options.seatRule?.(n.body,e.stateTick+r);let u=i===Zt.INPUT_DECAY?Rd(n.input,r,e.tickHz,a):n.input;c(n.body,u,o,s)}contactPass(e){if(this.options.pass!==void 0){this.options.pass(e);return}for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++)this.options.rule(e[n],e[r])}touches(e,n){let r={...e},s={...n};return r.id<s.id?this.options.rule(r,s):this.options.rule(s,r),!h_(r,e)||!h_(s,n)}};function y_(t,e,n,r){if(t===void 0||!Number.isFinite(t.seq))return{seq:e,at:n};let s=Math.max(0,n-t.at),o=t.seq+s*r/1e3,i=e-o;if(Math.abs(i)>Rt.SEAT_CLOCK_SNAP_INPUTS)return{seq:e,at:n};let a=o+i*(1-Math.exp(-s/Rt.SEAT_CLOCK_TAU_MS));return{seq:Math.max(t.seq,a),at:n}}function g_(t,e,n){if(t===void 0||!Number.isFinite(t))return e?1:0;let r=Math.max(0,n)/Rt.SEAT_CLOCK_TAU_MS;return e?Math.min(1,t+r):Math.max(0,t-r)}var XO=.01;function b_(t,e){let n=Math.exp(-e/Rt.SEAT_TAU_MS),r=Math.max(Math.abs(t.dx),Math.abs(t.dy),Math.abs(t.dz))*n<XO;return{dx:t.dx*n,dy:t.dy*n,dz:t.dz*n,done:r}}var JO=t=>t?Rt.SEAT_CONTACT_TAU_MS:Rt.SEAT_TAU_MS;function Id(t,e,n,r){let s=1/r,o=Math.exp(-s*n),i=e+s*t;return[(t+i*n)*o,(e-s*i*n)*o]}function w_(t,e,n,r,s,o,i,a,c){let u={ax:s.pose.x,ay:s.pose.y,az:s.pose.z},l={pass:e,epoch:n,dx:0,dy:0,dz:0,dyaw:0,vx:0,vy:0,vz:0,vyaw:0,...u,hx:0,hy:0,hz:0,stillMs:0,stopFound:!1};if(t===void 0||t.epoch!==n)return l;let d=JO(i),f=Math.max(0,o),[h,p]=Id(t.dx,t.vx,f,d),[y,S]=Id(t.dy,t.vy,f,d),[b,x]=Id(t.dz,t.vz,f,d),[R,A]=Id(t.dyaw,t.vyaw,f,d),E=t.pass!==e&&r!==void 0,P=E?r.before:s,k=E?r.after:s,M={x:P.pose.x-k.pose.x,y:P.pose.y-k.pose.y,z:P.pose.z-k.pose.z,yaw:vs(P.pose.yaw-k.pose.yaw)},B={vx:P.rate.vx-k.rate.vx,vy:P.rate.vy-k.rate.vy,vz:P.rate.vz-k.rate.vz,vyaw:P.rate.vyaw-k.rate.vyaw},K={pose:{...s.pose,x:s.pose.x+M.x,y:s.pose.y+M.y,z:s.pose.z+M.z},rate:{vx:s.rate.vx+B.vx,vy:s.rate.vy+B.vy,vz:s.rate.vz+B.vz,vyaw:s.rate.vyaw+B.vyaw}},j=E?ZO(t,B)||t.stopFound&&t.stillMs>0:t.stopFound,L=QO(t,{...t,pass:e,dx:h,dy:y,dz:b,dyaw:R,vx:p,vy:S,vz:x,vyaw:A,stopFound:j},K,s.rate,c),se={dx:L.dx+M.x,dy:L.dy+M.y,dz:L.dz+M.z,dyaw:vs(L.dyaw+M.yaw)};if(Math.hypot(se.dx,se.dy,se.dz)>a)return l;let v={vx:L.vx+B.vx,vy:L.vy+B.vy,vz:L.vz+B.vz,vyaw:L.vyaw+B.vyaw};return eI({...L,...se,...v,...u},s.rate,f)}function ZO(t,e){return e.vx*t.hx+e.vy*t.hy+e.vz*t.hz>Rt.SEAT_MOVING_UNITS_PER_MS}function QO(t,e,n,r,s){let o={x:t.hx,y:t.hy,z:t.hz},i=R=>R.x*o.x+R.y*o.y+R.z*o.z,a=i({x:n.rate.vx,y:n.rate.vy,z:n.rate.vz}),c=n.pose,l=i({x:c.x-t.ax,y:c.y-t.ay,z:c.z-t.az})+i({x:e.dx-t.dx,y:e.dy-t.dy,z:e.dz-t.dz}),d=i({x:r.vx,y:r.vy,z:r.vz})<0,f=s!==void 0&&i({x:s.vx,y:s.vy,z:s.vz})>Rt.SEAT_MOVING_UNITS_PER_MS,h=i({x:t.dx,y:t.dy,z:t.dz})>0,p=e.stopFound&&f&&h;if(t.stillMs>=Rt.SEAT_HOLD_MS||d&&!p)return e;let S=a+i({x:e.vx,y:e.vy,z:e.vz});if(l>=0&&S>=0)return e;let b=Math.max(0,-l),x=-S;return{...e,dx:e.dx+b*o.x,dy:e.dy+b*o.y,dz:e.dz+b*o.z,vx:e.vx+x*o.x,vy:e.vy+x*o.y,vz:e.vz+x*o.z}}function eI(t,e,n){let r=e.vx+t.vx,s=e.vy+t.vy,o=e.vz+t.vz,i=Math.hypot(r,s,o);return i>Rt.SEAT_MOVING_UNITS_PER_MS?{...t,hx:r/i,hy:s/i,hz:o/i,stillMs:0}:{...t,stillMs:t.stillMs+n}}function tI(t){if(!(t===void 0||typeof t.inMoveX!="number"))return{moveX:vt(t.inMoveX),moveY:vt(t.inMoveY),moveZ:vt(t.inMoveZ),yaw:vt(t.inYaw),pitch:vt(t.inPitch),buttons:vt(t.inButtons)}}var S_=1e3/60,nI=S_,rI=0,vt=t=>typeof t=="number"&&Number.isFinite(t)?t:rI;function x_(t){let e={status:t.enabled?We.LOADING:We.OFF,matched:0,replayed:0,peakResimMs:0,lastResimMs:0,slowResims:0,fallbacks:0,recoveries:0},n=null,r=null,s=0,o=0,i=new Map,a,c=t.state,u=new Map,l=x=>{e.status=x,n?.stop(x),n=null},d=()=>{if(r!==null||t.loadCore===void 0){t.loadCore===void 0&&(e.status=We.UNAVAILABLE);return}r=t.loadCore().then(x=>{if(e.status!==We.LOADING)return;if(!Wx(x))return l(We.SELF_TEST);let R=Nc(c.physDesc);if(R===null)return l(We.MISMATCH);let A=t.staticWorld();n=new Ad(x,{desc:R,staticWorld:{boxes:A.boxes.map(E=>[...E]),ramps:A.ramps.map(E=>[...E])},physicsHash:c.physics??"",tickHz:t.tickHz(),budgetMs:t.budgetMs,remoteStep:t.remoteStep?.(),bodyRule:t.bodyRule,...t.headSlide===void 0?{}:{headSlide:t.headSlide},kinematicRule:t.kinematicRule,...t.lifts===void 0?{}:{lifts:t.lifts},seatRule:t.seatRule,seatPose:t.seatPose,contactPass:t.contactPass,...t.clock===void 0?{}:{clock:t.clock}}),n.predicting||l(n.status)}).catch(()=>l(We.UNAVAILABLE))},f=()=>{let x=c.entities??new Map,R=j=>c.shapes?.get(j)?.data,A=[],E=[],P=j=>c.bodies?.has(j)===!0;for(let[j,L]of c.bodies??[]){let se=L.desc===void 0||L.desc===""?null:Bx(L.desc,R),v=x.get(j);if(v===void 0||t.motionKnown?.(j)===!1){let W=u.get(j)??(v===void 0?[0,0,0]:[v.x,v.y,v.z]);E.push({key:j,x:W[0],y:W[1],z:W[2],radius:se===null?0:Bc(se)});continue}u.set(j,[v.x,v.y,v.z]);let $=new Array(15),G={x:v.x,y:v.y,z:v.z,qx:vt(v.qx),qy:vt(v.qy),qz:vt(v.qz),qw:vt(v.qw),lvx:vt(v.lvx),lvy:vt(v.lvy),lvz:vt(v.lvz),avx:vt(v.avx),avy:vt(v.avy),avz:vt(v.avz),sleep:v.sleep===!0,rest:vt(v.rest)};Ix(G,$,0),A.push({key:j,desc:se,row:$,epoch:v.epoch})}for(let j of u.keys())c.bodies?.has(j)!==!0&&u.delete(j);let k=[];for(let[j,L]of c.joints??[])try{k.push({key:j,desc:JSON.parse(L.desc),motor:L.motor===""?null:JSON.parse(L.motor)})}catch{}let M=[],B=new Set,K=t.ownId();for(let[j,L]of x){if(L.owner===""||B.has(L.owner)||jr(L)||P(j)||c.players?.has(L.owner)!==!0)continue;B.add(L.owner);let se={...L};M.push({key:j,x:L.x,y:L.y,z:L.z,vx:L.vx,vy:L.vy,vz:L.vz,epoch:L.epoch,own:j===K,input:tI(c.players?.get(L.owner)),body:se})}return{tick:c.keyframe??0,ack:t.acked(),bodies:A,outside:E,joints:k,seats:M}},h=null,p=0,y=t.clock??(()=>performance.now()),S=()=>{let x=h;h=null,p=0,x!==null&&b(x)},b=x=>{if(n===null)return;for(let[A,E]of t.ownPath?.()??[])i.set(A,E);let R=n.adopt(x.keyframe,x.sent,A=>i.get(A)?.p,x.now,A=>i.get(A)?.v);R.kind==="match"&&e.matched++,R.kind==="replay"&&e.replayed++,R.kind==="replay"&&(e.lastResimMs=R.ms,R.ms>S_&&e.slowResims++),e.peakResimMs=Math.max(e.peakResimMs,R.ms),e.fallbacks=n.fallbacks,e.recoveries=n.recoveries,n.stopped?l(n.status):e.status=n.status,o=x.sent};return{status:e,onState(x){if(e.status===We.OFF)return;let R=c.keyframe??0;if(R===0||(c.physDesc??"")==="")return;if(n===null){d();return}if(R===s||c.tick!==R)return;s=R;let A={keyframe:f(),sent:t.sent(),now:x};if(p>=nI){h=A;return}let E=y();b(A),p+=y()-E},settle:S,afterSend(x,R){S();let A=t.sent(),E=a??x,P=A-o;for(let k=1;k<=P;k++){let M=k/P;if(x!==void 0&&E!==void 0){let B=[E.p[0]+(x.p[0]-E.p[0])*M,E.p[1]+(x.p[1]-E.p[1])*M,E.p[2]+(x.p[2]-E.p[2])*M];i.set(o+k,{p:B,v:x.v})}n?.advance(o+k,R)}o=A,a=x;for(let k of i.keys())k<A-256&&i.delete(k)},draw(x,R){return S(),n===null||!n.draws(x)?null:n.draw(x,R)},dispose(){n?.stop(We.OFF),n=null}}}Pt();var Nd={min:-1,max:1,bits:16,mode:"clamp"},Ki={min:-64,max:64,bits:16,mode:"clamp"},__=zt({moveX:Y.float32().default(0),moveY:Y.float32().default(0),moveZ:Y.float32().default(0),yaw:Y.float32().default(0),pitch:Y.float32().default(0),buttons:Y.number().default(0),tick:Y.number().default(0)},"AuthorityInput"),sI=1,R_=t=>({kind:Y.string().default(""),owner:Y.string().default(""),x:t(Y.float32().default(0)),y:t(Y.float32().default(0)),z:t(Y.float32().default(0)),vx:t(Y.float32().default(0)),vy:t(Y.float32().default(0)),vz:t(Y.float32().default(0)),yaw:t(Y.float32().default(0)),hp:Y.number().default(0),flags:Y.number().default(0),epoch:t(Y.number().default(0)),data:Y.string().default(""),t0:Y.number().default(0),g:Y.float32().default(0),src:Y.string().default(""),pitch:t(Y.float32().default(0)),duck:t(Y.float32().default(0)),mstate:t(Y.number().default(0)),cap:Y.float32().default(1),spin:t(Y.float32().default(0)),fuel:t(Y.float32().default(0)),qx:t(Y.quantized(Nd).optional()),qy:t(Y.quantized(Nd).optional()),qz:t(Y.quantized(Nd).optional()),qw:t(Y.quantized(Nd).optional()),lvx:t(Y.quantized(Ki).optional()),lvy:t(Y.quantized(Ki).optional()),lvz:t(Y.quantized(Ki).optional()),avx:t(Y.quantized(Ki).optional()),avy:t(Y.quantized(Ki).optional()),avz:t(Y.quantized(Ki).optional()),sleep:t(Y.boolean().optional()),rest:t(Y.number().optional())}),oI=zt(R_(t=>t),"AuthorityEntity"),iI=zt(R_(t=>t.view(sI)),"AuthorityEntity"),aI=zt({type:Y.string().default(""),kind:Y.string().default(""),colliders:Y.string().default(""),desc:Y.string().optional()},"AuthorityBody"),cI=zt({data:Y.string().default("")},"AuthorityShape"),uI=zt({desc:Y.string().default(""),motor:Y.string().default("")},"AuthorityJoint"),lI=zt({name:Y.string().default(""),uid:Y.string().default(""),team:Y.string().default(""),connected:Y.boolean().default(!0),avatarUrl:Y.string().default(""),seqBase:Y.number().default(0),inMoveX:Y.float32().optional(),inMoveY:Y.float32().optional(),inMoveZ:Y.float32().optional(),inYaw:Y.float32().optional(),inPitch:Y.float32().optional(),inButtons:Y.number().optional(),inRep:Y.number().optional(),inStarve:Y.number().optional(),inBuf:Y.number().optional()},"AuthorityPlayer"),E_={players:Y.map(lI),entities:Y.map(oI),tick:Y.number().default(0),clockOrigin:Y.float64().default(0),preset:Y.string().default(""),moduleSha:Y.string().default(""),tickOrigin:Y.float64().default(0),physics:Y.string().optional(),lengthUnit:Y.float32().optional(),bodies:Y.map(aI).optional(),physDesc:Y.string().optional(),keyframe:Y.number().optional(),shapes:Y.map(cI).optional(),joints:Y.map(uI).optional(),lifts:Y.string().optional(),matchKey:Y.string().optional()},CV=zt(E_,"AuthorityRoomState"),OV=zt({...E_,entities:Y.map(iI).view()},"AuthorityRoomState");var dI=(t,e)=>t+Math.atan2(Math.sin(e-t),Math.cos(e-t)),fI=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n,z:t.z+(e.z-t.z)*n,yaw:t.yaw+(e.yaw-t.yaw)*n,pitch:t.pitch+(e.pitch-t.pitch)*n,duck:t.duck+(e.duck-t.duck)*n}),Bd=class{constructor(){m(this,"rings",new WeakMap)}push(e,n,r,s,o=0){let i=this.rings.get(e);i===void 0&&(i=[],this.rings.set(e,i));let a=i.at(-1);if(a!==void 0&&n<=a.t)return;let c=a!==void 0&&a.life===o,u=c?dI(a.pose.yaw,r.yaw):r.yaw;c&&n-a.t>s*1.5&&i.push({t:n-s,life:o,pose:a.pose}),i.push({t:n,life:o,pose:{...r,yaw:u}}),i.length>80&&i.splice(0,i.length-80)}at(e,n){let r=this.rings.get(e);if(r===void 0||r.length===0)return;let s=r[0],o=r.at(-1);if(n<=s.t)return s.pose;if(n>=o.t)return o.pose;let i=r.length-2;for(;i>0&&r[i].t>n;)i--;let a=r[i],c=r[i+1];return a.life!==c.life?a.pose:fI(a.pose,c.pose,(n-a.t)/(c.t-a.t))}forget(e){this.rings.delete(e)}};var gt={On:"on",Off:"off"};var LV={[Wn.Shooter]:{repeat:gt.On},[Wn.Platformer]:{repeat:gt.On},[Wn.VehicleArena]:{repeat:gt.Off},[Wn.PhysicsSandbox]:{repeat:gt.On},[Wn.Party]:{repeat:gt.On}},FV={repeat:gt.On};var k_=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);function A_(t){let e;try{e=JSON.parse(t)}catch{return gt.On}let n=k_(e)?e.inputs:void 0;return k_(n)&&n.repeat===gt.Off?gt.Off:gt.On}var P_={IDLE_SEAT_S:1800,IDLE_SEAT_MIN_S:30,IDLE_SEAT_MAX_S:86400,ROOM_AGE_S:86400,ROOM_AGE_MIN_S:60,ROOM_AGE_MAX_S:604800},VV={idleSeatS:P_.IDLE_SEAT_S,maxRoomAgeS:P_.ROOM_AGE_S};var f3={MAX_ENTITIES:256,MAX_HANDOFF_CHARS:256*1024,MAX_ROOM_ENTITIES:1024,MAX_OUTPUT_BYTES:32*1024,MAX_EVENTS_PER_TICK:64,MAX_ENTITY_DATA_BYTES:256,MAX_ENTITY_ID_CHARS:64,MAX_KIND_CHARS:64,MAX_SESSION_ID_CHARS:64,MAX_ABS:1e9,MASK_LIMIT:16777216,MAX_EPOCH:2**32-1,MAX_PROJECTILE_TICK:TS,MAX_PROJECTILE_G:wc,MAX_LAUNCH_UPDATES:224,MAX_LAUNCH_BYTES:28*1024,MAX_EVENT_TYPE_CHARS:Xt.MAX_EVENT_TYPE_CHARS,MAX_EVENT_BYTES:Xt.MAX_EVENT_BYTES,MAX_JSON_DEPTH:Xt.MAX_JSON_DEPTH,MAX_JSON_NODES:Xt.MAX_JSON_NODES,MAX_PLAYERS:Xt.ROOM_MAX_CLIENTS,MAX_PHYS_COMMANDS:256,MAX_PHYS_BYTES:32*1024,MAX_PHYSICS_OUTPUT_BYTES:64*1024,MAX_PHYSICS_WORLD_BOXES:32768,MAX_PHYSICS_WORLD_RAMPS:4096,MAX_WORLD_TEXT_CHARS:1245196};function Xi(t){return{moveX:Hn(t.moveX),moveY:Hn(t.moveY),moveZ:Hn(t.moveZ),yaw:Rs(t.yaw)??0,pitch:Rs(t.pitch)??0,buttons:fo(t.buttons)}}var p3=2**31-1;var S3=Ss.INPUT_REPEAT_MAX_MS,x3=Ss.INPUT_REPEAT_RUN_MS;function v_(t,e,n,r=gt.On){return r===gt.Off?t:Math.max(t,Math.min(t+C_(e),n))}function M_(t,e,n=gt.On){return n===gt.Off?t:t+C_(e)}var pI=(t,e,n)=>e<=n?e:Math.min(t,n),C_=t=>typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;function O_(){return{shown:0,heldFrom:null}}function I_(t,e,n,r,s){let o=pI(t.shown,e,n);return o<=t.shown?(o<t.shown&&(t.heldFrom=null),t.shown=o,o):o===n||n-(o+1)<r||s?(t.heldFrom=null,t.shown=o,o):(t.heldFrom??(t.heldFrom=n),n-t.heldFrom<r?t.shown:(t.shown=o,o))}var hI=.03,mI=1,T_=.5;function D_(){return{seenRuns:null,owedMs:0,accMs:0,aheadMs:0}}function N_(t,e,n,r,s=gt.On){if(s===gt.Off||typeof e!="number"||!Number.isFinite(e))return;let o=t.seenRuns!==null&&e>t.seenRuns;if(t.seenRuns=e,!o||!(r>0))return;(typeof n=="number"&&Number.isFinite(n)?n:0)<=mI&&(t.owedMs=Math.max(t.owedMs,r))}function B_(t,e,n,r,s){let o=r>0?n.accMs/r:0;return{raw:t+e+T_*o,at:s+T_*n.aheadMs}}function L_(t,e,n){if(!(n>0)||!(e>0)||t.owedMs<=0)return 0;let r=Math.min(t.owedMs,e*hI);t.owedMs-=r,t.accMs+=r,t.aheadMs+=r;let s=Math.floor(t.accMs/n+.5);return t.accMs-=s*n,s}Pt();var V_=1,H_=1200,om=8,yI=170,gI=3,$_=32,im=8;var bI=5e3,wI=32,SI=32,xI=4,_I=1024,Po=1e3,j_=2e3,W_=250,Ld=50,q_=32,G_=20,Y_=65536,K_=250,Fd=2,X_=3,RI=1e3,EI=6e4,J_=3e4;function Z_(t,e){let n=Math.min(EI,RI*2**Math.min(t,16));return n/2+n/2*e}var To={Bind:"__fast",Off:"__fast:off",Again:"__fast:again",On:"__fast:on"},Q_={Uplink:1,Snapshot:2},Te={Oversized:"oversized",Truncated:"truncated",Trailing:"trailing",Version:"version",Kind:"kind",Session:"session",Key:"key",Count:"count",Fresh:"fresh",Actions:"actions",Flags:"flags",Order:"order",Field:"field",Ahead:"ahead",Fragment:"fragment",Mismatch:"mismatch",Duplicate:"duplicate",Keyframe:"keyframe",Body:"body",Base:"base",Stale:"stale"};var eR=29,F_=29,zd=24,am=1,cm=2,um=4,E3=am|cm|um,z_=255,tR=10,kI=4+zd,zc=4294967295,nR=65536,rm=1;var lm=t=>({ok:!0,value:t}),kn=t=>({ok:!1,fault:t}),rR=(t,e)=>Math.ceil(t*(Number.isFinite(e)&&e>0?e:0)/1e3),Ao=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function Uc(t){return Math.min($_,Math.max(gI,rR(yI,t)))}function sR(t){return eR+im*(tR+zd)+Uc(t)*kI}var Vc=t=>rR(bI,t);function AI(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function dm(t){return/^(?:[0-9a-fA-F]{2})*$/.test(t)?Uint8Array.from(t.match(/../g)??[],e=>Number.parseInt(e,16)):new Uint8Array(0)}var PI=t=>typeof t=="string"&&t.length===2*om&&/^[0-9a-f]+$/.test(t),TI=(t,e)=>(e.buttons&~(t?.buttons??0))!==0,vI=t=>[t.moveX,t.moveY,t.moveZ,t.yaw,t.pitch].every(e=>typeof e=="number"&&Number.isFinite(Math.fround(e)))&&Ao(t.buttons,zc),MI=t=>Ao(t.seq,zc)&&t.seq>=1&&Ao(t.tick,nR-1)&&Ao(t.render,zc)&&vI(t.input),CI=t=>t.reduce((e,n)=>Math.max(e,n.render),0),OI=(t,e)=>e.render===0||t-e.render>=z_?z_:t-e.render;function II(t){let{window:e,actions:n}=t;if(!Ao(t.sid,zc)||!PI(t.key)||!Ao(t.ackSnap,zc))return!1;if(e.length===0)return t.fresh===0&&n.length===0;if(e.length>$_||n.length>im||!Ao(t.fresh,e.length)||t.fresh<1||![...n,...e].every(MI))return!1;let r=e.every((o,i)=>i===0||o.seq===e[i-1].seq+1),s=n.every((o,i)=>o.seq<(i+1<n.length?n[i+1].seq:e[0].seq));return r&&s}function sm(t,e,n){return t.setFloat32(e,n.moveX,!0),t.setFloat32(e+4,n.moveY,!0),t.setFloat32(e+8,n.moveZ,!0),t.setFloat32(e+12,n.yaw,!0),t.setFloat32(e+16,n.pitch,!0),t.setUint32(e+20,n.buttons,!0),e+zd}var U_=t=>{let e=new Uint8Array(zd);return sm(new DataView(e.buffer),0,t),AI(e)};function DI(t,e){if(t===null)return 0;let n=U_(t.input)===U_(e.input)?am:0;return e.tick===t.tick?n|=cm:e.tick===(t.tick+1)%nR&&(n|=um),n}function fm(t){if(!II(t))return kn(Te.Field);let e=new Uint8Array(H_),n=new DataView(e.buffer);e[0]=V_,e[1]=Q_.Uplink,n.setUint32(2,t.sid,!0),e.set(dm(t.key),6),n.setUint32(14,t.ackSnap,!0),n.setUint32(18,t.window.at(-1)?.seq??0,!0),e[22]=t.window.length,e[23]=t.fresh,e[24]=t.actions.length;let r=CI(t.window);n.setUint32(25,r,!0);let s=eR;for(let o of t.actions)n.setUint32(s,o.seq,!0),n.setUint16(s+4,o.tick,!0),n.setUint32(s+6,o.render,!0),s=sm(n,s+tR,o.input);return t.window.forEach((o,i)=>{let a=DI(i===0?null:t.window[i-1],o);e[s]=a,s+=1,(a&(cm|um))===0&&(n.setUint16(s,o.tick,!0),s+=2),e[s]=OI(r,o),s+=1,(a&am)===0&&(s=sm(n,s,o.input))}),lm(e.slice(0,s))}function NI(t,e,n){return t.length>H_?Te.Oversized:t.length<2?Te.Truncated:t[0]!==V_?Te.Version:t[1]!==e?Te.Kind:t.length<n?Te.Truncated:null}function oR(t,e){let n=t.slice(-Uc(e.tickHz)),r=n.length>0?n[0].seq:Number.POSITIVE_INFINITY,s=t.filter((o,i)=>o.seq>e.inputAck&&o.seq<r&&TI(i>0?t[i-1].input:null,o.input)).slice(0,im);return{sid:e.sid,key:e.key,ackSnap:e.ackSnap,fresh:Math.min(e.fresh,n.length),actions:s,window:n}}var BI=t=>[...t].sort((e,n)=>e.key-n.key);var k3=new Uint8Array(4096);function LI(t,e){let n=NI(t,Q_.Snapshot,F_);if(n!==null)return kn(n);let r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.getUint32(2,!0)!==e)return kn(Te.Session);let s=r.getUint32(6,!0),o=r.getUint32(10,!0),i=t[22],a=t[23],c=t[24];if(c<1||c>SI||a>=c)return kn(Te.Fragment);if(!((i&~rm)===0&&i===rm==(o===0))||s<1||o>=s)return kn(Te.Keyframe);let l=t.slice(F_);return lm({snap:s,base:o,tick:r.getUint32(14,!0),inputAck:r.getUint32(18,!0),sent:r.getUint32(25,!0),keyframe:i===rm,frag:a,frags:c,chunk:l})}function FI(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<2)return kn(Te.Body);let n=e.getUint16(0,!0),r=2,s=[];for(let a=0;a<n;a+=1){if(r+2>t.length)return kn(Te.Body);let c=e.getUint16(r,!0);if(a>0&&c<=s[a-1])return kn(Te.Body);s.push(c),r+=2}if(r+2>t.length)return kn(Te.Body);let o=e.getUint16(r,!0);r+=2;let i=[];for(let a=0;a<o;a+=1){if(r+4>t.length)return kn(Te.Body);let c=e.getUint16(r,!0),u=e.getUint16(r+2,!0);if(u>_I||r+4+u>t.length||a>0&&c<=i[a-1].key)return kn(Te.Body);i.push({key:c,bytes:t.slice(r+4,r+4+u)}),r+=4+u}return r===t.length?lm({removed:s,records:i}):kn(Te.Body)}function zI(t,e){let n=new Set(e.removed),r=new Map(t.filter(s=>!n.has(s.key)).map(s=>[s.key,s]));for(let s of e.records)r.set(s.key,s);return BI([...r.values()])}var iR=()=>({partials:[],history:[],newest:0}),UI=(t,e)=>t.base===e.base&&t.tick===e.tick&&t.inputAck===e.inputAck&&t.sent===e.sent&&t.keyframe===e.keyframe&&t.frags===e.frags;function aR(t,e,n){let r=LI(e,n);if(!r.ok)return{rx:t,applied:null,fault:r.fault};let s=r.value;if(s.snap<=t.newest)return{rx:t,applied:null,fault:Te.Stale};let o=t.partials.find(u=>u.snap===s.snap);if(o!==void 0&&!UI(o,s))return{rx:t,applied:null,fault:Te.Mismatch};if(o?.chunks[s.frag])return{rx:t,applied:null,fault:Te.Duplicate};let i=o??{snap:s.snap,base:s.base,tick:s.tick,inputAck:s.inputAck,sent:s.sent,keyframe:s.keyframe,frags:s.frags,chunks:Array(s.frags).fill(null)},a={...i,chunks:i.chunks.map((u,l)=>l===s.frag?s.chunk:u)},c=t.partials.filter(u=>u.snap!==s.snap);if(a.chunks.some(u=>u===null)){let u=[...c,a].sort((l,d)=>l.snap-d.snap).slice(-xI);return{rx:{...t,partials:u},applied:null}}return VI({...t,partials:c},t,a)}function VI(t,e,n){let r=t.partials.length===e.partials.length?e:t,s=FI(HI(n.chunks));if(!s.ok)return{rx:r,applied:null,fault:Te.Body};let o=n.keyframe?null:e.history.find(u=>u.snap===n.base);if(o===void 0)return{rx:r,applied:null,fault:Te.Base};if(n.keyframe&&s.value.removed.length>0)return{rx:r,applied:null,fault:Te.Body};let i=zI(o?.records??[],s.value),a=[...e.history,{snap:n.snap,tick:n.tick,inputAck:n.inputAck,sent:n.sent,records:i}].slice(-wI);return{rx:{partials:t.partials.filter(u=>u.snap>n.snap),history:a,newest:n.snap},applied:n.snap}}function HI(t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}var Ht={Entity:1,Seat:2},_e={F32:"f32",U32:"u32",U16:"u16",Orientation:"q-orientation",Velocity:"q-velocity",Flag:"flag"},$I=[["x",_e.F32],["y",_e.F32],["z",_e.F32],["vx",_e.F32],["vy",_e.F32],["vz",_e.F32],["yaw",_e.F32],["pitch",_e.F32],["duck",_e.F32],["spin",_e.F32],["fuel",_e.F32],["epoch",_e.U32],["mstate",_e.U32],["qx",_e.Orientation],["qy",_e.Orientation],["qz",_e.Orientation],["qw",_e.Orientation],["lvx",_e.Velocity],["lvy",_e.Velocity],["lvz",_e.Velocity],["avx",_e.Velocity],["avy",_e.Velocity],["avz",_e.Velocity],["sleep",_e.Flag],["rest",_e.U16]],jI=[["inMoveX",_e.F32],["inMoveY",_e.F32],["inMoveZ",_e.F32],["inYaw",_e.F32],["inPitch",_e.F32],["inButtons",_e.U32],["inRep",_e.U32],["inStarve",_e.U32],["inBuf",_e.U32],["inAck",_e.U32]],WI=64,Ji=2,pm=4;var hm=65534,qI=hm/2,GI={[_e.Orientation]:1,[_e.Velocity]:64},Ud=()=>({x:0,y:0,z:0,vx:0,vy:0,vz:0,yaw:0,pitch:0,duck:0,spin:0,fuel:0,epoch:0,mstate:0,qx:0,qy:0,qz:0,qw:0,lvx:0,lvy:0,lvz:0,avx:0,avy:0,avz:0,sleep:!1,rest:0}),Vd=()=>({inMoveX:0,inMoveY:0,inMoveZ:0,inYaw:0,inPitch:0,inButtons:0,inRep:0,inStarve:0,inBuf:0,inAck:0});var YI=(t,e)=>-t+e/hm*(2*t),KI=t=>t===Ht.Entity?$I:t===Ht.Seat?jI:null;var uR={f32:4,u32:4,u16:2,"q-orientation":2,"q-velocity":2,flag:0},XI=255,JI=4,ZI=32,QI=new Uint8Array(Ji+XI+pm+ZI*JI),T3=new DataView(QI.buffer);var v3=new TextEncoder;function e1(t,e,n){if(e+uR[n]>t.byteLength)return{ok:!1,fault:Te.Truncated};switch(n){case _e.Flag:return{ok:!0,value:!0};case _e.F32:{let r=t.getFloat32(e,!0);return Number.isFinite(r)&&r!==0?{ok:!0,value:r}:{ok:!1,fault:Te.Field}}case _e.U32:{let r=t.getUint32(e,!0);return r!==0?{ok:!0,value:r}:{ok:!1,fault:Te.Field}}case _e.U16:{let r=t.getUint16(e,!0);return r!==0?{ok:!0,value:r}:{ok:!1,fault:Te.Field}}default:{let r=t.getUint16(e,!0);return r!==qI&&r<=hm?{ok:!0,value:YI(GI[n],r)}:{ok:!1,fault:Te.Field}}}}var t1=new TextDecoder("utf-8",{fatal:!0});function n1(t){let e=t[1];if(Ji+e>t.length)return{ok:!1,fault:Te.Truncated};if(e===0)return{ok:!1,fault:Te.Field};try{let n=t1.decode(t.subarray(Ji,Ji+e));return n.length<=WI?{ok:!0,value:n}:{ok:!1,fault:Te.Field}}catch{return{ok:!1,fault:Te.Field}}}function lR(t){if(t.length<Ji)return{ok:!1,fault:Te.Truncated};let e=KI(t[0]);if(e===null)return{ok:!1,fault:Te.Kind};let n=n1(t);if(!n.ok)return n;let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=Ji+t[1];if(s+pm>t.length)return{ok:!1,fault:Te.Truncated};let o=r.getUint32(s,!0);if(s+=pm,e.length<32&&o>>>e.length)return{ok:!1,fault:Te.Flags};if(t[0]===Ht.Entity){let a=cR(r,s,o,Ud(),e);return a.ok?{ok:!0,value:{kind:Ht.Entity,id:n.value,motion:a.value}}:a}let i=cR(r,s,o,Vd(),e);return i.ok?{ok:!0,value:{kind:Ht.Seat,id:n.value,motion:i.value}}:i}function cR(t,e,n,r,s){let o={},i=e;for(let[a,[c,u]]of s.entries()){if((n&1<<a)===0)continue;let l=e1(t,i,u);if(!l.ok)return l;o[c]=l.value,i+=uR[u]}return i!==t.byteLength?{ok:!1,fault:Te.Trailing}:{ok:!0,value:Object.assign(r,o)}}var r1=4294967295,s1=4,at={Unreachable:"unreachable",Handshake:"handshake",Stall:"stall",Server:"server",NoWebTransport:"no-webtransport",NoRelay:"no-relay",NotOffered:"not-offered"},o1=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function mm(t){if(typeof t!="object"||t===null)return!1;let{sid:e,key:n,url:r}=t,s=typeof n=="string"&&n.length===2*om&&/^[0-9a-f]+$/.test(n);return o1(e,r1)&&s&&typeof r=="string"&&r.length>0}function i1(t,e,n){if(t.length===0)return[];let r=t[t.length-1].seq,s=Math.min(e,r-Uc(n)+1),o=Math.max(s,r-Vc(n)+1);return t.filter(i=>i.seq>=o)}var dR=(t,e)=>`${t}:${e}`;function ym(t){let e=iR(),n=[],r=new Map,s=0,o=!1,i=null,a=null,c=null,u=null,l=typeof t.bind.rev=="number"&&t.bind.rev>=Fd,d=null,f=new Map,h=new Map,p=()=>e.history.at(-1)?.inputAck??0,y=E=>{let P=new Map,k=new Map,M=[];for(let B of E){let K=f.get(B.key),j=K!==void 0&&(K.bytes===B.bytes||u1(K.bytes,B.bytes)),L=j?K.record:c1(B.bytes);P.set(B.key,{bytes:B.bytes,record:L}),L!==null&&(k.set(dR(L.kind,L.id),L),j||M.push(L))}return f=P,h=k,M};function S(E){if(o)return{applied:null};let P=aR(e,E,t.bind.sid);if(e=P.rx,P.fault!==void 0||P.applied===null)return{applied:null,fault:P.fault};let k=e.history.at(-1);if(k===void 0)return{applied:null};let M=x;x=k.snap,a=t.now(),n=i1(n,k.inputAck,t.tickHz);let B={snap:k.snap,tick:k.tick,inputAck:k.inputAck,sent:k.sent,changed:y(k.records)};t.onSnapshot?.(B);let K=B.changed.length>=q_&&(c===null||t.now()-c>=G_);return(k.snap-M>=Y_||K)&&b(),{applied:B}}function b(){if(o||!l||R===null)return;let E=fm({sid:t.bind.sid,key:t.bind.key,ackSnap:e.newest,fresh:0,actions:[],window:[]});if(!E.ok)return;let P=t.now();i??(i=P),c=P,R.send(E.value)}let x=0,R=t.open(t.bind.url,E=>{S(E)},t.bind);if(R===null)return null;let A=sR(t.tickHz);return{bind:t.bind,get rx(){return e},get lastQueued(){return n.at(-1)?.seq??0},get closed(){return o},opening:()=>R.opening?.()===!0,queue(E){o||(n.push({seq:E.seq,tick:E.tick,render:E.render,input:{...E.input}}),s+=1)},flush(){if(o||s===0)return;let E=t.now();for(let M of n.slice(-s))r.set(M.seq,E);a1(r,(n.at(-1)?.seq??0)-Vc(t.tickHz)+1);let P=Uc(t.tickHz),k=n.length-s;for(s=0;k<n.length;){let M=Math.min(k+P,n.length),B=oR(n.slice(0,M),{sid:t.bind.sid,key:t.bind.key,ackSnap:e.newest,inputAck:p(),fresh:M-k,tickHz:t.tickHz});k=M;let K=fm(B);K.ok&&(i??(i=E),c=E,R.send(K.value))}},framed(){let E=t.now(),P=u===null?0:E-u;u=E,!(P<=K_)&&(a!==null&&(a=Math.min(E,a+P)),i!==null&&(i=Math.min(E,i+P)))},keepalive(){if(o||!l)return;let E=a===null?Ld:W_;(c===null||t.now()-c>=E)&&b()},inputAt:E=>n.find(P=>P.seq===E),sentAt:E=>r.get(E),motionOf:(E,P)=>h.get(dR(E,P)),records:()=>[...h.values()],due(){if(o)return null;if(R.failed?.()===!0)return at.Unreachable;let E=R.maxDatagramBytes?.();if(E!==void 0&&E<A)return at.Unreachable;let P=t.now();if(a!==null)return P-a>j_?at.Stall:null;if(i===null)return null;let k=R.opening?.();if(k===!0){let B=Math.max(Po,s1*(t.roundTripMs?.()??0));return P-i>B?at.Handshake:null}k===!1&&(d??(d=P));let M=k===!1?Math.max(i,d??P):i;return P-M>Po?at.Handshake:null},receive:S,close(){o||(o=!0,R.close())}}}function a1(t,e){for(let n of t.keys()){if(n>=e)return;t.delete(n)}}function c1(t){let e=lR(t);return e.ok?e.value:null}var u1=(t,e)=>t.length===e.length&&t.every((n,r)=>n===e[r]);var Hc={Udp:"udp",WebSocket:"websocket"},Zi={Off:"off",NoUdp:"no_udp",NotOffered:"not_offered"},l1=Po,d1={[Zi.Off]:"the game turned the fast channel off",[Zi.NoUdp]:"this platform has no UDP",[Zi.NotOffered]:"the room does not offer the fast channel",unreachable:"fell back, the binding could not be used or its socket failed",handshake:"fell back, no UDP snapshot within 1 s of the first datagram (UDP blocked?)",stall:"fell back, no UDP snapshot for 2 s",server:"fell back, the room closed the channel","no-webtransport":"this browser has no WebTransport","no-relay":"the room has no WebTransport relay"},f1=t=>`genex transport: udp fast@1 ${t}`,Hd=t=>`genex transport: websocket, ${t}: ${d1[t]??"unknown"}`;function fR(){let t=new Set,e=n=>t.has(n)?null:(t.add(n),n);return{observe(n){return n.joinedMs===null?null:n.asked?n.udp?n.fallback!==null?e(Hd(n.fallback)):n.url!==null?n.snapshots>0?e(f1(n.url)):null:n.joinedMs>=l1?e(Hd(Zi.NotOffered)):null:e(Hd(Zi.NoUdp)):e(Hd(Zi.Off))},reset(){t.clear()}}}var p1=19,h1=3,m1=31,y1=Object.keys(Ud()),g1=Object.keys(Vd()).filter(t=>t!=="inAck"),b1=t=>t===Ht.Entity?y1:g1,w1=["tick","keyframe"],pR=64;function S1(){let t=[],e=0;return{snapshot(n,r){let s=t.at(-1)?.ack??e;r<=s||(t.push({tick:n,ack:r}),t.length>pR&&(t=t.slice(-pR)))},through(n){let r=0;for(;r<t.length&&t[r].tick<=n;)e=Math.max(e,t[r].ack),r+=1;return r>0&&(t=t.slice(r)),e},reset(n){t=[],e=n}}}function yR(t){let e=globalThis.process?.stderr;e?.write!==void 0?e.write(`${t}
|
|
15
|
+
`):console.info(t)}var x1=(t,e)=>{let n=setInterval(e,t);return n.unref?.(),()=>clearInterval(n)};function _1(t){if(typeof t!="object"||t===null)return null;let e=t,n=e._encoder;return typeof e._lastStamp!="number"||typeof n?.reset!="function"?null:t}function R1(t){let e=t;if(typeof e?._sampleStamp!="function")return()=>0;let n=e;return()=>{let r=n._sampleStamp().stamp;return typeof r=="number"&&Number.isInteger(r)&&r>=0&&r<=4294967295?r:0}}function gR(t){let{room:e,handle:n}=t,r={live:!1,snapshots:0,fallback:t.neverAsked,fallbacks:0,returns:0,transport:Hc.WebSocket,line:null},s=0,o=fR(),i=null,a=null,c=0,u=null,l=null,d=0,f=S1(),h=[],p=null,y=null,S=0,b=t.open===void 0?null:A1(e,()=>u?.client??null),x=t.open===void 0?null:(t.every??x1)(Ld,()=>{u?.client.keepalive(),A?.client.keepalive()}),R=t.random??Math.random,A=null,E=!1,P=0,k=null,M=null,B=_1(n),K=R1(n),j=()=>{if(u!==null)return Math.min(n.sentCount,d);if(l===null)return n.lastProcessed;let ee=n.lastProcessed-l.wsBefore;return ee>0?Math.max(l.ack,l.at+ee):l.ack},L=()=>e.state.players?.get(e.sessionId)?.seqBase??0,se=()=>{!E||t.open===void 0||(k=t.now()+Z_(P,R()),P+=1)},v=ee=>{if(l!==null)return;M!==null&&t.now()-M>=J_&&(P=0),ee===at.Server&&(P=Math.max(P,h1)),M=null,r.fallbacks+=1;let ue=u,Ae=u?.seqBase??L();l={at:n.sentCount,wsBefore:u?.wsBefore??n.sentCount,ack:j(),reason:ee},u?.client.close(),u=null,h=[],r.live=!1,r.fallback=ee,ue!==null&&B!==null&&(B._encoder.reset(),B._lastStamp=ue.stampAtBind);let pt={last:Ae+n.sentCount};e.send(To.Off,pt),b?.release(),se()},$=ee=>{r.fallback===null&&(r.fallbacks+=1),r.fallback=ee},G=ee=>{if(A===null)return;A.client.close(),A=null,$(ee);let ue={last:L()+n.sentCount};e.send(To.Off,ue),se()},W=ee=>{let ue=A;if(ue===null||l===null)return;A=null;let Ae=L(),pt=l.wsBefore+(n.sentCount-l.at);d=j(),f.reset(d),u={client:ue.client,seqBase:Ae,wsBefore:pt,stampAtBind:B?._lastStamp??0},l=null,k=null,M=t.now(),r.live=!0,r.fallback=null,r.fallbacks>0&&(r.returns+=1);let Bt={last:Ae+n.sentCount};e.send(To.On,Bt),ce({...ee,changed:ue.client.records()})},q=ee=>{ee.opening()&&e.ping(ue=>{S=ue})},ae=ee=>{if(t.open===void 0)return;if(P=Math.max(0,P-1),E=!0,A?.client.close(),A=null,l===null&&(r.fallback=null),l??(l={at:0,wsBefore:0,ack:0,reason:at.Unreachable}),h=[],!mm(ee))return $(at.Unreachable),se();a=ee.url;let ue={client:null,applied:0},Ae=ym({bind:ee,tickHz:t.tickHz(),open:t.open,now:t.now,roundTripMs:()=>S,onSnapshot:pt=>{if(u!==null&&u.client===ue.client)return ce(pt);ue.applied+=1,ue.applied>=X_&&W(pt)}});if(Ae===null)return $(t.open.whyNull?.(ee)??at.Unreachable),se();q(Ae),ue.client=Ae,A=ue,k=null,Ae.keepalive()},ce=ee=>{let ue=u;if(ue===null)return;r.snapshots+=1;let Ae=ue.client.motionOf(Ht.Seat,e.sessionId),pt=Ae?.kind===Ht.Seat?Ae.motion.inAck:0,Bt=Math.max(0,Math.min(n.sentCount,pt-ue.seqBase)),_r=-1;if(Bt>d){let Gn=ue.client.sentAt(ue.seqBase+Bt);Gn!==void 0&&(_r=t.now()-Gn),d=Bt}f.snapshot(ee.tick,d),e.clock.sample(ee.sent,_r),b?.write(ee)},ne=ee=>{let ue=ee?.probe===!0;if(t.open===void 0||u!==null||l!==null&&!ue)return;if(!t.stateCurrent()){p=ee;return}if(p=null,ue)return ae(ee);if(r.fallback=null,!mm(ee))return v(at.Unreachable);a=ee.url,E=typeof ee.rev=="number"&&ee.rev>=Fd;let Ae=ym({bind:ee,tickHz:t.tickHz(),open:t.open,now:t.now,roundTripMs:()=>S,onSnapshot:ce});if(Ae===null)return v(t.open.whyNull?.(ee)??at.Unreachable);q(Ae),u={client:Ae,seqBase:L(),wsBefore:n.sentCount,stampAtBind:B?._lastStamp??0},d=0,f.reset(0),r.live=!0,M=t.now();for(let pt of h)Ae.queue({...pt,seq:u.seqBase+pt.seq});h=[],Ae.flush(),Ae.keepalive()},Re=()=>{t.open!==void 0&&u===null&&l===null&&p===null&&t.stateCurrent()&&(y??(y=t.now()),t.now()-y>Po&&(r.fallback=at.NotOffered))},oe=()=>{i===null&&t.stateCurrent()&&e.state.players?.get(e.sessionId)!==void 0&&(i=t.now());let ee=r.snapshots-c;r.transport=r.live&&ee>0?Hc.Udp:Hc.WebSocket,r.returns!==s&&(s=r.returns,o.reset());let ue=r.fallback===at.NotOffered?null:r.fallback,Ae=o.observe({asked:!t.off,udp:t.open!==void 0,joinedMs:i===null?null:t.now()-i,url:a,snapshots:ee,fallback:ue});Ae!==null&&(r.line=Ae,t.log(Ae))};return t.open!==void 0&&(e.onMessage(To.Bind,ee=>ne(ee)),e.onMessage(To.Off,()=>v(at.Server)),e.onStateChange(()=>{p!==null&&t.stateCurrent()&&ne(p)}),B!==null&&E1(e,()=>u!==null)),{status:r,ack:j,settleAck(){return u===null?j():Math.min(j(),f.through(b?.webSocketTick()??Number(e.state.tick??0)))},sent(ee,ue,Ae){if(t.open===void 0||l!==null)return;let pt=K();if(u!==null){u.client.queue({seq:u.seqBase+ee,tick:ue,render:pt,input:Ae});return}h.push({seq:ee,tick:ue,render:pt,input:{...Ae}});let Bt=Vc(t.tickHz());h.length>Bt&&(h=h.slice(-Bt))},flush(){u?.client.flush()},poll(){u?.client.framed();let ee=u?.client.due()??null;ee!==null&&v(ee),u?.client.keepalive(),A?.client.framed();let ue=A?.client.due()??null;ue!==null&&G(ue),A?.client.keepalive(),k!==null&&t.now()>=k&&A===null&&l!==null&&(e.send(To.Again,{}),se()),Re(),oe()},motionKnown(ee){return u===null||u.client.motionOf(Ht.Entity,ee)!==void 0},inputAt(ee){if(u===null)return;let ue=u.client.inputAt(u.seqBase+ee);return ue===void 0?void 0:{...ue.input,tick:ue.tick}},dropped(){u?.client.close(),u=null,A?.client.close(),A=null,k=null,P=0,M=null,E=!1,b?.forget(),l=null,d=0,h=[],p=null,y=null,r.live=!1,r.fallback=t.neverAsked,r.transport=Hc.WebSocket,o.reset(),i=null,a=null,c=r.snapshots},dispose(){x?.(),A?.client.close(),A=null,u?.client.close(),u=null,r.live=!1,b?.dispose()}}}function E1(t,e){let n=t.connection;if(n===void 0)return;let r=n.send.bind(n);n.send=s=>{e()&&s.length>0&&(s[0]&m1)===p1||r(s)}}var k1={...Ud(),...Vd()};function A1(t,e){let n=t.serializer.decoder,r=t.state,s=new WeakMap,o=new Map,i=!1,a=n.triggerChanges,c=Object.getOwnPropertyDescriptor(n,"decode"),u=n.decode,l=x=>{let R=s.get(x),A=e();return R===void 0||A===null?void 0:A.motionOf(R.kind,R.id)},d=()=>{t.state.entities?.forEach((x,R)=>s.set(x,{kind:Ht.Entity,id:R})),t.state.players?.forEach((x,R)=>s.set(x,{kind:Ht.Seat,id:R}))},f=x=>{if(x===r)return!0;let R=s.get(x);return R===void 0?!1:(R.kind===Ht.Entity?t.state.entities?.get(R.id):t.state.players?.get(R.id))===x},h=(x,R,A,E)=>{let P=o.get(x);P===void 0&&(P=new Map,o.set(x,P));let k=P.get(R);k===void 0?P.set(R,{fast:A,ws:x[R]??k1[R]}):k.fast=A,mR(x,R,A,E)},p=()=>{d();for(let[x,R]of o){if(!f(x)){o.delete(x);continue}for(let[A,E]of R)E.ws!==E.fast&&(x[A]=E.ws)}i=!0},y=()=>{if(i){i=!1;for(let[x,R]of o)for(let[A,E]of R)E.ws!==E.fast&&(x[A]=E.fast)}},S=x=>{let R=x.field;if(R===void 0)return!1;let A=o.get(x.ref)?.get(R);return A===void 0?!1:(A.ws=x.value,!0)},b=x=>{if(e()===null)return a?.(x);d();for(let A of x){let E=A.value;if(A.field!==void 0||typeof E!="object"||E===null)continue;let P=l(E);P!==void 0&&hR(E,P,(k,M,B)=>h(k,M,B,null))}let R=x.filter(A=>!S(A));y(),a?.(R)};return Object.defineProperty(n,"triggerChanges",{configurable:!0,get:()=>b,set:x=>{a=x}}),Object.defineProperty(n,"decode",{configurable:!0,writable:!0,value:(...x)=>{e()!==null&&o.size>0&&p();try{return u.apply(n,x)}finally{y()}}}),{webSocketTick(){return Number(o.get(r)?.get("tick")?.ws??t.state.tick??0)},write(x){d();let R=[];for(let E of x.changed){let P=E.kind===Ht.Entity?t.state.entities?.get(E.id):t.state.players?.get(E.id);P!==void 0&&hR(P,E,(k,M,B)=>h(k,M,B,R))}let A=t.state.keyframe===void 0?["tick"]:w1;for(let E of A)h(r,E,x.tick,R);R.length>0&&a?.(R),t.onStateChange.invoke(t.state)},release(){d();let x=[],R=t.state.physics!==void 0;for(let[A,E]of o)if(!(!f(A)||R&&s.get(A)?.kind===Ht.Entity))for(let[P,k]of E)mR(A,P,k.ws,x);o.clear(),x.length!==0&&(a?.(x),t.onStateChange.invoke(t.state))},forget(){o.clear()},dispose(){o.clear(),Object.defineProperty(n,"triggerChanges",{configurable:!0,writable:!0,value:a}),c===void 0?Reflect.deleteProperty(n,"decode"):Object.defineProperty(n,"decode",c)}}}function hR(t,e,n){let r=e.motion;for(let s of b1(e.kind)){let o=r[s];(o===0||o===!1)&&t[s]===void 0||n(t,s,o)}}function mR(t,e,n,r){let s=t[e];s!==n&&(t[e]=n,r?.push({ref:t,refId:t[Q],op:N.REPLACE,field:e,value:n,previousValue:s}))}var bR=new Map,P1="udp:",T1=65535,v1=32,M1=["","/"],C1=t=>t.username===""&&t.password===""&&M1.includes(t.pathname)&&t.search===""&&t.hash==="";function O1(t){let e;try{e=new URL(t)}catch{return null}let n=Number(e.port),r=Number.isInteger(n)&&n>=1&&n<=T1;return e.protocol!==P1||!r||e.hostname===""||!C1(e)?null:{host:e.hostname.replace(/^\[(.*)\]$/,"$1"),port:n}}var wR=({createSocket:t,lookup:e,isIP:n})=>(r,s)=>{let o=O1(r);if(o===null)return null;let i=null,a=!1,c=!1,u=[],l=(h,p)=>{if(c)return;let y=t(p===6?"udp6":"udp4");i=y,y.on("message",S=>s(new Uint8Array(S.buffer,S.byteOffset,S.byteLength))),y.on("error",()=>{}),y.connect(o.port,h,()=>{if(a=!0,!c)for(let S of u)y.send(S);u=[]})},d=n(o.host);return d!==0?l(o.host,d):e(o.host,{all:!0,verbatim:!0},(h,p)=>{if(h!==null||p.length===0)return;let y=(bR.get(o.host)??0)%p.length;bR.set(o.host,y+1),l(p[y].address,p[y].family)}),{send(h){c||(a?i?.send(h):u=[...u,h].slice(-v1))},close(){c||(c=!0,i?.close())}}};function SR(){let t=globalThis.process?.getBuiltinModule,e=t?.("node:dgram"),n=t?.("node:dns"),r=t?.("node:net");if(!(e===void 0||n===void 0||r===void 0))return wR({createSocket:e.createSocket,lookup:n.lookup,isIP:r.isIP})}var I1=64,D1=4,N1="https:",B1=32,L1=/^[0-9a-f]+$/,F1="reliable-only";function xR(t){let e=t.wt;if(typeof e!="object"||e===null)return null;let{url:n,hashes:r}=e;if(typeof n!="string"||!Array.isArray(r)||r.length===0||r.length>D1)return null;let s=a=>typeof a=="string"&&a.length===I1&&L1.test(a);if(!r.every(s))return null;let o;try{o=new URL(n)}catch{return null}let i=o.username===""&&o.password===""&&o.search===""&&o.hash==="";return o.protocol!==N1||o.hostname===""||!i?null:{url:n,hashes:r.map(a=>dm(a))}}function z1(t){return{serverCertificateHashes:t.hashes.map(e=>({algorithm:"sha-256",value:e})),requireUnreliable:!0,allowPooling:!1,congestionControl:"low-latency"}}var U1=t=>t.reliability!==F1;function V1(t){return(t.datagrams.createWritable?.()??t.datagrams.writable)?.getWriter()??null}var $t={Connecting:"connecting",Open:"open",Failed:"failed",Closed:"closed"};function _R(t){let e=(n,r,s)=>{let o=s===void 0?null:xR(s);if(o===null||t===void 0)return null;let i;try{i=new t(o.url,z1(o))}catch{return null}let a=$t.Connecting,c=[],u=null,l=()=>{if(!(a===$t.Closed||a===$t.Failed)){a=$t.Failed,u=null,c=[];try{i.close()}catch{}}},d=(p,y)=>{p.write(y).catch(()=>{})},f=async p=>{for(;;){let y=await p.read();if(y.done)return;a===$t.Open&&r(y.value)}};return i.ready.then(()=>{if(a!==$t.Connecting)return;if(!U1(i))return l();let p=V1(i);if(p===null)return l();a=$t.Open,u=p;for(let y of c)d(p,y);c=[],f(i.datagrams.readable.getReader()).then(l,l)},()=>l()),i.closed.then(l,l),{send(p){a===$t.Open&&u!==null?d(u,p):a===$t.Connecting&&(c=[...c,p].slice(-B1))},close(){if(a===$t.Closed)return;let p=a;if(a=$t.Closed,u=null,c=[],p!==$t.Failed)try{i.close()}catch{}},failed:()=>a===$t.Failed,opening:()=>a===$t.Connecting,maxDatagramBytes(){let p=a===$t.Open?i.datagrams.maxDatagramSize:void 0;return typeof p=="number"?p:void 0}}};return e.whyNull=n=>t===void 0?at.NoWebTransport:xR(n)===null?at.NoRelay:at.Unreachable,e}var gm=t=>typeof t.WebTransport=="function"?t.WebTransport:void 0,RR=(t,e,n)=>_R(gm(globalThis))(t,e,n);RR.whyNull=t=>_R(gm(globalThis)).whyNull?.(t)??at.Unreachable;function ER(t,e=globalThis){return t===!1?{open:void 0,fallback:null}:t!==void 0?{open:t,fallback:null}:gm(e)!==void 0?{open:RR,fallback:null}:{open:void 0,fallback:e.document!==void 0||typeof e.importScripts=="function"?at.NoWebTransport:null}}var kR=100,$d=["x","y","z","yaw"],H1=.001;function AR(t,e,n,r){if(t===void 0)return[0,0,0,0];let s=t.err.map(o=>o*r);return t.k===e?s:t.shift.map((o,i)=>o+s[i]-n[i])}var $1=[1e3,2e3,4e3],PR=8,j1=250,TR=600,W1=["x","y","z","vx","vy","vz","yaw"],jd={Reconnecting:"reconnecting",Reconnected:"reconnected",Disconnect:"disconnect",...Es},q1=new Set(Object.values(jd)),bm={protocol:`[multiplayer] the authority server refused protocol ${4} (code 426) \u2014 this game was built with a @genex-ai/multiplayer that the server no longer serves. Update the package and republish.`,notEntitled:"[multiplayer] server-authoritative rooms are not available for this game (code 402): its owner is not entitled to them. This is final; the session does not retry.",freeQuota:"[multiplayer] no new server-authoritative room for this game (code 429): its owner is on Genex's free tier and has used the free included room time for this period. Rooms already running are not affected; new rooms open again next period, or with Genex Pro."},Wd=t=>t&&typeof t=="object"?t.code:void 0,G1=t=>t&&typeof t=="object"?t.message:void 0,Y1=t=>Wd(t)===fn.ROOM_QUOTA&&G1(t)===A0;function vR(t){throw fc(t)?console.error(bm.protocol):Wd(t)===fn.NOT_ENTITLED?console.error(bm.notEntitled):Y1(t)&&console.error(bm.freeQuota),t}var IR=t=>t.physicsCore!==void 0&&t.predictPhysics!==!1;function K1(){let t=typeof navigator>"u"?"":String(navigator.userAgent??"");return/Mobi|Android|iPhone|iPad/i.test(t)?Pd.mobile:Pd.desktop}async function X1(t){if(t.url)return[t.url];let e=tS(t.regions,t.urls);if(e.length===0)throw new Error("genex multiplayer: `urls` must contain at least one authority server URL");return(await oS(e,t.probe===void 0?{}:{probe:t.probe})).map(r=>r.url)}async function J1(t,e){let n=uS(e);if("refused"in n)throw new TypeError(`genex multiplayer: this room cannot be asked for (${n.refused})`);let r=await X1(t),s=t.capacityRetryMs??$1,o={region:0,refused:0,step:0};for(;;){let i=r[o.region];try{return{room:await NR(new Br(i),t,n),url:i,targets:r}}catch(a){if(n.method===Sr.JoinById){let d=lS(Wd(a),o.region,r.length);d===null&&vR(a),o={region:d,refused:0,step:0};continue}let c=rS(Wd(a));if(c===Ni.NextRegion&&o.region+1<r.length){o={region:o.region+1,refused:0,step:o.step};continue}let u=c===Ni.Capacity?sS(o,r.length,s):null;u===null&&vR(a);let l=u.attempt.waitMs;l>0&&await new Promise(d=>setTimeout(d,l)),o=u.state}}}var DR=t=>ER(t.fast??SR());function NR(t,e,n){let r=DR(e).open===void 0?[]:[dn.FAST,dn.FAST_RETURN],s={...dc(e.room,e.name,e.auth),...n.options,[Wp.CAPS]:IR(e)?[dn.PHYSICS,dn.PHYSICS_PREDICT,dn.INPUT_REPEAT,dn.LIFTS,dn.INPUT_TICK,...r]:[dn.PHYSICS,dn.INPUT_REPEAT,dn.LIFTS,dn.INPUT_TICK,...r],[Wp.SDK]:k0,protocol:4};return n.method===Sr.JoinById?t.joinById(n.roomId,s):n.method===Sr.Create?t.create(co.AUTHORITY,s):t.joinOrCreate(co.AUTHORITY,s)}function Qi(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e.name,r=bc(n);if(r===void 0)return null;let s=Di(n,e.params);return{name:n,definition:r,params:s}}function wm(t,e){let{definition:n,params:r}=t,s=[...n.fields,...n.reads],o=n.fields;return{fields:s,step:(i,a,c,u)=>{let l=n.step(i,a,c,r,e,u);for(let d of o)i[d]=l[d]}}}var Sm=t=>t!==null&&t.definition.world?t.params.world??null:null,fe=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e;function Z1(t){if(typeof t.inMoveX=="number")return{moveX:fe(t.inMoveX,0),moveY:fe(t.inMoveY,0),moveZ:fe(t.inMoveZ,0),yaw:fe(t.inYaw,0),pitch:fe(t.inPitch,0),buttons:fe(t.inButtons,0)}}var xm={body:!1,qx:0,qy:0,qz:0,qw:1,sleep:!1},MR=new Map,CR=2*Math.PI,vo=t=>t-CR*Math.floor((t+Math.PI)/CR),CH=[gn.Predicted,gn.Separate,gn.Timeline],Q1=gn.Predicted,ea=t=>{let e=t;return typeof e.local=="object"&&typeof e.error=="object"&&typeof e.prev=="object"&&typeof e.renderAlpha=="function"?e:null};async function BR(t){let e=await J1(t,t.matchKey===void 0?{}:{matchKey:t.matchKey});return eD(LR(xs(e.room),t,e.url),t,e,!1)}function eD(t,e,n,r){if(e.rejoin===!1)return t;let s=n.targets.filter(o=>o!==n.url);return mS(t,{closed:r,targets:[n.url,...s],join:async(o,i,a)=>{let c=await NR(new Br(o),e,tD(i,a)),u=LR(xs(c),e,o);return await pc(c,hn.firstStateTimeoutMs),u}})}function tD(t,e){return t===Li.Room?{method:Sr.JoinById,roomId:e.roomId,options:{}}:t===Li.Successor?{method:Sr.JoinOrCreate,options:hS({lostRoomId:e.roomId,matchKey:e.matchKey,closed:e.closed})}:{method:Sr.JoinOrCreate,options:e.matchKey===""?{}:{matchKey:e.matchKey}}}function LR(t,e,n){let r=t.state,s=()=>r.entities??MR,o=()=>r.players??MR,i=e.renderDelayMs??Ss.RENDER_DELAY_MS,a=t.input({type:__,mode:"reliable",renderDelay:i}),c=DR(e),u=gR({room:t,handle:a,open:c.open,neverAsked:c.fallback,off:e.fast===!1,log:e.fastLog??yR,now:e.fastClock??(()=>performance.now()),tickHz:()=>X(),stateCurrent:()=>!Jn}),l=null,d=gt.On,f=()=>{let g=r.preset??"";return g!==l&&(l=g,d=A_(g)),d},h=()=>v_(u.ack(),o().get(t.sessionId)?.inRep,a.sentCount,f()),p=g=>a.at(g)??u.inputAt(g),y=O_(),S=()=>{let g=M_(u.ack(),o().get(t.sessionId)?.inRep,f()),_=a.sentCount,T=g<_&&u.inputAt(g+1)!==void 0;return I_(y,g,_,a.replayBufferSize,T)},b=new Map,x=new Proxy(a,{get(g,_){if(_==="lastProcessed")return S();if(_==="pendingCount")return a.sentCount-u.ack();if(_==="at")return p;let T=Reflect.get(g,_,g);if(typeof T!="function")return T;let z=b.get(_);return z===void 0&&(z=T.bind(g),b.set(_,z)),z}}),R=ao.get(t,{mode:"lerp",delay:i}),A={mode:"lerp",fields:["x","y","z"]},E={mode:"lerp",fields:["yaw"],angle:!0};R.attachAll("entities",A),R.attachAll("entities",E),R.attachAll("entities",{mode:"lerp",fields:["pitch"]}),R.attachAll("entities",{mode:"lerp",fields:["duck"]});let P={moveX:0,moveY:0,moveZ:0,yaw:0,pitch:0,buttons:0},k={inputsSent:0,inputsDropped:0,reconciles:0,visibleCorrections:0,correctionBuckets:Od.map(()=>0).concat(0),peakCorrection:0,lastCorrection:0,peakStateCorrection:0,reseeds:0,bodyStates:0,bodySnaps:0,peakBodyCorrection:0,projectilesPredicted:0,projectilesConfirmed:0,projectilesRejected:0,lastProjectileLeadMs:0},M=new Map,B=(g,..._)=>{for(let T of M.get(g)??[])T(..._)},K=!0,j=!1,L=null,se=!0,v=()=>{L?.predicted?.reconciler.dispose(),L=null},$=e.world===void 0?yc:mo(e.world),G="no_entity",W="",q=typeof e.physics=="string"?e.physics:"",ae="",ce=()=>{if(e.predict===!1)return{prediction:null,reason:"off"};if(e.predict)return{prediction:e.predict,reason:""};let g=Qi(r.preset);if(g===null)return{prediction:null,reason:"no_preset"};let _=Sm(g);if(_!==null&&_!==$.hash){let T=`${_}/${$.hash}`;return W!==T&&(W=T,console.warn(`[multiplayer] the room's ${g.name} world (hash ${_}) is not this client's (hash ${$.hash}): your own entity is drawn from the server without prediction. Pass the room module's world to session.setWorld().`)),{prediction:null,reason:"world_mismatch"}}return{prediction:wm(g,$),reason:""}},ne=()=>{let g=[];for(let[_,T]of s())_===L?.id||T.owner===""||jr(T)||r.bodies?.has(_)===!0||!o().has(T.owner)||g.push({id:_,x:T.x,y:T.y,z:T.z,vx:T.vx,vy:T.vy,vz:T.vz,yaw:T.yaw,spin:fe(T.spin,0)});return g},Re=null,oe=()=>{if(e.contacts!==void 0)return null;let g=r.preset??"";return(Re===null||Re.text!==g||Re.hash!==$.hash)&&(Re={text:g,hash:$.hash,contacts:r_(g,$)}),Re.contacts},ee=()=>e.contacts!==void 0||oe()!==null,ue=e.contacts??((g,_)=>oe()?.rule(g,_)),Ae=e.contactPass??(e.contacts===void 0?g=>oe()?.pass(g):void 0),pt=new Td(ue,()=>Ms(ne())),Bt=()=>e.seatDrawing??oe()?.policy.drawing??Q1,_r=e.seatDrawing===void 0||e.seatDrawing===gn.Predicted?qd(ue):null,Gn=()=>ee()?_r:null,Co=()=>Bt()===gn.Predicted?Gn():null;function Ms(g){return oe()===null?g:g.map(_=>({..._,flags:fe(s().get(_.id)?.flags,0)}))}let na=(g,_,T=null)=>{if(L===null||!ee())return null;let z={..._,id:L.id,...oe()===null?{}:{flags:fe(L.entity.flags,0)}},H=Gn(),U=null;H!==null?U=H.apply(g,h(),r.tick??0,z,X(),T):pt.apply(g,h(),z,X());for(let re of Eo)typeof z[re]=="number"&&(_[re]=z[re]);return U};function qd(g){let _=null,T=()=>{let H=r.preset??"";if(_!==null&&_.text===H&&_.hash===$.hash)return _;let U=Qi(H),re=Sm(U),J=U!==null&&(re===null||re===$.hash)?wm(U,$):null;return _={text:H,hash:$.hash,fields:U===null?[]:[...U.definition.fields,...U.definition.reads],step:J===null?void 0:(ge,le,me,wt)=>J.step(ge,Xi({...le}),me,wt)},_},z=()=>{let{fields:H}=T(),U=[];for(let[re,te]of s()){if(re===L?.id||te.owner===""||jr(te)||r.bodies?.has(re)===!0)continue;let J=o().get(te.owner);if(J===void 0)continue;let ge=te,le={x:te.x,y:te.y,z:te.z,vx:te.vx,vy:te.vy,vz:te.vz,yaw:te.yaw,spin:fe(te.spin,0)};for(let me of H)le[me]=fe(ge[me],me==="cap"?1:0);oe()!==null&&(le.flags=fe(te.flags,0)),U.push({id:re,epoch:te.epoch,body:le,input:Z1(J)})}return U};return new Dd({rule:g,pass:Ae,others:z,step:()=>T().step,seatRule:e.seatRule,lifts:()=>{let H=bn();return H===null?null:{lifts:H,starts:ct(),cache:Gd}},remote:()=>{let H=Ls();return{predict:H?.remotePredict??Zt.HOLD,decayMs:H?.remoteDecayMs??xr.DEFAULT_REMOTE_DECAY_MS}},maxAheadMs:()=>(Ls()?.leadMs??xr.DEFAULT_LEAD_MS)+m_})}let An=null,bn=()=>{let g=r.preset??"",_=oe();if(An===null||An.text!==g||An.hash!==$.hash||An.heads!==_){let T=_!==null&&tx(_.policy)?{policy:_.policy,env:_.env}:void 0;An={text:g,hash:$.hash,heads:_,lifts:xx(g,$,T,X())}}return An.lifts},Yn={text:void 0,starts:void 0},ct=()=>{let g=r.lifts;return Yn.text!==g&&(Yn={text:g,starts:_x(g)}),Yn.starts},Kn=new Vi,Gd=new Vi,Wc=g=>{let _=Gn();return ne().map(T=>{let z=_?.poseAt(T.id,g-1),H=fe(s().get(T.id)?.flags,0),U=fe(s().get(T.id)?.duck,0);return z===void 0?{...T,duck:U,flags:H}:{id:T.id,x:z.x,y:z.y,z:z.z,vx:z.vx,vy:z.vy,vz:z.vz,yaw:z.yaw,duck:U,flags:H}})},qc=["x","y","z"],en=["vx","vy","vz"],Pn=(g,_,T,z,H)=>{if(L===null)return null;let U=z,re={id:L.id,x:U.x??0,y:U.y??0,z:U.z??0,vx:U.vx??0,vy:U.vy??0,vz:U.vz??0,yaw:U.yaw??0,duck:U.duck??0,flags:fe(L.entity.flags,0)},J=[...g.heads===void 0?[]:Wc(_),re].sort((le,me)=>le.id<me.id?-1:le.id>me.id?1:0),ge=vc(g,J,T,ct(),H,Kn);for(let le of qc)U[le]=re[le];return g.vehicle&&(U.yaw=re.yaw),{t:ge,mine:re}},bt=Number.NaN,Xr=null,ra=null,Jr=(g,_,T,z,H,U)=>{let re=Gi(r.tick??0,h(),_),te=bn(),J=te===null?null:Pn(te,_,U??re,T,H);e.seatRule?.(T,re,_),g(T,Xi(z),H,J===null?void 0:Mc(J.t,J.mine.id));let ge=J===null?-1:J.t.seats.indexOf(J.mine),le=J===null?null:J.t.report.on[ge]??null,me=na(_,T,le);if(te===null||J===null)return;me!==null&&Ex(te,J.t,ge,me);let wt=T;Xr=le;for(let nn of[...qc,...en])J.mine[nn]=wt[nn]??0;Cc(te,J.t,ct());for(let nn of en)wt[nn]=J.mine[nn]},sa=new Vi,oa=(g,_,T,z,H)=>{let U=bn();U===null||U.policy.platforms.length===0?g(_,T,z):Ax(U,ct(),sa,(re,te)=>g(re,T,z,te),_,H,z)},Cs=g=>{let{prediction:_,reason:T}=ce();if(G=T,!_)return null;let z=_.fields??W1;return{reconciler:R.reconciler(g,{input:x,fields:z,step:(U,re,te)=>{(U.isReplay||Number.isNaN(bt))&&(bt=Gi(r.tick??0,h(),U.tick)-U.tick),Xr=null,Jr(_.step,U.tick,re,te,U.dt,U.tick+bt),ra=Xr}}),fields:z,step:_.step}},Os=()=>{let g=L?.predicted;if(!L||!g)return null;let _=L.entity,T={};for(let U of g.fields)T[U]=fe(_[U],0);let z=a.stepSeconds??g.reconciler.stepMs/1e3,H=new Map;for(let U=h()+1;U<=a.sentCount;U++){let re=p(U);re!==void 0&&(Jr(g.step,U,T,re,z),H.set(U,{p:[T.x??0,T.y??0,T.z??0],v:[T.vx??0,T.vy??0,T.vz??0]}))}return H},Is=g=>{g.predicted&&(k.reseeds++,Oo(g))},Oo=g=>{g.predicted?.reconciler.dispose();let _=Cs(g.entity);if(g.predicted=_,!_)return;let T=_.reconciler.state,z=a.stepSeconds??_.reconciler.stepMs/1e3;bt=Gi(r.tick??0,h(),0);for(let H=h()+1;H<=a.sentCount;H++){let U=p(H);U!==void 0&&Jr(_.step,H,T,U,z)}g.reseeded=!0},ia=(g,_)=>_.owner===t.sessionId&&!jr(_)&&r.bodies?.has(g)!==!0,Zr=g=>s().get(g.id)===g.entity&&ia(g.id,g.entity),Qr=()=>{if(L&&Zr(L)){L.entity.epoch!==L.epoch&&(L.epoch=L.entity.epoch,Is(L));return}if(!(!L&&!se)){v(),se=!1,G="no_entity";for(let[g,_]of s())if(ia(g,_)){L={id:g,entity:_,epoch:_.epoch,predicted:Cs(_),reseeded:!1};return}}},tt=g=>{let _=g.reconciler.state;return g.fields.map(T=>_[T]??0)},Io=(g,_,T)=>{if(g.reconciler.reconcileSeq===T)return;let{place:z,state:H}=o_(g.fields,_,tt(g));k.reconciles++,k.lastCorrection=z,k.peakCorrection=Math.max(k.peakCorrection,z),k.peakStateCorrection=Math.max(k.peakStateCorrection,H);let U=Im();i_(z,U)&&(k.visibleCorrections++,k.correctionBuckets[a_(z,U)]+=1)},Gc=g=>{if(!g.fields.includes("yaw"))return null;let _=ea(g.reconciler),T=_?.local.yaw;return _&&typeof T=="number"?{local:T,error:_.error.yaw??0}:null},Yc=(g,_,T)=>{if(T===null||g.reconciler.reconcileSeq===_)return;let z=ea(g.reconciler),H=z?.local.yaw,U=z?.error.yaw;if(!z||typeof H!="number"||typeof U!="number")return;let re=T.local+T.error-H;(re<-Math.PI||re>=Math.PI)&&(z.error.yaw=vo(re)*(U/re))},Kc=g=>{let _=ea(g.reconciler);if(_===null||Number.isNaN(bt))return null;let T=z=>Object.fromEntries($d.map(H=>[H,fe(z[H],0)]));return{offset:bt,local:T(_.local),error:T(_.error),prev:T(_.prev)}},Xc=(g,_,T,z)=>{if(z===null||g.reconciler.reconcileSeq===_||z.offset===bt)return T;let H=bn(),U=ea(g.reconciler);if(H===null||H.policy.platforms.length===0||U===null)return T;let re=ct(),te=a.sentCount+z.offset+1,J=a.sentCount+bt+1,ge=qe=>({x:qe.x??0,y:qe.y??0,z:qe.z??0,yaw:qe.yaw??0,duck:fe(U.local.duck,0)}),le=Oc(H,ge(z.local),te,re);if(le<0||Oc(H,ge(U.local),J,re)!==le)return T;let me=(qe,wn,er)=>{let Tn=Vh(H.policy,le,ge(qe),wn,er,re);return{...Tn,yaw:H.vehicle?Tn.yaw:qe.yaw??0}},wt=Object.fromEntries($d.map(qe=>[qe,(z.local[qe]??0)+(z.error[qe]??0)])),nn=me(wt,te,J),kt=me(z.prev,te-1,J-1),zo=me(z.local,te,J);for(let qe of $d){if(typeof U.local[qe]!="number")continue;let wn=fe(U.local[qe],0),er=(wt[qe]??0)-wn,Tn=er===0?0:(U.error[qe]??0)/er;U.error[qe]=(nn[qe]-wn)*Tn,U.prev[qe]!==void 0&&(U.prev[qe]=kt[qe])}return g.fields.map((qe,wn)=>$d.includes(qe)?zo[qe]:T[wn]??0)},Ve=g=>{let _=L?.entity===g?L.predicted:null;if(!_||!_.fields.includes("yaw"))return;let T=ea(_.reconciler),z=T?.local.yaw;if(!T||typeof z!="number")return;let H=z+(T.error.yaw??0),U=T.prev.yaw??H;return U+vo(H-U)*T.renderAlpha()},es=D_(),Ds=Number.NaN,Do=g=>{let _=a.stepMs??0,T=o().get(t.sessionId);N_(es,T?.inStarve,T?.inBuf,_,f());let z=Number.isNaN(Ds)?0:g-Ds;return Ds=g,L_(es,z,_)},Xn,Rr=g=>{let _=a.stepMs;if(!_)return 0;if(Xn===void 0)return Xn=g,0;let T=Math.floor((g-Xn)/_);return T>PR?(Xn=g,PR):(Xn+=T*_,T)},No=()=>Gi(r.tick??0,h(),0),Ns=null,Bs=g=>{if(!K)return k.inputsDropped+=g,0;let _=0,T=c_((Ns??No())+a.sentCount+1);for(let z=0;z<g;z++){let H=Xi({...P});Object.assign(a.data,H),a.data.tick=T;let U=a.send();if(U===0){k.inputsDropped++;continue}_++,u.sent(U,T,H)}return u.flush(),k.inputsSent+=_,_},Lt=t.clock,Jc=()=>Lt.lastServerTime()>0?Lt.lastServerTime():performance.now(),Et=()=>Lt.lastServerTime()>0?Lt.serverNow()-i-Lt.smoothedRtt()/2:performance.now()-i,Bo=new WeakMap,Lo=g=>({x:g.x,y:g.y,z:g.z,yaw:g.yaw,pitch:fe(g.pitch,0),duck:fe(g.duck,0)}),Zc=g=>{let _=Jc(),T=Bo.get(g);if(T===void 0){Bo.set(g,{at:_,epoch:g.epoch,pose:Lo(g),respawns:[]});return}T.epoch!==g.epoch&&g.owner!==t.sessionId&&T.respawns.push({from:T.at,at:_,epoch:T.epoch,pose:T.pose}),T.at=_,T.epoch=g.epoch,T.pose=Lo(g)},Qc=g=>{let _=Bo.get(g)?.respawns;if(_===void 0||_.length===0)return;let T=Et();for(;_.length>0&&T>=_[0].at;)_.shift();return _[0]},ts=new Bd,ns=new Set,aa={text:"",k:1},eu=g=>(aa.text!==g&&(aa={text:g,k:Nc(g)?.keyframeTicks??1}),aa.k),Fo={text:"\0",desc:null},Ls=()=>{let g=r.physDesc??"";return Fo.text!==g&&(Fo={text:g,desc:Nc(g)}),Fo.desc},w=()=>e.remoteSamples!=="patch"&&(r.physDesc??"")!=="",C=()=>{if(ns.size===0)return;let g=r.tick??0;if(w()&&g===(r.keyframe??-1)){let T=ad(g,we(),X()),z=1e3/X()*eu(r.physDesc??"");for(let H of ns)ts.push(H,T,Lo(H),z,H.epoch)}ns.clear()},V=Ja(t);V(r).entities.onAdd(g=>{se=!0,Zc(g),ns.add(g),V(g).onChange(()=>{Zc(g),ns.add(g)})}),t.onStateChange(C),V(r).entities.onRemove(()=>{se=!0});let X=()=>a.stepMs?Math.round(1e3/a.stepMs):Ss.TICK_HZ,we=()=>r.tickOrigin??0,pe=()=>vh(Lt.serverNow(),we(),X()),Me=g=>({x:g.x,y:g.y,z:g.z,vx:g.vx,vy:g.vy,vz:g.vz,g:g.g??0,t0:g.t0??0}),ie=g=>ad(g.t0??0,we(),X()),Ne=R.spawns("entities",{owned:g=>jr(g)&&g.src===t.sessionId,correlate:(g,_)=>s().get(g.id)!==_?!1:(ut.delete(g),k.projectilesConfirmed++,k.lastProjectileLeadMs=ie(_)-g.at,!0),spawnTime:ie,ttl:g=>{let _=Math.max(2*g,TR);if(!K)return _;let T=performance.now(),z=T-nt.endedAt<_+nt.ms?nt.ms:0;return _+Math.max(T-ze,z)},onReject:g=>{ut.delete(g),k.projectilesRejected++}}),ze=performance.now(),nt={ms:0,endedAt:0},ut=new Map,Qe=()=>{if(ut.size===0)return;let g=u.settleAck();for(let[_,T]of ut)_.epoch!==a.epoch||_.seq>g||s().has(_.id)||(ut.delete(_),T(),k.projectilesRejected++)},Jn=!1,Zn=()=>{Jn=!1;for(let[g,_]of ut)g.epoch!==a.epoch&&(ut.delete(g),_(),k.projectilesRejected++)};t.onStateChange(()=>{let g=performance.now();(g-ze>nt.ms||g-nt.endedAt>TR+nt.ms)&&(nt={ms:g-ze,endedAt:g}),ze=g,Jn&&Zn(),Qe()});let rt=new Map,Er=()=>{let g=fe(r.lengthUnit,0);return{tickHz:X(),tickOrigin:we(),lengthUnit:g>0?g:1}},Yd=g=>({x:g.x,y:g.y,z:g.z,qx:fe(g.qx,0),qy:fe(g.qy,0),qz:fe(g.qz,0),qw:fe(g.qw,0),lvx:fe(g.lvx,0),lvy:fe(g.lvy,0),lvz:fe(g.lvz,0),avx:fe(g.avx,0),avy:fe(g.avy,0),avz:fe(g.avz,0),sleep:g.sleep===!0,epoch:g.epoch}),tu=()=>{let g=r.bodies;for(let[H,U]of rt)g?.get(H)!==U.descriptor&&rt.delete(H);if(g===void 0||g.size===0)return;let _=Lt.serverNow(),T=Er(),z=r.tick??0;for(let[H,U]of g){let re=s().get(H);if(re===void 0)continue;let te=rt.get(H),J=ES(Yd(re),z);if(te!==void 0&&PS(te.last,J)){te.entity=re;continue}let{drawing:ge,snap:le}=AS(te?.drawing??null,J,_,T);k.bodyStates++,le!==null?k.bodySnaps++:k.peakBodyCorrection=Math.max(k.peakBodyCorrection,Math.hypot(...ge.dp)),rt.set(H,{descriptor:U,entity:re,last:J,drawing:ge,handoff:te?.handoff??new _d})}};t.onStateChange(tu);let Qn=x_({enabled:IR(e),loadCore:e.physicsCore,state:r,sessionId:t.sessionId,staticWorld:()=>$,tickHz:X,sent:()=>a.sentCount,acked:()=>h(),ownId:()=>L?.id,ownPath:Os,bodyRule:e.bodyRule,headSlide:()=>{let g=oe()?.policy;return g?.headFriction===go.Slide?g.propSlide:null},kinematicRule:e.kinematicRule,lifts:()=>{let g=bn();return g===null||g.policy.platforms.length===0?null:{policy:g.policy,starts:ct()}},seatRule:e.seatRule,budgetMs:jx(e.physicsBudgetMs,K1()),contactPass:g=>oe()?.pass(g),motionKnown:g=>u.motionKnown(g),...typeof e.physicsClock=="function"?{clock:e.physicsClock}:{},..._r===null?{}:{seatPose:(g,_)=>{let T=Gn()?.poseAt(g,_);return T===void 0?void 0:{key:g,x:T.x,y:T.y,z:T.z,vx:T.vx,vy:T.vy,vz:T.vz}}},remoteStep:()=>{let g=Qi(r.preset??"");if(g===null)return;let{step:_}=wm(g,$);return(T,z,H,U)=>oa(_,T,Xi({...z}),H,U)}});t.onStateChange(()=>Qn.onState(Lt.serverNow()));let HR=()=>{let g=L?.predicted?.reconciler.state;return g===void 0?void 0:{p:[g.x??0,g.y??0,g.z??0],v:[g.vx??0,g.vy??0,g.vz??0]}},Pm=g=>(!rt.has(g)&&r.bodies?.has(g)===!0&&tu(),rt.get(g)),Kd=(g,_)=>{let T=Er(),z=Lt.serverNow(),H=Qn.draw(g,z),U=_.entity,re=_.descriptor?.kind,te=H===null&&e.kinematicRule!==void 0?$x(e.kinematicRule,g,z,T):null,J=_.handoff.draw(H??te??Ph(_.drawing,z,T),H!==null,U.epoch,z,kd(re),T.lengthUnit),[ge,le,me]=_.last.lv;return{id:g,kind:U.kind,owner:U.owner,x:J.p[0],y:J.p[1],z:J.p[2],yaw:vo(U.yaw),vx:ge*T.lengthUnit,vy:le*T.lengthUnit,vz:me*T.lengthUnit,hp:U.hp,flags:U.flags,epoch:U.epoch,data:U.data,t0:0,g:0,src:"",pitch:0,duck:0,mstate:0,cap:1,spin:0,fuel:0,body:!0,qx:J.q[0],qy:J.q[1],qz:J.q[2],qw:J.q[3],sleep:_.last.sleep,predicted:H!==null}},nu={epoch:-1,seq:0,n:0},Fs=g=>typeof g=="number"&&Number.isFinite(g)?Oe(Math.fround(g)):0,Tm=g=>{let _=Th(g.launch,pe(),X());return{id:g.id,kind:g.kind,owner:"",..._,yaw:0,hp:0,flags:0,epoch:0,data:"",t0:g.launch.t0,g:g.launch.g,src:t.sessionId,pitch:0,duck:0,mstate:0,cap:1,spin:0,fuel:0,...xm}},vm=()=>{let g=new Map;for(let _ of Ne.entries())_.state==="pending"&&_.local&&g.set(_.local.id,_.local);return g};t.onDrop(g=>{u.dropped(),K=!1,Jn=!0,B(jd.Reconnecting,{code:g})}),t.onReconnect(()=>{if(j){t.leave(!0).catch(()=>{});return}(async()=>(await pc(t,hn.firstStateTimeoutMs),!j&&(Jn&&Zn(),L?.predicted&&(L.predicted.reconciler.reset(),k.reseeds++),Xn=void 0,K=!0,B(jd.Reconnected))))()});let Mm=()=>{j=!0,K=!1,u.dispose(),v(),R.dispose(),Qn.dispose()};t.onLeave((g,_)=>{j||(Mm(),B(jd.Disconnect,g,P0(_)))}),t.onMessage("*",(g,_)=>{typeof g=="string"&&(e.onEvent?.(g,_),q1.has(g)||B(g,_))});let $R=g=>{if(!L?.reseeded||L.entity!==g||!L.predicted)return;let _=L.predicted.reconciler.state;return{x:_.x??g.x,y:_.y??g.y,z:_.z??g.z,yaw:_.yaw??g.yaw,pitch:_.pitch??fe(g.pitch,0),duck:_.duck??fe(g.duck,0),epoch:g.epoch}},jR=()=>{if(L===null||L.predicted===null)return null;let g=zm(L.entity);return{id:L.id,x:g.x,y:g.y,z:g.z,vx:0,vy:0,vz:0,yaw:g.yaw}},Cm=g=>{let T=L?.reseeded===!0&&L.predicted===g?1:ea(g.reconciler)?.renderAlpha()??1;return Math.max(0,a.sentCount-h()-1+T)},ru=new Map,tn=0,Om=()=>ee()&&Bt()!==gn.Timeline,Xd=g=>L?.entity!==g&&g.owner!==""&&!jr(g)&&o().has(g.owner),WR=(g,_)=>{let T=ru.get(g);return T!==void 0&&T.lives===_&&tn-T.at<=j1?T:void 0},su=new Map,Jd,ou=new Map,Zd=Number.NaN,ca={tick:Number.NaN,leadMs:Number.NaN},Im=()=>{let g=fe(r.lengthUnit,0);return g>0?g:yS[Qi(r.preset??"")?.name??""]??1},qR=()=>{let g=Co(),_=g?.current??null;if(g===null||_===null||L===null||L.predicted===null)return ca={tick:Number.NaN,leadMs:Number.NaN},null;let T=h(),z=Cm(L.predicted),H=B_(T,z,es,a.stepMs??0,tn);Jd=y_(Jd,H.raw,H.at,X());let U=Jd.seq,re=T+z,te=Number.isNaN(Zd)?0:tn-Zd;Zd=tn;let J=_.stateTick+(U-_.ack);ca={tick:J,leadMs:ad(J+1,we(),X())-Lt.serverNow()};let ge=Rt.SEAT_SNAP_METRES*Im(),le=new Map;for(let[me,wt]of s()){if(!Xd(wt))continue;let nn=g.motionAt(me,U);if(nn===void 0)continue;let kt=nn.pose,zo=su.get(me),qe=zo?.pass!=null&&zo.pass!==_?g.changeAt(me,U,zo.pass):void 0,wn=w_(zo,_,wt.epoch,qe,nn,te,g.touchingAt(me,U),ge,g.stateRate(me));su.set(me,wn);let er={x:kt.x+wn.dx,y:kt.y+wn.dy,z:kt.z+wn.dz,yaw:kt.yaw+wn.dyaw,pitch:fe(wt.pitch,0),duck:fe(wt.duck,0),epoch:wt.epoch},Tn=g_(ou.get(me),g.touchAheadMs(me,re)!==void 0,te);ou.set(me,Tn);let ua=Tn>0?g.motionAt(me,re)?.pose:void 0;ua!==void 0&&(er.x+=(ua.x-kt.x)*Tn,er.y+=(ua.y-kt.y)*Tn,er.z+=(ua.z-kt.z)*Tn,er.yaw+=vo(ua.yaw-kt.yaw)*Tn),le.set(me,{pose:er,at:kt})}for(let me of[...su.keys()])le.has(me)||su.delete(me);for(let me of[...ou.keys()])le.has(me)||ou.delete(me);return le},GR=g=>{if(!ee())return;let _=e.contacts===void 0?oe():null;return _===null||g===null?ue:_.drawRule(g.id)},YR=()=>{let g=new Map,_=Om()?jR():null,T=GR(_);if(T===void 0||_===null||L===null||L.predicted===null)return ru.clear(),ca={tick:Number.NaN,leadMs:Number.NaN},g;let z=Co()===null?null:qR(),H=[];for(let[J,ge]of s()){if(!Xd(ge))continue;let le=z?.get(J)?.pose??au(ge);g.set(J,le),H.push({id:J,x:le.x,y:le.y,z:le.z,vx:0,vy:0,vz:0,yaw:le.yaw,...oe()===null?{}:{flags:fe(ge.flags,0)}})}let U=new Map;for(let[J,ge]of g)U.set(J,`${L.entity.epoch}/${ge.epoch}`);for(let[J,ge]of g)for(let[le,me]of g)J<le&&U.set(Fc(J,le),`${ge.epoch}/${me.epoch}`);let re=new Map;for(let[J,ge]of U){let le=WR(J,ge);le!==void 0&&re.set(J,le)}let te=n_(T,_,H,re,tn);ru.clear();for(let[J,ge]of te.sides)ru.set(J,{...ge,lives:U.get(J)??""});for(let[J,ge]of te.drawn){let le=g.get(J);if(le===void 0)continue;let me=z?.get(J)?.at,wt=me===void 0?void 0:Math.hypot(ge.x-me.x,ge.y-me.y,ge.z-me.z);g.set(J,{...le,x:ge.x,y:ge.y,z:ge.z,...wt===void 0?{}:{correction:wt}})}return KR(g,_),g},iu=new Map,KR=(g,_)=>{let T=L?.entity;for(let[z,H]of g){let U=s().get(z),re=z===ra&&T!==void 0&&U!==void 0,te=re?[_.x-(T.x-U.x)-H.x,_.y-(T.y-U.y)-H.y,_.z-(T.z-U.z)-H.z,0]:[0,0,0,0],J=iu.get(z),ge=J===void 0?0:Math.exp(-Math.max(0,tn-J.at)/kR),le=AR(J,re?1:0,te,ge);iu.set(z,{k:re?1:0,shift:te,err:le,at:tn}),!(!re&&le.every(me=>Math.abs(me)<H1))&&g.set(z,{...H,x:H.x+te[0]+le[0],y:H.y+te[1]+le[1],z:H.z+te[2]+le[2]})}for(let z of[...iu.keys()])g.has(z)||iu.delete(z)},Qd=0;t.onStateChange(()=>{Qd++});let Dm,Nm=()=>{let g=Dm;if(g!==void 0&&g.at===tn&&g.states===Qd)return g.seats;let _=YR();return Dm={at:tn,states:Qd,seats:_},_},ef=null,Bm=()=>L?.predicted?(Number.isNaN(bt)?(r.tick??0)-h():bt)+h()+Cm(L.predicted)+1:Lm(),Lm=()=>(Et()-we())*X()/1e3,Fm=new WeakMap,XR=(g,_)=>{let T=bn();if(T===null||T.policy.platforms.length===0||!L?.predicted)return _;let z=Lm(),H=Bm(),U=ct(),re=(r.tick??0)+1,te=Oc(T,{x:g.x,y:g.y,z:g.z,duck:fe(g.duck,0)},re,U),J=te<0?_:{..._,...Vh(T.policy,te,_,z,H,U)};te>=0&&(J.z=Hh(T.policy,te,H,U)+(g.z-Hh(T.policy,te,re,U)));let ge=[J.x-_.x,J.y-_.y,J.z-_.z,J.yaw-_.yaw],le=Fm.get(g),me=tn,wt=le===void 0?0:Math.max(0,me-le.at),nn=Math.exp(-wt/kR),kt=AR(le,te,ge,nn);return Fm.set(g,{k:te,shift:ge,err:kt,at:me}),{..._,x:J.x+kt[0],y:J.y+kt[1],z:J.z+kt[2],yaw:J.yaw+kt[3]}},tf=null,JR=g=>{let _=au(g.entity);Oo(g);let T=au(g.entity);tf={dx:_.x-T.x,dy:_.y-T.y,dz:_.z-T.z,at:tn}},au=g=>{let _=ZR(g),T=L?.entity===g?tf:null;if(T===null)return _;let z=b_(T,tn-T.at);return z.done?(tf=null,_):{..._,x:_.x+z.dx,y:_.y+z.dy,z:_.z+z.dz}},ZR=g=>{let _=$R(g);if(_)return _;let T=Qc(g),z=R.value(g,"yaw"),U=(L?.entity!==g&&w()?ts.at(g,Et()):void 0)??{x:R.value(g,"x"),y:R.value(g,"y"),z:R.value(g,"z"),yaw:Ve(g)??z,pitch:fe(R.value(g,"pitch"),fe(g.pitch,0)),duck:fe(R.value(g,"duck"),fe(g.duck,0))};return T===void 0?{...L?.entity===g?U:XR(g,U),epoch:g.epoch}:{...Et()>T.from?T.pose:U,epoch:T.epoch}},zm=(g,_,T)=>(_!==void 0&&Om()&&Xd(g)?(T??Nm()).get(_):void 0)??au(g),QR=(g,_)=>{let T=Ne.entryFor(_),z=T?.local!==void 0&&_.src===t.sessionId?T.leadMs*X()/1e3:0,H=Th(Me(_),pe()+z,X());return{id:g,kind:_.kind,owner:_.owner,...H,yaw:vo(_.yaw),hp:_.hp,flags:_.flags,epoch:_.epoch,data:_.data,t0:_.t0,g:_.g,src:_.src,pitch:fe(_.pitch,0),duck:fe(_.duck,0),mstate:fe(_.mstate,0),cap:fe(_.cap,1),spin:fe(_.spin,0),fuel:fe(_.fuel,0),...xm}},nf={text:"",limit:Math.PI},eE=()=>{let g=r.preset??"";if(nf.text!==g){let _=Qi(g)?.params.pitchLimit;nf={text:g,limit:_===void 0?Math.PI:Math.fround(_)}}return nf.limit},tE=g=>{let _=eE(),T=vo(g);return T<-_?-_:T>_?_:T},rf=(g,_,T)=>L?.entity===g&&L.predicted?.fields.includes(_)?fe(L.predicted.reconciler.state[_],T):fe(g[_],T),sf=(g,_,T)=>{let z=Pm(g);if(z!==void 0)return Kd(g,z);if(jr(_))return QR(g,_);let H=zm(_,g,T);return{id:g,kind:_.kind,owner:_.owner,x:H.x,y:H.y,z:H.z,yaw:vo(H.yaw),vx:_.vx,vy:_.vy,vz:_.vz,hp:_.hp,flags:_.flags,epoch:H.epoch,data:_.data,t0:_.t0??0,g:_.g??0,src:_.src??"",pitch:tE(H.pitch),duck:H.duck<0?0:H.duck>1?1:H.duck,mstate:rf(_,"mstate",0),cap:fe(_.cap,1),spin:rf(_,"spin",0),fuel:rf(_,"fuel",0),...xm,...H.correction===void 0?{}:{predicted:!0,correction:H.correction}}};return{id:t.sessionId,url:n,input:P,frame(g=performance.now()){if(j)return 0;tn=g,u.poll(),Qn.settle(),Qr();let _=L?.predicted??null,T=_?tt(_):[],z=_?Gc(_):null,H=_?Kc(_):null,U=_?.reconciler.reconcileSeq??0,re=Do(g),te=R.tick(g)+re;if(!_){let ge=Bs(Rr(g)+re);return Qn.afterSend(void 0,Lt.serverNow()),Ns=No(),ge}Xn=void 0,Io(_,Xc(_,U,T,H),U),Yc(_,U,z);let J=Bs(te);return Qn.afterSend(HR(),Lt.serverNow()),Ns=No(),J>0&&L&&(L.reseeded=!1),(_r?.takeMissed()??[]).length>0&&L!==null&&JR(L),J},me(){return j||Qr(),L?sf(L.id,L.entity):void 0},code:t.roomId,get matchKey(){return r.matchKey??""},setWorld(g){let _=mo(g),T=_.hash!==$.hash;return $=_,T&&L&&!j&&Oo(L),$.hash},setPhysics(g){if(typeof g!="string")throw new TypeError("setPhysics: the hash is a string (the world's physicsHash)");return q=g,q},get physics(){let g=r.physics??"",_=g!==""&&g!==q;return _&&ae!==`${g}/${q}`&&(ae=`${g}/${q}`,console.warn(`[multiplayer] the room's physics world (hash ${g}) is not this client's (hash ${q||"none"}): your copy is never stepped from the room's state. Pass your world's physicsHash to session.setPhysics().`)),{reason:_?"physics_mismatch":"",physics:q,roomPhysics:g}},get physicsPrediction(){return Qn.status},drawTick(){return ca.tick},drawLead(){return ca.leadMs},liftPose(g){let _=bn();return _===null?void 0:kx(_.policy,g,Bm(),ct())},viewCarry(){let g=bn(),_=L?.predicted?L.predicted.reconciler.state:void 0;if(g===null||_===void 0)return ef=null,0;let T=Gi(r.tick??0,h(),a.sentCount)+1,z=Oc(g,{x:_.x??0,y:_.y??0,z:_.z??0,duck:_.duck??0},T,ct()),H=g.policy.platforms[z],U=ef;return ef=H===void 0?null:{k:z,tick:T},H===void 0||U===null||U.k!==z?0:Uh(H)*(T-U.tick)},get prediction(){j||Qr();let g=L?.predicted!=null,_=g?"":L?G:e.predict===!1?"off":"no_entity";return{predicting:g,reason:_,world:$.hash,roomWorld:Sm(Qi(r.preset??""))}},predictProjectile(g){if(!K)return"";let _=a.sentCount+1;(nu.epoch!==a.epoch||nu.seq!==_)&&(nu={epoch:a.epoch,seq:_,n:0});let T=o().get(t.sessionId)?.seqBase??0,z=`${t.sessionId}.${T+_}.${nu.n++}`,H=Lt.serverNow(),U=Fs(g.g),re={x:Fs(g.x),y:Fs(g.y),z:Fs(g.z),vx:Fs(g.vx),vy:Fs(g.vy),vz:Fs(g.vz),g:U<0?0:U>wc?wc:U,t0:vh(H,we(),X())},te={id:z,kind:String(g.kind),launch:re,at:H,seq:_,epoch:a.epoch},J=Ne.spawn(te);return ut.set(te,()=>J.cancel()),k.projectilesPredicted++,z},entity(g){let _=s().get(g);if(_)return sf(g,_);let T=Pm(g);if(T!==void 0)return Kd(g,T);let z=vm().get(g);return z?Tm(z):void 0},entities(){let g=new Map,_=Nm();for(let[T,z]of s())g.set(T,sf(T,z,_));for(let[T,z]of rt)g.has(T)||g.set(T,Kd(T,z));for(let[T,z]of vm())g.has(T)||g.set(T,Tm(z));return g},players(){let g=new Map;for(let[_,T]of o())g.set(_,{id:_,name:T.name,uid:T.uid,team:T.team,connected:T.connected,avatarUrl:T.avatarUrl});return g},get tick(){return r.tick??0},get connected(){return K},telemetry:k,fast:u.status,on(g,_){let T=M.get(g)??new Set;M.set(g,T);let z=_;return T.add(z),()=>{T.delete(z)}},async leave(){j||(Mm(),t.reconnection.enabled=!1,await t.leave(!0))}}}var nD=3,FR={ready:t=>ga.ready(t),auth:()=>Au(),urls:()=>Py(),regions:()=>Ty()},$c=FR;function rD(t){$c=t??FR}var zR;function sD(t){zR=t??void 0}var oD=Ss.MAX_REWIND_MS,iD=5,aD=3e4,cD=["moveX","moveY","moveZ","yaw","pitch","buttons"],ta=t=>typeof t=="number"&&Number.isFinite(t);function uD(t){return!Array.isArray(t)||t.length>iD?void 0:t.every(n=>ta(n)&&n>=0&&n<=aD)?t:void 0}function lD(t){let e=nr(t,"options"),n=typeof e.gameId=="string"?e.gameId:"";if(!n)throw new TypeError("genex bridge: `gameId` (the game slug) is required");let r=e.renderDelayMs,s=ta(r)&&r>=0&&r<=oD;return{gameId:n,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:Array.isArray(e.urls)?e.urls.filter(o=>typeof o=="string"&&o!==""):[],predict:e.predict!==!1,predictPhysics:e.predictPhysics!==!1,renderDelayMs:s?r:void 0,capacityRetryMs:uD(e.capacityRetryMs),fast:e.fast===!1?!1:void 0}}var Em=new Map,dD=2**30,fD=dD,jc=t=>typeof t=="number"?Em.get(t):void 0,Mo=t=>{let e=jc(t);return e&&!e.closed?e.session:null};function km(t){t.closed=!0;for(let e of t.unwire.splice(0))e();t.session=null}function pD(t,e,n){ws(e)?e===xe.SERVER_RESTART&&ye(t,{type:"serverRestart"}):ye(t,{type:"message",kind:e,data:n??null})}async function hD(t){let e=t.opts;if(await $c.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:$c.urls(),r=e.urls.length?[]:$c.regions?.()??[];if(!n.length&&!r.length)throw Object.assign(new Error("genex bridge: no authority server URL (pass urls, or run on a Genex page that serves authority rooms)"),{code:0});let s=await BR({urls:n,regions:r,room:e.gameId,name:e.name,auth:()=>$c.auth(),predict:e.predict?void 0:!1,physicsCore:zR,predictPhysics:e.predictPhysics,renderDelayMs:e.renderDelayMs,capacityRetryMs:e.capacityRetryMs,fast:e.fast,onEvent:(o,i)=>{t.closed||pD(t,o,i)}});if(t.closed){await s.leave();return}t.session=s,t.sessionId=s.id,t.world&&s.setWorld(t.world),t.unwire.push(s.on("reconnecting",({code:o})=>ye(t,{type:"reconnecting",code:o})),s.on("reconnected",()=>ye(t,{type:"reconnected"})),s.on("disconnect",o=>{km(t),ye(t,{type:"disconnected",code:o,reason:""})})),ye(t,{type:"joined",sessionId:s.id})}function mD(t){let e=lD(t),n=++fD,r={opts:e,q:[],overflowed:!1,session:null,unwire:[],roster:new Set,sessionId:"",closed:!1,world:null};return Em.set(n,r),hD(r).catch(s=>{r.closed||(km(r),ye(r,{type:"joinFailed",code:Jo(s),message:tr(s)}))}),n}function yD(t,e){let n=nr(e,"input"),r=Mo(t);if(!r)return!1;for(let s of cD){let o=n[s];ta(o)&&(r.input[s]=o)}return!0}function gD(t,e){let n=nr(e,"projectile"),r=Mo(t);if(!r)return"";let s=o=>ta(o)?o:0;return r.predictProjectile({kind:typeof n.kind=="string"?n.kind:"",x:s(n.x),y:s(n.y),z:s(n.z),vx:s(n.vx),vy:s(n.vy),vz:s(n.vz),...ta(n.g)?{g:n.g}:{}})}function bD(t,e){let n=nr(e,"world"),r=jc(t);if(!r||r.closed)return!1;let s;try{s=mo(n)}catch(o){return ye(r,Xo(tr(o))),!1}return r.world=s,r.session?.setWorld(s),!0}var wD=JSON.stringify({tick:0,sent:0,connected:!1,me:null,entities:[]});function SD(t,e){let n=Mo(t);if(!n)return wD;let r=n.frame(ta(e)?e:performance.now());return JSON.stringify({tick:n.tick,sent:r,connected:n.connected,me:n.me()??null,entities:[...n.entities().values()]})}var _m=8,Rm={PREDICTED:1,ASLEEP:2},xD=new Float32Array(0);function UR(t){return[...t.entities().values()].filter(e=>e.body).sort((e,n)=>e.id<n.id?-1:e.id>n.id?1:0)}function _D(t){let e=Mo(t);if(!e)return xD;let n=UR(e),r=new Float32Array(n.length*_m);return n.forEach((s,o)=>{let i=o*_m;r.set([s.x,s.y,s.z,s.qx,s.qy,s.qz,s.qw],i),r[i+7]=(s.predicted?Rm.PREDICTED:0)|(s.sleep?Rm.ASLEEP:0)}),r}function RD(t){let e=Mo(t);return JSON.stringify(e?UR(e).map(n=>n.id):[])}function ED(t){let e=jc(t),n=Mo(t);return JSON.stringify({sessionId:e?.sessionId??"",connected:!!n&&n.connected,closed:!e||e.closed,tick:n?.tick??0,queued:e?.q.length??0,players:n?[...n.players().values()]:[],telemetry:n?{...n.telemetry}:null,prediction:n?n.prediction:null,fast:n?n.fast:null,physicsPrediction:n?n.physicsPrediction:null})}function kD(t,e){let n=new Set(e.players().keys());for(let r of n)t.roster.has(r)||ye(t,{type:"playerJoined",id:r});for(let r of t.roster)n.has(r)||ye(t,{type:"playerLeft",id:r});t.roster=n}function AD(t){let e=jc(t);if(!e)return"[]";try{let n=Mo(t);n&&kD(e,n)}catch(n){ye(e,Xo(tr(n)))}return Mu(e)}function VR(t){let e=jc(t);if(!e||e.closed)return;let n=e.session;km(e),n?.leave().catch(()=>{}),ye(e,{type:"disconnected",code:pn.CONSENTED,reason:"left"})}function PD(t){VR(t),typeof t=="number"&&Em.delete(t)}var TD=Object.freeze({...rh,...Am,initEmbed:ku});globalThis.GenexMultiplayerBridge=TD;})();
|